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