1 -----------------------------------------------------------------------------
5 -- (c) The University of Glasgow 2005
7 -----------------------------------------------------------------------------
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
16 module DriverPipeline (
17 -- Run a series of compilation steps in a pipeline, for a
18 -- collection of source files.
21 -- Interfaces for the batch-mode driver
24 -- Interfaces for the compilation manager (interpreted/batch-mode)
31 #include "HsVersions.h"
42 import UniqFM ( eltsUFM )
45 import StaticFlags ( v_Ld_inputs, opt_Static, opt_HardwireLibPaths, WayName(..) )
49 import StringBuffer ( hGetStringBuffer )
50 import BasicTypes ( SuccessFlag(..) )
51 import Maybes ( expectJust )
52 import ParserCoreUtils ( getCoreModuleName )
53 import SrcLoc ( unLoc )
54 import SrcLoc ( Located(..) )
56 import Control.Exception as Exception
57 import Data.IORef ( readIORef, writeIORef, IORef )
58 import GHC.Exts ( Int(..) )
59 import System.Directory
61 import SYSTEM_IO_ERROR as IO
63 import Data.List ( isSuffixOf )
66 import System.Environment
68 -- ---------------------------------------------------------------------------
71 -- Just preprocess a file, put the result in a temp. file (used by the
72 -- compilation manager during the summary phase).
74 -- We return the augmented DynFlags, because they contain the result
75 -- of slurping in the OPTIONS pragmas
77 preprocess :: DynFlags -> (FilePath, Maybe Phase) -> IO (DynFlags, FilePath)
78 preprocess dflags (filename, mb_phase) =
79 ASSERT2(isJust mb_phase || isHaskellSrcFilename filename, text filename)
80 runPipeline anyHsc dflags (filename, mb_phase)
81 Nothing Temporary Nothing{-no ModLocation-}
83 -- ---------------------------------------------------------------------------
86 -- Compile a single module, under the control of the compilation manager.
88 -- This is the interface between the compilation manager and the
89 -- compiler proper (hsc), where we deal with tedious details like
90 -- reading the OPTIONS pragma from the source file, and passing the
91 -- output of hsc through the C compiler.
93 -- NB. No old interface can also mean that the source has changed.
96 -> ModSummary -- summary for module being compiled
97 -> Int -> Int -- module N of M
98 -> Maybe ModIface -- old interface, if we have one
99 -> Maybe Linkable -- old linkable, if we have one
100 -> IO (Maybe HomeModInfo) -- the complete HomeModInfo, if successful
102 compile hsc_env summary mod_index nmods mb_old_iface maybe_old_linkable
104 let dflags0 = ms_hspp_opts summary
105 this_mod = ms_mod summary
106 src_flavour = ms_hsc_src summary
109 | Just l <- maybe_old_linkable, isObjectLinkable l = True
112 let location = ms_location summary
113 let input_fn = expectJust "compile:hs" (ml_hs_file location)
114 let input_fnpp = ms_hspp_file summary
116 debugTraceMsg dflags0 2 (text "compile: input file" <+> text input_fnpp)
118 let (basename, _) = splitFilename input_fn
120 -- We add the directory in which the .hs files resides) to the import path.
121 -- This is needed when we try to compile the .hc file later, if it
122 -- imports a _stub.h file that we created here.
123 let current_dir = directoryOf basename
124 old_paths = includePaths dflags0
125 dflags = dflags0 { includePaths = current_dir : old_paths }
127 -- Figure out what lang we're generating
128 let hsc_lang = hscMaybeAdjustTarget dflags StopLn src_flavour (hscTarget dflags)
129 -- ... and what the next phase should be
130 let next_phase = hscNextPhase dflags src_flavour hsc_lang
131 -- ... and what file to generate the output into
132 output_fn <- getOutputFilename next_phase
133 Temporary basename dflags next_phase (Just location)
135 let dflags' = dflags { hscTarget = hsc_lang,
136 hscOutName = output_fn,
137 extCoreName = basename ++ ".hcr" }
139 -- -no-recomp should also work with --make
140 let force_recomp = dopt Opt_ForceRecomp dflags
141 source_unchanged = isJust maybe_old_linkable && not force_recomp
142 hsc_env' = hsc_env { hsc_dflags = dflags' }
143 object_filename = ml_obj_file location
145 let getStubLinkable False = return []
147 = do stub_o <- compileStub dflags' this_mod location
148 return [ DotO stub_o ]
150 handleBatch HscNoRecomp
151 = ASSERT (isJust maybe_old_linkable)
152 return maybe_old_linkable
154 handleBatch (HscRecomp hasStub)
155 | isHsBoot src_flavour
156 = do when (isObjectTarget hsc_lang) $ -- interpreted reaches here too
157 SysTools.touch dflags' "Touching object file"
159 return maybe_old_linkable
162 = do stub_unlinked <- getStubLinkable hasStub
163 (hs_unlinked, unlinked_time) <-
166 -> return ([], ms_hs_date summary)
167 -- We're in --make mode: finish the compilation pipeline.
169 -> do runPipeline StopLn dflags (output_fn,Nothing)
173 -- The object filename comes from the ModLocation
174 o_time <- getModificationTime object_filename
175 return ([DotO object_filename], o_time)
176 let linkable = LM unlinked_time this_mod
177 (hs_unlinked ++ stub_unlinked)
178 return (Just linkable)
180 handleInterpreted InteractiveNoRecomp
181 = ASSERT (isJust maybe_old_linkable)
182 return maybe_old_linkable
183 handleInterpreted (InteractiveRecomp hasStub comp_bc modBreaks)
184 = do stub_unlinked <- getStubLinkable hasStub
185 let hs_unlinked = [BCOs comp_bc modBreaks]
186 unlinked_time = ms_hs_date summary
187 -- Why do we use the timestamp of the source file here,
188 -- rather than the current time? This works better in
189 -- the case where the local clock is out of sync
190 -- with the filesystem's clock. It's just as accurate:
191 -- if the source is modified, then the linkable will
193 let linkable = LM unlinked_time this_mod
194 (hs_unlinked ++ stub_unlinked)
195 return (Just linkable)
197 let -- runCompiler :: Compiler result -> (result -> Maybe Linkable)
198 -- -> IO (Maybe HomeModInfo)
199 runCompiler compiler handle
200 = do mbResult <- compiler hsc_env' summary source_unchanged mb_old_iface
201 (Just (mod_index, nmods))
203 Nothing -> return Nothing
204 Just (result, iface, details) -> do
205 linkable <- handle result
206 return (Just HomeModInfo{ hm_details = details,
208 hm_linkable = linkable })
212 | isHsBoot src_flavour ->
213 runCompiler hscCompileNothing handleBatch
215 runCompiler hscCompileInteractive handleInterpreted
217 runCompiler hscCompileNothing handleBatch
219 runCompiler hscCompileBatch handleBatch
221 -----------------------------------------------------------------------------
222 -- stub .h and .c files (for foreign export support)
224 -- The _stub.c file is derived from the haskell source file, possibly taking
225 -- into account the -stubdir option.
227 -- Consequently, we derive the _stub.o filename from the haskell object
230 -- This isn't necessarily the same as the object filename we
231 -- would get if we just compiled the _stub.c file using the pipeline.
234 -- ghc src/A.hs -odir obj
236 -- results in obj/A.o, and src/A_stub.c. If we compile src/A_stub.c with
237 -- -odir obj, we would get obj/src/A_stub.o, which is wrong; we want
240 compileStub :: DynFlags -> Module -> ModLocation -> IO FilePath
241 compileStub dflags mod location = do
242 let (o_base, o_ext) = splitFilename (ml_obj_file location)
243 stub_o = o_base ++ "_stub" `joinFileExt` o_ext
245 -- compile the _stub.c file w/ gcc
246 let (stub_c,_) = mkStubPaths dflags (moduleName mod) location
247 runPipeline StopLn dflags (stub_c,Nothing) Nothing
248 (SpecificFile stub_o) Nothing{-no ModLocation-}
253 -- ---------------------------------------------------------------------------
256 link :: GhcLink -- interactive or batch
257 -> DynFlags -- dynamic flags
258 -> Bool -- attempt linking in batch mode?
259 -> HomePackageTable -- what to link
262 -- For the moment, in the batch linker, we don't bother to tell doLink
263 -- which packages to link -- it just tries all that are available.
264 -- batch_attempt_linking should only be *looked at* in batch mode. It
265 -- should only be True if the upsweep was successful and someone
266 -- exports main, i.e., we have good reason to believe that linking
270 link LinkInMemory dflags batch_attempt_linking hpt
271 = do -- Not Linking...(demand linker will do the job)
275 link NoLink dflags batch_attempt_linking hpt
278 link LinkBinary dflags batch_attempt_linking hpt
279 | batch_attempt_linking
282 home_mod_infos = eltsUFM hpt
284 -- the packages we depend on
285 pkg_deps = concatMap (dep_pkgs . mi_deps . hm_iface) home_mod_infos
287 -- the linkables to link
288 linkables = map (expectJust "link".hm_linkable) home_mod_infos
290 debugTraceMsg dflags 3 (text "link: linkables are ..." $$ vcat (map ppr linkables))
292 -- check for the -no-link flag
293 if isNoLink (ghcLink dflags)
294 then do debugTraceMsg dflags 3 (text "link(batch): linking omitted (-c flag given).")
298 let getOfiles (LM _ _ us) = map nameOfObject (filter isObject us)
299 obj_files = concatMap getOfiles linkables
301 exe_file = exeFileName dflags
303 -- if the modification time on the executable is later than the
304 -- modification times on all of the objects, then omit linking
305 -- (unless the -no-recomp flag was given).
306 e_exe_time <- IO.try $ getModificationTime exe_file
308 | Left _ <- e_exe_time = True
309 | Right t <- e_exe_time =
310 any (t <) (map linkableTime linkables)
312 if not (dopt Opt_ForceRecomp dflags) && not linking_needed
313 then do debugTraceMsg dflags 2 (text exe_file <+> ptext SLIT("is up to date, linking not required."))
317 debugTraceMsg dflags 1 (ptext SLIT("Linking") <+> text exe_file
320 -- Don't showPass in Batch mode; doLink will do that for us.
321 let link = case ghcLink dflags of
322 LinkBinary -> linkBinary
323 LinkDynLib -> linkDynLib
324 link dflags obj_files pkg_deps
326 debugTraceMsg dflags 3 (text "link: done")
328 -- linkBinary only returns if it succeeds
332 = do debugTraceMsg dflags 3 (text "link(batch): upsweep (partially) failed OR" $$
333 text " Main.main not exported; not linking.")
336 -- -----------------------------------------------------------------------------
337 -- Compile files in one-shot mode.
339 oneShot :: DynFlags -> Phase -> [(String, Maybe Phase)] -> IO ()
340 oneShot dflags stop_phase srcs = do
341 o_files <- mapM (compileFile dflags stop_phase) srcs
342 doLink dflags stop_phase o_files
344 compileFile :: DynFlags -> Phase -> (FilePath, Maybe Phase) -> IO FilePath
345 compileFile dflags stop_phase (src, mb_phase) = do
346 exists <- doesFileExist src
348 throwDyn (CmdLineError ("does not exist: " ++ src))
351 split = dopt Opt_SplitObjs dflags
352 mb_o_file = outputFile dflags
353 ghc_link = ghcLink dflags -- Set by -c or -no-link
355 -- When linking, the -o argument refers to the linker's output.
356 -- otherwise, we use it as the name for the pipeline's output.
358 | StopLn <- stop_phase, not (isNoLink ghc_link) = Persistent
359 -- -o foo applies to linker
360 | Just o_file <- mb_o_file = SpecificFile o_file
361 -- -o foo applies to the file we are compiling now
362 | otherwise = Persistent
364 stop_phase' = case stop_phase of
365 As | split -> SplitAs
368 (_, out_file) <- runPipeline stop_phase' dflags
369 (src, mb_phase) Nothing output
370 Nothing{-no ModLocation-}
374 doLink :: DynFlags -> Phase -> [FilePath] -> IO ()
375 doLink dflags stop_phase o_files
376 | not (isStopLn stop_phase)
377 = return () -- We stopped before the linking phase
380 = case ghcLink dflags of
382 LinkBinary -> linkBinary dflags o_files link_pkgs
383 LinkDynLib -> linkDynLib dflags o_files []
385 -- Always link in the haskell98 package for static linking. Other
386 -- packages have to be specified via the -package flag.
387 link_pkgs = [haskell98PackageId]
390 -- ---------------------------------------------------------------------------
391 -- Run a compilation pipeline, consisting of multiple phases.
393 -- This is the interface to the compilation pipeline, which runs
394 -- a series of compilation steps on a single source file, specifying
395 -- at which stage to stop.
397 -- The DynFlags can be modified by phases in the pipeline (eg. by
398 -- GHC_OPTIONS pragmas), and the changes affect later phases in the
403 -- output should be to a temporary file: we're going to
404 -- run more compilation steps on this output later
406 -- we want a persistent file, i.e. a file in the current directory
407 -- derived from the input filename, but with the appropriate extension.
408 -- eg. in "ghc -c Foo.hs" the output goes into ./Foo.o.
409 | SpecificFile FilePath
410 -- the output must go into the specified file.
413 :: Phase -- When to stop
414 -> DynFlags -- Dynamic flags
415 -> (FilePath,Maybe Phase) -- Input filename (and maybe -x suffix)
416 -> Maybe FilePath -- original basename (if different from ^^^)
417 -> PipelineOutput -- Output filename
418 -> Maybe ModLocation -- A ModLocation, if this is a Haskell module
419 -> IO (DynFlags, FilePath) -- (final flags, output filename)
421 runPipeline stop_phase dflags0 (input_fn, mb_phase) mb_basename output maybe_loc
424 (input_basename, suffix) = splitFilename input_fn
425 basename | Just b <- mb_basename = b
426 | otherwise = input_basename
428 -- Decide where dump files should go based on the pipeline output
429 dflags = dflags0 { dumpPrefix = Just (basename ++ ".") }
431 -- If we were given a -x flag, then use that phase to start from
432 start_phase = fromMaybe (startPhase suffix) mb_phase
434 -- We want to catch cases of "you can't get there from here" before
435 -- we start the pipeline, because otherwise it will just run off the
438 -- There is a partial ordering on phases, where A < B iff A occurs
439 -- before B in a normal compilation pipeline.
441 when (not (start_phase `happensBefore` stop_phase)) $
443 ("cannot compile this file to desired target: "
446 -- this is a function which will be used to calculate output file names
447 -- as we go along (we partially apply it to some of its inputs here)
448 let get_output_fn = getOutputFilename stop_phase output basename
450 -- Execute the pipeline...
451 (dflags', output_fn, maybe_loc) <-
452 pipeLoop dflags start_phase stop_phase input_fn
453 basename suffix get_output_fn maybe_loc
455 -- Sometimes, a compilation phase doesn't actually generate any output
456 -- (eg. the CPP phase when -fcpp is not turned on). If we end on this
457 -- stage, but we wanted to keep the output, then we have to explicitly
458 -- copy the file, remembering to prepend a {-# LINE #-} pragma so that
459 -- further compilation stages can tell what the original filename was.
462 return (dflags', output_fn)
464 do final_fn <- get_output_fn dflags' stop_phase maybe_loc
465 when (final_fn /= output_fn) $ do
466 let msg = ("Copying `" ++ output_fn ++"' to `" ++ final_fn ++ "'")
467 line_prag = Just ("{-# LINE 1 \"" ++ input_fn ++ "\" #-}\n")
468 copyWithHeader dflags msg line_prag output_fn final_fn
469 return (dflags', final_fn)
473 pipeLoop :: DynFlags -> Phase -> Phase
474 -> FilePath -> String -> Suffix
475 -> (DynFlags -> Phase -> Maybe ModLocation -> IO FilePath)
477 -> IO (DynFlags, FilePath, Maybe ModLocation)
479 pipeLoop dflags phase stop_phase
480 input_fn orig_basename orig_suff
481 orig_get_output_fn maybe_loc
483 | phase `eqPhase` stop_phase -- All done
484 = return (dflags, input_fn, maybe_loc)
486 | not (phase `happensBefore` stop_phase)
487 -- Something has gone wrong. We'll try to cover all the cases when
488 -- this could happen, so if we reach here it is a panic.
489 -- eg. it might happen if the -C flag is used on a source file that
490 -- has {-# OPTIONS -fasm #-}.
491 = panic ("pipeLoop: at phase " ++ show phase ++
492 " but I wanted to stop at phase " ++ show stop_phase)
495 = do { (next_phase, dflags', maybe_loc, output_fn)
496 <- runPhase phase stop_phase dflags orig_basename
497 orig_suff input_fn orig_get_output_fn maybe_loc
498 ; pipeLoop dflags' next_phase stop_phase output_fn
499 orig_basename orig_suff orig_get_output_fn maybe_loc }
502 :: Phase -> PipelineOutput -> String
503 -> DynFlags -> Phase{-next phase-} -> Maybe ModLocation -> IO FilePath
504 getOutputFilename stop_phase output basename
507 func dflags next_phase maybe_location
508 | is_last_phase, Persistent <- output = persistent_fn
509 | is_last_phase, SpecificFile f <- output = return f
510 | keep_this_output = persistent_fn
511 | otherwise = newTempName dflags suffix
514 odir = objectDir dflags
515 osuf = objectSuf dflags
516 keep_hc = dopt Opt_KeepHcFiles dflags
517 keep_raw_s = dopt Opt_KeepRawSFiles dflags
518 keep_s = dopt Opt_KeepSFiles dflags
520 myPhaseInputExt HCc = hcsuf
521 myPhaseInputExt StopLn = osuf
522 myPhaseInputExt other = phaseInputExt other
524 is_last_phase = next_phase `eqPhase` stop_phase
526 -- sometimes, we keep output from intermediate stages
530 Mangle | keep_raw_s -> True
532 HCc | keep_hc -> True
535 suffix = myPhaseInputExt next_phase
537 -- persistent object files get put in odir
539 | StopLn <- next_phase = return odir_persistent
540 | otherwise = return persistent
542 persistent = basename `joinFileExt` suffix
545 | Just loc <- maybe_location = ml_obj_file loc
546 | Just d <- odir = d `joinFileName` persistent
547 | otherwise = persistent
550 -- -----------------------------------------------------------------------------
551 -- Each phase in the pipeline returns the next phase to execute, and the
552 -- name of the file in which the output was placed.
554 -- We must do things dynamically this way, because we often don't know
555 -- what the rest of the phases will be until part-way through the
556 -- compilation: for example, an {-# OPTIONS -fasm #-} at the beginning
557 -- of a source file can change the latter stages of the pipeline from
558 -- taking the via-C route to using the native code generator.
560 runPhase :: Phase -- Do this phase first
561 -> Phase -- Stop just before this phase
563 -> String -- basename of original input source
564 -> String -- its extension
565 -> FilePath -- name of file which contains the input to this phase.
566 -> (DynFlags -> Phase -> Maybe ModLocation -> IO FilePath)
567 -- how to calculate the output filename
568 -> Maybe ModLocation -- the ModLocation, if we have one
569 -> IO (Phase, -- next phase
570 DynFlags, -- new dynamic flags
571 Maybe ModLocation, -- the ModLocation, if we have one
572 FilePath) -- output filename
574 -- Invariant: the output filename always contains the output
575 -- Interesting case: Hsc when there is no recompilation to do
576 -- Then the output filename is still a .o file
578 -------------------------------------------------------------------------------
581 runPhase (Unlit sf) _stop dflags _basename _suff input_fn get_output_fn maybe_loc
582 = do let unlit_flags = getOpts dflags opt_L
583 -- The -h option passes the file name for unlit to put in a #line directive
584 output_fn <- get_output_fn dflags (Cpp sf) maybe_loc
586 SysTools.runUnlit dflags
587 (map SysTools.Option unlit_flags ++
588 [ SysTools.Option "-h"
589 , SysTools.Option input_fn
590 , SysTools.FileOption "" input_fn
591 , SysTools.FileOption "" output_fn
594 return (Cpp sf, dflags, maybe_loc, output_fn)
596 -------------------------------------------------------------------------------
597 -- Cpp phase : (a) gets OPTIONS out of file
598 -- (b) runs cpp if necessary
600 runPhase (Cpp sf) _stop dflags0 basename suff input_fn get_output_fn maybe_loc
601 = do src_opts <- getOptionsFromFile input_fn
602 (dflags,unhandled_flags) <- parseDynamicFlags dflags0 (map unLoc src_opts)
603 checkProcessArgsResult unhandled_flags (basename `joinFileExt` suff)
605 if not (dopt Opt_Cpp dflags) then
606 -- no need to preprocess CPP, just pass input file along
607 -- to the next phase of the pipeline.
608 return (HsPp sf, dflags, maybe_loc, input_fn)
610 output_fn <- get_output_fn dflags (HsPp sf) maybe_loc
611 doCpp dflags True{-raw-} False{-no CC opts-} input_fn output_fn
612 return (HsPp sf, dflags, maybe_loc, output_fn)
614 -------------------------------------------------------------------------------
617 runPhase (HsPp sf) _stop dflags basename suff input_fn get_output_fn maybe_loc
618 = do if not (dopt Opt_Pp dflags) then
619 -- no need to preprocess, just pass input file along
620 -- to the next phase of the pipeline.
621 return (Hsc sf, dflags, maybe_loc, input_fn)
623 let hspp_opts = getOpts dflags opt_F
624 let orig_fn = basename `joinFileExt` suff
625 output_fn <- get_output_fn dflags (Hsc sf) maybe_loc
626 SysTools.runPp dflags
627 ( [ SysTools.Option orig_fn
628 , SysTools.Option input_fn
629 , SysTools.FileOption "" output_fn
631 map SysTools.Option hspp_opts
633 return (Hsc sf, dflags, maybe_loc, output_fn)
635 -----------------------------------------------------------------------------
638 -- Compilation of a single module, in "legacy" mode (_not_ under
639 -- the direction of the compilation manager).
640 runPhase (Hsc src_flavour) stop dflags0 basename suff input_fn get_output_fn _maybe_loc
641 = do -- normal Hsc mode, not mkdependHS
643 -- we add the current directory (i.e. the directory in which
644 -- the .hs files resides) to the import path, since this is
645 -- what gcc does, and it's probably what you want.
646 let current_dir = directoryOf basename
648 paths = includePaths dflags0
649 dflags = dflags0 { includePaths = current_dir : paths }
651 -- gather the imports and module name
652 (hspp_buf,mod_name,imps,src_imps) <-
654 ExtCoreFile -> do { -- no explicit imports in ExtCore input.
655 ; m <- getCoreModuleName input_fn
656 ; return (Nothing, mkModuleName m, [], []) }
658 other -> do { buf <- hGetStringBuffer input_fn
659 ; (src_imps,imps,L _ mod_name) <- getImports dflags buf input_fn (basename `joinFileExt` suff)
660 ; return (Just buf, mod_name, imps, src_imps) }
662 -- Build a ModLocation to pass to hscMain.
663 -- The source filename is rather irrelevant by now, but it's used
664 -- by hscMain for messages. hscMain also needs
665 -- the .hi and .o filenames, and this is as good a way
666 -- as any to generate them, and better than most. (e.g. takes
667 -- into accout the -osuf flags)
668 location1 <- mkHomeModLocation2 dflags mod_name basename suff
670 -- Boot-ify it if necessary
671 let location2 | isHsBoot src_flavour = addBootSuffixLocn location1
672 | otherwise = location1
675 -- Take -ohi into account if present
676 -- This can't be done in mkHomeModuleLocation because
677 -- it only applies to the module being compiles
678 let ohi = outputHi dflags
679 location3 | Just fn <- ohi = location2{ ml_hi_file = fn }
680 | otherwise = location2
682 -- Take -o into account if present
683 -- Very like -ohi, but we must *only* do this if we aren't linking
684 -- (If we're linking then the -o applies to the linked thing, not to
685 -- the object file for one module.)
686 -- Note the nasty duplication with the same computation in compileFile above
687 let expl_o_file = outputFile dflags
688 location4 | Just ofile <- expl_o_file
689 , isNoLink (ghcLink dflags)
690 = location3 { ml_obj_file = ofile }
691 | otherwise = location3
693 o_file = ml_obj_file location4 -- The real object file
696 -- Figure out if the source has changed, for recompilation avoidance.
698 -- Setting source_unchanged to True means that M.o seems
699 -- to be up to date wrt M.hs; so no need to recompile unless imports have
700 -- changed (which the compiler itself figures out).
701 -- Setting source_unchanged to False tells the compiler that M.o is out of
702 -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
703 src_timestamp <- getModificationTime (basename `joinFileExt` suff)
705 let force_recomp = dopt Opt_ForceRecomp dflags
707 if force_recomp || not (isStopLn stop)
708 -- Set source_unchanged to False unconditionally if
709 -- (a) recompilation checker is off, or
710 -- (b) we aren't going all the way to .o file (e.g. ghc -S)
712 -- Otherwise look at file modification dates
713 else do o_file_exists <- doesFileExist o_file
715 then return False -- Need to recompile
716 else do t2 <- getModificationTime o_file
717 if t2 > src_timestamp
722 let hsc_lang = hscMaybeAdjustTarget dflags stop src_flavour (hscTarget dflags)
723 let next_phase = hscNextPhase dflags src_flavour hsc_lang
724 output_fn <- get_output_fn dflags next_phase (Just location4)
726 let dflags' = dflags { hscTarget = hsc_lang,
727 hscOutName = output_fn,
728 extCoreName = basename ++ ".hcr" }
730 hsc_env <- newHscEnv dflags'
732 -- Tell the finder cache about this module
733 mod <- addHomeModuleToFinder hsc_env mod_name location4
735 -- Make the ModSummary to hand to hscMain
737 unused_field = panic "runPhase:ModSummary field"
738 -- Some fields are not looked at by hscMain
739 mod_summary = ModSummary { ms_mod = mod,
740 ms_hsc_src = src_flavour,
741 ms_hspp_file = input_fn,
742 ms_hspp_opts = dflags,
743 ms_hspp_buf = hspp_buf,
744 ms_location = location4,
745 ms_hs_date = src_timestamp,
746 ms_obj_date = Nothing,
748 ms_srcimps = src_imps }
751 mbResult <- hscCompileOneShot hsc_env
752 mod_summary source_unchanged
754 Nothing -- No "module i of n" progress info
757 Nothing -> throwDyn (PhaseFailed "hsc" (ExitFailure 1))
759 -> do SysTools.touch dflags' "Touching object file" o_file
760 -- The .o file must have a later modification date
761 -- than the source file (else we wouldn't be in HscNoRecomp)
762 -- but we touch it anyway, to keep 'make' happy (we think).
763 return (StopLn, dflags', Just location4, o_file)
764 Just (HscRecomp hasStub)
766 do stub_o <- compileStub dflags' mod location4
767 consIORef v_Ld_inputs stub_o
768 -- In the case of hs-boot files, generate a dummy .o-boot
769 -- stamp file for the benefit of Make
770 when (isHsBoot src_flavour) $
771 SysTools.touch dflags' "Touching object file" o_file
772 return (next_phase, dflags', Just location4, output_fn)
774 -----------------------------------------------------------------------------
777 runPhase CmmCpp stop dflags basename suff input_fn get_output_fn maybe_loc
779 output_fn <- get_output_fn dflags Cmm maybe_loc
780 doCpp dflags False{-not raw-} True{-include CC opts-} input_fn output_fn
781 return (Cmm, dflags, maybe_loc, output_fn)
783 runPhase Cmm stop dflags basename suff input_fn get_output_fn maybe_loc
785 let hsc_lang = hscMaybeAdjustTarget dflags stop HsSrcFile (hscTarget dflags)
786 let next_phase = hscNextPhase dflags HsSrcFile hsc_lang
787 output_fn <- get_output_fn dflags next_phase maybe_loc
789 let dflags' = dflags { hscTarget = hsc_lang,
790 hscOutName = output_fn,
791 extCoreName = basename ++ ".hcr" }
793 ok <- hscCmmFile dflags' input_fn
795 when (not ok) $ throwDyn (PhaseFailed "cmm" (ExitFailure 1))
797 return (next_phase, dflags, maybe_loc, output_fn)
799 -----------------------------------------------------------------------------
802 -- we don't support preprocessing .c files (with -E) now. Doing so introduces
803 -- way too many hacks, and I can't say I've ever used it anyway.
805 runPhase cc_phase stop dflags basename suff input_fn get_output_fn maybe_loc
806 | cc_phase `eqPhase` Cc || cc_phase `eqPhase` Ccpp || cc_phase `eqPhase` HCc
807 = do let cc_opts = getOpts dflags opt_c
808 hcc = cc_phase `eqPhase` HCc
810 let cmdline_include_paths = includePaths dflags
812 -- HC files have the dependent packages stamped into them
813 pkgs <- if hcc then getHCFilePackages input_fn else return []
815 -- add package include paths even if we're just compiling .c
816 -- files; this is the Value Add(TM) that using ghc instead of
818 pkg_include_dirs <- getPackageIncludePath dflags pkgs
819 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
820 (cmdline_include_paths ++ pkg_include_dirs)
822 let (md_c_flags, md_regd_c_flags) = machdepCCOpts dflags
823 gcc_extra_viac_flags <- getExtraViaCOpts dflags
824 let pic_c_flags = picCCOpts dflags
826 let verb = getVerbFlag dflags
828 pkg_extra_cc_opts <- getPackageExtraCcOpts dflags pkgs
830 let split_objs = dopt Opt_SplitObjs dflags
831 split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
834 let excessPrecision = dopt Opt_ExcessPrecision dflags
836 let cc_opt | optLevel dflags >= 2 = "-O2"
841 let mangle = dopt Opt_DoAsmMangling dflags
843 | hcc && mangle = Mangle
845 output_fn <- get_output_fn dflags next_phase maybe_loc
850 -- on x86 the floating point regs have greater precision
851 -- than a double, which leads to unpredictable results.
852 -- By default, we turn this off with -ffloat-store unless
853 -- the user specified -fexcess-precision.
854 (if excessPrecision then [] else [ "-ffloat-store" ]) ++
856 -- gcc's -fstrict-aliasing allows two accesses to memory
857 -- to be considered non-aliasing if they have different types.
858 -- This interacts badly with the C code we generate, which is
859 -- very weakly typed, being derived from C--.
860 ["-fno-strict-aliasing"]
864 SysTools.runCc dflags (
865 -- force the C compiler to interpret this file as C when
866 -- compiling .hc files, by adding the -x c option.
867 -- Also useful for plain .c files, just in case GHC saw a
869 [ SysTools.Option "-x", if cc_phase `eqPhase` Ccpp
870 then SysTools.Option "c++" else SysTools.Option "c"] ++
871 [ SysTools.FileOption "" input_fn
872 , SysTools.Option "-o"
873 , SysTools.FileOption "" output_fn
875 ++ map SysTools.Option (
878 #ifdef sparc_TARGET_ARCH
879 -- We only support SparcV9 and better because V8 lacks an atomic CAS
880 -- instruction. Note that the user can still override this
881 -- (e.g., -mcpu=ultrasparc) as GCC picks the "best" -mcpu flag
882 -- regardless of the ordering.
884 -- This is a temporary hack.
892 then gcc_extra_viac_flags
893 else filter (=="-fwrapv")
895 -- still want -fwrapv even for unreg'd
900 ++ [ verb, "-S", "-Wimplicit", cc_opt ]
901 ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
908 return (next_phase, dflags, maybe_loc, output_fn)
910 -- ToDo: postprocess the output from gcc
912 -----------------------------------------------------------------------------
915 runPhase Mangle stop dflags _basename _suff input_fn get_output_fn maybe_loc
916 = do let mangler_opts = getOpts dflags opt_m
919 machdep_opts <- return [ show (stolen_x86_regs dflags) ]
921 machdep_opts <- return []
924 let split = dopt Opt_SplitObjs dflags
926 | split = SplitMangle
928 output_fn <- get_output_fn dflags next_phase maybe_loc
930 SysTools.runMangle dflags (map SysTools.Option mangler_opts
931 ++ [ SysTools.FileOption "" input_fn
932 , SysTools.FileOption "" output_fn
934 ++ map SysTools.Option machdep_opts)
936 return (next_phase, dflags, maybe_loc, output_fn)
938 -----------------------------------------------------------------------------
941 runPhase SplitMangle stop dflags _basename _suff input_fn get_output_fn maybe_loc
942 = do -- tmp_pfx is the prefix used for the split .s files
943 -- We also use it as the file to contain the no. of split .s files (sigh)
944 split_s_prefix <- SysTools.newTempName dflags "split"
945 let n_files_fn = split_s_prefix
947 SysTools.runSplit dflags
948 [ SysTools.FileOption "" input_fn
949 , SysTools.FileOption "" split_s_prefix
950 , SysTools.FileOption "" n_files_fn
953 -- Save the number of split files for future references
954 s <- readFile n_files_fn
955 let n_files = read s :: Int
956 writeIORef v_Split_info (split_s_prefix, n_files)
958 -- Remember to delete all these files
959 addFilesToClean [ split_s_prefix ++ "__" ++ show n ++ ".s"
962 return (SplitAs, dflags, maybe_loc, "**splitmangle**")
963 -- we don't use the filename
965 -----------------------------------------------------------------------------
968 runPhase As stop dflags _basename _suff input_fn get_output_fn maybe_loc
969 = do let as_opts = getOpts dflags opt_a
970 let cmdline_include_paths = includePaths dflags
972 output_fn <- get_output_fn dflags StopLn maybe_loc
974 -- we create directories for the object file, because it
975 -- might be a hierarchical module.
976 createDirectoryHierarchy (directoryOf output_fn)
978 SysTools.runAs dflags
979 (map SysTools.Option as_opts
980 ++ [ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ]
981 #ifdef sparc_TARGET_ARCH
982 -- We only support SparcV9 and better because V8 lacks an atomic CAS
983 -- instruction so we have to make sure that the assembler accepts the
984 -- instruction set. Note that the user can still override this
985 -- (e.g., -mcpu=ultrasparc). GCC picks the "best" -mcpu flag
986 -- regardless of the ordering.
988 -- This is a temporary hack.
989 ++ [ SysTools.Option "-mcpu=v9" ]
991 ++ [ SysTools.Option "-c"
992 , SysTools.FileOption "" input_fn
993 , SysTools.Option "-o"
994 , SysTools.FileOption "" output_fn
997 return (StopLn, dflags, maybe_loc, output_fn)
1000 runPhase SplitAs stop dflags basename _suff _input_fn get_output_fn maybe_loc
1002 output_fn <- get_output_fn dflags StopLn maybe_loc
1004 let (base_o, _) = splitFilename output_fn
1005 split_odir = base_o ++ "_split"
1006 osuf = objectSuf dflags
1008 createDirectoryHierarchy split_odir
1010 -- remove M_split/ *.o, because we're going to archive M_split/ *.o
1011 -- later and we don't want to pick up any old objects.
1012 fs <- getDirectoryContents split_odir
1013 mapM_ removeFile $ map (split_odir `joinFileName`)
1014 $ filter (osuf `isSuffixOf`) fs
1016 let as_opts = getOpts dflags opt_a
1018 (split_s_prefix, n) <- readIORef v_Split_info
1020 let split_s n = split_s_prefix ++ "__" ++ show n `joinFileExt` "s"
1021 split_obj n = split_odir `joinFileName`
1022 filenameOf base_o ++ "__" ++ show n
1026 = SysTools.runAs dflags
1027 (map SysTools.Option as_opts ++
1028 [ SysTools.Option "-c"
1029 , SysTools.Option "-o"
1030 , SysTools.FileOption "" (split_obj n)
1031 , SysTools.FileOption "" (split_s n)
1034 mapM_ assemble_file [1..n]
1036 -- and join the split objects into a single object file:
1037 let ld_r args = SysTools.runLink dflags ([
1038 SysTools.Option "-nostdlib",
1039 SysTools.Option "-nodefaultlibs",
1040 SysTools.Option "-Wl,-r",
1041 SysTools.Option ld_x_flag,
1042 SysTools.Option "-o",
1043 SysTools.FileOption "" output_fn ] ++ args)
1044 ld_x_flag | null cLD_X = ""
1045 | otherwise = "-Wl,-x"
1047 if cLdIsGNULd == "YES"
1049 let script = split_odir `joinFileName` "ld.script"
1051 "INPUT(" ++ unwords (map split_obj [1..n]) ++ ")"
1052 ld_r [SysTools.FileOption "" script]
1054 ld_r (map (SysTools.FileOption "" . split_obj) [1..n])
1056 return (StopLn, dflags, maybe_loc, output_fn)
1059 -----------------------------------------------------------------------------
1060 -- MoveBinary sort-of-phase
1061 -- After having produced a binary, move it somewhere else and generate a
1062 -- wrapper script calling the binary. Currently, we need this only in
1063 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
1064 -- central directory.
1065 -- This is called from linkBinary below, after linking. I haven't made it
1066 -- a separate phase to minimise interfering with other modules, and
1067 -- we don't need the generality of a phase (MoveBinary is always
1068 -- done after linking and makes only sense in a parallel setup) -- HWL
1070 runPhase_MoveBinary dflags input_fn
1072 let sysMan = pgm_sysman dflags
1073 pvm_root <- getEnv "PVM_ROOT"
1074 pvm_arch <- getEnv "PVM_ARCH"
1076 pvm_executable_base = "=" ++ input_fn
1077 pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
1078 -- nuke old binary; maybe use configur'ed names for cp and rm?
1079 Panic.try (removeFile pvm_executable)
1080 -- move the newly created binary into PVM land
1081 copy dflags "copying PVM executable" input_fn pvm_executable
1082 -- generate a wrapper script for running a parallel prg under PVM
1083 writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
1086 -- generates a Perl skript starting a parallel prg under PVM
1087 mk_pvm_wrapper_script :: String -> String -> String -> String
1088 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
1090 "eval 'exec perl -S $0 ${1+\"$@\"}'",
1091 " if $running_under_some_shell;",
1092 "# =!=!=!=!=!=!=!=!=!=!=!",
1093 "# This script is automatically generated: DO NOT EDIT!!!",
1094 "# Generated by Glasgow Haskell Compiler",
1095 "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
1097 "$pvm_executable = '" ++ pvm_executable ++ "';",
1098 "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
1099 "$SysMan = '" ++ sysMan ++ "';",
1101 {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
1102 "# first, some magical shortcuts to run "commands" on the binary",
1103 "# (which is hidden)",
1104 "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
1105 " local($cmd) = $1;",
1106 " system("$cmd $pvm_executable");",
1107 " exit(0); # all done",
1110 "# Now, run the real binary; process the args first",
1111 "$ENV{'PE'} = $pvm_executable_base;", -- ++ pvm_executable_base,
1113 "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
1114 "@nonPVM_args = ();",
1115 "$in_RTS_args = 0;",
1117 "args: while ($a = shift(@ARGV)) {",
1118 " if ( $a eq '+RTS' ) {",
1119 " $in_RTS_args = 1;",
1120 " } elsif ( $a eq '-RTS' ) {",
1121 " $in_RTS_args = 0;",
1123 " if ( $a eq '-d' && $in_RTS_args ) {",
1125 " } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
1126 " $nprocessors = $1;",
1127 " } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
1128 " $nprocessors = $1;",
1130 " push(@nonPVM_args, $a);",
1134 "local($return_val) = 0;",
1135 "# Start the parallel execution by calling SysMan",
1136 "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
1137 "$return_val = $?;",
1138 "# ToDo: fix race condition moving files and flushing them!!",
1139 "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
1140 "exit($return_val);"
1143 -----------------------------------------------------------------------------
1144 -- Complain about non-dynamic flags in OPTIONS pragmas
1146 checkProcessArgsResult flags filename
1147 = do when (notNull flags) (throwDyn (ProgramError (
1148 showSDoc (hang (text filename <> char ':')
1149 4 (text "unknown flags in {-# OPTIONS #-} pragma:" <+>
1150 hsep (map text flags)))
1153 -----------------------------------------------------------------------------
1154 -- Look for the /* GHC_PACKAGES ... */ comment at the top of a .hc file
1156 getHCFilePackages :: FilePath -> IO [PackageId]
1157 getHCFilePackages filename =
1158 Exception.bracket (openFile filename ReadMode) hClose $ \h -> do
1161 '/':'*':' ':'G':'H':'C':'_':'P':'A':'C':'K':'A':'G':'E':'S':rest ->
1162 return (map stringToPackageId (words rest))
1166 -----------------------------------------------------------------------------
1167 -- Static linking, of .o files
1169 -- The list of packages passed to link is the list of packages on
1170 -- which this program depends, as discovered by the compilation
1171 -- manager. It is combined with the list of packages that the user
1172 -- specifies on the command line with -package flags.
1174 -- In one-shot linking mode, we can't discover the package
1175 -- dependencies (because we haven't actually done any compilation or
1176 -- read any interface files), so the user must explicitly specify all
1179 linkBinary :: DynFlags -> [FilePath] -> [PackageId] -> IO ()
1180 linkBinary dflags o_files dep_packages = do
1181 let verb = getVerbFlag dflags
1182 output_fn = exeFileName dflags
1184 -- get the full list of packages to link with, by combining the
1185 -- explicit packages with the auto packages and all of their
1186 -- dependencies, and eliminating duplicates.
1188 pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1189 let pkg_lib_path_opts = concat (map get_pkg_lib_path_opts pkg_lib_paths)
1190 get_pkg_lib_path_opts l | opt_HardwireLibPaths && not opt_Static = ["-L" ++ l, "-Wl,-rpath", "-Wl," ++ l]
1191 | otherwise = ["-L" ++ l]
1193 let lib_paths = libraryPaths dflags
1194 let lib_path_opts = map ("-L"++) lib_paths
1196 pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1198 #ifdef darwin_TARGET_OS
1199 pkg_framework_paths <- getPackageFrameworkPath dflags dep_packages
1200 let pkg_framework_path_opts = map ("-F"++) pkg_framework_paths
1202 let framework_paths = frameworkPaths dflags
1203 framework_path_opts = map ("-F"++) framework_paths
1205 pkg_frameworks <- getPackageFrameworks dflags dep_packages
1206 let pkg_framework_opts = concat [ ["-framework", fw] | fw <- pkg_frameworks ]
1208 let frameworks = cmdlineFrameworks dflags
1209 framework_opts = concat [ ["-framework", fw] | fw <- reverse frameworks ]
1210 -- reverse because they're added in reverse order from the cmd line
1213 -- probably _stub.o files
1214 extra_ld_inputs <- readIORef v_Ld_inputs
1216 -- opts from -optl-<blah> (including -l<blah> options)
1217 let extra_ld_opts = getOpts dflags opt_l
1219 let ways = wayNames dflags
1221 -- Here are some libs that need to be linked at the *end* of
1222 -- the command line, because they contain symbols that are referred to
1223 -- by the RTS. We can't therefore use the ordinary way opts for these.
1225 debug_opts | WayDebug `elem` ways = [
1226 #if defined(HAVE_LIBBFD)
1233 thread_opts | WayThreaded `elem` ways = [
1234 #if !defined(mingw32_TARGET_OS) && !defined(freebsd_TARGET_OS)
1237 #if defined(osf3_TARGET_OS)
1243 rc_objs <- maybeCreateManifest dflags output_fn
1245 let (md_c_flags, _) = machdepCCOpts dflags
1246 SysTools.runLink dflags (
1247 [ SysTools.Option verb
1248 , SysTools.Option "-o"
1249 , SysTools.FileOption "" output_fn
1251 ++ map SysTools.Option (
1258 #ifdef darwin_TARGET_OS
1259 ++ framework_path_opts
1262 ++ pkg_lib_path_opts
1264 #ifdef darwin_TARGET_OS
1265 ++ pkg_framework_path_opts
1266 ++ pkg_framework_opts
1272 -- parallel only: move binary to another dir -- HWL
1273 when (WayPar `elem` ways)
1274 (do success <- runPhase_MoveBinary dflags output_fn
1275 if success then return ()
1276 else throwDyn (InstallationError ("cannot move binary to PVM dir")))
1279 exeFileName :: DynFlags -> FilePath
1281 | Just s <- outputFile dflags =
1282 #if defined(mingw32_HOST_OS)
1283 if null (suffixOf s)
1284 then s `joinFileExt` "exe"
1290 #if defined(mingw32_HOST_OS)
1298 -> FilePath -- filename of executable
1299 -> IO [FilePath] -- extra objects to embed, maybe
1300 maybeCreateManifest dflags exe_filename = do
1301 #ifndef mingw32_TARGET_OS
1304 if not (dopt Opt_GenManifest dflags) then return [] else do
1306 let manifest_filename = exe_filename `joinFileExt` "manifest"
1308 writeFile manifest_filename $
1309 "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"++
1310 " <assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">\n"++
1311 " <assemblyIdentity version=\"1.0.0.0\"\n"++
1312 " processorArchitecture=\"X86\"\n"++
1313 " name=\"" ++ basenameOf exe_filename ++ "\"\n"++
1314 " type=\"win32\"/>\n\n"++
1315 " <trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v3\">\n"++
1317 " <requestedPrivileges>\n"++
1318 " <requestedExecutionLevel level=\"asInvoker\" uiAccess=\"false\"/>\n"++
1319 " </requestedPrivileges>\n"++
1324 -- Windows will fine the manifest file if it is named foo.exe.manifest.
1325 -- However, for extra robustness, and so that we can move the binary around,
1326 -- we can embed the manifest in the binary itself using windres:
1327 if not (dopt Opt_EmbedManifest dflags) then return [] else do
1329 rc_filename <- newTempName dflags "rc"
1330 rc_obj_filename <- newTempName dflags (objectSuf dflags)
1332 writeFile rc_filename $
1333 "1 24 MOVEABLE PURE \"" ++ manifest_filename ++ "\"\n"
1334 -- magic numbers :-)
1336 let wr_opts = getOpts dflags opt_windres
1337 runWindres dflags $ map SysTools.Option $
1338 ["--input="++rc_filename,
1339 "--output="++rc_obj_filename,
1340 "--output-format=coff"]
1342 -- no FileOptions here: windres doesn't like seeing
1343 -- backslashes, apparently
1345 return [rc_obj_filename]
1349 linkDynLib :: DynFlags -> [String] -> [PackageId] -> IO ()
1350 linkDynLib dflags o_files dep_packages = do
1351 let verb = getVerbFlag dflags
1352 let static = opt_Static
1353 let no_hs_main = dopt Opt_NoHsMain dflags
1354 let o_file = outputFile dflags
1356 pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1357 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1359 let lib_paths = libraryPaths dflags
1360 let lib_path_opts = map ("-L"++) lib_paths
1362 pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1364 -- probably _stub.o files
1365 extra_ld_inputs <- readIORef v_Ld_inputs
1367 let (md_c_flags, _) = machdepCCOpts dflags
1368 let extra_ld_opts = getOpts dflags opt_l
1369 #if defined(mingw32_HOST_OS)
1370 -----------------------------------------------------------------------------
1372 -----------------------------------------------------------------------------
1373 let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
1375 SysTools.runLink dflags
1376 ([ SysTools.Option verb
1377 , SysTools.Option "-o"
1378 , SysTools.FileOption "" output_fn
1379 , SysTools.Option "-shared"
1380 , SysTools.Option "-Wl,--export-all-symbols"
1381 , SysTools.FileOption "-Wl,--out-implib=" (output_fn ++ ".a")
1383 ++ map (SysTools.FileOption "") o_files
1384 ++ map SysTools.Option (
1389 ++ pkg_lib_path_opts
1392 #elif defined(darwin_TARGET_OS)
1393 -----------------------------------------------------------------------------
1394 -- Making a darwin dylib
1395 -----------------------------------------------------------------------------
1396 -- About the options used for Darwin:
1398 -- Apple's way of saying -shared
1399 -- -undefined dynamic_lookup:
1400 -- Without these options, we'd have to specify the correct dependencies
1401 -- for each of the dylibs. Note that we could (and should) do without this
1402 -- for all libraries except the RTS; all we need to do is to pass the
1403 -- correct HSfoo_dyn.dylib files to the link command.
1404 -- This feature requires Mac OS X 10.3 or later; there is a similar feature,
1405 -- -flat_namespace -undefined suppress, which works on earlier versions,
1406 -- but it has other disadvantages.
1408 -- Build the dynamic library as a single "module", i.e. no dynamic binding
1409 -- nonsense when referring to symbols from within the library. The NCG
1410 -- assumes that this option is specified (on i386, at least).
1411 -- -Wl,-macosx_version_min -Wl,10.3
1412 -- Tell the linker its safe to assume that the library will run on 10.3 or
1413 -- later, so that it will not complain about the use of the option
1414 -- -undefined dynamic_lookup above.
1416 -- Causes the dynamic linker to ignore the DYLD_LIBRARY_PATH when loading
1417 -- this lib and instead look for it at its absolute path.
1418 -- When installing the .dylibs (see target.mk), we'll change that path to
1419 -- point to the place they are installed. Therefore, we won't have to set
1420 -- up DYLD_LIBRARY_PATH specifically for ghc.
1421 -----------------------------------------------------------------------------
1423 let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
1425 pwd <- getCurrentDirectory
1426 SysTools.runLink dflags
1427 ([ SysTools.Option verb
1428 , SysTools.Option "-dynamiclib"
1429 , SysTools.Option "-o"
1430 , SysTools.FileOption "" output_fn
1432 ++ map SysTools.Option (
1435 ++ [ "-undefined", "dynamic_lookup", "-single_module", "-Wl,-macosx_version_min","-Wl,10.3", "-install_name " ++ (pwd `joinFileName` output_fn) ]
1439 ++ pkg_lib_path_opts
1443 -----------------------------------------------------------------------------
1445 -----------------------------------------------------------------------------
1447 let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
1449 SysTools.runLink dflags
1450 ([ SysTools.Option verb
1451 , SysTools.Option "-o"
1452 , SysTools.FileOption "" output_fn
1454 ++ map SysTools.Option (
1457 ++ [ "-shared", "-Wl,-Bsymbolic" ] -- we need symbolic linking to resolve non-PIC intra-package-relocations
1461 ++ pkg_lib_path_opts
1465 -- -----------------------------------------------------------------------------
1468 doCpp :: DynFlags -> Bool -> Bool -> FilePath -> FilePath -> IO ()
1469 doCpp dflags raw include_cc_opts input_fn output_fn = do
1470 let hscpp_opts = getOpts dflags opt_P
1471 let cmdline_include_paths = includePaths dflags
1473 pkg_include_dirs <- getPackageIncludePath dflags []
1474 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
1475 (cmdline_include_paths ++ pkg_include_dirs)
1477 let verb = getVerbFlag dflags
1480 | not include_cc_opts = []
1481 | otherwise = (optc ++ md_c_flags)
1483 optc = getOpts dflags opt_c
1484 (md_c_flags, _) = machdepCCOpts dflags
1486 let cpp_prog args | raw = SysTools.runCpp dflags args
1487 | otherwise = SysTools.runCc dflags (SysTools.Option "-E" : args)
1490 [ "-D" ++ HOST_OS ++ "_BUILD_OS=1",
1491 "-D" ++ HOST_ARCH ++ "_BUILD_ARCH=1",
1492 "-D" ++ TARGET_OS ++ "_HOST_OS=1",
1493 "-D" ++ TARGET_ARCH ++ "_HOST_ARCH=1" ]
1494 -- remember, in code we *compile*, the HOST is the same our TARGET,
1495 -- and BUILD is the same as our HOST.
1497 cpp_prog ([SysTools.Option verb]
1498 ++ map SysTools.Option include_paths
1499 ++ map SysTools.Option hsSourceCppOpts
1500 ++ map SysTools.Option hscpp_opts
1501 ++ map SysTools.Option cc_opts
1502 ++ map SysTools.Option target_defs
1503 ++ [ SysTools.Option "-x"
1504 , SysTools.Option "c"
1505 , SysTools.Option input_fn
1506 -- We hackily use Option instead of FileOption here, so that the file
1507 -- name is not back-slashed on Windows. cpp is capable of
1508 -- dealing with / in filenames, so it works fine. Furthermore
1509 -- if we put in backslashes, cpp outputs #line directives
1510 -- with *double* backslashes. And that in turn means that
1511 -- our error messages get double backslashes in them.
1512 -- In due course we should arrange that the lexer deals
1513 -- with these \\ escapes properly.
1514 , SysTools.Option "-o"
1515 , SysTools.FileOption "" output_fn
1518 cHaskell1Version = "5" -- i.e., Haskell 98
1520 -- Default CPP defines in Haskell source
1522 [ "-D__HASKELL1__="++cHaskell1Version
1523 , "-D__GLASGOW_HASKELL__="++cProjectVersionInt
1525 , "-D__CONCURRENT_HASKELL__"
1529 -- -----------------------------------------------------------------------------
1532 hscNextPhase :: DynFlags -> HscSource -> HscTarget -> Phase
1533 hscNextPhase dflags HsBootFile hsc_lang = StopLn
1534 hscNextPhase dflags other hsc_lang =
1537 HscAsm | dopt Opt_SplitObjs dflags -> SplitMangle
1539 HscNothing -> StopLn
1540 HscInterpreted -> StopLn
1544 hscMaybeAdjustTarget :: DynFlags -> Phase -> HscSource -> HscTarget -> HscTarget
1545 hscMaybeAdjustTarget dflags stop other current_hsc_lang
1548 keep_hc = dopt Opt_KeepHcFiles dflags
1550 -- don't change the lang if we're interpreting
1551 | current_hsc_lang == HscInterpreted = current_hsc_lang
1553 -- force -fvia-C if we are being asked for a .hc file
1554 | HCc <- stop = HscC
1556 -- otherwise, stick to the plan
1557 | otherwise = current_hsc_lang
1559 GLOBAL_VAR(v_Split_info, ("",0), (String,Int))
1560 -- The split prefix and number of files