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