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