1 {-# OPTIONS -fno-cse #-}
2 -- -fno-cse is needed for GLOBAL_VAR's to behave properly
4 -----------------------------------------------------------------------------
8 -- (c) The University of Glasgow 2005
10 -----------------------------------------------------------------------------
12 module DriverPipeline (
13 -- Run a series of compilation steps in a pipeline, for a
14 -- collection of source files.
17 -- Interfaces for the batch-mode driver
20 -- Interfaces for the compilation manager (interpreted/batch-mode)
27 #include "HsVersions.h"
38 import LazyUniqFM ( eltsUFM )
41 import StaticFlags ( v_Ld_inputs, opt_Static, WayName(..) )
45 import StringBuffer ( hGetStringBuffer )
46 import BasicTypes ( SuccessFlag(..) )
47 import Maybes ( expectJust )
48 import ParserCoreUtils ( getCoreModuleName )
53 import Data.IORef ( readIORef, writeIORef, IORef )
54 import GHC.Exts ( Int(..) )
55 import System.Directory
56 import System.FilePath
58 import System.IO.Error as IO
60 import Data.List ( isSuffixOf )
63 import System.Environment
65 -- ---------------------------------------------------------------------------
68 -- Just preprocess a file, put the result in a temp. file (used by the
69 -- compilation manager during the summary phase).
71 -- We return the augmented DynFlags, because they contain the result
72 -- of slurping in the OPTIONS pragmas
74 preprocess :: HscEnv -> (FilePath, Maybe Phase) -> IO (DynFlags, FilePath)
75 preprocess hsc_env (filename, mb_phase) =
76 ASSERT2(isJust mb_phase || isHaskellSrcFilename filename, text filename)
77 runPipeline anyHsc hsc_env (filename, mb_phase)
78 Nothing Temporary Nothing{-no ModLocation-}
80 -- ---------------------------------------------------------------------------
83 -- Compile a single module, under the control of the compilation manager.
85 -- This is the interface between the compilation manager and the
86 -- compiler proper (hsc), where we deal with tedious details like
87 -- reading the OPTIONS pragma from the source file, and passing the
88 -- output of hsc through the C compiler.
90 -- NB. No old interface can also mean that the source has changed.
93 -> ModSummary -- summary for module being compiled
94 -> Int -> Int -- module N of M
95 -> Maybe ModIface -- old interface, if we have one
96 -> Maybe Linkable -- old linkable, if we have one
97 -> IO (Maybe HomeModInfo) -- the complete HomeModInfo, if successful
99 compile hsc_env0 summary mod_index nmods mb_old_iface maybe_old_linkable
101 let dflags0 = ms_hspp_opts summary
102 this_mod = ms_mod summary
103 src_flavour = ms_hsc_src summary
104 location = ms_location summary
105 input_fn = expectJust "compile:hs" (ml_hs_file location)
106 input_fnpp = ms_hspp_file summary
108 debugTraceMsg dflags0 2 (text "compile: input file" <+> text input_fnpp)
110 let basename = dropExtension input_fn
112 -- We add the directory in which the .hs files resides) to the import path.
113 -- This is needed when we try to compile the .hc file later, if it
114 -- imports a _stub.h file that we created here.
115 let current_dir = case takeDirectory basename of
116 "" -> "." -- XXX Hack
118 old_paths = includePaths dflags0
119 dflags = dflags0 { includePaths = current_dir : old_paths }
120 hsc_env = hsc_env0 {hsc_dflags = dflags}
122 -- Figure out what lang we're generating
123 let hsc_lang = hscMaybeAdjustTarget dflags StopLn src_flavour (hscTarget dflags)
124 -- ... and what the next phase should be
125 let next_phase = hscNextPhase dflags src_flavour hsc_lang
126 -- ... and what file to generate the output into
127 output_fn <- getOutputFilename next_phase
128 Temporary basename dflags next_phase (Just location)
130 let dflags' = dflags { hscTarget = hsc_lang,
131 hscOutName = output_fn,
132 extCoreName = basename ++ ".hcr" }
133 let hsc_env' = hsc_env { hsc_dflags = dflags' }
135 -- -fforce-recomp should also work with --make
136 let force_recomp = dopt Opt_ForceRecomp dflags
137 source_unchanged = isJust maybe_old_linkable && not force_recomp
138 object_filename = ml_obj_file location
140 let getStubLinkable False = return []
142 = do stub_o <- compileStub hsc_env' this_mod location
143 return [ DotO stub_o ]
145 handleBatch HscNoRecomp
146 = ASSERT (isJust maybe_old_linkable)
147 return maybe_old_linkable
149 handleBatch (HscRecomp hasStub)
150 | isHsBoot src_flavour
151 = do when (isObjectTarget hsc_lang) $ -- interpreted reaches here too
152 SysTools.touch dflags' "Touching object file"
154 return maybe_old_linkable
157 = do stub_unlinked <- getStubLinkable hasStub
158 (hs_unlinked, unlinked_time) <-
161 -> return ([], ms_hs_date summary)
162 -- We're in --make mode: finish the compilation pipeline.
164 -> do runPipeline StopLn hsc_env' (output_fn,Nothing)
168 -- The object filename comes from the ModLocation
169 o_time <- getModificationTime object_filename
170 return ([DotO object_filename], o_time)
171 let linkable = LM unlinked_time this_mod
172 (hs_unlinked ++ stub_unlinked)
173 return (Just linkable)
175 handleInterpreted InteractiveNoRecomp
176 = ASSERT (isJust maybe_old_linkable)
177 return maybe_old_linkable
178 handleInterpreted (InteractiveRecomp hasStub comp_bc modBreaks)
179 = do stub_unlinked <- getStubLinkable hasStub
180 let hs_unlinked = [BCOs comp_bc modBreaks]
181 unlinked_time = ms_hs_date summary
182 -- Why do we use the timestamp of the source file here,
183 -- rather than the current time? This works better in
184 -- the case where the local clock is out of sync
185 -- with the filesystem's clock. It's just as accurate:
186 -- if the source is modified, then the linkable will
188 let linkable = LM unlinked_time this_mod
189 (hs_unlinked ++ stub_unlinked)
190 return (Just linkable)
192 let -- runCompiler :: Compiler result -> (result -> Maybe Linkable)
193 -- -> IO (Maybe HomeModInfo)
194 runCompiler compiler handle
195 = do mbResult <- compiler hsc_env' summary source_unchanged mb_old_iface
196 (Just (mod_index, nmods))
198 Nothing -> return Nothing
199 Just (result, iface, details) -> do
200 linkable <- handle result
201 return (Just HomeModInfo{ hm_details = details,
203 hm_linkable = linkable })
207 | isHsBoot src_flavour ->
208 runCompiler hscCompileNothing handleBatch
210 runCompiler hscCompileInteractive handleInterpreted
212 runCompiler hscCompileNothing handleBatch
214 runCompiler hscCompileBatch handleBatch
216 -----------------------------------------------------------------------------
217 -- stub .h and .c files (for foreign export support)
219 -- The _stub.c file is derived from the haskell source file, possibly taking
220 -- into account the -stubdir option.
222 -- Consequently, we derive the _stub.o filename from the haskell object
225 -- This isn't necessarily the same as the object filename we
226 -- would get if we just compiled the _stub.c file using the pipeline.
229 -- ghc src/A.hs -odir obj
231 -- results in obj/A.o, and src/A_stub.c. If we compile src/A_stub.c with
232 -- -odir obj, we would get obj/src/A_stub.o, which is wrong; we want
235 compileStub :: HscEnv -> Module -> ModLocation -> IO FilePath
236 compileStub hsc_env mod location = do
237 let (o_base, o_ext) = splitExtension (ml_obj_file location)
238 stub_o = (o_base ++ "_stub") <.> o_ext
240 -- compile the _stub.c file w/ gcc
241 let (stub_c,_,_) = mkStubPaths (hsc_dflags hsc_env) (moduleName mod) location
242 runPipeline StopLn hsc_env (stub_c,Nothing) Nothing
243 (SpecificFile stub_o) Nothing{-no ModLocation-}
248 -- ---------------------------------------------------------------------------
251 link :: GhcLink -- interactive or batch
252 -> DynFlags -- dynamic flags
253 -> Bool -- attempt linking in batch mode?
254 -> HomePackageTable -- what to link
257 -- For the moment, in the batch linker, we don't bother to tell doLink
258 -- which packages to link -- it just tries all that are available.
259 -- batch_attempt_linking should only be *looked at* in batch mode. It
260 -- should only be True if the upsweep was successful and someone
261 -- exports main, i.e., we have good reason to believe that linking
265 link LinkInMemory _ _ _
266 = do -- Not Linking...(demand linker will do the job)
273 link LinkBinary dflags batch_attempt_linking hpt
274 | batch_attempt_linking
277 home_mod_infos = eltsUFM hpt
279 -- the packages we depend on
280 pkg_deps = concatMap (dep_pkgs . mi_deps . hm_iface) home_mod_infos
282 -- the linkables to link
283 linkables = map (expectJust "link".hm_linkable) home_mod_infos
285 debugTraceMsg dflags 3 (text "link: linkables are ..." $$ vcat (map ppr linkables))
287 -- check for the -no-link flag
288 if isNoLink (ghcLink dflags)
289 then do debugTraceMsg dflags 3 (text "link(batch): linking omitted (-c flag given).")
293 let getOfiles (LM _ _ us) = map nameOfObject (filter isObject us)
294 obj_files = concatMap getOfiles linkables
296 exe_file = exeFileName dflags
298 -- if the modification time on the executable is later than the
299 -- modification times on all of the objects, then omit linking
300 -- (unless the -fforce-recomp flag was given).
301 e_exe_time <- IO.try $ getModificationTime exe_file
302 extra_ld_inputs <- readIORef v_Ld_inputs
303 extra_times <- mapM (IO.try . getModificationTime) extra_ld_inputs
304 let other_times = map linkableTime linkables
305 ++ [ t' | Right t' <- extra_times ]
306 linking_needed = case e_exe_time of
308 Right t -> any (t <) other_times
310 if not (dopt Opt_ForceRecomp dflags) && not linking_needed
311 then do debugTraceMsg dflags 2 (text exe_file <+> ptext (sLit "is up to date, linking not required."))
315 debugTraceMsg dflags 1 (ptext (sLit "Linking") <+> text exe_file
318 -- Don't showPass in Batch mode; doLink will do that for us.
319 let link = case ghcLink dflags of
320 LinkBinary -> linkBinary
321 LinkDynLib -> linkDynLib
322 other -> panicBadLink other
323 link dflags obj_files pkg_deps
325 debugTraceMsg dflags 3 (text "link: done")
327 -- linkBinary only returns if it succeeds
331 = do debugTraceMsg dflags 3 (text "link(batch): upsweep (partially) failed OR" $$
332 text " Main.main not exported; not linking.")
335 -- warning suppression
336 link other _ _ _ = panicBadLink other
338 panicBadLink :: GhcLink -> a
339 panicBadLink other = panic ("link: GHC not built to link this way: " ++
341 -- -----------------------------------------------------------------------------
342 -- Compile files in one-shot mode.
344 oneShot :: HscEnv -> Phase -> [(String, Maybe Phase)] -> IO ()
345 oneShot hsc_env stop_phase srcs = do
346 o_files <- mapM (compileFile hsc_env stop_phase) srcs
347 doLink (hsc_dflags hsc_env) stop_phase o_files
349 compileFile :: HscEnv -> Phase -> (FilePath, Maybe Phase) -> IO FilePath
350 compileFile hsc_env stop_phase (src, mb_phase) = do
351 exists <- doesFileExist src
353 ghcError (CmdLineError ("does not exist: " ++ src))
356 dflags = hsc_dflags hsc_env
357 split = dopt Opt_SplitObjs dflags
358 mb_o_file = outputFile dflags
359 ghc_link = ghcLink dflags -- Set by -c or -no-link
361 -- When linking, the -o argument refers to the linker's output.
362 -- otherwise, we use it as the name for the pipeline's output.
364 | StopLn <- stop_phase, not (isNoLink ghc_link) = Persistent
365 -- -o foo applies to linker
366 | Just o_file <- mb_o_file = SpecificFile o_file
367 -- -o foo applies to the file we are compiling now
368 | otherwise = Persistent
370 stop_phase' = case stop_phase of
371 As | split -> SplitAs
374 (_, out_file) <- runPipeline stop_phase' hsc_env
375 (src, mb_phase) Nothing output
376 Nothing{-no ModLocation-}
380 doLink :: DynFlags -> Phase -> [FilePath] -> IO ()
381 doLink dflags stop_phase o_files
382 | not (isStopLn stop_phase)
383 = return () -- We stopped before the linking phase
386 = case ghcLink dflags of
388 LinkBinary -> linkBinary dflags o_files link_pkgs
389 LinkDynLib -> linkDynLib dflags o_files []
390 other -> panicBadLink other
392 -- Always link in the haskell98 package for static linking. Other
393 -- packages have to be specified via the -package flag.
395 | dopt Opt_AutoLinkPackages dflags = [haskell98PackageId]
399 -- ---------------------------------------------------------------------------
400 -- Run a compilation pipeline, consisting of multiple phases.
402 -- This is the interface to the compilation pipeline, which runs
403 -- a series of compilation steps on a single source file, specifying
404 -- at which stage to stop.
406 -- The DynFlags can be modified by phases in the pipeline (eg. by
407 -- GHC_OPTIONS pragmas), and the changes affect later phases in the
412 -- output should be to a temporary file: we're going to
413 -- run more compilation steps on this output later
415 -- we want a persistent file, i.e. a file in the current directory
416 -- derived from the input filename, but with the appropriate extension.
417 -- eg. in "ghc -c Foo.hs" the output goes into ./Foo.o.
418 | SpecificFile FilePath
419 -- the output must go into the specified file.
422 :: Phase -- When to stop
423 -> HscEnv -- Compilation environment
424 -> (FilePath,Maybe Phase) -- Input filename (and maybe -x suffix)
425 -> Maybe FilePath -- original basename (if different from ^^^)
426 -> PipelineOutput -- Output filename
427 -> Maybe ModLocation -- A ModLocation, if this is a Haskell module
428 -> IO (DynFlags, FilePath) -- (final flags, output filename)
430 runPipeline stop_phase hsc_env0 (input_fn, mb_phase) mb_basename output maybe_loc
432 let dflags0 = hsc_dflags hsc_env0
433 (input_basename, suffix) = splitExtension input_fn
434 suffix' = drop 1 suffix -- strip off the .
435 basename | Just b <- mb_basename = b
436 | otherwise = input_basename
438 -- Decide where dump files should go based on the pipeline output
439 dflags = dflags0 { dumpPrefix = Just (basename ++ ".") }
440 hsc_env = hsc_env0 {hsc_dflags = dflags}
442 -- If we were given a -x flag, then use that phase to start from
443 start_phase = fromMaybe (startPhase suffix') mb_phase
445 -- We want to catch cases of "you can't get there from here" before
446 -- we start the pipeline, because otherwise it will just run off the
449 -- There is a partial ordering on phases, where A < B iff A occurs
450 -- before B in a normal compilation pipeline.
452 when (not (start_phase `happensBefore` stop_phase)) $
454 ("cannot compile this file to desired target: "
457 -- this is a function which will be used to calculate output file names
458 -- as we go along (we partially apply it to some of its inputs here)
459 let get_output_fn = getOutputFilename stop_phase output basename
461 -- Execute the pipeline...
462 (dflags', output_fn, maybe_loc) <-
463 pipeLoop hsc_env start_phase stop_phase input_fn
464 basename suffix' get_output_fn maybe_loc
466 -- Sometimes, a compilation phase doesn't actually generate any output
467 -- (eg. the CPP phase when -fcpp is not turned on). If we end on this
468 -- stage, but we wanted to keep the output, then we have to explicitly
469 -- copy the file, remembering to prepend a {-# LINE #-} pragma so that
470 -- further compilation stages can tell what the original filename was.
473 return (dflags', output_fn)
475 do final_fn <- get_output_fn dflags' stop_phase maybe_loc
476 when (final_fn /= output_fn) $ do
477 let msg = ("Copying `" ++ output_fn ++"' to `" ++ final_fn ++ "'")
478 line_prag = Just ("{-# LINE 1 \"" ++ input_fn ++ "\" #-}\n")
479 copyWithHeader dflags msg line_prag output_fn final_fn
480 return (dflags', final_fn)
484 pipeLoop :: HscEnv -> Phase -> Phase
485 -> FilePath -> String -> Suffix
486 -> (DynFlags -> Phase -> Maybe ModLocation -> IO FilePath)
488 -> IO (DynFlags, FilePath, Maybe ModLocation)
490 pipeLoop hsc_env phase stop_phase
491 input_fn orig_basename orig_suff
492 orig_get_output_fn maybe_loc
494 | phase `eqPhase` stop_phase -- All done
495 = return (hsc_dflags hsc_env, input_fn, maybe_loc)
497 | not (phase `happensBefore` stop_phase)
498 -- Something has gone wrong. We'll try to cover all the cases when
499 -- this could happen, so if we reach here it is a panic.
500 -- eg. it might happen if the -C flag is used on a source file that
501 -- has {-# OPTIONS -fasm #-}.
502 = panic ("pipeLoop: at phase " ++ show phase ++
503 " but I wanted to stop at phase " ++ show stop_phase)
506 = do (next_phase, dflags', maybe_loc, output_fn)
507 <- runPhase phase stop_phase hsc_env orig_basename
508 orig_suff input_fn orig_get_output_fn maybe_loc
509 let hsc_env' = hsc_env {hsc_dflags = dflags'}
510 pipeLoop hsc_env' next_phase stop_phase output_fn
511 orig_basename orig_suff orig_get_output_fn maybe_loc
514 :: Phase -> PipelineOutput -> String
515 -> DynFlags -> Phase{-next phase-} -> Maybe ModLocation -> IO FilePath
516 getOutputFilename stop_phase output basename
519 func dflags next_phase maybe_location
520 | is_last_phase, Persistent <- output = persistent_fn
521 | is_last_phase, SpecificFile f <- output = return f
522 | keep_this_output = persistent_fn
523 | otherwise = newTempName dflags suffix
526 odir = objectDir dflags
527 osuf = objectSuf dflags
528 keep_hc = dopt Opt_KeepHcFiles dflags
529 keep_raw_s = dopt Opt_KeepRawSFiles dflags
530 keep_s = dopt Opt_KeepSFiles dflags
532 myPhaseInputExt HCc = hcsuf
533 myPhaseInputExt StopLn = osuf
534 myPhaseInputExt other = phaseInputExt other
536 is_last_phase = next_phase `eqPhase` stop_phase
538 -- sometimes, we keep output from intermediate stages
542 Mangle | keep_raw_s -> True
544 HCc | keep_hc -> True
547 suffix = myPhaseInputExt next_phase
549 -- persistent object files get put in odir
551 | StopLn <- next_phase = return odir_persistent
552 | otherwise = return persistent
554 persistent = basename <.> suffix
557 | Just loc <- maybe_location = ml_obj_file loc
558 | Just d <- odir = d </> persistent
559 | otherwise = persistent
562 -- -----------------------------------------------------------------------------
563 -- Each phase in the pipeline returns the next phase to execute, and the
564 -- name of the file in which the output was placed.
566 -- We must do things dynamically this way, because we often don't know
567 -- what the rest of the phases will be until part-way through the
568 -- compilation: for example, an {-# OPTIONS -fasm #-} at the beginning
569 -- of a source file can change the latter stages of the pipeline from
570 -- taking the via-C route to using the native code generator.
572 runPhase :: Phase -- Do this phase first
573 -> Phase -- Stop just before this phase
575 -> String -- basename of original input source
576 -> String -- its extension
577 -> FilePath -- name of file which contains the input to this phase.
578 -> (DynFlags -> Phase -> Maybe ModLocation -> IO FilePath)
579 -- how to calculate the output filename
580 -> Maybe ModLocation -- the ModLocation, if we have one
581 -> IO (Phase, -- next phase
582 DynFlags, -- new dynamic flags
583 Maybe ModLocation, -- the ModLocation, if we have one
584 FilePath) -- output filename
586 -- Invariant: the output filename always contains the output
587 -- Interesting case: Hsc when there is no recompilation to do
588 -- Then the output filename is still a .o file
590 -------------------------------------------------------------------------------
593 runPhase (Unlit sf) _stop hsc_env _basename _suff input_fn get_output_fn maybe_loc
595 let dflags = hsc_dflags hsc_env
596 output_fn <- get_output_fn dflags (Cpp sf) maybe_loc
598 let unlit_flags = getOpts dflags opt_L
599 flags = map SysTools.Option unlit_flags ++
600 [ -- The -h option passes the file name for unlit to
601 -- put in a #line directive
603 -- cpp interprets \b etc as escape sequences,
604 -- so we use / for filenames in pragmas
605 , SysTools.Option $ reslash Forwards $ normalise input_fn
606 , SysTools.FileOption "" input_fn
607 , SysTools.FileOption "" output_fn
610 SysTools.runUnlit dflags flags
612 return (Cpp sf, dflags, maybe_loc, output_fn)
614 -------------------------------------------------------------------------------
615 -- Cpp phase : (a) gets OPTIONS out of file
616 -- (b) runs cpp if necessary
618 runPhase (Cpp sf) _stop hsc_env _basename _suff input_fn get_output_fn maybe_loc
619 = do let dflags0 = hsc_dflags hsc_env
620 src_opts <- getOptionsFromFile dflags0 input_fn
621 (dflags, unhandled_flags, warns) <- parseDynamicFlags dflags0 src_opts
622 handleFlagWarnings dflags warns
623 checkProcessArgsResult unhandled_flags
625 if not (dopt Opt_Cpp dflags) then
626 -- no need to preprocess CPP, just pass input file along
627 -- to the next phase of the pipeline.
628 return (HsPp sf, dflags, maybe_loc, input_fn)
630 output_fn <- get_output_fn dflags (HsPp sf) maybe_loc
631 doCpp dflags True{-raw-} False{-no CC opts-} input_fn output_fn
632 return (HsPp sf, dflags, maybe_loc, output_fn)
634 -------------------------------------------------------------------------------
637 runPhase (HsPp sf) _stop hsc_env basename suff input_fn get_output_fn maybe_loc
638 = do let dflags = hsc_dflags hsc_env
639 if not (dopt Opt_Pp dflags) then
640 -- no need to preprocess, just pass input file along
641 -- to the next phase of the pipeline.
642 return (Hsc sf, dflags, maybe_loc, input_fn)
644 let hspp_opts = getOpts dflags opt_F
645 let orig_fn = basename <.> suff
646 output_fn <- get_output_fn dflags (Hsc sf) maybe_loc
647 SysTools.runPp dflags
648 ( [ SysTools.Option orig_fn
649 , SysTools.Option input_fn
650 , SysTools.FileOption "" output_fn
652 map SysTools.Option hspp_opts
654 return (Hsc sf, dflags, maybe_loc, output_fn)
656 -----------------------------------------------------------------------------
659 -- Compilation of a single module, in "legacy" mode (_not_ under
660 -- the direction of the compilation manager).
661 runPhase (Hsc src_flavour) stop hsc_env basename suff input_fn get_output_fn _maybe_loc
662 = do -- normal Hsc mode, not mkdependHS
663 let dflags0 = hsc_dflags hsc_env
665 -- we add the current directory (i.e. the directory in which
666 -- the .hs files resides) to the include path, since this is
667 -- what gcc does, and it's probably what you want.
668 let current_dir = case takeDirectory basename of
669 "" -> "." -- XXX Hack
672 paths = includePaths dflags0
673 dflags = dflags0 { includePaths = current_dir : paths }
675 -- gather the imports and module name
676 (hspp_buf,mod_name,imps,src_imps) <-
678 ExtCoreFile -> do { -- no explicit imports in ExtCore input.
679 ; m <- getCoreModuleName input_fn
680 ; return (Nothing, mkModuleName m, [], []) }
682 _ -> do { buf <- hGetStringBuffer input_fn
683 ; (src_imps,imps,L _ mod_name) <- getImports dflags buf input_fn (basename <.> suff)
684 ; return (Just buf, mod_name, imps, src_imps) }
686 -- Build a ModLocation to pass to hscMain.
687 -- The source filename is rather irrelevant by now, but it's used
688 -- by hscMain for messages. hscMain also needs
689 -- the .hi and .o filenames, and this is as good a way
690 -- as any to generate them, and better than most. (e.g. takes
691 -- into accout the -osuf flags)
692 location1 <- mkHomeModLocation2 dflags mod_name basename suff
694 -- Boot-ify it if necessary
695 let location2 | isHsBoot src_flavour = addBootSuffixLocn location1
696 | otherwise = location1
699 -- Take -ohi into account if present
700 -- This can't be done in mkHomeModuleLocation because
701 -- it only applies to the module being compiles
702 let ohi = outputHi dflags
703 location3 | Just fn <- ohi = location2{ ml_hi_file = fn }
704 | otherwise = location2
706 -- Take -o into account if present
707 -- Very like -ohi, but we must *only* do this if we aren't linking
708 -- (If we're linking then the -o applies to the linked thing, not to
709 -- the object file for one module.)
710 -- Note the nasty duplication with the same computation in compileFile above
711 let expl_o_file = outputFile dflags
712 location4 | Just ofile <- expl_o_file
713 , isNoLink (ghcLink dflags)
714 = location3 { ml_obj_file = ofile }
715 | otherwise = location3
717 o_file = ml_obj_file location4 -- The real object file
720 -- Figure out if the source has changed, for recompilation avoidance.
722 -- Setting source_unchanged to True means that M.o seems
723 -- to be up to date wrt M.hs; so no need to recompile unless imports have
724 -- changed (which the compiler itself figures out).
725 -- Setting source_unchanged to False tells the compiler that M.o is out of
726 -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
727 src_timestamp <- getModificationTime (basename <.> suff)
729 let force_recomp = dopt Opt_ForceRecomp dflags
731 if force_recomp || not (isStopLn stop)
732 -- Set source_unchanged to False unconditionally if
733 -- (a) recompilation checker is off, or
734 -- (b) we aren't going all the way to .o file (e.g. ghc -S)
736 -- Otherwise look at file modification dates
737 else do o_file_exists <- doesFileExist o_file
739 then return False -- Need to recompile
740 else do t2 <- getModificationTime o_file
741 if t2 > src_timestamp
746 let hsc_lang = hscMaybeAdjustTarget dflags stop src_flavour (hscTarget dflags)
747 let next_phase = hscNextPhase dflags src_flavour hsc_lang
748 output_fn <- get_output_fn dflags next_phase (Just location4)
750 let dflags' = dflags { hscTarget = hsc_lang,
751 hscOutName = output_fn,
752 extCoreName = basename ++ ".hcr" }
754 let hsc_env' = hsc_env {hsc_dflags = dflags'}
756 -- Tell the finder cache about this module
757 mod <- addHomeModuleToFinder hsc_env' mod_name location4
759 -- Make the ModSummary to hand to hscMain
761 mod_summary = ModSummary { ms_mod = mod,
762 ms_hsc_src = src_flavour,
763 ms_hspp_file = input_fn,
764 ms_hspp_opts = dflags,
765 ms_hspp_buf = hspp_buf,
766 ms_location = location4,
767 ms_hs_date = src_timestamp,
768 ms_obj_date = Nothing,
770 ms_srcimps = src_imps }
773 mbResult <- hscCompileOneShot hsc_env'
774 mod_summary source_unchanged
776 Nothing -- No "module i of n" progress info
779 Nothing -> ghcError (PhaseFailed "hsc" (ExitFailure 1))
781 -> do SysTools.touch dflags' "Touching object file" o_file
782 -- The .o file must have a later modification date
783 -- than the source file (else we wouldn't be in HscNoRecomp)
784 -- but we touch it anyway, to keep 'make' happy (we think).
785 return (StopLn, dflags', Just location4, o_file)
786 Just (HscRecomp hasStub)
788 do stub_o <- compileStub hsc_env' mod location4
789 consIORef v_Ld_inputs stub_o
790 -- In the case of hs-boot files, generate a dummy .o-boot
791 -- stamp file for the benefit of Make
792 when (isHsBoot src_flavour) $
793 SysTools.touch dflags' "Touching object file" o_file
794 return (next_phase, dflags', Just location4, output_fn)
796 -----------------------------------------------------------------------------
799 runPhase CmmCpp _stop hsc_env _basename _suff input_fn get_output_fn maybe_loc
801 let dflags = hsc_dflags hsc_env
802 output_fn <- get_output_fn dflags Cmm maybe_loc
803 doCpp dflags False{-not raw-} True{-include CC opts-} input_fn output_fn
804 return (Cmm, dflags, maybe_loc, output_fn)
806 runPhase Cmm stop hsc_env basename _ input_fn get_output_fn maybe_loc
808 let dflags = hsc_dflags hsc_env
809 let hsc_lang = hscMaybeAdjustTarget dflags stop HsSrcFile (hscTarget dflags)
810 let next_phase = hscNextPhase dflags HsSrcFile hsc_lang
811 output_fn <- get_output_fn dflags next_phase maybe_loc
813 let dflags' = dflags { hscTarget = hsc_lang,
814 hscOutName = output_fn,
815 extCoreName = basename ++ ".hcr" }
816 let hsc_env' = hsc_env {hsc_dflags = dflags'}
818 ok <- hscCmmFile hsc_env' input_fn
820 when (not ok) $ ghcError (PhaseFailed "cmm" (ExitFailure 1))
822 return (next_phase, dflags, maybe_loc, output_fn)
824 -----------------------------------------------------------------------------
827 -- we don't support preprocessing .c files (with -E) now. Doing so introduces
828 -- way too many hacks, and I can't say I've ever used it anyway.
830 runPhase cc_phase _stop hsc_env _basename _suff input_fn get_output_fn maybe_loc
831 | cc_phase `eqPhase` Cc || cc_phase `eqPhase` Ccpp || cc_phase `eqPhase` HCc
832 = do let dflags = hsc_dflags hsc_env
833 let cc_opts = getOpts dflags opt_c
834 hcc = cc_phase `eqPhase` HCc
836 let cmdline_include_paths = includePaths dflags
838 -- HC files have the dependent packages stamped into them
839 pkgs <- if hcc then getHCFilePackages input_fn else return []
841 -- add package include paths even if we're just compiling .c
842 -- files; this is the Value Add(TM) that using ghc instead of
844 pkg_include_dirs <- getPackageIncludePath dflags pkgs
845 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
846 (cmdline_include_paths ++ pkg_include_dirs)
848 let (md_c_flags, md_regd_c_flags) = machdepCCOpts dflags
849 gcc_extra_viac_flags <- getExtraViaCOpts dflags
850 let pic_c_flags = picCCOpts dflags
852 let verb = getVerbFlag dflags
854 -- cc-options are not passed when compiling .hc files. Our
855 -- hc code doesn't not #include any header files anyway, so these
856 -- options aren't necessary.
858 if cc_phase `eqPhase` HCc
860 else getPackageExtraCcOpts dflags pkgs
862 #ifdef darwin_TARGET_OS
863 pkg_framework_paths <- getPackageFrameworkPath dflags pkgs
864 let cmdline_framework_paths = frameworkPaths dflags
865 let framework_paths = map ("-F"++)
866 (cmdline_framework_paths ++ pkg_framework_paths)
869 let split_objs = dopt Opt_SplitObjs dflags
870 split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
873 let cc_opt | optLevel dflags >= 2 = "-O2"
878 let mangle = dopt Opt_DoAsmMangling dflags
880 | hcc && mangle = Mangle
882 output_fn <- get_output_fn dflags next_phase maybe_loc
887 -- on x86 the floating point regs have greater precision
888 -- than a double, which leads to unpredictable results.
889 -- By default, we turn this off with -ffloat-store unless
890 -- the user specified -fexcess-precision.
891 (if dopt Opt_ExcessPrecision dflags
893 else [ "-ffloat-store" ]) ++
895 -- gcc's -fstrict-aliasing allows two accesses to memory
896 -- to be considered non-aliasing if they have different types.
897 -- This interacts badly with the C code we generate, which is
898 -- very weakly typed, being derived from C--.
899 ["-fno-strict-aliasing"]
903 SysTools.runCc dflags (
904 -- force the C compiler to interpret this file as C when
905 -- compiling .hc files, by adding the -x c option.
906 -- Also useful for plain .c files, just in case GHC saw a
908 [ SysTools.Option "-x", if cc_phase `eqPhase` Ccpp
909 then SysTools.Option "c++" else SysTools.Option "c"] ++
910 [ SysTools.FileOption "" input_fn
911 , SysTools.Option "-o"
912 , SysTools.FileOption "" output_fn
914 ++ map SysTools.Option (
917 #ifdef sparc_TARGET_ARCH
918 -- We only support SparcV9 and better because V8 lacks an atomic CAS
919 -- instruction. Note that the user can still override this
920 -- (e.g., -mcpu=ultrasparc) as GCC picks the "best" -mcpu flag
921 -- regardless of the ordering.
923 -- This is a temporary hack.
931 then gcc_extra_viac_flags
932 else filter (=="-fwrapv")
934 -- still want -fwrapv even for unreg'd
939 ++ [ verb, "-S", "-Wimplicit", cc_opt ]
940 ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
941 #ifdef darwin_TARGET_OS
950 return (next_phase, dflags, maybe_loc, output_fn)
952 -- ToDo: postprocess the output from gcc
954 -----------------------------------------------------------------------------
957 runPhase Mangle _stop hsc_env _basename _suff input_fn get_output_fn maybe_loc
958 = do let dflags = hsc_dflags hsc_env
959 let mangler_opts = getOpts dflags opt_m
962 machdep_opts <- return [ show (stolen_x86_regs dflags) ]
964 machdep_opts <- return []
967 let split = dopt Opt_SplitObjs dflags
969 | split = SplitMangle
971 output_fn <- get_output_fn dflags next_phase maybe_loc
973 SysTools.runMangle dflags (map SysTools.Option mangler_opts
974 ++ [ SysTools.FileOption "" input_fn
975 , SysTools.FileOption "" output_fn
977 ++ map SysTools.Option machdep_opts)
979 return (next_phase, dflags, maybe_loc, output_fn)
981 -----------------------------------------------------------------------------
984 runPhase SplitMangle _stop hsc_env _basename _suff input_fn _get_output_fn maybe_loc
985 = do -- tmp_pfx is the prefix used for the split .s files
986 -- We also use it as the file to contain the no. of split .s files (sigh)
987 let dflags = hsc_dflags hsc_env
988 split_s_prefix <- SysTools.newTempName dflags "split"
989 let n_files_fn = split_s_prefix
991 SysTools.runSplit dflags
992 [ SysTools.FileOption "" input_fn
993 , SysTools.FileOption "" split_s_prefix
994 , SysTools.FileOption "" n_files_fn
997 -- Save the number of split files for future references
998 s <- readFile n_files_fn
999 let n_files = read s :: Int
1000 writeIORef v_Split_info (split_s_prefix, n_files)
1002 -- Remember to delete all these files
1003 addFilesToClean [ split_s_prefix ++ "__" ++ show n ++ ".s"
1004 | n <- [1..n_files]]
1006 return (SplitAs, dflags, maybe_loc, "**splitmangle**")
1007 -- we don't use the filename
1009 -----------------------------------------------------------------------------
1012 runPhase As _stop hsc_env _basename _suff input_fn get_output_fn maybe_loc
1013 = do let dflags = hsc_dflags hsc_env
1014 let as_opts = getOpts dflags opt_a
1015 let cmdline_include_paths = includePaths dflags
1017 output_fn <- get_output_fn dflags StopLn maybe_loc
1019 -- we create directories for the object file, because it
1020 -- might be a hierarchical module.
1021 createDirectoryHierarchy (takeDirectory output_fn)
1023 SysTools.runAs dflags
1024 (map SysTools.Option as_opts
1025 ++ [ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ]
1026 #ifdef sparc_TARGET_ARCH
1027 -- We only support SparcV9 and better because V8 lacks an atomic CAS
1028 -- instruction so we have to make sure that the assembler accepts the
1029 -- instruction set. Note that the user can still override this
1030 -- (e.g., -mcpu=ultrasparc). GCC picks the "best" -mcpu flag
1031 -- regardless of the ordering.
1033 -- This is a temporary hack.
1034 ++ [ SysTools.Option "-mcpu=v9" ]
1036 ++ [ SysTools.Option "-c"
1037 , SysTools.FileOption "" input_fn
1038 , SysTools.Option "-o"
1039 , SysTools.FileOption "" output_fn
1042 return (StopLn, dflags, maybe_loc, output_fn)
1045 runPhase SplitAs _stop hsc_env _basename _suff _input_fn get_output_fn maybe_loc
1047 let dflags = hsc_dflags hsc_env
1048 output_fn <- get_output_fn dflags StopLn maybe_loc
1050 let base_o = dropExtension output_fn
1051 split_odir = base_o ++ "_split"
1052 osuf = objectSuf dflags
1054 createDirectoryHierarchy split_odir
1056 -- remove M_split/ *.o, because we're going to archive M_split/ *.o
1057 -- later and we don't want to pick up any old objects.
1058 fs <- getDirectoryContents split_odir
1059 mapM_ removeFile $ map (split_odir </>) $ filter (osuf `isSuffixOf`) fs
1061 let as_opts = getOpts dflags opt_a
1063 (split_s_prefix, n) <- readIORef v_Split_info
1065 let split_s n = split_s_prefix ++ "__" ++ show n <.> "s"
1066 split_obj n = split_odir </>
1067 takeFileName base_o ++ "__" ++ show n <.> osuf
1070 = SysTools.runAs dflags
1071 (map SysTools.Option as_opts ++
1072 [ SysTools.Option "-c"
1073 , SysTools.Option "-o"
1074 , SysTools.FileOption "" (split_obj n)
1075 , SysTools.FileOption "" (split_s n)
1078 mapM_ assemble_file [1..n]
1080 -- and join the split objects into a single object file:
1081 let ld_r args = SysTools.runLink dflags ([
1082 SysTools.Option "-nostdlib",
1083 SysTools.Option "-nodefaultlibs",
1084 SysTools.Option "-Wl,-r",
1085 SysTools.Option ld_x_flag,
1086 SysTools.Option "-o",
1087 SysTools.FileOption "" output_fn ] ++ args)
1088 ld_x_flag | null cLD_X = ""
1089 | otherwise = "-Wl,-x"
1091 if cLdIsGNULd == "YES"
1093 let script = split_odir </> "ld.script"
1095 "INPUT(" ++ unwords (map split_obj [1..n]) ++ ")"
1096 ld_r [SysTools.FileOption "" script]
1098 ld_r (map (SysTools.FileOption "" . split_obj) [1..n])
1100 return (StopLn, dflags, maybe_loc, output_fn)
1102 -- warning suppression
1103 runPhase other _stop _dflags _basename _suff _input_fn _get_output_fn _maybe_loc =
1104 panic ("runPhase: don't know how to run phase " ++ show other)
1105 -----------------------------------------------------------------------------
1106 -- MoveBinary sort-of-phase
1107 -- After having produced a binary, move it somewhere else and generate a
1108 -- wrapper script calling the binary. Currently, we need this only in
1109 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
1110 -- central directory.
1111 -- This is called from linkBinary below, after linking. I haven't made it
1112 -- a separate phase to minimise interfering with other modules, and
1113 -- we don't need the generality of a phase (MoveBinary is always
1114 -- done after linking and makes only sense in a parallel setup) -- HWL
1116 runPhase_MoveBinary :: DynFlags -> FilePath -> [PackageId] -> IO Bool
1117 runPhase_MoveBinary dflags input_fn dep_packages
1118 | WayPar `elem` (wayNames dflags) && not opt_Static =
1119 panic ("Don't know how to combine PVM wrapper and dynamic wrapper")
1120 | WayPar `elem` (wayNames dflags) = do
1121 let sysMan = pgm_sysman dflags
1122 pvm_root <- getEnv "PVM_ROOT"
1123 pvm_arch <- getEnv "PVM_ARCH"
1125 pvm_executable_base = "=" ++ input_fn
1126 pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
1127 -- nuke old binary; maybe use configur'ed names for cp and rm?
1128 tryIO (removeFile pvm_executable)
1129 -- move the newly created binary into PVM land
1130 copy dflags "copying PVM executable" input_fn pvm_executable
1131 -- generate a wrapper script for running a parallel prg under PVM
1132 writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
1135 case (dynLibLoader dflags) of
1138 let (o_base, o_ext) = splitExtension input_fn
1139 let wrapped_executable | o_ext == "exe" = (o_base ++ "_real") <.> o_ext
1140 | otherwise = input_fn ++ "_real"
1141 behaviour <- wrapper_behaviour dflags wrapmode dep_packages
1143 -- THINKME isn't this possible to do a bit nicer?
1144 let behaviour' = concatMap (\x -> if x=='\\' then "\\\\" else [x]) behaviour
1145 renameFile input_fn wrapped_executable
1146 let rtsDetails = (getPackageDetails (pkgState dflags) rtsPackageId);
1147 SysTools.runCc dflags
1148 ([ SysTools.FileOption "" ((head (libraryDirs rtsDetails)) ++ "/dyn-wrapper.c")
1149 , SysTools.Option ("-DBEHAVIOUR=\"" ++ behaviour' ++ "\"")
1150 , SysTools.Option "-o"
1151 , SysTools.FileOption "" input_fn
1152 ] ++ map (SysTools.FileOption "-I") (includeDirs rtsDetails))
1155 | otherwise = return True
1157 wrapper_behaviour :: DynFlags -> Maybe [Char] -> [PackageId] -> IO [Char]
1158 wrapper_behaviour dflags mode dep_packages =
1159 let seperateBySemiColon strs = tail $ concatMap (';':) strs
1162 pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1163 return ('H' : (seperateBySemiColon pkg_lib_paths))
1165 allpkg <- getPreloadPackagesAnd dflags dep_packages
1166 putStrLn (unwords (map (packageIdString . packageConfigId) allpkg))
1167 return $ 'F':s ++ ';':(seperateBySemiColon (map (packageIdString . packageConfigId) allpkg))
1169 -- generates a Perl skript starting a parallel prg under PVM
1170 mk_pvm_wrapper_script :: String -> String -> String -> String
1171 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
1173 "eval 'exec perl -S $0 ${1+\"$@\"}'",
1174 " if $running_under_some_shell;",
1175 "# =!=!=!=!=!=!=!=!=!=!=!",
1176 "# This script is automatically generated: DO NOT EDIT!!!",
1177 "# Generated by Glasgow Haskell Compiler",
1178 "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
1180 "$pvm_executable = '" ++ pvm_executable ++ "';",
1181 "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
1182 "$SysMan = '" ++ sysMan ++ "';",
1184 {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
1185 "# first, some magical shortcuts to run "commands" on the binary",
1186 "# (which is hidden)",
1187 "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
1188 " local($cmd) = $1;",
1189 " system("$cmd $pvm_executable");",
1190 " exit(0); # all done",
1193 "# Now, run the real binary; process the args first",
1194 "$ENV{'PE'} = $pvm_executable_base;", -- ++ pvm_executable_base,
1196 "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
1197 "@nonPVM_args = ();",
1198 "$in_RTS_args = 0;",
1200 "args: while ($a = shift(@ARGV)) {",
1201 " if ( $a eq '+RTS' ) {",
1202 " $in_RTS_args = 1;",
1203 " } elsif ( $a eq '-RTS' ) {",
1204 " $in_RTS_args = 0;",
1206 " if ( $a eq '-d' && $in_RTS_args ) {",
1208 " } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
1209 " $nprocessors = $1;",
1210 " } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
1211 " $nprocessors = $1;",
1213 " push(@nonPVM_args, $a);",
1217 "local($return_val) = 0;",
1218 "# Start the parallel execution by calling SysMan",
1219 "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
1220 "$return_val = $?;",
1221 "# ToDo: fix race condition moving files and flushing them!!",
1222 "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
1223 "exit($return_val);"
1226 -----------------------------------------------------------------------------
1227 -- Look for the /* GHC_PACKAGES ... */ comment at the top of a .hc file
1229 getHCFilePackages :: FilePath -> IO [PackageId]
1230 getHCFilePackages filename =
1231 Exception.bracket (openFile filename ReadMode) hClose $ \h -> do
1234 '/':'*':' ':'G':'H':'C':'_':'P':'A':'C':'K':'A':'G':'E':'S':rest ->
1235 return (map stringToPackageId (words rest))
1239 -----------------------------------------------------------------------------
1240 -- Static linking, of .o files
1242 -- The list of packages passed to link is the list of packages on
1243 -- which this program depends, as discovered by the compilation
1244 -- manager. It is combined with the list of packages that the user
1245 -- specifies on the command line with -package flags.
1247 -- In one-shot linking mode, we can't discover the package
1248 -- dependencies (because we haven't actually done any compilation or
1249 -- read any interface files), so the user must explicitly specify all
1252 linkBinary :: DynFlags -> [FilePath] -> [PackageId] -> IO ()
1253 linkBinary dflags o_files dep_packages = do
1254 let verb = getVerbFlag dflags
1255 output_fn = exeFileName dflags
1257 -- get the full list of packages to link with, by combining the
1258 -- explicit packages with the auto packages and all of their
1259 -- dependencies, and eliminating duplicates.
1261 pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1262 let pkg_lib_path_opts = concat (map get_pkg_lib_path_opts pkg_lib_paths)
1263 #ifdef linux_TARGET_OS
1264 get_pkg_lib_path_opts l | (dynLibLoader dflags)==SystemDependent && not opt_Static = ["-L" ++ l, "-Wl,-rpath", "-Wl," ++ l]
1265 | otherwise = ["-L" ++ l]
1267 get_pkg_lib_path_opts l = ["-L" ++ l]
1270 let lib_paths = libraryPaths dflags
1271 let lib_path_opts = map ("-L"++) lib_paths
1273 pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1275 #ifdef darwin_TARGET_OS
1276 pkg_framework_paths <- getPackageFrameworkPath dflags dep_packages
1277 let pkg_framework_path_opts = map ("-F"++) pkg_framework_paths
1279 let framework_paths = frameworkPaths dflags
1280 framework_path_opts = map ("-F"++) framework_paths
1282 pkg_frameworks <- getPackageFrameworks dflags dep_packages
1283 let pkg_framework_opts = concat [ ["-framework", fw] | fw <- pkg_frameworks ]
1285 let frameworks = cmdlineFrameworks dflags
1286 framework_opts = concat [ ["-framework", fw] | fw <- reverse frameworks ]
1287 -- reverse because they're added in reverse order from the cmd line
1289 #ifdef mingw32_TARGET_OS
1290 let dynMain = if not opt_Static then
1291 (head (libraryDirs (getPackageDetails (pkgState dflags) rtsPackageId))) ++ "/Main.dyn_o"
1295 -- probably _stub.o files
1296 extra_ld_inputs <- readIORef v_Ld_inputs
1298 -- opts from -optl-<blah> (including -l<blah> options)
1299 let extra_ld_opts = getOpts dflags opt_l
1301 let ways = wayNames dflags
1303 -- Here are some libs that need to be linked at the *end* of
1304 -- the command line, because they contain symbols that are referred to
1305 -- by the RTS. We can't therefore use the ordinary way opts for these.
1307 debug_opts | WayDebug `elem` ways = [
1308 #if defined(HAVE_LIBBFD)
1315 thread_opts | WayThreaded `elem` ways = [
1316 #if !defined(mingw32_TARGET_OS) && !defined(freebsd_TARGET_OS)
1319 #if defined(osf3_TARGET_OS)
1325 rc_objs <- maybeCreateManifest dflags output_fn
1327 let (md_c_flags, _) = machdepCCOpts dflags
1328 SysTools.runLink dflags (
1329 [ SysTools.Option verb
1330 , SysTools.Option "-o"
1331 , SysTools.FileOption "" output_fn
1333 ++ map SysTools.Option (
1336 #ifdef mingw32_TARGET_OS
1343 #ifdef darwin_TARGET_OS
1344 ++ framework_path_opts
1347 ++ pkg_lib_path_opts
1349 #ifdef darwin_TARGET_OS
1350 ++ pkg_framework_path_opts
1351 ++ pkg_framework_opts
1357 -- parallel only: move binary to another dir -- HWL
1358 success <- runPhase_MoveBinary dflags output_fn dep_packages
1359 if success then return ()
1360 else ghcError (InstallationError ("cannot move binary"))
1363 exeFileName :: DynFlags -> FilePath
1365 | Just s <- outputFile dflags =
1366 #if defined(mingw32_HOST_OS)
1367 if null (takeExtension s)
1374 #if defined(mingw32_HOST_OS)
1382 -> FilePath -- filename of executable
1383 -> IO [FilePath] -- extra objects to embed, maybe
1384 #ifndef mingw32_TARGET_OS
1385 maybeCreateManifest _ _ = do
1388 maybeCreateManifest dflags exe_filename = do
1389 if not (dopt Opt_GenManifest dflags) then return [] else do
1391 let manifest_filename = exe_filename <.> "manifest"
1393 writeFile manifest_filename $
1394 "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"++
1395 " <assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">\n"++
1396 " <assemblyIdentity version=\"1.0.0.0\"\n"++
1397 " processorArchitecture=\"X86\"\n"++
1398 " name=\"" ++ dropExtension exe_filename ++ "\"\n"++
1399 " type=\"win32\"/>\n\n"++
1400 " <trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v3\">\n"++
1402 " <requestedPrivileges>\n"++
1403 " <requestedExecutionLevel level=\"asInvoker\" uiAccess=\"false\"/>\n"++
1404 " </requestedPrivileges>\n"++
1409 -- Windows will find the manifest file if it is named foo.exe.manifest.
1410 -- However, for extra robustness, and so that we can move the binary around,
1411 -- we can embed the manifest in the binary itself using windres:
1412 if not (dopt Opt_EmbedManifest dflags) then return [] else do
1414 rc_filename <- newTempName dflags "rc"
1415 rc_obj_filename <- newTempName dflags (objectSuf dflags)
1417 writeFile rc_filename $
1418 "1 24 MOVEABLE PURE " ++ show manifest_filename ++ "\n"
1419 -- magic numbers :-)
1420 -- show is a bit hackish above, but we need to escape the
1421 -- backslashes in the path.
1423 let wr_opts = getOpts dflags opt_windres
1424 runWindres dflags $ map SysTools.Option $
1425 ["--input="++rc_filename,
1426 "--output="++rc_obj_filename,
1427 "--output-format=coff"]
1429 -- no FileOptions here: windres doesn't like seeing
1430 -- backslashes, apparently
1432 return [rc_obj_filename]
1436 linkDynLib :: DynFlags -> [String] -> [PackageId] -> IO ()
1437 linkDynLib dflags o_files dep_packages = do
1438 let verb = getVerbFlag dflags
1439 let o_file = outputFile dflags
1441 -- We don't want to link our dynamic libs against the RTS package,
1442 -- because the RTS lib comes in several flavours and we want to be
1443 -- able to pick the flavour when a binary is linked.
1444 pkgs <- getPreloadPackagesAnd dflags dep_packages
1445 let pkgs_no_rts = filter ((/= rtsPackageId) . packageConfigId) pkgs
1447 let pkg_lib_paths = collectLibraryPaths pkgs_no_rts
1448 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1450 let lib_paths = libraryPaths dflags
1451 let lib_path_opts = map ("-L"++) lib_paths
1453 let pkg_link_opts = collectLinkOpts dflags pkgs_no_rts
1455 -- probably _stub.o files
1456 extra_ld_inputs <- readIORef v_Ld_inputs
1458 let (md_c_flags, _) = machdepCCOpts dflags
1459 let extra_ld_opts = getOpts dflags opt_l
1460 #if defined(mingw32_HOST_OS)
1461 -----------------------------------------------------------------------------
1463 -----------------------------------------------------------------------------
1464 let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
1466 SysTools.runLink dflags
1467 ([ SysTools.Option verb
1468 , SysTools.Option "-o"
1469 , SysTools.FileOption "" output_fn
1470 , SysTools.Option "-shared"
1471 , SysTools.FileOption "-Wl,--out-implib=" (output_fn ++ ".a")
1473 ++ map (SysTools.FileOption "") o_files
1474 ++ map SysTools.Option (
1479 ++ pkg_lib_path_opts
1482 #elif defined(darwin_TARGET_OS)
1483 -----------------------------------------------------------------------------
1484 -- Making a darwin dylib
1485 -----------------------------------------------------------------------------
1486 -- About the options used for Darwin:
1488 -- Apple's way of saying -shared
1489 -- -undefined dynamic_lookup:
1490 -- Without these options, we'd have to specify the correct dependencies
1491 -- for each of the dylibs. Note that we could (and should) do without this
1492 -- for all libraries except the RTS; all we need to do is to pass the
1493 -- correct HSfoo_dyn.dylib files to the link command.
1494 -- This feature requires Mac OS X 10.3 or later; there is a similar feature,
1495 -- -flat_namespace -undefined suppress, which works on earlier versions,
1496 -- but it has other disadvantages.
1498 -- Build the dynamic library as a single "module", i.e. no dynamic binding
1499 -- nonsense when referring to symbols from within the library. The NCG
1500 -- assumes that this option is specified (on i386, at least).
1501 -- -Wl,-macosx_version_min -Wl,10.3
1502 -- Tell the linker its safe to assume that the library will run on 10.3 or
1503 -- later, so that it will not complain about the use of the option
1504 -- -undefined dynamic_lookup above.
1506 -- Causes the dynamic linker to ignore the DYLD_LIBRARY_PATH when loading
1507 -- this lib and instead look for it at its absolute path.
1508 -- When installing the .dylibs (see target.mk), we'll change that path to
1509 -- point to the place they are installed. Therefore, we won't have to set
1510 -- up DYLD_LIBRARY_PATH specifically for ghc.
1511 -----------------------------------------------------------------------------
1513 let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
1515 pwd <- getCurrentDirectory
1516 SysTools.runLink dflags
1517 ([ SysTools.Option verb
1518 , SysTools.Option "-dynamiclib"
1519 , SysTools.Option "-o"
1520 , SysTools.FileOption "" output_fn
1522 ++ map SysTools.Option (
1525 ++ [ "-undefined", "dynamic_lookup", "-single_module", "-Wl,-macosx_version_min","-Wl,10.3", "-install_name " ++ (pwd </> output_fn) ]
1529 ++ pkg_lib_path_opts
1533 -----------------------------------------------------------------------------
1535 -----------------------------------------------------------------------------
1537 let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
1539 SysTools.runLink dflags
1540 ([ SysTools.Option verb
1541 , SysTools.Option "-o"
1542 , SysTools.FileOption "" output_fn
1544 ++ map SysTools.Option (
1547 ++ [ "-shared", "-Wl,-Bsymbolic" ] -- we need symbolic linking to resolve non-PIC intra-package-relocations
1551 ++ pkg_lib_path_opts
1555 -- -----------------------------------------------------------------------------
1558 doCpp :: DynFlags -> Bool -> Bool -> FilePath -> FilePath -> IO ()
1559 doCpp dflags raw include_cc_opts input_fn output_fn = do
1560 let hscpp_opts = getOpts dflags opt_P
1561 let cmdline_include_paths = includePaths dflags
1563 pkg_include_dirs <- getPackageIncludePath dflags []
1564 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
1565 (cmdline_include_paths ++ pkg_include_dirs)
1567 let verb = getVerbFlag dflags
1570 | not include_cc_opts = []
1571 | otherwise = (optc ++ md_c_flags)
1573 optc = getOpts dflags opt_c
1574 (md_c_flags, _) = machdepCCOpts dflags
1576 let cpp_prog args | raw = SysTools.runCpp dflags args
1577 | otherwise = SysTools.runCc dflags (SysTools.Option "-E" : args)
1580 [ "-D" ++ HOST_OS ++ "_BUILD_OS=1",
1581 "-D" ++ HOST_ARCH ++ "_BUILD_ARCH=1",
1582 "-D" ++ TARGET_OS ++ "_HOST_OS=1",
1583 "-D" ++ TARGET_ARCH ++ "_HOST_ARCH=1" ]
1584 -- remember, in code we *compile*, the HOST is the same our TARGET,
1585 -- and BUILD is the same as our HOST.
1587 cpp_prog ([SysTools.Option verb]
1588 ++ map SysTools.Option include_paths
1589 ++ map SysTools.Option hsSourceCppOpts
1590 ++ map SysTools.Option hscpp_opts
1591 ++ map SysTools.Option cc_opts
1592 ++ map SysTools.Option target_defs
1593 ++ [ SysTools.Option "-x"
1594 , SysTools.Option "c"
1595 , SysTools.Option input_fn
1596 -- We hackily use Option instead of FileOption here, so that the file
1597 -- name is not back-slashed on Windows. cpp is capable of
1598 -- dealing with / in filenames, so it works fine. Furthermore
1599 -- if we put in backslashes, cpp outputs #line directives
1600 -- with *double* backslashes. And that in turn means that
1601 -- our error messages get double backslashes in them.
1602 -- In due course we should arrange that the lexer deals
1603 -- with these \\ escapes properly.
1604 , SysTools.Option "-o"
1605 , SysTools.FileOption "" output_fn
1608 cHaskell1Version :: String
1609 cHaskell1Version = "5" -- i.e., Haskell 98
1611 hsSourceCppOpts :: [String]
1612 -- Default CPP defines in Haskell source
1614 [ "-D__HASKELL1__="++cHaskell1Version
1615 , "-D__GLASGOW_HASKELL__="++cProjectVersionInt
1617 , "-D__CONCURRENT_HASKELL__"
1621 -- -----------------------------------------------------------------------------
1624 hscNextPhase :: DynFlags -> HscSource -> HscTarget -> Phase
1625 hscNextPhase _ HsBootFile _ = StopLn
1626 hscNextPhase dflags _ hsc_lang =
1629 HscAsm | dopt Opt_SplitObjs dflags -> SplitMangle
1631 HscNothing -> StopLn
1632 HscInterpreted -> StopLn
1636 hscMaybeAdjustTarget :: DynFlags -> Phase -> HscSource -> HscTarget -> HscTarget
1637 hscMaybeAdjustTarget dflags stop _ current_hsc_lang
1640 keep_hc = dopt Opt_KeepHcFiles dflags
1642 -- don't change the lang if we're interpreting
1643 | current_hsc_lang == HscInterpreted = current_hsc_lang
1645 -- force -fvia-C if we are being asked for a .hc file
1646 | HCc <- stop = HscC
1648 -- otherwise, stick to the plan
1649 | otherwise = current_hsc_lang
1651 GLOBAL_VAR(v_Split_info, ("",0), (String,Int))
1652 -- The split prefix and number of files