1 -----------------------------------------------------------------------------
5 -- (c) The University of Glasgow 2002
7 -----------------------------------------------------------------------------
9 #include "../includes/ghcconfig.h"
11 module DriverPipeline (
13 -- Interfaces for the batch-mode driver
14 compileFile, staticLink,
16 -- Interfaces for the compilation manager (interpreted/batch-mode)
18 compile, CompResult(..),
25 #include "HsVersions.h"
33 import SysTools ( newTempName, addFilesToClean, getSysMan, copy )
34 import qualified SysTools
43 import RdrName ( GlobalRdrEnv )
46 import StringBuffer ( hGetStringBuffer )
47 import BasicTypes ( SuccessFlag(..) )
48 import Maybes ( expectJust )
50 import ParserCoreUtils ( getCoreModuleName )
53 import DATA_IOREF ( readIORef, writeIORef )
62 -- ---------------------------------------------------------------------------
65 -- Just preprocess a file, put the result in a temp. file (used by the
66 -- compilation manager during the summary phase).
68 -- We return the augmented DynFlags, because they contain the result
69 -- of slurping in the OPTIONS pragmas
71 preprocess :: DynFlags -> FilePath -> IO (DynFlags, FilePath)
72 preprocess dflags filename =
73 ASSERT2(isHaskellSrcFilename filename, text filename)
74 runPipeline (StopBefore anyHsc) dflags ("preprocess")
75 False{-temporary output file-}
76 Nothing{-no specific output file-}
78 Nothing{-no ModLocation-}
82 -- ---------------------------------------------------------------------------
84 -- This is used in batch mode
85 compileFile :: GhcMode -> DynFlags -> FilePath -> IO FilePath
86 compileFile mode dflags src = do
87 exists <- doesFileExist src
89 throwDyn (CmdLineError ("file `" ++ src ++ "' does not exist"))
91 o_file <- readIORef v_Output_file
92 no_link <- readIORef v_NoLink -- Set by -c or -no-link
93 -- When linking, the -o argument refers to the linker's output.
94 -- otherwise, we use it as the name for the pipeline's output.
95 let maybe_o_file | no_link = o_file
98 stop_flag <- readIORef v_GhcModeFlag
99 (_, out_file) <- runPipeline mode dflags stop_flag True maybe_o_file
100 src Nothing{-no ModLocation-}
104 -- ---------------------------------------------------------------------------
107 -- Compile a single module, under the control of the compilation manager.
109 -- This is the interface between the compilation manager and the
110 -- compiler proper (hsc), where we deal with tedious details like
111 -- reading the OPTIONS pragma from the source file, and passing the
112 -- output of hsc through the C compiler.
114 -- The driver sits between 'compile' and 'hscMain', translating calls
115 -- to the former into calls to the latter, and results from the latter
116 -- into results from the former. It does things like preprocessing
117 -- the .hs file if necessary, and compiling up the .stub_c files to
118 -- generate Linkables.
120 -- NB. No old interface can also mean that the source has changed.
124 -> Bool -- True <=> source unchanged
125 -> Bool -- True <=> have object
126 -> Maybe ModIface -- Old interface, if available
130 = CompOK ModDetails -- New details
131 (Maybe GlobalRdrEnv) -- Lexical environment for the module
132 -- (Maybe because we may have loaded it from
133 -- its precompiled interface)
134 ModIface -- New iface
135 (Maybe Linkable) -- New code; Nothing => compilation was not reqd
136 -- (old code is still valid)
141 compile hsc_env mod_summary
142 source_unchanged have_object old_iface = do
144 let dyn_flags = hsc_dflags hsc_env
145 this_mod = ms_mod mod_summary
146 src_flavour = ms_hsc_src mod_summary
148 showPass dyn_flags ("Compiling " ++ showModMsg have_object mod_summary)
150 let verb = verbosity dyn_flags
151 let location = ms_location mod_summary
152 let input_fn = expectJust "compile:hs" (ml_hs_file location)
153 let input_fnpp = expectJust "compile:hspp" (ms_hspp_file mod_summary)
155 when (verb >= 2) (hPutStrLn stderr ("compile: input file " ++ input_fnpp))
157 -- Add in the OPTIONS from the source file
158 -- This is nasty: we've done this once already, in the compilation manager
159 -- It might be better to cache the flags in the ml_hspp_file field,say
160 opts <- getOptionsFromSource input_fnpp
161 (dyn_flags,unhandled_flags) <- processDynamicFlags opts dyn_flags
162 checkProcessArgsResult unhandled_flags input_fn
164 let (basename, _) = splitFilename input_fn
166 -- We add the directory in which the .hs files resides) to the import path.
167 -- This is needed when we try to compile the .hc file later, if it
168 -- imports a _stub.h file that we created here.
169 let current_dir = directoryOf basename
170 old_paths <- readIORef v_Include_paths
171 writeIORef v_Include_paths (current_dir : old_paths)
172 -- put back the old include paths afterward.
173 later (writeIORef v_Include_paths old_paths) $ do
175 -- Figure out what lang we're generating
176 todo <- readIORef v_GhcMode
177 hsc_lang <- hscMaybeAdjustTarget todo src_flavour (hscTarget dyn_flags)
178 -- ... and what the next phase should be
179 next_phase <- hscNextPhase src_flavour hsc_lang
180 -- ... and what file to generate the output into
181 get_output_fn <- genOutputFilenameFunc next_phase False Nothing basename
182 output_fn <- get_output_fn next_phase (Just location)
184 let dyn_flags' = dyn_flags { hscTarget = hsc_lang,
185 hscOutName = output_fn,
186 hscStubCOutName = basename ++ "_stub.c",
187 hscStubHOutName = basename ++ "_stub.h",
188 extCoreName = basename ++ ".hcr" }
190 -- -no-recomp should also work with --make
191 let do_recomp = recompFlag dyn_flags
192 source_unchanged' = source_unchanged && do_recomp
193 hsc_env' = hsc_env { hsc_dflags = dyn_flags' }
196 hsc_result <- hscMain hsc_env' printErrorsAndWarnings mod_summary
197 source_unchanged' have_object old_iface
200 HscFail -> return CompErrs
202 HscNoRecomp details iface -> return (CompOK details Nothing iface Nothing)
204 HscRecomp details rdr_env iface
205 stub_h_exists stub_c_exists maybe_interpreted_code
207 | isHsBoot src_flavour -- No further compilation to do
208 -> return (CompOK details rdr_env iface Nothing)
210 | otherwise -- Normal Haskell source files
213 maybe_stub_o <- compileStub dyn_flags' stub_c_exists
214 let stub_unlinked = case maybe_stub_o of
216 Just stub_o -> [ DotO stub_o ]
218 (hs_unlinked, unlinked_time) <-
221 -- in interpreted mode, just return the compiled code
222 -- as our "unlinked" object.
224 case maybe_interpreted_code of
226 Just comp_bc -> return ([BCOs comp_bc], ms_hs_date mod_summary)
227 -- Why do we use the timestamp of the source file here,
228 -- rather than the current time? This works better in
229 -- the case where the local clock is out of sync
230 -- with the filesystem's clock. It's just as accurate:
231 -- if the source is modified, then the linkable will
234 Nothing -> panic "compile: no interpreted code"
236 -- we're in batch mode: finish the compilation pipeline.
238 let object_filename = ml_obj_file location
240 runPipeline DoLink dyn_flags ""
241 True Nothing output_fn (Just location)
242 -- the object filename comes from the ModLocation
244 o_time <- getModificationTime object_filename
245 return ([DotO object_filename], o_time)
247 let linkable = LM unlinked_time this_mod
248 (hs_unlinked ++ stub_unlinked)
250 return (CompOK details rdr_env iface (Just linkable))
252 -----------------------------------------------------------------------------
253 -- stub .h and .c files (for foreign export support)
255 compileStub dflags stub_c_exists
256 | not stub_c_exists = return Nothing
258 -- compile the _stub.c file w/ gcc
259 let stub_c = hscStubCOutName dflags
260 (_, stub_o) <- runPipeline DoLink dflags "stub-compile"
261 True{-persistent output-}
262 Nothing{-no specific output file-}
264 Nothing{-no ModLocation-}
268 -- ---------------------------------------------------------------------------
271 link :: GhciMode -- interactive or batch
272 -> DynFlags -- dynamic flags
273 -> Bool -- attempt linking in batch mode?
274 -> HomePackageTable -- what to link
277 -- For the moment, in the batch linker, we don't bother to tell doLink
278 -- which packages to link -- it just tries all that are available.
279 -- batch_attempt_linking should only be *looked at* in batch mode. It
280 -- should only be True if the upsweep was successful and someone
281 -- exports main, i.e., we have good reason to believe that linking
285 link Interactive dflags batch_attempt_linking hpt
286 = do -- Not Linking...(demand linker will do the job)
290 link Batch dflags batch_attempt_linking hpt
291 | batch_attempt_linking
294 home_mod_infos = moduleEnvElts hpt
296 -- the packages we depend on
297 pkg_deps = concatMap (dep_pkgs . mi_deps . hm_iface) home_mod_infos
299 -- the linkables to link
300 linkables = map hm_linkable home_mod_infos
302 when (verb >= 3) $ do
303 hPutStrLn stderr "link: linkables are ..."
304 hPutStrLn stderr (showSDoc (vcat (map ppr linkables)))
306 -- check for the -no-link flag
307 omit_linking <- readIORef v_NoLink
309 then do when (verb >= 3) $
310 hPutStrLn stderr "link(batch): linking omitted (-c flag given)."
315 hPutStrLn stderr "Linking ..."
317 let getOfiles (LM _ _ us) = map nameOfObject (filter isObject us)
318 obj_files = concatMap getOfiles linkables
320 -- Don't showPass in Batch mode; doLink will do that for us.
321 staticLink dflags obj_files pkg_deps
323 when (verb >= 3) (hPutStrLn stderr "link: done")
325 -- staticLink only returns if it succeeds
329 = do when (verb >= 3) $ do
330 hPutStrLn stderr "link(batch): upsweep (partially) failed OR"
331 hPutStrLn stderr " Main.main not exported; not linking."
334 verb = verbosity dflags
336 -- ---------------------------------------------------------------------------
337 -- Run a compilation pipeline, consisting of multiple phases.
339 -- The DynFlags can be modified by phases in the pipeline (eg. by
340 -- OPTIONS pragmas), and the changes affect later phases in the
341 -- pipeline, but we throw away the resulting DynFlags at the end.
344 :: GhcMode -- when to stop
345 -> DynFlags -- dynamic flags
346 -> String -- "stop after" flag
347 -> Bool -- final output is persistent?
348 -> Maybe FilePath -- where to put the output, optionally
349 -> FilePath -- input filename
350 -> Maybe ModLocation -- a ModLocation for this module, if we have one
351 -> IO (DynFlags, FilePath) -- (final flags, output filename)
353 runPipeline todo dflags stop_flag keep_output
354 maybe_output_filename input_fn maybe_loc
356 split <- readIORef v_Split_object_files
357 let (basename, suffix) = splitFilename input_fn
358 start_phase = startPhase suffix
361 StopBefore As | split -> StopBefore SplitAs
364 -- We want to catch cases of "you can't get there from here" before
365 -- we start the pipeline, because otherwise it will just run off the
368 -- There is a partial ordering on phases, where A < B iff A occurs
369 -- before B in a normal compilation pipeline.
371 let stop_phase = case todo' of
372 StopBefore phase -> phase
375 when (not (start_phase `happensBefore` stop_phase)) $
377 ("flag `" ++ stop_flag
378 ++ "' is incompatible with source file `"
381 -- generate a function which will be used to calculate output file names
383 get_output_fn <- genOutputFilenameFunc stop_phase keep_output
384 maybe_output_filename basename
386 -- Execute the pipeline...
387 (dflags', output_fn, maybe_loc) <- pipeLoop todo' dflags start_phase stop_phase input_fn
388 basename suffix get_output_fn maybe_loc
390 -- Sometimes, a compilation phase doesn't actually generate any output
391 -- (eg. the CPP phase when -fcpp is not turned on). If we end on this
392 -- stage, but we wanted to keep the output, then we have to explicitly
395 then do final_fn <- get_output_fn stop_phase maybe_loc
396 when (final_fn /= output_fn) $
397 copy dflags ("Copying `" ++ output_fn ++ "' to `" ++ final_fn
398 ++ "'") output_fn final_fn
399 return (dflags', final_fn)
401 return (dflags', output_fn)
404 pipeLoop :: GhcMode -> DynFlags -> Phase -> Phase
405 -> FilePath -> String -> Suffix
406 -> (Phase -> Maybe ModLocation -> IO FilePath)
408 -> IO (DynFlags, FilePath, Maybe ModLocation)
410 pipeLoop orig_todo dflags phase stop_phase
411 input_fn orig_basename orig_suff
412 orig_get_output_fn maybe_loc
414 | phase `eqPhase` stop_phase -- All done
415 = return (dflags, input_fn, maybe_loc)
417 | not (phase `happensBefore` stop_phase)
418 -- Something has gone wrong. We'll try to cover all the cases when
419 -- this could happen, so if we reach here it is a panic.
420 -- eg. it might happen if the -C flag is used on a source file that
421 -- has {-# OPTIONS -fasm #-}.
422 = panic ("pipeLoop: at phase " ++ show phase ++
423 " but I wanted to stop at phase " ++ show stop_phase)
426 = do { (next_phase, dflags', maybe_loc, output_fn)
427 <- runPhase phase orig_todo dflags orig_basename
428 orig_suff input_fn orig_get_output_fn maybe_loc
429 ; pipeLoop orig_todo dflags' next_phase stop_phase output_fn
430 orig_basename orig_suff orig_get_output_fn maybe_loc }
432 genOutputFilenameFunc :: Phase -> Bool -> Maybe FilePath -> String
433 -> IO (Phase{-next phase-} -> Maybe ModLocation -> IO FilePath)
434 genOutputFilenameFunc stop_phase keep_final_output maybe_output_filename basename
436 hcsuf <- readIORef v_HC_suf
437 odir <- readIORef v_Output_dir
438 osuf <- readIORef v_Object_suf
439 keep_hc <- readIORef v_Keep_hc_files
441 keep_il <- readIORef v_Keep_il_files
442 keep_ilx <- readIORef v_Keep_ilx_files
444 keep_raw_s <- readIORef v_Keep_raw_s_files
445 keep_s <- readIORef v_Keep_s_files
447 myPhaseInputExt HCc = hcsuf
448 myPhaseInputExt StopLn = osuf
449 myPhaseInputExt other = phaseInputExt other
451 func next_phase maybe_location
452 | is_last_phase, Just f <- maybe_output_filename = return f
453 | is_last_phase && keep_final_output = persistent_fn
454 | keep_this_output = persistent_fn
455 | otherwise = newTempName suffix
458 is_last_phase = next_phase `eqPhase` stop_phase
460 -- sometimes, we keep output from intermediate stages
464 Mangle | keep_raw_s -> True
466 HCc | keep_hc -> True
469 suffix = myPhaseInputExt next_phase
471 -- persistent object files get put in odir
473 | StopLn <- next_phase = return odir_persistent
474 | otherwise = return persistent
476 persistent = basename ++ '.':suffix
479 | Just loc <- maybe_location = ml_obj_file loc
480 | Just d <- odir = replaceFilenameDirectory persistent d
481 | otherwise = persistent
486 -- -----------------------------------------------------------------------------
487 -- Each phase in the pipeline returns the next phase to execute, and the
488 -- name of the file in which the output was placed.
490 -- We must do things dynamically this way, because we often don't know
491 -- what the rest of the phases will be until part-way through the
492 -- compilation: for example, an {-# OPTIONS -fasm #-} at the beginning
493 -- of a source file can change the latter stages of the pipeline from
494 -- taking the via-C route to using the native code generator.
499 -> String -- basename of original input source
500 -> String -- its extension
501 -> FilePath -- name of file which contains the input to this phase.
502 -> (Phase -> Maybe ModLocation -> IO FilePath)
503 -- how to calculate the output filename
504 -> Maybe ModLocation -- the ModLocation, if we have one
505 -> IO (Phase, -- next phase
506 DynFlags, -- new dynamic flags
507 Maybe ModLocation, -- the ModLocation, if we have one
508 FilePath) -- output filename
510 -- Invariant: the output filename always contains the output
511 -- Interesting case: Hsc when there is no recompilation to do
512 -- Then the output filename is still a .o file
514 -------------------------------------------------------------------------------
517 runPhase (Unlit sf) _todo dflags _basename _suff input_fn get_output_fn maybe_loc
518 = do let unlit_flags = getOpts dflags opt_L
519 -- The -h option passes the file name for unlit to put in a #line directive
520 output_fn <- get_output_fn (Cpp sf) maybe_loc
522 SysTools.runUnlit dflags
523 (map SysTools.Option unlit_flags ++
524 [ SysTools.Option "-h"
525 , SysTools.Option input_fn
526 , SysTools.FileOption "" input_fn
527 , SysTools.FileOption "" output_fn
530 return (Cpp sf, dflags, maybe_loc, output_fn)
532 -------------------------------------------------------------------------------
533 -- Cpp phase : (a) gets OPTIONS out of file
534 -- (b) runs cpp if necessary
536 runPhase (Cpp sf) _todo dflags basename suff input_fn get_output_fn maybe_loc
537 = do src_opts <- getOptionsFromSource input_fn
538 (dflags,unhandled_flags) <- processDynamicFlags src_opts dflags
539 checkProcessArgsResult unhandled_flags (basename++'.':suff)
541 if not (cppFlag dflags) then
542 -- no need to preprocess CPP, just pass input file along
543 -- to the next phase of the pipeline.
544 return (HsPp sf, dflags, maybe_loc, input_fn)
546 output_fn <- get_output_fn (HsPp sf) maybe_loc
547 doCpp dflags True{-raw-} False{-no CC opts-} input_fn output_fn
548 return (HsPp sf, dflags, maybe_loc, output_fn)
550 -------------------------------------------------------------------------------
553 runPhase (HsPp sf) _todo dflags basename suff input_fn get_output_fn maybe_loc
554 = do if not (ppFlag dflags) then
555 -- no need to preprocess, just pass input file along
556 -- to the next phase of the pipeline.
557 return (Hsc sf, dflags, maybe_loc, input_fn)
559 let hspp_opts = getOpts dflags opt_F
560 hs_src_pp_opts <- readIORef v_Hs_source_pp_opts
561 let orig_fn = basename ++ '.':suff
562 output_fn <- get_output_fn (Hsc sf) maybe_loc
563 SysTools.runPp dflags
564 ( [ SysTools.Option orig_fn
565 , SysTools.Option input_fn
566 , SysTools.FileOption "" output_fn
568 map SysTools.Option hs_src_pp_opts ++
569 map SysTools.Option hspp_opts
571 return (Hsc sf, dflags, maybe_loc, output_fn)
573 -----------------------------------------------------------------------------
576 -- Compilation of a single module, in "legacy" mode (_not_ under
577 -- the direction of the compilation manager).
578 runPhase (Hsc src_flavour) todo dflags basename suff input_fn get_output_fn _maybe_loc
579 = do -- normal Hsc mode, not mkdependHS
581 -- we add the current directory (i.e. the directory in which
582 -- the .hs files resides) to the import path, since this is
583 -- what gcc does, and it's probably what you want.
584 let current_dir = directoryOf basename
586 paths <- readIORef v_Include_paths
587 writeIORef v_Include_paths (current_dir : paths)
589 -- gather the imports and module name
590 (hspp_buf,mod_name) <-
592 ExtCoreFile -> do { -- no explicit imports in ExtCore input.
593 ; m <- getCoreModuleName input_fn
594 ; return (Nothing, mkModule m) }
596 other -> do { buf <- hGetStringBuffer input_fn
597 ; (_,_,mod_name) <- getImports dflags buf input_fn
598 ; return (Just buf, mod_name) }
600 -- Build a ModLocation to pass to hscMain.
601 -- The source filename is rather irrelevant by now, but it's used
602 -- by hscMain for messages. hscMain also needs
603 -- the .hi and .o filenames, and this is as good a way
604 -- as any to generate them, and better than most. (e.g. takes
605 -- into accout the -osuf flags)
606 location1 <- mkHomeModLocation2 mod_name basename suff
608 -- Boot-ify it if necessary
609 let location2 | isHsBoot src_flavour = addBootSuffixLocn location1
610 | otherwise = location1
613 -- Take -ohi into account if present
614 -- This can't be done in mkHomeModuleLocation because
615 -- it only applies to the module being compiles
616 ohi <- readIORef v_Output_hi
617 let location3 | Just fn <- ohi = location2{ ml_hi_file = fn }
618 | otherwise = location2
620 -- Take -o into account if present
621 -- Very like -ohi, but we must *only* do this if we aren't linking
622 -- (If we're linking then the -o applies to the linked thing, not to
623 -- the object file for one module.)
624 -- Note the nasty duplication with the same computation in compileFile above
625 expl_o_file <- readIORef v_Output_file
626 no_link <- readIORef v_NoLink
627 let location4 | Just ofile <- expl_o_file, no_link
628 = location3 { ml_obj_file = ofile }
629 | otherwise = location3
631 -- Tell the finder cache about this module
632 addHomeModuleToFinder mod_name location4
634 -- Make the ModSummary to hand to hscMain
635 src_timestamp <- getModificationTime (basename ++ '.':suff)
637 unused_field = panic "runPhase:ModSummary field"
638 -- Some fields are not looked at by hscMain
639 mod_summary = ModSummary { ms_mod = mod_name,
640 ms_hsc_src = src_flavour,
641 ms_hspp_file = Just input_fn,
642 ms_hspp_buf = hspp_buf,
643 ms_location = location4,
644 ms_hs_date = src_timestamp,
645 ms_imps = unused_field,
646 ms_srcimps = unused_field }
648 o_file = ml_obj_file location4 -- The real object file
651 -- Figure out if the source has changed, for recompilation avoidance.
652 -- only do this if we're eventually going to generate a .o file.
653 -- (ToDo: do when generating .hc files too?)
655 -- Setting source_unchanged to True means that M.o seems
656 -- to be up to date wrt M.hs; so no need to recompile unless imports have
657 -- changed (which the compiler itself figures out).
658 -- Setting source_unchanged to False tells the compiler that M.o is out of
659 -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
660 let do_recomp = recompFlag dflags
662 if not (do_recomp && case todo of { DoLink -> True; other -> False })
664 else do o_file_exists <- doesFileExist o_file
666 then return False -- Need to recompile
667 else do t2 <- getModificationTime o_file
668 if t2 > src_timestamp
673 hsc_lang <- hscMaybeAdjustTarget todo src_flavour (hscTarget dflags)
674 next_phase <- hscNextPhase src_flavour hsc_lang
675 output_fn <- get_output_fn next_phase (Just location4)
677 let dflags' = dflags { hscTarget = hsc_lang,
678 hscOutName = output_fn,
679 hscStubCOutName = basename ++ "_stub.c",
680 hscStubHOutName = basename ++ "_stub.h",
681 extCoreName = basename ++ ".hcr" }
683 hsc_env <- newHscEnv OneShot dflags'
686 result <- hscMain hsc_env printErrorsAndWarnings
687 mod_summary source_unchanged
688 False -- No object file
693 HscFail -> throwDyn (PhaseFailed "hsc" (ExitFailure 1))
695 HscNoRecomp details iface -> do
696 SysTools.touch dflags' "Touching object file" o_file
697 return (StopLn, dflags', Just location4, o_file)
699 HscRecomp _details _rdr_env _iface
700 stub_h_exists stub_c_exists
701 _maybe_interpreted_code -> do
704 maybe_stub_o <- compileStub dflags' stub_c_exists
707 Just stub_o -> add v_Ld_inputs stub_o
709 -- In the case of hs-boot files, generate a dummy .o-boot
710 -- stamp file for the benefit of Make
712 HsBootFile -> SysTools.touch dflags' "Touching object file" o_file
715 return (next_phase, dflags', Just location4, output_fn)
717 -----------------------------------------------------------------------------
720 runPhase CmmCpp todo dflags basename suff input_fn get_output_fn maybe_loc
722 output_fn <- get_output_fn Cmm maybe_loc
723 doCpp dflags False{-not raw-} True{-include CC opts-} input_fn output_fn
724 return (Cmm, dflags, maybe_loc, output_fn)
726 runPhase Cmm todo dflags basename suff input_fn get_output_fn maybe_loc
728 hsc_lang <- hscMaybeAdjustTarget todo HsSrcFile (hscTarget dflags)
729 next_phase <- hscNextPhase HsSrcFile hsc_lang
730 output_fn <- get_output_fn next_phase maybe_loc
732 let dflags' = dflags { hscTarget = hsc_lang,
733 hscOutName = output_fn,
734 hscStubCOutName = basename ++ "_stub.c",
735 hscStubHOutName = basename ++ "_stub.h",
736 extCoreName = basename ++ ".hcr" }
738 ok <- hscCmmFile dflags' input_fn
740 when (not ok) $ throwDyn (PhaseFailed "cmm" (ExitFailure 1))
742 return (next_phase, dflags, maybe_loc, output_fn)
744 -----------------------------------------------------------------------------
747 -- we don't support preprocessing .c files (with -E) now. Doing so introduces
748 -- way too many hacks, and I can't say I've ever used it anyway.
750 runPhase cc_phase todo dflags basename suff input_fn get_output_fn maybe_loc
751 | cc_phase `eqPhase` Cc || cc_phase `eqPhase` HCc
752 = do let cc_opts = getOpts dflags opt_c
753 hcc = cc_phase `eqPhase` HCc
755 cmdline_include_paths <- readIORef v_Include_paths
757 -- HC files have the dependent packages stamped into them
758 pkgs <- if hcc then getHCFilePackages input_fn else return []
760 -- add package include paths even if we're just compiling .c
761 -- files; this is the Value Add(TM) that using ghc instead of
763 pkg_include_dirs <- getPackageIncludePath dflags pkgs
764 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
765 (cmdline_include_paths ++ pkg_include_dirs)
767 (md_c_flags, md_regd_c_flags) <- machdepCCOpts dflags
768 pic_c_flags <- picCCOpts dflags
770 let verb = getVerbFlag dflags
772 pkg_extra_cc_opts <- getPackageExtraCcOpts dflags pkgs
774 split_objs <- readIORef v_Split_object_files
775 let split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
778 excessPrecision <- readIORef v_Excess_precision
781 mangle <- readIORef v_Do_asm_mangling
783 | hcc && mangle = Mangle
785 output_fn <- get_output_fn next_phase maybe_loc
787 -- force the C compiler to interpret this file as C when
788 -- compiling .hc files, by adding the -x c option.
789 let langopt | hcc = [ SysTools.Option "-x", SysTools.Option "c"]
792 SysTools.runCc dflags (langopt ++
793 [ SysTools.FileOption "" input_fn
794 , SysTools.Option "-o"
795 , SysTools.FileOption "" output_fn
797 ++ map SysTools.Option (
803 ++ [ verb, "-S", "-Wimplicit", "-O" ]
804 ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
807 ++ (if excessPrecision then [] else [ "-ffloat-store" ])
812 return (next_phase, dflags, maybe_loc, output_fn)
814 -- ToDo: postprocess the output from gcc
816 -----------------------------------------------------------------------------
819 runPhase Mangle todo dflags _basename _suff input_fn get_output_fn maybe_loc
820 = do let mangler_opts = getOpts dflags opt_m
823 machdep_opts <- return [ show (stolen_x86_regs dflags) ]
825 machdep_opts <- return []
828 split <- readIORef v_Split_object_files
830 | split = SplitMangle
832 output_fn <- get_output_fn next_phase maybe_loc
834 SysTools.runMangle dflags (map SysTools.Option mangler_opts
835 ++ [ SysTools.FileOption "" input_fn
836 , SysTools.FileOption "" output_fn
838 ++ map SysTools.Option machdep_opts)
840 return (next_phase, dflags, maybe_loc, output_fn)
842 -----------------------------------------------------------------------------
845 runPhase SplitMangle todo dflags _basename _suff input_fn get_output_fn maybe_loc
846 = do -- tmp_pfx is the prefix used for the split .s files
847 -- We also use it as the file to contain the no. of split .s files (sigh)
848 split_s_prefix <- SysTools.newTempName "split"
849 let n_files_fn = split_s_prefix
851 SysTools.runSplit dflags
852 [ SysTools.FileOption "" input_fn
853 , SysTools.FileOption "" split_s_prefix
854 , SysTools.FileOption "" n_files_fn
857 -- Save the number of split files for future references
858 s <- readFile n_files_fn
859 let n_files = read s :: Int
860 writeIORef v_Split_info (split_s_prefix, n_files)
862 -- Remember to delete all these files
863 addFilesToClean [ split_s_prefix ++ "__" ++ show n ++ ".s"
866 return (SplitAs, dflags, maybe_loc, "**splitmangle**")
867 -- we don't use the filename
869 -----------------------------------------------------------------------------
872 runPhase As todo dflags _basename _suff input_fn get_output_fn maybe_loc
873 = do let as_opts = getOpts dflags opt_a
874 cmdline_include_paths <- readIORef v_Include_paths
876 output_fn <- get_output_fn StopLn maybe_loc
878 -- we create directories for the object file, because it
879 -- might be a hierarchical module.
880 createDirectoryHierarchy (directoryOf output_fn)
882 SysTools.runAs dflags
883 (map SysTools.Option as_opts
884 ++ [ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ]
885 ++ [ SysTools.Option "-c"
886 , SysTools.FileOption "" input_fn
887 , SysTools.Option "-o"
888 , SysTools.FileOption "" output_fn
891 return (StopLn, dflags, maybe_loc, output_fn)
894 runPhase SplitAs todo dflags basename _suff _input_fn get_output_fn maybe_loc
895 = do let as_opts = getOpts dflags opt_a
897 (split_s_prefix, n) <- readIORef v_Split_info
899 odir <- readIORef v_Output_dir
900 let real_odir = case odir of
901 Nothing -> basename ++ "_split"
905 = do let input_s = split_s_prefix ++ "__" ++ show n ++ ".s"
906 let output_o = replaceFilenameDirectory
907 (basename ++ "__" ++ show n ++ ".o")
909 real_o <- osuf_ify output_o
910 SysTools.runAs dflags
911 (map SysTools.Option as_opts ++
912 [ SysTools.Option "-c"
913 , SysTools.Option "-o"
914 , SysTools.FileOption "" real_o
915 , SysTools.FileOption "" input_s
918 mapM_ assemble_file [1..n]
920 output_fn <- get_output_fn StopLn maybe_loc
921 return (StopLn, dflags, maybe_loc, output_fn)
924 -----------------------------------------------------------------------------
926 -- Run ilx2il over the ILX output, getting an IL file
928 runPhase Ilx2Il todo dflags _basename _suff input_fn get_output_fn maybe_loc
929 = do let ilx2il_opts = getOpts dflags opt_I
930 SysTools.runIlx2il (map SysTools.Option ilx2il_opts
931 ++ [ SysTools.Option "--no-add-suffix-to-assembly",
932 SysTools.Option "mscorlib",
933 SysTools.Option "-o",
934 SysTools.FileOption "" output_fn,
935 SysTools.FileOption "" input_fn ])
938 -----------------------------------------------------------------------------
940 -- Run ilasm over the IL, getting a DLL
942 runPhase Ilasm todo dflags _basename _suff input_fn get_output_fn maybe_loc
943 = do let ilasm_opts = getOpts dflags opt_i
944 SysTools.runIlasm (map SysTools.Option ilasm_opts
945 ++ [ SysTools.Option "/QUIET",
946 SysTools.Option "/DLL",
947 SysTools.FileOption "/OUT=" output_fn,
948 SysTools.FileOption "" input_fn ])
953 -----------------------------------------------------------------------------
954 -- MoveBinary sort-of-phase
955 -- After having produced a binary, move it somewhere else and generate a
956 -- wrapper script calling the binary. Currently, we need this only in
957 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
958 -- central directory.
959 -- This is called from staticLink below, after linking. I haven't made it
960 -- a separate phase to minimise interfering with other modules, and
961 -- we don't need the generality of a phase (MoveBinary is always
962 -- done after linking and makes only sense in a parallel setup) -- HWL
964 runPhase_MoveBinary input_fn
967 pvm_root <- getEnv "PVM_ROOT"
968 pvm_arch <- getEnv "PVM_ARCH"
970 pvm_executable_base = "=" ++ input_fn
971 pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
972 -- nuke old binary; maybe use configur'ed names for cp and rm?
973 system ("rm -f " ++ pvm_executable)
974 -- move the newly created binary into PVM land
975 system ("cp -p " ++ input_fn ++ " " ++ pvm_executable)
976 -- generate a wrapper script for running a parallel prg under PVM
977 writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
980 -- generates a Perl skript starting a parallel prg under PVM
981 mk_pvm_wrapper_script :: String -> String -> String -> String
982 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
984 "eval 'exec perl -S $0 ${1+\"$@\"}'",
985 " if $running_under_some_shell;",
986 "# =!=!=!=!=!=!=!=!=!=!=!",
987 "# This script is automatically generated: DO NOT EDIT!!!",
988 "# Generated by Glasgow Haskell Compiler",
989 "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
991 "$pvm_executable = '" ++ pvm_executable ++ "';",
992 "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
993 "$SysMan = '" ++ sysMan ++ "';",
995 {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
996 "# first, some magical shortcuts to run "commands" on the binary",
997 "# (which is hidden)",
998 "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
999 " local($cmd) = $1;",
1000 " system("$cmd $pvm_executable");",
1001 " exit(0); # all done",
1004 "# Now, run the real binary; process the args first",
1005 "$ENV{'PE'} = $pvm_executable_base;", -- ++ pvm_executable_base,
1007 "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
1008 "@nonPVM_args = ();",
1009 "$in_RTS_args = 0;",
1011 "args: while ($a = shift(@ARGV)) {",
1012 " if ( $a eq '+RTS' ) {",
1013 " $in_RTS_args = 1;",
1014 " } elsif ( $a eq '-RTS' ) {",
1015 " $in_RTS_args = 0;",
1017 " if ( $a eq '-d' && $in_RTS_args ) {",
1019 " } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
1020 " $nprocessors = $1;",
1021 " } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
1022 " $nprocessors = $1;",
1024 " push(@nonPVM_args, $a);",
1028 "local($return_val) = 0;",
1029 "# Start the parallel execution by calling SysMan",
1030 "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
1031 "$return_val = $?;",
1032 "# ToDo: fix race condition moving files and flushing them!!",
1033 "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
1034 "exit($return_val);"
1037 -----------------------------------------------------------------------------
1038 -- Complain about non-dynamic flags in OPTIONS pragmas
1040 checkProcessArgsResult flags filename
1041 = do when (notNull flags) (throwDyn (ProgramError (
1042 showSDoc (hang (text filename <> char ':')
1043 4 (text "unknown flags in {-# OPTIONS #-} pragma:" <+>
1044 hsep (map text flags)))
1047 -----------------------------------------------------------------------------
1048 -- Look for the /* GHC_PACKAGES ... */ comment at the top of a .hc file
1050 getHCFilePackages :: FilePath -> IO [PackageId]
1051 getHCFilePackages filename =
1052 EXCEPTION.bracket (openFile filename ReadMode) hClose $ \h -> do
1055 '/':'*':' ':'G':'H':'C':'_':'P':'A':'C':'K':'A':'G':'E':'S':rest ->
1056 return (map stringToPackageId (words rest))
1060 -----------------------------------------------------------------------------
1061 -- Static linking, of .o files
1063 -- The list of packages passed to link is the list of packages on
1064 -- which this program depends, as discovered by the compilation
1065 -- manager. It is combined with the list of packages that the user
1066 -- specifies on the command line with -package flags.
1068 -- In one-shot linking mode, we can't discover the package
1069 -- dependencies (because we haven't actually done any compilation or
1070 -- read any interface files), so the user must explicitly specify all
1073 staticLink :: DynFlags -> [FilePath] -> [PackageId] -> IO ()
1074 staticLink dflags o_files dep_packages = do
1075 let verb = getVerbFlag dflags
1076 static <- readIORef v_Static
1077 no_hs_main <- readIORef v_NoHsMain
1079 -- get the full list of packages to link with, by combining the
1080 -- explicit packages with the auto packages and all of their
1081 -- dependencies, and eliminating duplicates.
1083 o_file <- readIORef v_Output_file
1084 #if defined(mingw32_HOST_OS)
1085 let output_fn = case o_file of { Just s -> s; Nothing -> "main.exe"; }
1087 let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
1090 pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1091 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1093 lib_paths <- readIORef v_Library_paths
1094 let lib_path_opts = map ("-L"++) lib_paths
1096 pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1098 #ifdef darwin_TARGET_OS
1099 pkg_framework_paths <- getPackageFrameworkPath dflags dep_packages
1100 let pkg_framework_path_opts = map ("-F"++) pkg_framework_paths
1102 framework_paths <- readIORef v_Framework_paths
1103 let framework_path_opts = map ("-F"++) framework_paths
1105 pkg_frameworks <- getPackageFrameworks dflags dep_packages
1106 let pkg_framework_opts = concat [ ["-framework", fw] | fw <- pkg_frameworks ]
1107 frameworks <- readIORef v_Cmdline_frameworks
1108 let framework_opts = concat [ ["-framework", fw] | fw <- reverse frameworks ]
1109 -- reverse because they're added in reverse order from the cmd line
1112 -- probably _stub.o files
1113 extra_ld_inputs <- readIORef v_Ld_inputs
1115 -- opts from -optl-<blah> (including -l<blah> options)
1116 extra_ld_opts <- getStaticOpts v_Opt_l
1118 ways <- readIORef v_Ways
1120 -- Here are some libs that need to be linked at the *end* of
1121 -- the command line, because they contain symbols that are referred to
1122 -- by the RTS. We can't therefore use the ordinary way opts for these.
1124 debug_opts | WayDebug `elem` ways = [
1125 #if defined(HAVE_LIBBFD)
1132 thread_opts | WayThreaded `elem` ways = [
1133 #if !defined(mingw32_TARGET_OS) && !defined(freebsd_TARGET_OS)
1136 #if defined(osf3_TARGET_OS)
1142 (md_c_flags, _) <- machdepCCOpts dflags
1143 SysTools.runLink dflags (
1144 [ SysTools.Option verb
1145 , SysTools.Option "-o"
1146 , SysTools.FileOption "" output_fn
1148 ++ map SysTools.Option (
1154 #ifdef darwin_TARGET_OS
1155 ++ framework_path_opts
1158 ++ pkg_lib_path_opts
1160 #ifdef darwin_TARGET_OS
1161 ++ pkg_framework_path_opts
1162 ++ pkg_framework_opts
1168 -- parallel only: move binary to another dir -- HWL
1169 ways_ <- readIORef v_Ways
1170 when (WayPar `elem` ways_)
1171 (do success <- runPhase_MoveBinary output_fn
1172 if success then return ()
1173 else throwDyn (InstallationError ("cannot move binary to PVM dir")))
1175 -----------------------------------------------------------------------------
1176 -- Making a DLL (only for Win32)
1178 doMkDLL :: DynFlags -> [String] -> [PackageId] -> IO ()
1179 doMkDLL dflags o_files dep_packages = do
1180 let verb = getVerbFlag dflags
1181 static <- readIORef v_Static
1182 no_hs_main <- readIORef v_NoHsMain
1184 o_file <- readIORef v_Output_file
1185 let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
1187 pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1188 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1190 lib_paths <- readIORef v_Library_paths
1191 let lib_path_opts = map ("-L"++) lib_paths
1193 pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1195 -- probably _stub.o files
1196 extra_ld_inputs <- readIORef v_Ld_inputs
1198 -- opts from -optdll-<blah>
1199 extra_ld_opts <- getStaticOpts v_Opt_dll
1201 let pstate = pkgState dflags
1202 rts_id | ExtPackage id <- rtsPackageId pstate = id
1203 | otherwise = panic "staticLink: rts package missing"
1204 base_id | ExtPackage id <- basePackageId pstate = id
1205 | otherwise = panic "staticLink: base package missing"
1206 rts_pkg = getPackageDetails pstate rts_id
1207 base_pkg = getPackageDetails pstate base_id
1209 let extra_os = if static || no_hs_main
1211 else [ head (libraryDirs rts_pkg) ++ "/Main.dll_o",
1212 head (libraryDirs base_pkg) ++ "/PrelMain.dll_o" ]
1214 (md_c_flags, _) <- machdepCCOpts dflags
1215 SysTools.runMkDLL dflags
1216 ([ SysTools.Option verb
1217 , SysTools.Option "-o"
1218 , SysTools.FileOption "" output_fn
1220 ++ map SysTools.Option (
1224 ++ [ "--target=i386-mingw32" ]
1228 ++ pkg_lib_path_opts
1230 ++ (if "--def" `elem` (concatMap words extra_ld_opts)
1232 else [ "--export-all" ])
1235 -- -----------------------------------------------------------------------------
1238 doCpp :: DynFlags -> Bool -> Bool -> FilePath -> FilePath -> IO ()
1239 doCpp dflags raw include_cc_opts input_fn output_fn = do
1240 let hscpp_opts = getOpts dflags opt_P
1242 cmdline_include_paths <- readIORef v_Include_paths
1244 pkg_include_dirs <- getPackageIncludePath dflags []
1245 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
1246 (cmdline_include_paths ++ pkg_include_dirs)
1248 let verb = getVerbFlag dflags
1250 cc_opts <- if not include_cc_opts
1252 else do let optc = getOpts dflags opt_c
1253 (md_c_flags, _) <- machdepCCOpts dflags
1254 return (optc ++ md_c_flags)
1256 let cpp_prog args | raw = SysTools.runCpp dflags args
1257 | otherwise = SysTools.runCc dflags (SysTools.Option "-E" : args)
1260 [ "-D" ++ HOST_OS ++ "_BUILD_OS=1",
1261 "-D" ++ HOST_ARCH ++ "_BUILD_ARCH=1",
1262 "-D" ++ TARGET_OS ++ "_HOST_OS=1",
1263 "-D" ++ TARGET_ARCH ++ "_HOST_ARCH=1" ]
1264 -- remember, in code we *compile*, the HOST is the same our TARGET,
1265 -- and BUILD is the same as our HOST.
1267 cpp_prog ([SysTools.Option verb]
1268 ++ map SysTools.Option include_paths
1269 ++ map SysTools.Option hsSourceCppOpts
1270 ++ map SysTools.Option hscpp_opts
1271 ++ map SysTools.Option cc_opts
1272 ++ map SysTools.Option target_defs
1273 ++ [ SysTools.Option "-x"
1274 , SysTools.Option "c"
1275 , SysTools.Option input_fn
1276 -- We hackily use Option instead of FileOption here, so that the file
1277 -- name is not back-slashed on Windows. cpp is capable of
1278 -- dealing with / in filenames, so it works fine. Furthermore
1279 -- if we put in backslashes, cpp outputs #line directives
1280 -- with *double* backslashes. And that in turn means that
1281 -- our error messages get double backslashes in them.
1282 -- In due course we should arrange that the lexer deals
1283 -- with these \\ escapes properly.
1284 , SysTools.Option "-o"
1285 , SysTools.FileOption "" output_fn
1288 -- -----------------------------------------------------------------------------
1291 hscNextPhase :: HscSource -> HscTarget -> IO Phase
1292 hscNextPhase HsBootFile hsc_lang
1295 hscNextPhase other hsc_lang = do
1296 split <- readIORef v_Split_object_files
1297 return (case hsc_lang of
1299 HscAsm | split -> SplitMangle
1301 HscNothing -> StopLn
1302 HscInterpreted -> StopLn
1306 hscMaybeAdjustTarget :: GhcMode -> HscSource -> HscTarget -> IO HscTarget
1307 hscMaybeAdjustTarget todo HsBootFile current_hsc_lang
1308 = return HscNothing -- No output (other than Foo.hi-boot) for hs-boot files
1309 hscMaybeAdjustTarget todo other current_hsc_lang
1310 = do { keep_hc <- readIORef v_Keep_hc_files
1312 -- don't change the lang if we're interpreting
1313 | current_hsc_lang == HscInterpreted = current_hsc_lang
1315 -- force -fvia-C if we are being asked for a .hc file
1316 | StopBefore HCc <- todo = HscC
1318 -- otherwise, stick to the plan
1319 | otherwise = current_hsc_lang