Enable stack traces with ghci -fexternal-interpreter -prof
[ghc.git] / compiler / main / DriverPipeline.hs
1 {-# LANGUAGE CPP, NamedFieldPuns, NondecreasingIndentation #-}
2 {-# OPTIONS_GHC -fno-cse #-}
3 -- -fno-cse is needed for GLOBAL_VAR's to behave properly
4
5 -----------------------------------------------------------------------------
6 --
7 -- GHC Driver
8 --
9 -- (c) The University of Glasgow 2005
10 --
11 -----------------------------------------------------------------------------
12
13 module DriverPipeline (
14 -- Run a series of compilation steps in a pipeline, for a
15 -- collection of source files.
16 oneShot, compileFile,
17
18 -- Interfaces for the batch-mode driver
19 linkBinary,
20
21 -- Interfaces for the compilation manager (interpreted/batch-mode)
22 preprocess,
23 compileOne, compileOne',
24 link,
25
26 -- Exports for hooks to override runPhase and link
27 PhasePlus(..), CompPipeline(..), PipeEnv(..), PipeState(..),
28 phaseOutputFilename, getOutputFilename, getPipeState, getPipeEnv,
29 hscPostBackendPhase, getLocation, setModLocation, setDynFlags,
30 runPhase, exeFileName,
31 mkExtraObjToLinkIntoBinary, mkNoteObjsToLinkIntoBinary,
32 maybeCreateManifest,
33 linkingNeeded, checkLinkInfo, writeInterfaceOnlyMode
34 ) where
35
36 #include "HsVersions.h"
37
38 import PipelineMonad
39 import Packages
40 import HeaderInfo
41 import DriverPhases
42 import SysTools
43 import Elf
44 import HscMain
45 import Finder
46 import HscTypes hiding ( Hsc )
47 import Outputable
48 import Module
49 import UniqFM ( eltsUFM )
50 import ErrUtils
51 import DynFlags
52 import Config
53 import Panic
54 import Util
55 import StringBuffer ( hGetStringBuffer )
56 import BasicTypes ( SuccessFlag(..) )
57 import Maybes ( expectJust )
58 import SrcLoc
59 import FastString
60 import LlvmCodeGen ( llvmFixupAsm )
61 import MonadUtils
62 import Platform
63 import TcRnTypes
64 import Hooks
65 import qualified GHC.LanguageExtensions as LangExt
66
67 import Exception
68 import System.Directory
69 import System.FilePath
70 import System.IO
71 import Control.Monad
72 import Data.List ( isSuffixOf )
73 import Data.Maybe
74 import Data.Version
75
76 -- ---------------------------------------------------------------------------
77 -- Pre-process
78
79 -- | Just preprocess a file, put the result in a temp. file (used by the
80 -- compilation manager during the summary phase).
81 --
82 -- We return the augmented DynFlags, because they contain the result
83 -- of slurping in the OPTIONS pragmas
84
85 preprocess :: HscEnv
86 -> (FilePath, Maybe Phase) -- ^ filename and starting phase
87 -> IO (DynFlags, FilePath)
88 preprocess hsc_env (filename, mb_phase) =
89 ASSERT2(isJust mb_phase || isHaskellSrcFilename filename, text filename)
90 runPipeline anyHsc hsc_env (filename, fmap RealPhase mb_phase)
91 Nothing Temporary Nothing{-no ModLocation-} Nothing{-no stub-}
92
93 -- ---------------------------------------------------------------------------
94
95 -- | Compile
96 --
97 -- Compile a single module, under the control of the compilation manager.
98 --
99 -- This is the interface between the compilation manager and the
100 -- compiler proper (hsc), where we deal with tedious details like
101 -- reading the OPTIONS pragma from the source file, converting the
102 -- C or assembly that GHC produces into an object file, and compiling
103 -- FFI stub files.
104 --
105 -- NB. No old interface can also mean that the source has changed.
106
107 compileOne :: HscEnv
108 -> ModSummary -- ^ summary for module being compiled
109 -> Int -- ^ module N ...
110 -> Int -- ^ ... of M
111 -> Maybe ModIface -- ^ old interface, if we have one
112 -> Maybe Linkable -- ^ old linkable, if we have one
113 -> SourceModified
114 -> IO HomeModInfo -- ^ the complete HomeModInfo, if successful
115
116 compileOne = compileOne' Nothing (Just batchMsg)
117
118 compileOne' :: Maybe TcGblEnv
119 -> Maybe Messager
120 -> HscEnv
121 -> ModSummary -- ^ summary for module being compiled
122 -> Int -- ^ module N ...
123 -> Int -- ^ ... of M
124 -> Maybe ModIface -- ^ old interface, if we have one
125 -> Maybe Linkable -- ^ old linkable, if we have one
126 -> SourceModified
127 -> IO HomeModInfo -- ^ the complete HomeModInfo, if successful
128
129 compileOne' m_tc_result mHscMessage
130 hsc_env0 summary mod_index nmods mb_old_iface maybe_old_linkable
131 source_modified0
132 = do
133
134 debugTraceMsg dflags1 2 (text "compile: input file" <+> text input_fnpp)
135
136 (status, hmi0) <- hscIncrementalCompile
137 always_do_basic_recompilation_check
138 m_tc_result mHscMessage
139 hsc_env summary source_modified mb_old_iface (mod_index, nmods)
140
141 case (status, hsc_lang) of
142 (HscUpToDate, _) ->
143 ASSERT( isJust maybe_old_linkable || isNoLink (ghcLink dflags) )
144 return hmi0 { hm_linkable = maybe_old_linkable }
145 (HscNotGeneratingCode, HscNothing) ->
146 let mb_linkable = if isHsBootOrSig src_flavour
147 then Nothing
148 -- TODO: Questionable.
149 else Just (LM (ms_hs_date summary) this_mod [])
150 in return hmi0 { hm_linkable = mb_linkable }
151 (HscNotGeneratingCode, _) -> panic "compileOne HscNotGeneratingCode"
152 (_, HscNothing) -> panic "compileOne HscNothing"
153 (HscUpdateBoot, HscInterpreted) -> do
154 return hmi0
155 (HscUpdateBoot, _) -> do
156 touchObjectFile dflags object_filename
157 return hmi0
158 (HscUpdateSig, HscInterpreted) ->
159 let linkable = LM (ms_hs_date summary) this_mod []
160 in return hmi0 { hm_linkable = Just linkable }
161 (HscUpdateSig, _) -> do
162 output_fn <- getOutputFilename next_phase
163 Temporary basename dflags next_phase (Just location)
164
165 -- #10660: Use the pipeline instead of calling
166 -- compileEmptyStub directly, so -dynamic-too gets
167 -- handled properly
168 _ <- runPipeline StopLn hsc_env
169 (output_fn,
170 Just (HscOut src_flavour
171 mod_name HscUpdateSig))
172 (Just basename)
173 Persistent
174 (Just location)
175 Nothing
176 o_time <- getModificationUTCTime object_filename
177 let linkable = LM o_time this_mod [DotO object_filename]
178 return hmi0 { hm_linkable = Just linkable }
179 (HscRecomp cgguts summary, HscInterpreted) -> do
180 (hasStub, comp_bc) <- hscInteractive hsc_env cgguts summary
181
182 stub_o <- case hasStub of
183 Nothing -> return []
184 Just stub_c -> do
185 stub_o <- compileStub hsc_env stub_c
186 return [DotO stub_o]
187
188 let hs_unlinked = [BCOs comp_bc]
189 unlinked_time = ms_hs_date summary
190 -- Why do we use the timestamp of the source file here,
191 -- rather than the current time? This works better in
192 -- the case where the local clock is out of sync
193 -- with the filesystem's clock. It's just as accurate:
194 -- if the source is modified, then the linkable will
195 -- be out of date.
196 let linkable = LM unlinked_time (ms_mod summary)
197 (hs_unlinked ++ stub_o)
198 return hmi0 { hm_linkable = Just linkable }
199 (HscRecomp cgguts summary, _) -> do
200 output_fn <- getOutputFilename next_phase
201 Temporary basename dflags next_phase (Just location)
202 -- We're in --make mode: finish the compilation pipeline.
203 _ <- runPipeline StopLn hsc_env
204 (output_fn,
205 Just (HscOut src_flavour mod_name (HscRecomp cgguts summary)))
206 (Just basename)
207 Persistent
208 (Just location)
209 Nothing
210 -- The object filename comes from the ModLocation
211 o_time <- getModificationUTCTime object_filename
212 let linkable = LM o_time this_mod [DotO object_filename]
213 return hmi0 { hm_linkable = Just linkable }
214
215 where dflags0 = ms_hspp_opts summary
216
217 this_mod = ms_mod summary
218 location = ms_location summary
219 input_fn = expectJust "compile:hs" (ml_hs_file location)
220 input_fnpp = ms_hspp_file summary
221 mod_graph = hsc_mod_graph hsc_env0
222 needsTH = any (xopt LangExt.TemplateHaskell . ms_hspp_opts) mod_graph
223 needsQQ = any (xopt LangExt.QuasiQuotes . ms_hspp_opts) mod_graph
224 needsLinker = needsTH || needsQQ
225 isDynWay = any (== WayDyn) (ways dflags0)
226 isProfWay = any (== WayProf) (ways dflags0)
227 internalInterpreter = not (gopt Opt_ExternalInterpreter dflags0)
228
229 src_flavour = ms_hsc_src summary
230 mod_name = ms_mod_name summary
231 next_phase = hscPostBackendPhase dflags src_flavour hsc_lang
232 object_filename = ml_obj_file location
233
234 -- #8180 - when using TemplateHaskell, switch on -dynamic-too so
235 -- the linker can correctly load the object files. This isn't necessary
236 -- when using -fexternal-interpreter.
237 dflags1 = if needsLinker && dynamicGhc && internalInterpreter &&
238 not isDynWay && not isProfWay
239 then gopt_set dflags0 Opt_BuildDynamicToo
240 else dflags0
241
242 basename = dropExtension input_fn
243
244 -- We add the directory in which the .hs files resides) to the import
245 -- path. This is needed when we try to compile the .hc file later, if it
246 -- imports a _stub.h file that we created here.
247 current_dir = takeDirectory basename
248 old_paths = includePaths dflags1
249 dflags = dflags1 { includePaths = current_dir : old_paths }
250 hsc_env = hsc_env0 {hsc_dflags = dflags}
251
252 -- Figure out what lang we're generating
253 hsc_lang = hscTarget dflags
254
255 -- -fforce-recomp should also work with --make
256 force_recomp = gopt Opt_ForceRecomp dflags
257 source_modified
258 | force_recomp = SourceModified
259 | otherwise = source_modified0
260
261 always_do_basic_recompilation_check = case hsc_lang of
262 HscInterpreted -> True
263 _ -> False
264
265 -----------------------------------------------------------------------------
266 -- stub .h and .c files (for foreign export support)
267
268 -- The _stub.c file is derived from the haskell source file, possibly taking
269 -- into account the -stubdir option.
270 --
271 -- The object file created by compiling the _stub.c file is put into a
272 -- temporary file, which will be later combined with the main .o file
273 -- (see the MergeStubs phase).
274
275 compileStub :: HscEnv -> FilePath -> IO FilePath
276 compileStub hsc_env stub_c = do
277 (_, stub_o) <- runPipeline StopLn hsc_env (stub_c,Nothing) Nothing
278 Temporary Nothing{-no ModLocation-} Nothing
279
280 return stub_o
281
282 compileEmptyStub :: DynFlags -> HscEnv -> FilePath -> ModLocation -> IO ()
283 compileEmptyStub dflags hsc_env basename location = do
284 -- To maintain the invariant that every Haskell file
285 -- compiles to object code, we make an empty (but
286 -- valid) stub object file for signatures
287 empty_stub <- newTempName dflags "c"
288 writeFile empty_stub ""
289 _ <- runPipeline StopLn hsc_env
290 (empty_stub, Nothing)
291 (Just basename)
292 Persistent
293 (Just location)
294 Nothing
295 return ()
296
297 -- ---------------------------------------------------------------------------
298 -- Link
299
300 link :: GhcLink -- interactive or batch
301 -> DynFlags -- dynamic flags
302 -> Bool -- attempt linking in batch mode?
303 -> HomePackageTable -- what to link
304 -> IO SuccessFlag
305
306 -- For the moment, in the batch linker, we don't bother to tell doLink
307 -- which packages to link -- it just tries all that are available.
308 -- batch_attempt_linking should only be *looked at* in batch mode. It
309 -- should only be True if the upsweep was successful and someone
310 -- exports main, i.e., we have good reason to believe that linking
311 -- will succeed.
312
313 link ghcLink dflags
314 = lookupHook linkHook l dflags ghcLink dflags
315 where
316 l LinkInMemory _ _ _
317 = if cGhcWithInterpreter == "YES"
318 then -- Not Linking...(demand linker will do the job)
319 return Succeeded
320 else panicBadLink LinkInMemory
321
322 l NoLink _ _ _
323 = return Succeeded
324
325 l LinkBinary dflags batch_attempt_linking hpt
326 = link' dflags batch_attempt_linking hpt
327
328 l LinkStaticLib dflags batch_attempt_linking hpt
329 = link' dflags batch_attempt_linking hpt
330
331 l LinkDynLib dflags batch_attempt_linking hpt
332 = link' dflags batch_attempt_linking hpt
333
334 panicBadLink :: GhcLink -> a
335 panicBadLink other = panic ("link: GHC not built to link this way: " ++
336 show other)
337
338 link' :: DynFlags -- dynamic flags
339 -> Bool -- attempt linking in batch mode?
340 -> HomePackageTable -- what to link
341 -> IO SuccessFlag
342
343 link' dflags batch_attempt_linking hpt
344 | batch_attempt_linking
345 = do
346 let
347 staticLink = case ghcLink dflags of
348 LinkStaticLib -> True
349 _ -> platformBinariesAreStaticLibs (targetPlatform dflags)
350
351 home_mod_infos = eltsUFM hpt
352
353 -- the packages we depend on
354 pkg_deps = concatMap (map fst . dep_pkgs . mi_deps . hm_iface) home_mod_infos
355
356 -- the linkables to link
357 linkables = map (expectJust "link".hm_linkable) home_mod_infos
358
359 debugTraceMsg dflags 3 (text "link: linkables are ..." $$ vcat (map ppr linkables))
360
361 -- check for the -no-link flag
362 if isNoLink (ghcLink dflags)
363 then do debugTraceMsg dflags 3 (text "link(batch): linking omitted (-c flag given).")
364 return Succeeded
365 else do
366
367 let getOfiles (LM _ _ us) = map nameOfObject (filter isObject us)
368 obj_files = concatMap getOfiles linkables
369
370 exe_file = exeFileName staticLink dflags
371
372 linking_needed <- linkingNeeded dflags staticLink linkables pkg_deps
373
374 if not (gopt Opt_ForceRecomp dflags) && not linking_needed
375 then do debugTraceMsg dflags 2 (text exe_file <+> ptext (sLit "is up to date, linking not required."))
376 return Succeeded
377 else do
378
379 compilationProgressMsg dflags ("Linking " ++ exe_file ++ " ...")
380
381 -- Don't showPass in Batch mode; doLink will do that for us.
382 let link = case ghcLink dflags of
383 LinkBinary -> linkBinary
384 LinkStaticLib -> linkStaticLibCheck
385 LinkDynLib -> linkDynLibCheck
386 other -> panicBadLink other
387 link dflags obj_files pkg_deps
388
389 debugTraceMsg dflags 3 (text "link: done")
390
391 -- linkBinary only returns if it succeeds
392 return Succeeded
393
394 | otherwise
395 = do debugTraceMsg dflags 3 (text "link(batch): upsweep (partially) failed OR" $$
396 text " Main.main not exported; not linking.")
397 return Succeeded
398
399
400 linkingNeeded :: DynFlags -> Bool -> [Linkable] -> [UnitId] -> IO Bool
401 linkingNeeded dflags staticLink linkables pkg_deps = do
402 -- if the modification time on the executable is later than the
403 -- modification times on all of the objects and libraries, then omit
404 -- linking (unless the -fforce-recomp flag was given).
405 let exe_file = exeFileName staticLink dflags
406 e_exe_time <- tryIO $ getModificationUTCTime exe_file
407 case e_exe_time of
408 Left _ -> return True
409 Right t -> do
410 -- first check object files and extra_ld_inputs
411 let extra_ld_inputs = [ f | FileOption _ f <- ldInputs dflags ]
412 e_extra_times <- mapM (tryIO . getModificationUTCTime) extra_ld_inputs
413 let (errs,extra_times) = splitEithers e_extra_times
414 let obj_times = map linkableTime linkables ++ extra_times
415 if not (null errs) || any (t <) obj_times
416 then return True
417 else do
418
419 -- next, check libraries. XXX this only checks Haskell libraries,
420 -- not extra_libraries or -l things from the command line.
421 let pkg_hslibs = [ (libraryDirs c, lib)
422 | Just c <- map (lookupPackage dflags) pkg_deps,
423 lib <- packageHsLibs dflags c ]
424
425 pkg_libfiles <- mapM (uncurry (findHSLib dflags)) pkg_hslibs
426 if any isNothing pkg_libfiles then return True else do
427 e_lib_times <- mapM (tryIO . getModificationUTCTime)
428 (catMaybes pkg_libfiles)
429 let (lib_errs,lib_times) = splitEithers e_lib_times
430 if not (null lib_errs) || any (t <) lib_times
431 then return True
432 else checkLinkInfo dflags pkg_deps exe_file
433
434 -- Returns 'False' if it was, and we can avoid linking, because the
435 -- previous binary was linked with "the same options".
436 checkLinkInfo :: DynFlags -> [UnitId] -> FilePath -> IO Bool
437 checkLinkInfo dflags pkg_deps exe_file
438 | not (platformSupportsSavingLinkOpts (platformOS (targetPlatform dflags)))
439 -- ToDo: Windows and OS X do not use the ELF binary format, so
440 -- readelf does not work there. We need to find another way to do
441 -- this.
442 = return False -- conservatively we should return True, but not
443 -- linking in this case was the behaviour for a long
444 -- time so we leave it as-is.
445 | otherwise
446 = do
447 link_info <- getLinkInfo dflags pkg_deps
448 debugTraceMsg dflags 3 $ text ("Link info: " ++ link_info)
449 m_exe_link_info <- readElfNoteAsString dflags exe_file
450 ghcLinkInfoSectionName ghcLinkInfoNoteName
451 let sameLinkInfo = (Just link_info == m_exe_link_info)
452 debugTraceMsg dflags 3 $ case m_exe_link_info of
453 Nothing -> text "Exe link info: Not found"
454 Just s
455 | sameLinkInfo -> text ("Exe link info is the same")
456 | otherwise -> text ("Exe link info is different: " ++ s)
457 return (not sameLinkInfo)
458
459 platformSupportsSavingLinkOpts :: OS -> Bool
460 platformSupportsSavingLinkOpts os
461 | os == OSSolaris2 = False -- see #5382
462 | otherwise = osElfTarget os
463
464 -- See Note [LinkInfo section]
465 ghcLinkInfoSectionName :: String
466 ghcLinkInfoSectionName = ".debug-ghc-link-info"
467 -- if we use the ".debug" prefix, then strip will strip it by default
468
469 -- Identifier for the note (see Note [LinkInfo section])
470 ghcLinkInfoNoteName :: String
471 ghcLinkInfoNoteName = "GHC link info"
472
473 findHSLib :: DynFlags -> [String] -> String -> IO (Maybe FilePath)
474 findHSLib dflags dirs lib = do
475 let batch_lib_file = if WayDyn `notElem` ways dflags
476 then "lib" ++ lib <.> "a"
477 else mkSOName (targetPlatform dflags) lib
478 found <- filterM doesFileExist (map (</> batch_lib_file) dirs)
479 case found of
480 [] -> return Nothing
481 (x:_) -> return (Just x)
482
483 -- -----------------------------------------------------------------------------
484 -- Compile files in one-shot mode.
485
486 oneShot :: HscEnv -> Phase -> [(String, Maybe Phase)] -> IO ()
487 oneShot hsc_env stop_phase srcs = do
488 o_files <- mapM (compileFile hsc_env stop_phase) srcs
489 doLink (hsc_dflags hsc_env) stop_phase o_files
490
491 compileFile :: HscEnv -> Phase -> (FilePath, Maybe Phase) -> IO FilePath
492 compileFile hsc_env stop_phase (src, mb_phase) = do
493 exists <- doesFileExist src
494 when (not exists) $
495 throwGhcExceptionIO (CmdLineError ("does not exist: " ++ src))
496
497 let
498 dflags = hsc_dflags hsc_env
499 split = gopt Opt_SplitObjs dflags
500 mb_o_file = outputFile dflags
501 ghc_link = ghcLink dflags -- Set by -c or -no-link
502
503 -- When linking, the -o argument refers to the linker's output.
504 -- otherwise, we use it as the name for the pipeline's output.
505 output
506 -- If we are dong -fno-code, then act as if the output is
507 -- 'Temporary'. This stops GHC trying to copy files to their
508 -- final location.
509 | HscNothing <- hscTarget dflags = Temporary
510 | StopLn <- stop_phase, not (isNoLink ghc_link) = Persistent
511 -- -o foo applies to linker
512 | isJust mb_o_file = SpecificFile
513 -- -o foo applies to the file we are compiling now
514 | otherwise = Persistent
515
516 stop_phase' = case stop_phase of
517 As _ | split -> SplitAs
518 _ -> stop_phase
519
520 ( _, out_file) <- runPipeline stop_phase' hsc_env
521 (src, fmap RealPhase mb_phase) Nothing output
522 Nothing{-no ModLocation-} Nothing
523 return out_file
524
525
526 doLink :: DynFlags -> Phase -> [FilePath] -> IO ()
527 doLink dflags stop_phase o_files
528 | not (isStopLn stop_phase)
529 = return () -- We stopped before the linking phase
530
531 | otherwise
532 = case ghcLink dflags of
533 NoLink -> return ()
534 LinkBinary -> linkBinary dflags o_files []
535 LinkStaticLib -> linkStaticLibCheck dflags o_files []
536 LinkDynLib -> linkDynLibCheck dflags o_files []
537 other -> panicBadLink other
538
539
540 -- ---------------------------------------------------------------------------
541
542 -- | Run a compilation pipeline, consisting of multiple phases.
543 --
544 -- This is the interface to the compilation pipeline, which runs
545 -- a series of compilation steps on a single source file, specifying
546 -- at which stage to stop.
547 --
548 -- The DynFlags can be modified by phases in the pipeline (eg. by
549 -- OPTIONS_GHC pragmas), and the changes affect later phases in the
550 -- pipeline.
551 runPipeline
552 :: Phase -- ^ When to stop
553 -> HscEnv -- ^ Compilation environment
554 -> (FilePath,Maybe PhasePlus) -- ^ Input filename (and maybe -x suffix)
555 -> Maybe FilePath -- ^ original basename (if different from ^^^)
556 -> PipelineOutput -- ^ Output filename
557 -> Maybe ModLocation -- ^ A ModLocation, if this is a Haskell module
558 -> Maybe FilePath -- ^ stub object, if we have one
559 -> IO (DynFlags, FilePath) -- ^ (final flags, output filename)
560 runPipeline stop_phase hsc_env0 (input_fn, mb_phase)
561 mb_basename output maybe_loc maybe_stub_o
562
563 = do let
564 dflags0 = hsc_dflags hsc_env0
565
566 -- Decide where dump files should go based on the pipeline output
567 dflags = dflags0 { dumpPrefix = Just (basename ++ ".") }
568 hsc_env = hsc_env0 {hsc_dflags = dflags}
569
570 (input_basename, suffix) = splitExtension input_fn
571 suffix' = drop 1 suffix -- strip off the .
572 basename | Just b <- mb_basename = b
573 | otherwise = input_basename
574
575 -- If we were given a -x flag, then use that phase to start from
576 start_phase = fromMaybe (RealPhase (startPhase suffix')) mb_phase
577
578 isHaskell (RealPhase (Unlit _)) = True
579 isHaskell (RealPhase (Cpp _)) = True
580 isHaskell (RealPhase (HsPp _)) = True
581 isHaskell (RealPhase (Hsc _)) = True
582 isHaskell (HscOut {}) = True
583 isHaskell _ = False
584
585 isHaskellishFile = isHaskell start_phase
586
587 env = PipeEnv{ stop_phase,
588 src_filename = input_fn,
589 src_basename = basename,
590 src_suffix = suffix',
591 output_spec = output }
592
593 -- We want to catch cases of "you can't get there from here" before
594 -- we start the pipeline, because otherwise it will just run off the
595 -- end.
596 let happensBefore' = happensBefore dflags
597 case start_phase of
598 RealPhase start_phase' ->
599 -- See Note [Partial ordering on phases]
600 -- Not the same as: (stop_phase `happensBefore` start_phase')
601 when (not (start_phase' `happensBefore'` stop_phase ||
602 start_phase' `eqPhase` stop_phase)) $
603 throwGhcExceptionIO (UsageError
604 ("cannot compile this file to desired target: "
605 ++ input_fn))
606 HscOut {} -> return ()
607
608 debugTraceMsg dflags 4 (text "Running the pipeline")
609 r <- runPipeline' start_phase hsc_env env input_fn
610 maybe_loc maybe_stub_o
611
612 -- If we are compiling a Haskell module, and doing
613 -- -dynamic-too, but couldn't do the -dynamic-too fast
614 -- path, then rerun the pipeline for the dyn way
615 let dflags = extractDynFlags hsc_env
616 -- NB: Currently disabled on Windows (ref #7134, #8228, and #5987)
617 when (not $ platformOS (targetPlatform dflags) == OSMinGW32) $ do
618 when isHaskellishFile $ whenCannotGenerateDynamicToo dflags $ do
619 debugTraceMsg dflags 4
620 (text "Running the pipeline again for -dynamic-too")
621 let dflags' = dynamicTooMkDynamicDynFlags dflags
622 hsc_env' <- newHscEnv dflags'
623 _ <- runPipeline' start_phase hsc_env' env input_fn
624 maybe_loc maybe_stub_o
625 return ()
626 return r
627
628 runPipeline'
629 :: PhasePlus -- ^ When to start
630 -> HscEnv -- ^ Compilation environment
631 -> PipeEnv
632 -> FilePath -- ^ Input filename
633 -> Maybe ModLocation -- ^ A ModLocation, if this is a Haskell module
634 -> Maybe FilePath -- ^ stub object, if we have one
635 -> IO (DynFlags, FilePath) -- ^ (final flags, output filename)
636 runPipeline' start_phase hsc_env env input_fn
637 maybe_loc maybe_stub_o
638 = do
639 -- Execute the pipeline...
640 let state = PipeState{ hsc_env, maybe_loc, maybe_stub_o = maybe_stub_o }
641
642 evalP (pipeLoop start_phase input_fn) env state
643
644 -- ---------------------------------------------------------------------------
645 -- outer pipeline loop
646
647 -- | pipeLoop runs phases until we reach the stop phase
648 pipeLoop :: PhasePlus -> FilePath -> CompPipeline (DynFlags, FilePath)
649 pipeLoop phase input_fn = do
650 env <- getPipeEnv
651 dflags <- getDynFlags
652 -- See Note [Partial ordering on phases]
653 let happensBefore' = happensBefore dflags
654 stopPhase = stop_phase env
655 case phase of
656 RealPhase realPhase | realPhase `eqPhase` stopPhase -- All done
657 -> -- Sometimes, a compilation phase doesn't actually generate any output
658 -- (eg. the CPP phase when -fcpp is not turned on). If we end on this
659 -- stage, but we wanted to keep the output, then we have to explicitly
660 -- copy the file, remembering to prepend a {-# LINE #-} pragma so that
661 -- further compilation stages can tell what the original filename was.
662 case output_spec env of
663 Temporary ->
664 return (dflags, input_fn)
665 output ->
666 do pst <- getPipeState
667 final_fn <- liftIO $ getOutputFilename
668 stopPhase output (src_basename env)
669 dflags stopPhase (maybe_loc pst)
670 when (final_fn /= input_fn) $ do
671 let msg = ("Copying `" ++ input_fn ++"' to `" ++ final_fn ++ "'")
672 line_prag = Just ("{-# LINE 1 \"" ++ src_filename env ++ "\" #-}\n")
673 liftIO $ copyWithHeader dflags msg line_prag input_fn final_fn
674 return (dflags, final_fn)
675
676
677 | not (realPhase `happensBefore'` stopPhase)
678 -- Something has gone wrong. We'll try to cover all the cases when
679 -- this could happen, so if we reach here it is a panic.
680 -- eg. it might happen if the -C flag is used on a source file that
681 -- has {-# OPTIONS -fasm #-}.
682 -> panic ("pipeLoop: at phase " ++ show realPhase ++
683 " but I wanted to stop at phase " ++ show stopPhase)
684
685 _
686 -> do liftIO $ debugTraceMsg dflags 4
687 (ptext (sLit "Running phase") <+> ppr phase)
688 (next_phase, output_fn) <- runHookedPhase phase input_fn dflags
689 r <- pipeLoop next_phase output_fn
690 case phase of
691 HscOut {} ->
692 whenGeneratingDynamicToo dflags $ do
693 setDynFlags $ dynamicTooMkDynamicDynFlags dflags
694 -- TODO shouldn't ignore result:
695 _ <- pipeLoop phase input_fn
696 return ()
697 _ ->
698 return ()
699 return r
700
701 runHookedPhase :: PhasePlus -> FilePath -> DynFlags
702 -> CompPipeline (PhasePlus, FilePath)
703 runHookedPhase pp input dflags =
704 lookupHook runPhaseHook runPhase dflags pp input dflags
705
706 -- -----------------------------------------------------------------------------
707 -- In each phase, we need to know into what filename to generate the
708 -- output. All the logic about which filenames we generate output
709 -- into is embodied in the following function.
710
711 -- | Computes the next output filename after we run @next_phase@.
712 -- Like 'getOutputFilename', but it operates in the 'CompPipeline' monad
713 -- (which specifies all of the ambient information.)
714 phaseOutputFilename :: Phase{-next phase-} -> CompPipeline FilePath
715 phaseOutputFilename next_phase = do
716 PipeEnv{stop_phase, src_basename, output_spec} <- getPipeEnv
717 PipeState{maybe_loc, hsc_env} <- getPipeState
718 let dflags = hsc_dflags hsc_env
719 liftIO $ getOutputFilename stop_phase output_spec
720 src_basename dflags next_phase maybe_loc
721
722 -- | Computes the next output filename for something in the compilation
723 -- pipeline. This is controlled by several variables:
724 --
725 -- 1. 'Phase': the last phase to be run (e.g. 'stopPhase'). This
726 -- is used to tell if we're in the last phase or not, because
727 -- in that case flags like @-o@ may be important.
728 -- 2. 'PipelineOutput': is this intended to be a 'Temporary' or
729 -- 'Persistent' build output? Temporary files just go in
730 -- a fresh temporary name.
731 -- 3. 'String': what was the basename of the original input file?
732 -- 4. 'DynFlags': the obvious thing
733 -- 5. 'Phase': the phase we want to determine the output filename of.
734 -- 6. @Maybe ModLocation@: the 'ModLocation' of the module we're
735 -- compiling; this can be used to override the default output
736 -- of an object file. (TODO: do we actually need this?)
737 getOutputFilename
738 :: Phase -> PipelineOutput -> String
739 -> DynFlags -> Phase{-next phase-} -> Maybe ModLocation -> IO FilePath
740 getOutputFilename stop_phase output basename dflags next_phase maybe_location
741 | is_last_phase, Persistent <- output = persistent_fn
742 | is_last_phase, SpecificFile <- output = case outputFile dflags of
743 Just f -> return f
744 Nothing ->
745 panic "SpecificFile: No filename"
746 | keep_this_output = persistent_fn
747 | otherwise = newTempName dflags suffix
748 where
749 hcsuf = hcSuf dflags
750 odir = objectDir dflags
751 osuf = objectSuf dflags
752 keep_hc = gopt Opt_KeepHcFiles dflags
753 keep_s = gopt Opt_KeepSFiles dflags
754 keep_bc = gopt Opt_KeepLlvmFiles dflags
755
756 myPhaseInputExt HCc = hcsuf
757 myPhaseInputExt MergeStub = osuf
758 myPhaseInputExt StopLn = osuf
759 myPhaseInputExt other = phaseInputExt other
760
761 is_last_phase = next_phase `eqPhase` stop_phase
762
763 -- sometimes, we keep output from intermediate stages
764 keep_this_output =
765 case next_phase of
766 As _ | keep_s -> True
767 LlvmOpt | keep_bc -> True
768 HCc | keep_hc -> True
769 _other -> False
770
771 suffix = myPhaseInputExt next_phase
772
773 -- persistent object files get put in odir
774 persistent_fn
775 | StopLn <- next_phase = return odir_persistent
776 | otherwise = return persistent
777
778 persistent = basename <.> suffix
779
780 odir_persistent
781 | Just loc <- maybe_location = ml_obj_file loc
782 | Just d <- odir = d </> persistent
783 | otherwise = persistent
784
785 -- -----------------------------------------------------------------------------
786 -- | Each phase in the pipeline returns the next phase to execute, and the
787 -- name of the file in which the output was placed.
788 --
789 -- We must do things dynamically this way, because we often don't know
790 -- what the rest of the phases will be until part-way through the
791 -- compilation: for example, an {-# OPTIONS -fasm #-} at the beginning
792 -- of a source file can change the latter stages of the pipeline from
793 -- taking the LLVM route to using the native code generator.
794 --
795 runPhase :: PhasePlus -- ^ Run this phase
796 -> FilePath -- ^ name of the input file
797 -> DynFlags -- ^ for convenience, we pass the current dflags in
798 -> CompPipeline (PhasePlus, -- next phase to run
799 FilePath) -- output filename
800
801 -- Invariant: the output filename always contains the output
802 -- Interesting case: Hsc when there is no recompilation to do
803 -- Then the output filename is still a .o file
804
805
806 -------------------------------------------------------------------------------
807 -- Unlit phase
808
809 runPhase (RealPhase (Unlit sf)) input_fn dflags
810 = do
811 output_fn <- phaseOutputFilename (Cpp sf)
812
813 let flags = [ -- The -h option passes the file name for unlit to
814 -- put in a #line directive
815 SysTools.Option "-h"
816 -- See Note [Don't normalise input filenames].
817 , SysTools.Option $ escape input_fn
818 , SysTools.FileOption "" input_fn
819 , SysTools.FileOption "" output_fn
820 ]
821
822 liftIO $ SysTools.runUnlit dflags flags
823
824 return (RealPhase (Cpp sf), output_fn)
825 where
826 -- escape the characters \, ", and ', but don't try to escape
827 -- Unicode or anything else (so we don't use Util.charToC
828 -- here). If we get this wrong, then in
829 -- Coverage.isGoodTickSrcSpan where we check that the filename in
830 -- a SrcLoc is the same as the source filenaame, the two will
831 -- look bogusly different. See test:
832 -- libraries/hpc/tests/function/subdir/tough2.hs
833 escape ('\\':cs) = '\\':'\\': escape cs
834 escape ('\"':cs) = '\\':'\"': escape cs
835 escape ('\'':cs) = '\\':'\'': escape cs
836 escape (c:cs) = c : escape cs
837 escape [] = []
838
839 -------------------------------------------------------------------------------
840 -- Cpp phase : (a) gets OPTIONS out of file
841 -- (b) runs cpp if necessary
842
843 runPhase (RealPhase (Cpp sf)) input_fn dflags0
844 = do
845 src_opts <- liftIO $ getOptionsFromFile dflags0 input_fn
846 (dflags1, unhandled_flags, warns)
847 <- liftIO $ parseDynamicFilePragma dflags0 src_opts
848 setDynFlags dflags1
849 liftIO $ checkProcessArgsResult dflags1 unhandled_flags
850
851 if not (xopt LangExt.Cpp dflags1) then do
852 -- we have to be careful to emit warnings only once.
853 unless (gopt Opt_Pp dflags1) $
854 liftIO $ handleFlagWarnings dflags1 warns
855
856 -- no need to preprocess CPP, just pass input file along
857 -- to the next phase of the pipeline.
858 return (RealPhase (HsPp sf), input_fn)
859 else do
860 output_fn <- phaseOutputFilename (HsPp sf)
861 liftIO $ doCpp dflags1 True{-raw-}
862 input_fn output_fn
863 -- re-read the pragmas now that we've preprocessed the file
864 -- See #2464,#3457
865 src_opts <- liftIO $ getOptionsFromFile dflags0 output_fn
866 (dflags2, unhandled_flags, warns)
867 <- liftIO $ parseDynamicFilePragma dflags0 src_opts
868 liftIO $ checkProcessArgsResult dflags2 unhandled_flags
869 unless (gopt Opt_Pp dflags2) $
870 liftIO $ handleFlagWarnings dflags2 warns
871 -- the HsPp pass below will emit warnings
872
873 setDynFlags dflags2
874
875 return (RealPhase (HsPp sf), output_fn)
876
877 -------------------------------------------------------------------------------
878 -- HsPp phase
879
880 runPhase (RealPhase (HsPp sf)) input_fn dflags
881 = do
882 if not (gopt Opt_Pp dflags) then
883 -- no need to preprocess, just pass input file along
884 -- to the next phase of the pipeline.
885 return (RealPhase (Hsc sf), input_fn)
886 else do
887 PipeEnv{src_basename, src_suffix} <- getPipeEnv
888 let orig_fn = src_basename <.> src_suffix
889 output_fn <- phaseOutputFilename (Hsc sf)
890 liftIO $ SysTools.runPp dflags
891 ( [ SysTools.Option orig_fn
892 , SysTools.Option input_fn
893 , SysTools.FileOption "" output_fn
894 ]
895 )
896
897 -- re-read pragmas now that we've parsed the file (see #3674)
898 src_opts <- liftIO $ getOptionsFromFile dflags output_fn
899 (dflags1, unhandled_flags, warns)
900 <- liftIO $ parseDynamicFilePragma dflags src_opts
901 setDynFlags dflags1
902 liftIO $ checkProcessArgsResult dflags1 unhandled_flags
903 liftIO $ handleFlagWarnings dflags1 warns
904
905 return (RealPhase (Hsc sf), output_fn)
906
907 -----------------------------------------------------------------------------
908 -- Hsc phase
909
910 -- Compilation of a single module, in "legacy" mode (_not_ under
911 -- the direction of the compilation manager).
912 runPhase (RealPhase (Hsc src_flavour)) input_fn dflags0
913 = do -- normal Hsc mode, not mkdependHS
914
915 PipeEnv{ stop_phase=stop,
916 src_basename=basename,
917 src_suffix=suff } <- getPipeEnv
918
919 -- we add the current directory (i.e. the directory in which
920 -- the .hs files resides) to the include path, since this is
921 -- what gcc does, and it's probably what you want.
922 let current_dir = takeDirectory basename
923 paths = includePaths dflags0
924 dflags = dflags0 { includePaths = current_dir : paths }
925
926 setDynFlags dflags
927
928 -- gather the imports and module name
929 (hspp_buf,mod_name,imps,src_imps) <- liftIO $ do
930 do
931 buf <- hGetStringBuffer input_fn
932 (src_imps,imps,L _ mod_name) <- getImports dflags buf input_fn (basename <.> suff)
933 return (Just buf, mod_name, imps, src_imps)
934
935 -- Take -o into account if present
936 -- Very like -ohi, but we must *only* do this if we aren't linking
937 -- (If we're linking then the -o applies to the linked thing, not to
938 -- the object file for one module.)
939 -- Note the nasty duplication with the same computation in compileFile above
940 location <- getLocation src_flavour mod_name
941
942 let o_file = ml_obj_file location -- The real object file
943 hi_file = ml_hi_file location
944 dest_file | writeInterfaceOnlyMode dflags
945 = hi_file
946 | otherwise
947 = o_file
948
949 -- Figure out if the source has changed, for recompilation avoidance.
950 --
951 -- Setting source_unchanged to True means that M.o seems
952 -- to be up to date wrt M.hs; so no need to recompile unless imports have
953 -- changed (which the compiler itself figures out).
954 -- Setting source_unchanged to False tells the compiler that M.o is out of
955 -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
956 src_timestamp <- liftIO $ getModificationUTCTime (basename <.> suff)
957
958 source_unchanged <- liftIO $
959 if not (isStopLn stop)
960 -- SourceModified unconditionally if
961 -- (a) recompilation checker is off, or
962 -- (b) we aren't going all the way to .o file (e.g. ghc -S)
963 then return SourceModified
964 -- Otherwise look at file modification dates
965 else do dest_file_exists <- doesFileExist dest_file
966 if not dest_file_exists
967 then return SourceModified -- Need to recompile
968 else do t2 <- getModificationUTCTime dest_file
969 if t2 > src_timestamp
970 then return SourceUnmodified
971 else return SourceModified
972
973 PipeState{hsc_env=hsc_env'} <- getPipeState
974
975 -- Tell the finder cache about this module
976 mod <- liftIO $ addHomeModuleToFinder hsc_env' mod_name location
977
978 -- Make the ModSummary to hand to hscMain
979 let
980 mod_summary = ModSummary { ms_mod = mod,
981 ms_hsc_src = src_flavour,
982 ms_hspp_file = input_fn,
983 ms_hspp_opts = dflags,
984 ms_hspp_buf = hspp_buf,
985 ms_location = location,
986 ms_hs_date = src_timestamp,
987 ms_obj_date = Nothing,
988 ms_iface_date = Nothing,
989 ms_textual_imps = imps,
990 ms_srcimps = src_imps }
991
992 -- run the compiler!
993 let msg hsc_env _ what _ = oneShotMsg hsc_env what
994 (result, _) <- liftIO $ hscIncrementalCompile True Nothing (Just msg) hsc_env'
995 mod_summary source_unchanged Nothing (1,1)
996
997 return (HscOut src_flavour mod_name result,
998 panic "HscOut doesn't have an input filename")
999
1000 runPhase (HscOut src_flavour mod_name result) _ dflags = do
1001 location <- getLocation src_flavour mod_name
1002 setModLocation location
1003
1004 let o_file = ml_obj_file location -- The real object file
1005 hsc_lang = hscTarget dflags
1006 next_phase = hscPostBackendPhase dflags src_flavour hsc_lang
1007
1008 case result of
1009 HscNotGeneratingCode ->
1010 return (RealPhase StopLn,
1011 panic "No output filename from Hsc when no-code")
1012 HscUpToDate ->
1013 do liftIO $ touchObjectFile dflags o_file
1014 -- The .o file must have a later modification date
1015 -- than the source file (else we wouldn't get Nothing)
1016 -- but we touch it anyway, to keep 'make' happy (we think).
1017 return (RealPhase StopLn, o_file)
1018 HscUpdateBoot ->
1019 do -- In the case of hs-boot files, generate a dummy .o-boot
1020 -- stamp file for the benefit of Make
1021 liftIO $ touchObjectFile dflags o_file
1022 return (RealPhase StopLn, o_file)
1023 HscUpdateSig ->
1024 do -- We need to create a REAL but empty .o file
1025 -- because we are going to attempt to put it in a library
1026 PipeState{hsc_env=hsc_env'} <- getPipeState
1027 let input_fn = expectJust "runPhase" (ml_hs_file location)
1028 basename = dropExtension input_fn
1029 liftIO $ compileEmptyStub dflags hsc_env' basename location
1030 return (RealPhase StopLn, o_file)
1031 HscRecomp cgguts mod_summary
1032 -> do output_fn <- phaseOutputFilename next_phase
1033
1034 PipeState{hsc_env=hsc_env'} <- getPipeState
1035
1036 (outputFilename, mStub) <- liftIO $ hscGenHardCode hsc_env' cgguts mod_summary output_fn
1037 case mStub of
1038 Nothing -> return ()
1039 Just stub_c ->
1040 do stub_o <- liftIO $ compileStub hsc_env' stub_c
1041 setStubO stub_o
1042
1043 return (RealPhase next_phase, outputFilename)
1044
1045 -----------------------------------------------------------------------------
1046 -- Cmm phase
1047
1048 runPhase (RealPhase CmmCpp) input_fn dflags
1049 = do
1050 output_fn <- phaseOutputFilename Cmm
1051 liftIO $ doCpp dflags False{-not raw-}
1052 input_fn output_fn
1053 return (RealPhase Cmm, output_fn)
1054
1055 runPhase (RealPhase Cmm) input_fn dflags
1056 = do
1057 let hsc_lang = hscTarget dflags
1058
1059 let next_phase = hscPostBackendPhase dflags HsSrcFile hsc_lang
1060
1061 output_fn <- phaseOutputFilename next_phase
1062
1063 PipeState{hsc_env} <- getPipeState
1064
1065 liftIO $ hscCompileCmmFile hsc_env input_fn output_fn
1066
1067 return (RealPhase next_phase, output_fn)
1068
1069 -----------------------------------------------------------------------------
1070 -- Cc phase
1071
1072 -- we don't support preprocessing .c files (with -E) now. Doing so introduces
1073 -- way too many hacks, and I can't say I've ever used it anyway.
1074
1075 runPhase (RealPhase cc_phase) input_fn dflags
1076 | any (cc_phase `eqPhase`) [Cc, Ccxx, HCc, Cobjc, Cobjcxx]
1077 = do
1078 let platform = targetPlatform dflags
1079 hcc = cc_phase `eqPhase` HCc
1080
1081 let cmdline_include_paths = includePaths dflags
1082
1083 -- HC files have the dependent packages stamped into them
1084 pkgs <- if hcc then liftIO $ getHCFilePackages input_fn else return []
1085
1086 -- add package include paths even if we're just compiling .c
1087 -- files; this is the Value Add(TM) that using ghc instead of
1088 -- gcc gives you :)
1089 pkg_include_dirs <- liftIO $ getPackageIncludePath dflags pkgs
1090 let include_paths = foldr (\ x xs -> ("-I" ++ x) : xs) []
1091 (cmdline_include_paths ++ pkg_include_dirs)
1092
1093 let gcc_extra_viac_flags = extraGccViaCFlags dflags
1094 let pic_c_flags = picCCOpts dflags
1095
1096 let verbFlags = getVerbFlags dflags
1097
1098 -- cc-options are not passed when compiling .hc files. Our
1099 -- hc code doesn't not #include any header files anyway, so these
1100 -- options aren't necessary.
1101 pkg_extra_cc_opts <- liftIO $
1102 if cc_phase `eqPhase` HCc
1103 then return []
1104 else getPackageExtraCcOpts dflags pkgs
1105
1106 framework_paths <-
1107 if platformUsesFrameworks platform
1108 then do pkgFrameworkPaths <- liftIO $ getPackageFrameworkPath dflags pkgs
1109 let cmdlineFrameworkPaths = frameworkPaths dflags
1110 return $ map ("-F"++)
1111 (cmdlineFrameworkPaths ++ pkgFrameworkPaths)
1112 else return []
1113
1114 let split_objs = gopt Opt_SplitObjs dflags
1115 split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
1116 | otherwise = [ ]
1117
1118 let cc_opt | optLevel dflags >= 2 = [ "-O2" ]
1119 | optLevel dflags >= 1 = [ "-O" ]
1120 | otherwise = []
1121
1122 -- Decide next phase
1123 let next_phase = As False
1124 output_fn <- phaseOutputFilename next_phase
1125
1126 let
1127 more_hcc_opts =
1128 -- on x86 the floating point regs have greater precision
1129 -- than a double, which leads to unpredictable results.
1130 -- By default, we turn this off with -ffloat-store unless
1131 -- the user specified -fexcess-precision.
1132 (if platformArch platform == ArchX86 &&
1133 not (gopt Opt_ExcessPrecision dflags)
1134 then [ "-ffloat-store" ]
1135 else []) ++
1136
1137 -- gcc's -fstrict-aliasing allows two accesses to memory
1138 -- to be considered non-aliasing if they have different types.
1139 -- This interacts badly with the C code we generate, which is
1140 -- very weakly typed, being derived from C--.
1141 ["-fno-strict-aliasing"]
1142
1143 ghcVersionH <- liftIO $ getGhcVersionPathName dflags
1144
1145 let gcc_lang_opt | cc_phase `eqPhase` Ccxx = "c++"
1146 | cc_phase `eqPhase` Cobjc = "objective-c"
1147 | cc_phase `eqPhase` Cobjcxx = "objective-c++"
1148 | otherwise = "c"
1149 liftIO $ SysTools.runCc dflags (
1150 -- force the C compiler to interpret this file as C when
1151 -- compiling .hc files, by adding the -x c option.
1152 -- Also useful for plain .c files, just in case GHC saw a
1153 -- -x c option.
1154 [ SysTools.Option "-x", SysTools.Option gcc_lang_opt
1155 , SysTools.FileOption "" input_fn
1156 , SysTools.Option "-o"
1157 , SysTools.FileOption "" output_fn
1158 ]
1159 ++ map SysTools.Option (
1160 pic_c_flags
1161
1162 -- Stub files generated for foreign exports references the runIO_closure
1163 -- and runNonIO_closure symbols, which are defined in the base package.
1164 -- These symbols are imported into the stub.c file via RtsAPI.h, and the
1165 -- way we do the import depends on whether we're currently compiling
1166 -- the base package or not.
1167 ++ (if platformOS platform == OSMinGW32 &&
1168 thisPackage dflags == baseUnitId
1169 then [ "-DCOMPILING_BASE_PACKAGE" ]
1170 else [])
1171
1172 -- We only support SparcV9 and better because V8 lacks an atomic CAS
1173 -- instruction. Note that the user can still override this
1174 -- (e.g., -mcpu=ultrasparc) as GCC picks the "best" -mcpu flag
1175 -- regardless of the ordering.
1176 --
1177 -- This is a temporary hack. See #2872, commit
1178 -- 5bd3072ac30216a505151601884ac88bf404c9f2
1179 ++ (if platformArch platform == ArchSPARC
1180 then ["-mcpu=v9"]
1181 else [])
1182
1183 -- GCC 4.6+ doesn't like -Wimplicit when compiling C++.
1184 ++ (if (cc_phase /= Ccxx && cc_phase /= Cobjcxx)
1185 then ["-Wimplicit"]
1186 else [])
1187
1188 ++ (if hcc
1189 then gcc_extra_viac_flags ++ more_hcc_opts
1190 else [])
1191 ++ verbFlags
1192 ++ [ "-S" ]
1193 ++ cc_opt
1194 ++ [ "-include", ghcVersionH ]
1195 ++ framework_paths
1196 ++ split_opt
1197 ++ include_paths
1198 ++ pkg_extra_cc_opts
1199 ))
1200
1201 return (RealPhase next_phase, output_fn)
1202
1203 -----------------------------------------------------------------------------
1204 -- Splitting phase
1205
1206 runPhase (RealPhase Splitter) input_fn dflags
1207 = do -- tmp_pfx is the prefix used for the split .s files
1208
1209 split_s_prefix <- liftIO $ SysTools.newTempName dflags "split"
1210 let n_files_fn = split_s_prefix
1211
1212 liftIO $ SysTools.runSplit dflags
1213 [ SysTools.FileOption "" input_fn
1214 , SysTools.FileOption "" split_s_prefix
1215 , SysTools.FileOption "" n_files_fn
1216 ]
1217
1218 -- Save the number of split files for future references
1219 s <- liftIO $ readFile n_files_fn
1220 let n_files = read s :: Int
1221 dflags' = dflags { splitInfo = Just (split_s_prefix, n_files) }
1222
1223 setDynFlags dflags'
1224
1225 -- Remember to delete all these files
1226 liftIO $ addFilesToClean dflags'
1227 [ split_s_prefix ++ "__" ++ show n ++ ".s"
1228 | n <- [1..n_files]]
1229
1230 return (RealPhase SplitAs,
1231 "**splitter**") -- we don't use the filename in SplitAs
1232
1233 -----------------------------------------------------------------------------
1234 -- As, SpitAs phase : Assembler
1235
1236 -- This is for calling the assembler on a regular assembly file (not split).
1237 runPhase (RealPhase (As with_cpp)) input_fn dflags
1238 = do
1239 -- LLVM from version 3.0 onwards doesn't support the OS X system
1240 -- assembler, so we use clang as the assembler instead. (#5636)
1241 let whichAsProg | hscTarget dflags == HscLlvm &&
1242 platformOS (targetPlatform dflags) == OSDarwin
1243 = return SysTools.runClang
1244 | otherwise = return SysTools.runAs
1245
1246 as_prog <- whichAsProg
1247 let cmdline_include_paths = includePaths dflags
1248 let pic_c_flags = picCCOpts dflags
1249
1250 next_phase <- maybeMergeStub
1251 output_fn <- phaseOutputFilename next_phase
1252
1253 -- we create directories for the object file, because it
1254 -- might be a hierarchical module.
1255 liftIO $ createDirectoryIfMissing True (takeDirectory output_fn)
1256
1257 ccInfo <- liftIO $ getCompilerInfo dflags
1258 let runAssembler inputFilename outputFilename
1259 = liftIO $ as_prog dflags
1260 ([ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ]
1261
1262 -- See Note [-fPIC for assembler]
1263 ++ map SysTools.Option pic_c_flags
1264
1265 -- We only support SparcV9 and better because V8 lacks an atomic CAS
1266 -- instruction so we have to make sure that the assembler accepts the
1267 -- instruction set. Note that the user can still override this
1268 -- (e.g., -mcpu=ultrasparc). GCC picks the "best" -mcpu flag
1269 -- regardless of the ordering.
1270 --
1271 -- This is a temporary hack.
1272 ++ (if platformArch (targetPlatform dflags) == ArchSPARC
1273 then [SysTools.Option "-mcpu=v9"]
1274 else [])
1275 ++ (if any (ccInfo ==) [Clang, AppleClang, AppleClang51]
1276 then [SysTools.Option "-Qunused-arguments"]
1277 else [])
1278 ++ [ SysTools.Option "-x"
1279 , if with_cpp
1280 then SysTools.Option "assembler-with-cpp"
1281 else SysTools.Option "assembler"
1282 , SysTools.Option "-c"
1283 , SysTools.FileOption "" inputFilename
1284 , SysTools.Option "-o"
1285 , SysTools.FileOption "" outputFilename
1286 ])
1287
1288 liftIO $ debugTraceMsg dflags 4 (text "Running the assembler")
1289 runAssembler input_fn output_fn
1290 return (RealPhase next_phase, output_fn)
1291
1292
1293 -- This is for calling the assembler on a split assembly file (so a collection
1294 -- of assembly files)
1295 runPhase (RealPhase SplitAs) _input_fn dflags
1296 = do
1297 -- we'll handle the stub_o file in this phase, so don't MergeStub,
1298 -- just jump straight to StopLn afterwards.
1299 let next_phase = StopLn
1300 output_fn <- phaseOutputFilename next_phase
1301
1302 let base_o = dropExtension output_fn
1303 osuf = objectSuf dflags
1304 split_odir = base_o ++ "_" ++ osuf ++ "_split"
1305
1306 let pic_c_flags = picCCOpts dflags
1307
1308 -- this also creates the hierarchy
1309 liftIO $ createDirectoryIfMissing True split_odir
1310
1311 -- remove M_split/ *.o, because we're going to archive M_split/ *.o
1312 -- later and we don't want to pick up any old objects.
1313 fs <- liftIO $ getDirectoryContents split_odir
1314 liftIO $ mapM_ removeFile $
1315 map (split_odir </>) $ filter (osuf `isSuffixOf`) fs
1316
1317 let (split_s_prefix, n) = case splitInfo dflags of
1318 Nothing -> panic "No split info"
1319 Just x -> x
1320
1321 let split_s n = split_s_prefix ++ "__" ++ show n <.> "s"
1322
1323 split_obj :: Int -> FilePath
1324 split_obj n = split_odir </>
1325 takeFileName base_o ++ "__" ++ show n <.> osuf
1326
1327 let assemble_file n
1328 = SysTools.runAs dflags (
1329
1330 -- We only support SparcV9 and better because V8 lacks an atomic CAS
1331 -- instruction so we have to make sure that the assembler accepts the
1332 -- instruction set. Note that the user can still override this
1333 -- (e.g., -mcpu=ultrasparc). GCC picks the "best" -mcpu flag
1334 -- regardless of the ordering.
1335 --
1336 -- This is a temporary hack.
1337 (if platformArch (targetPlatform dflags) == ArchSPARC
1338 then [SysTools.Option "-mcpu=v9"]
1339 else []) ++
1340
1341 -- See Note [-fPIC for assembler]
1342 map SysTools.Option pic_c_flags ++
1343
1344 [ SysTools.Option "-c"
1345 , SysTools.Option "-o"
1346 , SysTools.FileOption "" (split_obj n)
1347 , SysTools.FileOption "" (split_s n)
1348 ])
1349
1350 liftIO $ mapM_ assemble_file [1..n]
1351
1352 -- Note [pipeline-split-init]
1353 -- If we have a stub file, it may contain constructor
1354 -- functions for initialisation of this module. We can't
1355 -- simply leave the stub as a separate object file, because it
1356 -- will never be linked in: nothing refers to it. We need to
1357 -- ensure that if we ever refer to the data in this module
1358 -- that needs initialisation, then we also pull in the
1359 -- initialisation routine.
1360 --
1361 -- To that end, we make a DANGEROUS ASSUMPTION here: the data
1362 -- that needs to be initialised is all in the FIRST split
1363 -- object. See Note [codegen-split-init].
1364
1365 PipeState{maybe_stub_o} <- getPipeState
1366 case maybe_stub_o of
1367 Nothing -> return ()
1368 Just stub_o -> liftIO $ do
1369 tmp_split_1 <- newTempName dflags osuf
1370 let split_1 = split_obj 1
1371 copyFile split_1 tmp_split_1
1372 removeFile split_1
1373 joinObjectFiles dflags [tmp_split_1, stub_o] split_1
1374
1375 -- join them into a single .o file
1376 liftIO $ joinObjectFiles dflags (map split_obj [1..n]) output_fn
1377
1378 return (RealPhase next_phase, output_fn)
1379
1380 -----------------------------------------------------------------------------
1381 -- LlvmOpt phase
1382
1383 runPhase (RealPhase LlvmOpt) input_fn dflags
1384 = do
1385 let opt_lvl = max 0 (min 2 $ optLevel dflags)
1386 -- don't specify anything if user has specified commands. We do this
1387 -- for opt but not llc since opt is very specifically for optimisation
1388 -- passes only, so if the user is passing us extra options we assume
1389 -- they know what they are doing and don't get in the way.
1390 optFlag = if null (getOpts dflags opt_lo)
1391 then map SysTools.Option $ words (llvmOpts !! opt_lvl)
1392 else []
1393 tbaa | gopt Opt_LlvmTBAA dflags = "--enable-tbaa=true"
1394 | otherwise = "--enable-tbaa=false"
1395
1396
1397 output_fn <- phaseOutputFilename LlvmLlc
1398
1399 liftIO $ SysTools.runLlvmOpt dflags
1400 ([ SysTools.FileOption "" input_fn,
1401 SysTools.Option "-o",
1402 SysTools.FileOption "" output_fn]
1403 ++ optFlag
1404 ++ [SysTools.Option tbaa])
1405
1406 return (RealPhase LlvmLlc, output_fn)
1407 where
1408 -- we always (unless -optlo specified) run Opt since we rely on it to
1409 -- fix up some pretty big deficiencies in the code we generate
1410 llvmOpts = [ "-mem2reg -globalopt"
1411 , "-O1 -globalopt"
1412 , "-O2"
1413 ]
1414
1415 -----------------------------------------------------------------------------
1416 -- LlvmLlc phase
1417
1418 runPhase (RealPhase LlvmLlc) input_fn dflags
1419 = do
1420 let opt_lvl = max 0 (min 2 $ optLevel dflags)
1421 -- iOS requires external references to be loaded indirectly from the
1422 -- DATA segment or dyld traps at runtime writing into TEXT: see #7722
1423 rmodel | platformOS (targetPlatform dflags) == OSiOS = "dynamic-no-pic"
1424 | gopt Opt_PIC dflags = "pic"
1425 | WayDyn `elem` ways dflags = "dynamic-no-pic"
1426 | otherwise = "static"
1427 tbaa | gopt Opt_LlvmTBAA dflags = "--enable-tbaa=true"
1428 | otherwise = "--enable-tbaa=false"
1429
1430 -- hidden debugging flag '-dno-llvm-mangler' to skip mangling
1431 let next_phase = case gopt Opt_NoLlvmMangler dflags of
1432 False -> LlvmMangle
1433 True | gopt Opt_SplitObjs dflags -> Splitter
1434 True -> As False
1435
1436 output_fn <- phaseOutputFilename next_phase
1437
1438 liftIO $ SysTools.runLlvmLlc dflags
1439 ([ SysTools.Option (llvmOpts !! opt_lvl),
1440 SysTools.Option $ "-relocation-model=" ++ rmodel,
1441 SysTools.FileOption "" input_fn,
1442 SysTools.Option "-o", SysTools.FileOption "" output_fn]
1443 ++ [SysTools.Option tbaa]
1444 ++ map SysTools.Option fpOpts
1445 ++ map SysTools.Option abiOpts
1446 ++ map SysTools.Option sseOpts
1447 ++ map SysTools.Option avxOpts
1448 ++ map SysTools.Option avx512Opts
1449 ++ map SysTools.Option stackAlignOpts)
1450
1451 return (RealPhase next_phase, output_fn)
1452 where
1453 -- Bug in LLVM at O3 on OSX.
1454 llvmOpts = if platformOS (targetPlatform dflags) == OSDarwin
1455 then ["-O1", "-O2", "-O2"]
1456 else ["-O1", "-O2", "-O3"]
1457 -- On ARMv7 using LLVM, LLVM fails to allocate floating point registers
1458 -- while compiling GHC source code. It's probably due to fact that it
1459 -- does not enable VFP by default. Let's do this manually here
1460 fpOpts = case platformArch (targetPlatform dflags) of
1461 ArchARM ARMv7 ext _ -> if (elem VFPv3 ext)
1462 then ["-mattr=+v7,+vfp3"]
1463 else if (elem VFPv3D16 ext)
1464 then ["-mattr=+v7,+vfp3,+d16"]
1465 else []
1466 ArchARM ARMv6 ext _ -> if (elem VFPv2 ext)
1467 then ["-mattr=+v6,+vfp2"]
1468 else ["-mattr=+v6"]
1469 _ -> []
1470 -- On Ubuntu/Debian with ARM hard float ABI, LLVM's llc still
1471 -- compiles into soft-float ABI. We need to explicitly set abi
1472 -- to hard
1473 abiOpts = case platformArch (targetPlatform dflags) of
1474 ArchARM _ _ HARD -> ["-float-abi=hard"]
1475 ArchARM _ _ _ -> []
1476 _ -> []
1477
1478 sseOpts | isSse4_2Enabled dflags = ["-mattr=+sse42"]
1479 | isSse2Enabled dflags = ["-mattr=+sse2"]
1480 | isSseEnabled dflags = ["-mattr=+sse"]
1481 | otherwise = []
1482
1483 avxOpts | isAvx512fEnabled dflags = ["-mattr=+avx512f"]
1484 | isAvx2Enabled dflags = ["-mattr=+avx2"]
1485 | isAvxEnabled dflags = ["-mattr=+avx"]
1486 | otherwise = []
1487
1488 avx512Opts =
1489 [ "-mattr=+avx512cd" | isAvx512cdEnabled dflags ] ++
1490 [ "-mattr=+avx512er" | isAvx512erEnabled dflags ] ++
1491 [ "-mattr=+avx512pf" | isAvx512pfEnabled dflags ]
1492
1493 stackAlignOpts =
1494 case platformArch (targetPlatform dflags) of
1495 ArchX86_64 | isAvxEnabled dflags -> ["-stack-alignment=32"]
1496 _ -> []
1497
1498 -----------------------------------------------------------------------------
1499 -- LlvmMangle phase
1500
1501 runPhase (RealPhase LlvmMangle) input_fn dflags
1502 = do
1503 let next_phase = if gopt Opt_SplitObjs dflags then Splitter else As False
1504 output_fn <- phaseOutputFilename next_phase
1505 liftIO $ llvmFixupAsm dflags input_fn output_fn
1506 return (RealPhase next_phase, output_fn)
1507
1508 -----------------------------------------------------------------------------
1509 -- merge in stub objects
1510
1511 runPhase (RealPhase MergeStub) input_fn dflags
1512 = do
1513 PipeState{maybe_stub_o} <- getPipeState
1514 output_fn <- phaseOutputFilename StopLn
1515 liftIO $ createDirectoryIfMissing True (takeDirectory output_fn)
1516 case maybe_stub_o of
1517 Nothing ->
1518 panic "runPhase(MergeStub): no stub"
1519 Just stub_o -> do
1520 liftIO $ joinObjectFiles dflags [input_fn, stub_o] output_fn
1521 return (RealPhase StopLn, output_fn)
1522
1523 -- warning suppression
1524 runPhase (RealPhase other) _input_fn _dflags =
1525 panic ("runPhase: don't know how to run phase " ++ show other)
1526
1527 maybeMergeStub :: CompPipeline Phase
1528 maybeMergeStub
1529 = do
1530 PipeState{maybe_stub_o} <- getPipeState
1531 if isJust maybe_stub_o then return MergeStub else return StopLn
1532
1533 getLocation :: HscSource -> ModuleName -> CompPipeline ModLocation
1534 getLocation src_flavour mod_name = do
1535 dflags <- getDynFlags
1536
1537 PipeEnv{ src_basename=basename,
1538 src_suffix=suff } <- getPipeEnv
1539
1540 -- Build a ModLocation to pass to hscMain.
1541 -- The source filename is rather irrelevant by now, but it's used
1542 -- by hscMain for messages. hscMain also needs
1543 -- the .hi and .o filenames, and this is as good a way
1544 -- as any to generate them, and better than most. (e.g. takes
1545 -- into account the -osuf flags)
1546 location1 <- liftIO $ mkHomeModLocation2 dflags mod_name basename suff
1547
1548 -- Boot-ify it if necessary
1549 let location2 | HsBootFile <- src_flavour = addBootSuffixLocn location1
1550 | otherwise = location1
1551
1552
1553 -- Take -ohi into account if present
1554 -- This can't be done in mkHomeModuleLocation because
1555 -- it only applies to the module being compiles
1556 let ohi = outputHi dflags
1557 location3 | Just fn <- ohi = location2{ ml_hi_file = fn }
1558 | otherwise = location2
1559
1560 -- Take -o into account if present
1561 -- Very like -ohi, but we must *only* do this if we aren't linking
1562 -- (If we're linking then the -o applies to the linked thing, not to
1563 -- the object file for one module.)
1564 -- Note the nasty duplication with the same computation in compileFile above
1565 let expl_o_file = outputFile dflags
1566 location4 | Just ofile <- expl_o_file
1567 , isNoLink (ghcLink dflags)
1568 = location3 { ml_obj_file = ofile }
1569 | otherwise = location3
1570
1571 return location4
1572
1573 mkExtraObj :: DynFlags -> Suffix -> String -> IO FilePath
1574 mkExtraObj dflags extn xs
1575 = do cFile <- newTempName dflags extn
1576 oFile <- newTempName dflags "o"
1577 writeFile cFile xs
1578 let rtsDetails = getPackageDetails dflags rtsUnitId
1579 pic_c_flags = picCCOpts dflags
1580 SysTools.runCc dflags
1581 ([Option "-c",
1582 FileOption "" cFile,
1583 Option "-o",
1584 FileOption "" oFile]
1585 ++ map (FileOption "-I") (includeDirs rtsDetails)
1586 ++ map Option pic_c_flags)
1587 return oFile
1588
1589 -- When linking a binary, we need to create a C main() function that
1590 -- starts everything off. This used to be compiled statically as part
1591 -- of the RTS, but that made it hard to change the -rtsopts setting,
1592 -- so now we generate and compile a main() stub as part of every
1593 -- binary and pass the -rtsopts setting directly to the RTS (#5373)
1594 --
1595 mkExtraObjToLinkIntoBinary :: DynFlags -> IO FilePath
1596 mkExtraObjToLinkIntoBinary dflags = do
1597 when (gopt Opt_NoHsMain dflags && haveRtsOptsFlags dflags) $ do
1598 log_action dflags dflags SevInfo noSrcSpan defaultUserStyle
1599 (text "Warning: -rtsopts and -with-rtsopts have no effect with -no-hs-main." $$
1600 text " Call hs_init_ghc() from your main() function to set these options.")
1601
1602 mkExtraObj dflags "c" (showSDoc dflags main)
1603
1604 where
1605 main
1606 | gopt Opt_NoHsMain dflags = Outputable.empty
1607 | otherwise = vcat [
1608 text "#include \"Rts.h\"",
1609 text "extern StgClosure ZCMain_main_closure;",
1610 text "int main(int argc, char *argv[])",
1611 char '{',
1612 text " RtsConfig __conf = defaultRtsConfig;",
1613 text " __conf.rts_opts_enabled = "
1614 <> text (show (rtsOptsEnabled dflags)) <> semi,
1615 text " __conf.rts_opts_suggestions = "
1616 <> text (if rtsOptsSuggestions dflags
1617 then "rtsTrue"
1618 else "rtsFalse") <> semi,
1619 case rtsOpts dflags of
1620 Nothing -> Outputable.empty
1621 Just opts -> ptext (sLit " __conf.rts_opts= ") <>
1622 text (show opts) <> semi,
1623 text " __conf.rts_hs_main = rtsTrue;",
1624 text " return hs_main(argc,argv,&ZCMain_main_closure,__conf);",
1625 char '}',
1626 char '\n' -- final newline, to keep gcc happy
1627 ]
1628
1629 -- Write out the link info section into a new assembly file. Previously
1630 -- this was included as inline assembly in the main.c file but this
1631 -- is pretty fragile. gas gets upset trying to calculate relative offsets
1632 -- that span the .note section (notably .text) when debug info is present
1633 mkNoteObjsToLinkIntoBinary :: DynFlags -> [UnitId] -> IO [FilePath]
1634 mkNoteObjsToLinkIntoBinary dflags dep_packages = do
1635 link_info <- getLinkInfo dflags dep_packages
1636
1637 if (platformSupportsSavingLinkOpts (platformOS (targetPlatform dflags)))
1638 then fmap (:[]) $ mkExtraObj dflags "s" (showSDoc dflags (link_opts link_info))
1639 else return []
1640
1641 where
1642 link_opts info = hcat [
1643 -- "link info" section (see Note [LinkInfo section])
1644 makeElfNote dflags ghcLinkInfoSectionName ghcLinkInfoNoteName 0 info,
1645
1646 -- ALL generated assembly must have this section to disable
1647 -- executable stacks. See also
1648 -- compiler/nativeGen/AsmCodeGen.hs for another instance
1649 -- where we need to do this.
1650 if platformHasGnuNonexecStack (targetPlatform dflags)
1651 then text ".section .note.GNU-stack,\"\",@progbits\n"
1652 else Outputable.empty
1653 ]
1654
1655 -- | Return the "link info" string
1656 --
1657 -- See Note [LinkInfo section]
1658 getLinkInfo :: DynFlags -> [UnitId] -> IO String
1659 getLinkInfo dflags dep_packages = do
1660 package_link_opts <- getPackageLinkOpts dflags dep_packages
1661 pkg_frameworks <- if platformUsesFrameworks (targetPlatform dflags)
1662 then getPackageFrameworks dflags dep_packages
1663 else return []
1664 let extra_ld_inputs = ldInputs dflags
1665 let
1666 link_info = (package_link_opts,
1667 pkg_frameworks,
1668 rtsOpts dflags,
1669 rtsOptsEnabled dflags,
1670 gopt Opt_NoHsMain dflags,
1671 map showOpt extra_ld_inputs,
1672 getOpts dflags opt_l)
1673 --
1674 return (show link_info)
1675
1676
1677 {- Note [LinkInfo section]
1678 ~~~~~~~~~~~~~~~~~~~~~~~
1679
1680 The "link info" is a string representing the parameters of the link. We save
1681 this information in the binary, and the next time we link, if nothing else has
1682 changed, we use the link info stored in the existing binary to decide whether
1683 to re-link or not.
1684
1685 The "link info" string is stored in a ELF section called ".debug-ghc-link-info"
1686 (see ghcLinkInfoSectionName) with the SHT_NOTE type. For some time, it used to
1687 not follow the specified record-based format (see #11022).
1688
1689 -}
1690
1691
1692 -----------------------------------------------------------------------------
1693 -- Look for the /* GHC_PACKAGES ... */ comment at the top of a .hc file
1694
1695 getHCFilePackages :: FilePath -> IO [UnitId]
1696 getHCFilePackages filename =
1697 Exception.bracket (openFile filename ReadMode) hClose $ \h -> do
1698 l <- hGetLine h
1699 case l of
1700 '/':'*':' ':'G':'H':'C':'_':'P':'A':'C':'K':'A':'G':'E':'S':rest ->
1701 return (map stringToUnitId (words rest))
1702 _other ->
1703 return []
1704
1705 -----------------------------------------------------------------------------
1706 -- Static linking, of .o files
1707
1708 -- The list of packages passed to link is the list of packages on
1709 -- which this program depends, as discovered by the compilation
1710 -- manager. It is combined with the list of packages that the user
1711 -- specifies on the command line with -package flags.
1712 --
1713 -- In one-shot linking mode, we can't discover the package
1714 -- dependencies (because we haven't actually done any compilation or
1715 -- read any interface files), so the user must explicitly specify all
1716 -- the packages.
1717
1718 linkBinary :: DynFlags -> [FilePath] -> [UnitId] -> IO ()
1719 linkBinary = linkBinary' False
1720
1721 linkBinary' :: Bool -> DynFlags -> [FilePath] -> [UnitId] -> IO ()
1722 linkBinary' staticLink dflags o_files dep_packages = do
1723 let platform = targetPlatform dflags
1724 mySettings = settings dflags
1725 verbFlags = getVerbFlags dflags
1726 output_fn = exeFileName staticLink dflags
1727
1728 -- get the full list of packages to link with, by combining the
1729 -- explicit packages with the auto packages and all of their
1730 -- dependencies, and eliminating duplicates.
1731
1732 full_output_fn <- if isAbsolute output_fn
1733 then return output_fn
1734 else do d <- getCurrentDirectory
1735 return $ normalise (d </> output_fn)
1736 pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1737 let pkg_lib_path_opts = concatMap get_pkg_lib_path_opts pkg_lib_paths
1738 get_pkg_lib_path_opts l
1739 | osElfTarget (platformOS platform) &&
1740 dynLibLoader dflags == SystemDependent &&
1741 WayDyn `elem` ways dflags
1742 = let libpath = if gopt Opt_RelativeDynlibPaths dflags
1743 then "$ORIGIN" </>
1744 (l `makeRelativeTo` full_output_fn)
1745 else l
1746 rpath = if gopt Opt_RPath dflags
1747 then ["-Wl,-rpath", "-Wl," ++ libpath]
1748 else []
1749 -- Solaris 11's linker does not support -rpath-link option. It silently
1750 -- ignores it and then complains about next option which is -l<some
1751 -- dir> as being a directory and not expected object file, E.g
1752 -- ld: elf error: file
1753 -- /tmp/ghc-src/libraries/base/dist-install/build:
1754 -- elf_begin: I/O error: region read: Is a directory
1755 rpathlink = if (platformOS platform) == OSSolaris2
1756 then []
1757 else ["-Wl,-rpath-link", "-Wl," ++ l]
1758 in ["-L" ++ l] ++ rpathlink ++ rpath
1759 | osMachOTarget (platformOS platform) &&
1760 dynLibLoader dflags == SystemDependent &&
1761 WayDyn `elem` ways dflags &&
1762 gopt Opt_RPath dflags
1763 = let libpath = if gopt Opt_RelativeDynlibPaths dflags
1764 then "@loader_path" </>
1765 (l `makeRelativeTo` full_output_fn)
1766 else l
1767 in ["-L" ++ l] ++ ["-Wl,-rpath", "-Wl," ++ libpath]
1768 | otherwise = ["-L" ++ l]
1769
1770 let lib_paths = libraryPaths dflags
1771 let lib_path_opts = map ("-L"++) lib_paths
1772
1773 extraLinkObj <- mkExtraObjToLinkIntoBinary dflags
1774 noteLinkObjs <- mkNoteObjsToLinkIntoBinary dflags dep_packages
1775
1776 pkg_link_opts <- do
1777 (package_hs_libs, extra_libs, other_flags) <- getPackageLinkOpts dflags dep_packages
1778 return $ if staticLink
1779 then package_hs_libs -- If building an executable really means making a static
1780 -- library (e.g. iOS), then we only keep the -l options for
1781 -- HS packages, because libtool doesn't accept other options.
1782 -- In the case of iOS these need to be added by hand to the
1783 -- final link in Xcode.
1784 else other_flags ++ package_hs_libs ++ extra_libs -- -Wl,-u,<sym> contained in other_flags
1785 -- needs to be put before -l<package>,
1786 -- otherwise Solaris linker fails linking
1787 -- a binary with unresolved symbols in RTS
1788 -- which are defined in base package
1789 -- the reason for this is a note in ld(1) about
1790 -- '-u' option: "The placement of this option
1791 -- on the command line is significant.
1792 -- This option must be placed before the library
1793 -- that defines the symbol."
1794
1795 -- frameworks
1796 pkg_framework_opts <- getPkgFrameworkOpts dflags platform dep_packages
1797 let framework_opts = getFrameworkOpts dflags platform
1798
1799 -- probably _stub.o files
1800 let extra_ld_inputs = ldInputs dflags
1801
1802 -- Here are some libs that need to be linked at the *end* of
1803 -- the command line, because they contain symbols that are referred to
1804 -- by the RTS. We can't therefore use the ordinary way opts for these.
1805 let
1806 debug_opts | WayDebug `elem` ways dflags = [
1807 #if defined(HAVE_LIBBFD)
1808 "-lbfd", "-liberty"
1809 #endif
1810 ]
1811 | otherwise = []
1812
1813 let thread_opts
1814 | WayThreaded `elem` ways dflags =
1815 let os = platformOS (targetPlatform dflags)
1816 in if os == OSOsf3 then ["-lpthread", "-lexc"]
1817 else if os `elem` [OSMinGW32, OSFreeBSD, OSOpenBSD,
1818 OSNetBSD, OSHaiku, OSQNXNTO, OSiOS, OSDarwin]
1819 then []
1820 else ["-lpthread"]
1821 | otherwise = []
1822
1823 rc_objs <- maybeCreateManifest dflags output_fn
1824
1825 let link = if staticLink
1826 then SysTools.runLibtool
1827 else SysTools.runLink
1828 link dflags (
1829 map SysTools.Option verbFlags
1830 ++ [ SysTools.Option "-o"
1831 , SysTools.FileOption "" output_fn
1832 ]
1833 ++ map SysTools.Option (
1834 []
1835
1836 -- Permit the linker to auto link _symbol to _imp_symbol.
1837 -- This lets us link against DLLs without needing an "import library".
1838 ++ (if platformOS platform == OSMinGW32
1839 then ["-Wl,--enable-auto-import"]
1840 else [])
1841
1842 -- '-no_compact_unwind'
1843 -- C++/Objective-C exceptions cannot use optimised
1844 -- stack unwinding code. The optimised form is the
1845 -- default in Xcode 4 on at least x86_64, and
1846 -- without this flag we're also seeing warnings
1847 -- like
1848 -- ld: warning: could not create compact unwind for .LFB3: non-standard register 5 being saved in prolog
1849 -- on x86.
1850 ++ (if sLdSupportsCompactUnwind mySettings &&
1851 not staticLink &&
1852 (platformOS platform == OSDarwin || platformOS platform == OSiOS) &&
1853 case platformArch platform of
1854 ArchX86 -> True
1855 ArchX86_64 -> True
1856 ArchARM {} -> True
1857 ArchARM64 -> True
1858 _ -> False
1859 then ["-Wl,-no_compact_unwind"]
1860 else [])
1861
1862 -- '-no_pie'
1863 -- iOS uses 'dynamic-no-pic', so we must pass this to ld to suppress a warning; see #7722
1864 ++ (if platformOS platform == OSiOS &&
1865 not staticLink
1866 then ["-Wl,-no_pie"]
1867 else [])
1868
1869 -- '-Wl,-read_only_relocs,suppress'
1870 -- ld gives loads of warnings like:
1871 -- ld: warning: text reloc in _base_GHCziArr_unsafeArray_info to _base_GHCziArr_unsafeArray_closure
1872 -- when linking any program. We're not sure
1873 -- whether this is something we ought to fix, but
1874 -- for now this flags silences them.
1875 ++ (if platformOS platform == OSDarwin &&
1876 platformArch platform == ArchX86 &&
1877 not staticLink
1878 then ["-Wl,-read_only_relocs,suppress"]
1879 else [])
1880
1881 ++ (if sLdIsGnuLd mySettings
1882 then ["-Wl,--gc-sections"]
1883 else [])
1884
1885 ++ o_files
1886 ++ lib_path_opts)
1887 ++ extra_ld_inputs
1888 ++ map SysTools.Option (
1889 rc_objs
1890 ++ framework_opts
1891 ++ pkg_lib_path_opts
1892 ++ extraLinkObj:noteLinkObjs
1893 ++ pkg_link_opts
1894 ++ pkg_framework_opts
1895 ++ debug_opts
1896 ++ thread_opts
1897 ))
1898
1899 exeFileName :: Bool -> DynFlags -> FilePath
1900 exeFileName staticLink dflags
1901 | Just s <- outputFile dflags =
1902 case platformOS (targetPlatform dflags) of
1903 OSMinGW32 -> s <?.> "exe"
1904 _ -> if staticLink
1905 then s <?.> "a"
1906 else s
1907 | otherwise =
1908 if platformOS (targetPlatform dflags) == OSMinGW32
1909 then "main.exe"
1910 else if staticLink
1911 then "liba.a"
1912 else "a.out"
1913 where s <?.> ext | null (takeExtension s) = s <.> ext
1914 | otherwise = s
1915
1916 maybeCreateManifest
1917 :: DynFlags
1918 -> FilePath -- filename of executable
1919 -> IO [FilePath] -- extra objects to embed, maybe
1920 maybeCreateManifest dflags exe_filename
1921 | platformOS (targetPlatform dflags) == OSMinGW32 &&
1922 gopt Opt_GenManifest dflags
1923 = do let manifest_filename = exe_filename <.> "manifest"
1924
1925 writeFile manifest_filename $
1926 "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"++
1927 " <assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">\n"++
1928 " <assemblyIdentity version=\"1.0.0.0\"\n"++
1929 " processorArchitecture=\"X86\"\n"++
1930 " name=\"" ++ dropExtension exe_filename ++ "\"\n"++
1931 " type=\"win32\"/>\n\n"++
1932 " <trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v3\">\n"++
1933 " <security>\n"++
1934 " <requestedPrivileges>\n"++
1935 " <requestedExecutionLevel level=\"asInvoker\" uiAccess=\"false\"/>\n"++
1936 " </requestedPrivileges>\n"++
1937 " </security>\n"++
1938 " </trustInfo>\n"++
1939 "</assembly>\n"
1940
1941 -- Windows will find the manifest file if it is named
1942 -- foo.exe.manifest. However, for extra robustness, and so that
1943 -- we can move the binary around, we can embed the manifest in
1944 -- the binary itself using windres:
1945 if not (gopt Opt_EmbedManifest dflags) then return [] else do
1946
1947 rc_filename <- newTempName dflags "rc"
1948 rc_obj_filename <- newTempName dflags (objectSuf dflags)
1949
1950 writeFile rc_filename $
1951 "1 24 MOVEABLE PURE " ++ show manifest_filename ++ "\n"
1952 -- magic numbers :-)
1953 -- show is a bit hackish above, but we need to escape the
1954 -- backslashes in the path.
1955
1956 runWindres dflags $ map SysTools.Option $
1957 ["--input="++rc_filename,
1958 "--output="++rc_obj_filename,
1959 "--output-format=coff"]
1960 -- no FileOptions here: windres doesn't like seeing
1961 -- backslashes, apparently
1962
1963 removeFile manifest_filename
1964
1965 return [rc_obj_filename]
1966 | otherwise = return []
1967
1968
1969 linkDynLibCheck :: DynFlags -> [String] -> [UnitId] -> IO ()
1970 linkDynLibCheck dflags o_files dep_packages
1971 = do
1972 when (haveRtsOptsFlags dflags) $ do
1973 log_action dflags dflags SevInfo noSrcSpan defaultUserStyle
1974 (text "Warning: -rtsopts and -with-rtsopts have no effect with -shared." $$
1975 text " Call hs_init_ghc() from your main() function to set these options.")
1976
1977 linkDynLib dflags o_files dep_packages
1978
1979 linkStaticLibCheck :: DynFlags -> [String] -> [UnitId] -> IO ()
1980 linkStaticLibCheck dflags o_files dep_packages
1981 = do
1982 when (platformOS (targetPlatform dflags) `notElem` [OSiOS, OSDarwin]) $
1983 throwGhcExceptionIO (ProgramError "Static archive creation only supported on Darwin/OS X/iOS")
1984 linkBinary' True dflags o_files dep_packages
1985
1986 -- -----------------------------------------------------------------------------
1987 -- Running CPP
1988
1989 doCpp :: DynFlags -> Bool -> FilePath -> FilePath -> IO ()
1990 doCpp dflags raw input_fn output_fn = do
1991 let hscpp_opts = picPOpts dflags
1992 let cmdline_include_paths = includePaths dflags
1993
1994 pkg_include_dirs <- getPackageIncludePath dflags []
1995 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
1996 (cmdline_include_paths ++ pkg_include_dirs)
1997
1998 let verbFlags = getVerbFlags dflags
1999
2000 let cpp_prog args | raw = SysTools.runCpp dflags args
2001 | otherwise = SysTools.runCc dflags (SysTools.Option "-E" : args)
2002
2003 let target_defs =
2004 [ "-D" ++ HOST_OS ++ "_BUILD_OS",
2005 "-D" ++ HOST_ARCH ++ "_BUILD_ARCH",
2006 "-D" ++ TARGET_OS ++ "_HOST_OS",
2007 "-D" ++ TARGET_ARCH ++ "_HOST_ARCH" ]
2008 -- remember, in code we *compile*, the HOST is the same our TARGET,
2009 -- and BUILD is the same as our HOST.
2010
2011 let sse_defs =
2012 [ "-D__SSE__" | isSseEnabled dflags ] ++
2013 [ "-D__SSE2__" | isSse2Enabled dflags ] ++
2014 [ "-D__SSE4_2__" | isSse4_2Enabled dflags ]
2015
2016 let avx_defs =
2017 [ "-D__AVX__" | isAvxEnabled dflags ] ++
2018 [ "-D__AVX2__" | isAvx2Enabled dflags ] ++
2019 [ "-D__AVX512CD__" | isAvx512cdEnabled dflags ] ++
2020 [ "-D__AVX512ER__" | isAvx512erEnabled dflags ] ++
2021 [ "-D__AVX512F__" | isAvx512fEnabled dflags ] ++
2022 [ "-D__AVX512PF__" | isAvx512pfEnabled dflags ]
2023
2024 backend_defs <- getBackendDefs dflags
2025
2026 #ifdef GHCI
2027 let th_defs = [ "-D__GLASGOW_HASKELL_TH__" ]
2028 #else
2029 let th_defs = [ "-D__GLASGOW_HASKELL_TH__=0" ]
2030 #endif
2031 -- Default CPP defines in Haskell source
2032 ghcVersionH <- getGhcVersionPathName dflags
2033 let hsSourceCppOpts = [ "-include", ghcVersionH ]
2034
2035 -- MIN_VERSION macros
2036 let uids = explicitPackages (pkgState dflags)
2037 pkgs = catMaybes (map (lookupPackage dflags) uids)
2038 mb_macro_include <-
2039 -- Only generate if we have (1) we have set -hide-all-packages
2040 -- (so we don't generate a HUGE macro file of things we don't
2041 -- care about but are exposed) and (2) we actually have packages
2042 -- to write macros for!
2043 if gopt Opt_HideAllPackages dflags && not (null pkgs)
2044 then do macro_stub <- newTempName dflags "h"
2045 writeFile macro_stub (generatePackageVersionMacros pkgs)
2046 return [SysTools.FileOption "-include" macro_stub]
2047 else return []
2048
2049 cpp_prog ( map SysTools.Option verbFlags
2050 ++ map SysTools.Option include_paths
2051 ++ map SysTools.Option hsSourceCppOpts
2052 ++ map SysTools.Option target_defs
2053 ++ map SysTools.Option backend_defs
2054 ++ map SysTools.Option th_defs
2055 ++ map SysTools.Option hscpp_opts
2056 ++ map SysTools.Option sse_defs
2057 ++ map SysTools.Option avx_defs
2058 ++ mb_macro_include
2059 -- Set the language mode to assembler-with-cpp when preprocessing. This
2060 -- alleviates some of the C99 macro rules relating to whitespace and the hash
2061 -- operator, which we tend to abuse. Clang in particular is not very happy
2062 -- about this.
2063 ++ [ SysTools.Option "-x"
2064 , SysTools.Option "assembler-with-cpp"
2065 , SysTools.Option input_fn
2066 -- We hackily use Option instead of FileOption here, so that the file
2067 -- name is not back-slashed on Windows. cpp is capable of
2068 -- dealing with / in filenames, so it works fine. Furthermore
2069 -- if we put in backslashes, cpp outputs #line directives
2070 -- with *double* backslashes. And that in turn means that
2071 -- our error messages get double backslashes in them.
2072 -- In due course we should arrange that the lexer deals
2073 -- with these \\ escapes properly.
2074 , SysTools.Option "-o"
2075 , SysTools.FileOption "" output_fn
2076 ])
2077
2078 getBackendDefs :: DynFlags -> IO [String]
2079 getBackendDefs dflags | hscTarget dflags == HscLlvm = do
2080 llvmVer <- figureLlvmVersion dflags
2081 return $ case llvmVer of
2082 Just n -> [ "-D__GLASGOW_HASKELL_LLVM__="++show n ]
2083 _ -> []
2084
2085 getBackendDefs _ =
2086 return []
2087
2088 -- ---------------------------------------------------------------------------
2089 -- Macros (cribbed from Cabal)
2090
2091 generatePackageVersionMacros :: [PackageConfig] -> String
2092 generatePackageVersionMacros pkgs = concat
2093 [ "/* package " ++ sourcePackageIdString pkg ++ " */\n"
2094 ++ generateMacros "" pkgname version
2095 | pkg <- pkgs
2096 , let version = packageVersion pkg
2097 pkgname = map fixchar (packageNameString pkg)
2098 ]
2099
2100 fixchar :: Char -> Char
2101 fixchar '-' = '_'
2102 fixchar c = c
2103
2104 generateMacros :: String -> String -> Version -> String
2105 generateMacros prefix name version =
2106 concat
2107 ["#define ", prefix, "VERSION_",name," ",show (showVersion version),"\n"
2108 ,"#define MIN_", prefix, "VERSION_",name,"(major1,major2,minor) (\\\n"
2109 ," (major1) < ",major1," || \\\n"
2110 ," (major1) == ",major1," && (major2) < ",major2," || \\\n"
2111 ," (major1) == ",major1," && (major2) == ",major2," && (minor) <= ",minor,")"
2112 ,"\n\n"
2113 ]
2114 where
2115 (major1:major2:minor:_) = map show (versionBranch version ++ repeat 0)
2116
2117 -- ---------------------------------------------------------------------------
2118 -- join object files into a single relocatable object file, using ld -r
2119
2120 joinObjectFiles :: DynFlags -> [FilePath] -> FilePath -> IO ()
2121 joinObjectFiles dflags o_files output_fn = do
2122 let mySettings = settings dflags
2123 ldIsGnuLd = sLdIsGnuLd mySettings
2124 osInfo = platformOS (targetPlatform dflags)
2125 ld_r args cc = SysTools.runLink dflags ([
2126 SysTools.Option "-nostdlib",
2127 SysTools.Option "-Wl,-r"
2128 ]
2129 ++ (if any (cc ==) [Clang, AppleClang, AppleClang51]
2130 then []
2131 else [SysTools.Option "-nodefaultlibs"])
2132 ++ (if osInfo == OSFreeBSD
2133 then [SysTools.Option "-L/usr/lib"]
2134 else [])
2135 -- gcc on sparc sets -Wl,--relax implicitly, but
2136 -- -r and --relax are incompatible for ld, so
2137 -- disable --relax explicitly.
2138 ++ (if platformArch (targetPlatform dflags)
2139 `elem` [ArchSPARC, ArchSPARC64]
2140 && ldIsGnuLd
2141 then [SysTools.Option "-Wl,-no-relax"]
2142 else [])
2143 ++ map SysTools.Option ld_build_id
2144 ++ [ SysTools.Option "-o",
2145 SysTools.FileOption "" output_fn ]
2146 ++ args)
2147
2148 -- suppress the generation of the .note.gnu.build-id section,
2149 -- which we don't need and sometimes causes ld to emit a
2150 -- warning:
2151 ld_build_id | sLdSupportsBuildId mySettings = ["-Wl,--build-id=none"]
2152 | otherwise = []
2153
2154 ccInfo <- getCompilerInfo dflags
2155 if ldIsGnuLd
2156 then do
2157 script <- newTempName dflags "ldscript"
2158 cwd <- getCurrentDirectory
2159 let o_files_abs = map (\x -> "\"" ++ (cwd </> x) ++ "\"") o_files
2160 writeFile script $ "INPUT(" ++ unwords o_files_abs ++ ")"
2161 ld_r [SysTools.FileOption "" script] ccInfo
2162 else if sLdSupportsFilelist mySettings
2163 then do
2164 filelist <- newTempName dflags "filelist"
2165 writeFile filelist $ unlines o_files
2166 ld_r [SysTools.Option "-Wl,-filelist",
2167 SysTools.FileOption "-Wl," filelist] ccInfo
2168 else do
2169 ld_r (map (SysTools.FileOption "") o_files) ccInfo
2170
2171 -- -----------------------------------------------------------------------------
2172 -- Misc.
2173
2174 writeInterfaceOnlyMode :: DynFlags -> Bool
2175 writeInterfaceOnlyMode dflags =
2176 gopt Opt_WriteInterface dflags &&
2177 HscNothing == hscTarget dflags
2178
2179 -- | What phase to run after one of the backend code generators has run
2180 hscPostBackendPhase :: DynFlags -> HscSource -> HscTarget -> Phase
2181 hscPostBackendPhase _ HsBootFile _ = StopLn
2182 hscPostBackendPhase _ HsigFile _ = StopLn
2183 hscPostBackendPhase dflags _ hsc_lang =
2184 case hsc_lang of
2185 HscC -> HCc
2186 HscAsm | gopt Opt_SplitObjs dflags -> Splitter
2187 | otherwise -> As False
2188 HscLlvm -> LlvmOpt
2189 HscNothing -> StopLn
2190 HscInterpreted -> StopLn
2191
2192 touchObjectFile :: DynFlags -> FilePath -> IO ()
2193 touchObjectFile dflags path = do
2194 createDirectoryIfMissing True $ takeDirectory path
2195 SysTools.touch dflags "Touching object file" path
2196
2197 haveRtsOptsFlags :: DynFlags -> Bool
2198 haveRtsOptsFlags dflags =
2199 isJust (rtsOpts dflags) || case rtsOptsEnabled dflags of
2200 RtsOptsSafeOnly -> False
2201 _ -> True
2202
2203 -- | Find out path to @ghcversion.h@ file
2204 getGhcVersionPathName :: DynFlags -> IO FilePath
2205 getGhcVersionPathName dflags = do
2206 dirs <- getPackageIncludePath dflags [rtsUnitId]
2207
2208 found <- filterM doesFileExist (map (</> "ghcversion.h") dirs)
2209 case found of
2210 [] -> throwGhcExceptionIO (InstallationError ("ghcversion.h missing"))
2211 (x:_) -> return x
2212
2213 -- Note [-fPIC for assembler]
2214 -- When compiling .c source file GHC's driver pipeline basically
2215 -- does the following two things:
2216 -- 1. ${CC} -S 'PIC_CFLAGS' source.c
2217 -- 2. ${CC} -x assembler -c 'PIC_CFLAGS' source.S
2218 --
2219 -- Why do we need to pass 'PIC_CFLAGS' both to C compiler and assembler?
2220 -- Because on some architectures (at least sparc32) assembler also chooses
2221 -- the relocation type!
2222 -- Consider the following C module:
2223 --
2224 -- /* pic-sample.c */
2225 -- int v;
2226 -- void set_v (int n) { v = n; }
2227 -- int get_v (void) { return v; }
2228 --
2229 -- $ gcc -S -fPIC pic-sample.c
2230 -- $ gcc -c pic-sample.s -o pic-sample.no-pic.o # incorrect binary
2231 -- $ gcc -c -fPIC pic-sample.s -o pic-sample.pic.o # correct binary
2232 --
2233 -- $ objdump -r -d pic-sample.pic.o > pic-sample.pic.o.od
2234 -- $ objdump -r -d pic-sample.no-pic.o > pic-sample.no-pic.o.od
2235 -- $ diff -u pic-sample.pic.o.od pic-sample.no-pic.o.od
2236 --
2237 -- Most of architectures won't show any difference in this test, but on sparc32
2238 -- the following assembly snippet:
2239 --
2240 -- sethi %hi(_GLOBAL_OFFSET_TABLE_-8), %l7
2241 --
2242 -- generates two kinds or relocations, only 'R_SPARC_PC22' is correct:
2243 --
2244 -- 3c: 2f 00 00 00 sethi %hi(0), %l7
2245 -- - 3c: R_SPARC_PC22 _GLOBAL_OFFSET_TABLE_-0x8
2246 -- + 3c: R_SPARC_HI22 _GLOBAL_OFFSET_TABLE_-0x8
2247
2248 {- Note [Don't normalise input filenames]
2249
2250 Summary
2251 We used to normalise input filenames when starting the unlit phase. This
2252 broke hpc in `--make` mode with imported literate modules (#2991).
2253
2254 Introduction
2255 1) --main
2256 When compiling a module with --main, GHC scans its imports to find out which
2257 other modules it needs to compile too. It turns out that there is a small
2258 difference between saying `ghc --make A.hs`, when `A` imports `B`, and
2259 specifying both modules on the command line with `ghc --make A.hs B.hs`. In
2260 the former case, the filename for B is inferred to be './B.hs' instead of
2261 'B.hs'.
2262
2263 2) unlit
2264 When GHC compiles a literate haskell file, the source code first needs to go
2265 through unlit, which turns it into normal Haskell source code. At the start
2266 of the unlit phase, in `Driver.Pipeline.runPhase`, we call unlit with the
2267 option `-h` and the name of the original file. We used to normalise this
2268 filename using System.FilePath.normalise, which among other things removes
2269 an initial './'. unlit then uses that filename in #line directives that it
2270 inserts in the transformed source code.
2271
2272 3) SrcSpan
2273 A SrcSpan represents a portion of a source code file. It has fields
2274 linenumber, start column, end column, and also a reference to the file it
2275 originated from. The SrcSpans for a literate haskell file refer to the
2276 filename that was passed to unlit -h.
2277
2278 4) -fhpc
2279 At some point during compilation with -fhpc, in the function
2280 `deSugar.Coverage.isGoodTickSrcSpan`, we compare the filename that a
2281 `SrcSpan` refers to with the name of the file we are currently compiling.
2282 For some reason I don't yet understand, they can sometimes legitimally be
2283 different, and then hpc ignores that SrcSpan.
2284
2285 Problem
2286 When running `ghc --make -fhpc A.hs`, where `A.hs` imports the literate
2287 module `B.lhs`, `B` is inferred to be in the file `./B.lhs` (1). At the
2288 start of the unlit phase, the name `./B.lhs` is normalised to `B.lhs` (2).
2289 Therefore the SrcSpans of `B` refer to the file `B.lhs` (3), but we are
2290 still compiling `./B.lhs`. Hpc thinks these two filenames are different (4),
2291 doesn't include ticks for B, and we have unhappy customers (#2991).
2292
2293 Solution
2294 Do not normalise `input_fn` when starting the unlit phase.
2295
2296 Alternative solution
2297 Another option would be to not compare the two filenames on equality, but to
2298 use System.FilePath.equalFilePath. That function first normalises its
2299 arguments. The problem is that by the time we need to do the comparison, the
2300 filenames have been turned into FastStrings, probably for performance
2301 reasons, so System.FilePath.equalFilePath can not be used directly.
2302
2303 Archeology
2304 The call to `normalise` was added in a commit called "Fix slash
2305 direction on Windows with the new filePath code" (c9b6b5e8). The problem
2306 that commit was addressing has since been solved in a different manner, in a
2307 commit called "Fix the filename passed to unlit" (1eedbc6b). So the
2308 `normalise` is no longer necessary.
2309 -}