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 anyHsc "preprocess" dflags
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 split <- readIORef v_Split_object_files
92 o_file <- readIORef v_Output_file
93 ghc_link <- readIORef v_GhcLink -- Set by -c or -no-link
94 -- When linking, the -o argument refers to the linker's output.
95 -- otherwise, we use it as the name for the pipeline's output.
97 | isLinkMode mode && not (isNoLink ghc_link) = Nothing
98 -- -o foo applies to linker
100 -- -o foo applies to the file we are compiling now
102 stop_phase = case mode of
103 StopBefore As | split -> SplitAs
104 StopBefore phase -> phase
107 mode_flag_string <- readIORef v_GhcModeFlag
108 (_, out_file) <- runPipeline stop_phase mode_flag_string dflags
109 True maybe_o_file src Nothing{-no ModLocation-}
113 -- ---------------------------------------------------------------------------
116 -- Compile a single module, under the control of the compilation manager.
118 -- This is the interface between the compilation manager and the
119 -- compiler proper (hsc), where we deal with tedious details like
120 -- reading the OPTIONS pragma from the source file, and passing the
121 -- output of hsc through the C compiler.
123 -- The driver sits between 'compile' and 'hscMain', translating calls
124 -- to the former into calls to the latter, and results from the latter
125 -- into results from the former. It does things like preprocessing
126 -- the .hs file if necessary, and compiling up the .stub_c files to
127 -- generate Linkables.
129 -- NB. No old interface can also mean that the source has changed.
133 -> Bool -- True <=> source unchanged
134 -> Bool -- True <=> have object
135 -> Maybe ModIface -- Old interface, if available
139 = CompOK ModDetails -- New details
140 ModIface -- New iface
141 (Maybe Linkable) -- New code; Nothing => compilation was not reqd
142 -- (old code is still valid)
147 compile hsc_env mod_summary
148 source_unchanged have_object old_iface = do
150 let dyn_flags = hsc_dflags hsc_env
151 this_mod = ms_mod mod_summary
152 src_flavour = ms_hsc_src mod_summary
154 showPass dyn_flags ("Compiling " ++ showModMsg have_object mod_summary)
156 let verb = verbosity dyn_flags
157 let location = ms_location mod_summary
158 let input_fn = expectJust "compile:hs" (ml_hs_file location)
159 let input_fnpp = expectJust "compile:hspp" (ms_hspp_file mod_summary)
161 when (verb >= 2) (hPutStrLn stderr ("compile: input file " ++ input_fnpp))
163 -- Add in the OPTIONS from the source file
164 -- This is nasty: we've done this once already, in the compilation manager
165 -- It might be better to cache the flags in the ml_hspp_file field,say
166 opts <- getOptionsFromSource input_fnpp
167 (dyn_flags,unhandled_flags) <- processDynamicFlags opts dyn_flags
168 checkProcessArgsResult unhandled_flags input_fn
170 let (basename, _) = splitFilename input_fn
172 -- We add the directory in which the .hs files resides) to the import path.
173 -- This is needed when we try to compile the .hc file later, if it
174 -- imports a _stub.h file that we created here.
175 let current_dir = directoryOf basename
176 old_paths <- readIORef v_Include_paths
177 writeIORef v_Include_paths (current_dir : old_paths)
178 -- put back the old include paths afterward.
179 later (writeIORef v_Include_paths old_paths) $ do
181 -- Figure out what lang we're generating
182 hsc_lang <- hscMaybeAdjustTarget StopLn src_flavour (hscTarget dyn_flags)
183 -- ... and what the next phase should be
184 next_phase <- hscNextPhase src_flavour hsc_lang
185 -- ... and what file to generate the output into
186 get_output_fn <- genOutputFilenameFunc next_phase False Nothing basename
187 output_fn <- get_output_fn next_phase (Just location)
189 let dyn_flags' = dyn_flags { hscTarget = hsc_lang,
190 hscOutName = output_fn,
191 hscStubCOutName = basename ++ "_stub.c",
192 hscStubHOutName = basename ++ "_stub.h",
193 extCoreName = basename ++ ".hcr" }
195 -- -no-recomp should also work with --make
196 let do_recomp = recompFlag dyn_flags
197 source_unchanged' = source_unchanged && do_recomp
198 hsc_env' = hsc_env { hsc_dflags = dyn_flags' }
201 hsc_result <- hscMain hsc_env' printErrorsAndWarnings mod_summary
202 source_unchanged' have_object old_iface
205 HscFail -> return CompErrs
207 HscNoRecomp details iface -> return (CompOK details iface Nothing)
209 HscRecomp details iface
210 stub_h_exists stub_c_exists maybe_interpreted_code
212 | isHsBoot src_flavour -- No further compilation to do
213 -> return (CompOK details iface Nothing)
215 | otherwise -- Normal Haskell source files
218 maybe_stub_o <- compileStub dyn_flags' stub_c_exists
219 let stub_unlinked = case maybe_stub_o of
221 Just stub_o -> [ DotO stub_o ]
223 (hs_unlinked, unlinked_time) <-
226 -- in interpreted mode, just return the compiled code
227 -- as our "unlinked" object.
229 case maybe_interpreted_code of
231 Just comp_bc -> return ([BCOs comp_bc], ms_hs_date mod_summary)
232 -- Why do we use the timestamp of the source file here,
233 -- rather than the current time? This works better in
234 -- the case where the local clock is out of sync
235 -- with the filesystem's clock. It's just as accurate:
236 -- if the source is modified, then the linkable will
239 Nothing -> panic "compile: no interpreted code"
241 -- we're in batch mode: finish the compilation pipeline.
243 let object_filename = ml_obj_file location
245 runPipeline StopLn "" dyn_flags
246 True Nothing output_fn (Just location)
247 -- the object filename comes from the ModLocation
249 o_time <- getModificationTime object_filename
250 return ([DotO object_filename], o_time)
252 let linkable = LM unlinked_time this_mod
253 (hs_unlinked ++ stub_unlinked)
255 return (CompOK details iface (Just linkable))
257 -----------------------------------------------------------------------------
258 -- stub .h and .c files (for foreign export support)
260 compileStub dflags stub_c_exists
261 | not stub_c_exists = return Nothing
263 -- compile the _stub.c file w/ gcc
264 let stub_c = hscStubCOutName dflags
265 (_, stub_o) <- runPipeline StopLn "stub-compile" dflags
266 True{-persistent output-}
267 Nothing{-no specific output file-}
269 Nothing{-no ModLocation-}
273 -- ---------------------------------------------------------------------------
276 link :: GhciMode -- interactive or batch
277 -> DynFlags -- dynamic flags
278 -> Bool -- attempt linking in batch mode?
279 -> HomePackageTable -- what to link
282 -- For the moment, in the batch linker, we don't bother to tell doLink
283 -- which packages to link -- it just tries all that are available.
284 -- batch_attempt_linking should only be *looked at* in batch mode. It
285 -- should only be True if the upsweep was successful and someone
286 -- exports main, i.e., we have good reason to believe that linking
290 link Interactive dflags batch_attempt_linking hpt
291 = do -- Not Linking...(demand linker will do the job)
295 link Batch dflags batch_attempt_linking hpt
296 | batch_attempt_linking
299 home_mod_infos = moduleEnvElts hpt
301 -- the packages we depend on
302 pkg_deps = concatMap (dep_pkgs . mi_deps . hm_iface) home_mod_infos
304 -- the linkables to link
305 linkables = map hm_linkable home_mod_infos
307 when (verb >= 3) $ do
308 hPutStrLn stderr "link: linkables are ..."
309 hPutStrLn stderr (showSDoc (vcat (map ppr linkables)))
311 -- check for the -no-link flag
312 ghc_link <- readIORef v_GhcLink
314 then do when (verb >= 3) $
315 hPutStrLn stderr "link(batch): linking omitted (-c flag given)."
320 hPutStrLn stderr "Linking ..."
322 let getOfiles (LM _ _ us) = map nameOfObject (filter isObject us)
323 obj_files = concatMap getOfiles linkables
325 -- Don't showPass in Batch mode; doLink will do that for us.
326 staticLink dflags obj_files pkg_deps
328 when (verb >= 3) (hPutStrLn stderr "link: done")
330 -- staticLink only returns if it succeeds
334 = do when (verb >= 3) $ do
335 hPutStrLn stderr "link(batch): upsweep (partially) failed OR"
336 hPutStrLn stderr " Main.main not exported; not linking."
339 verb = verbosity dflags
341 -- ---------------------------------------------------------------------------
342 -- Run a compilation pipeline, consisting of multiple phases.
344 -- The DynFlags can be modified by phases in the pipeline (eg. by
345 -- OPTIONS pragmas), and the changes affect later phases in the
346 -- pipeline, but we throw away the resulting DynFlags at the end.
349 :: Phase -- When to stop
350 -> String -- "GhcMode" flag as a string
351 -> DynFlags -- Dynamic flags
352 -> Bool -- Final output is persistent?
353 -> Maybe FilePath -- Where to put the output, optionally
354 -> FilePath -- Input filename
355 -> Maybe ModLocation -- A ModLocation for this module, if we have one
356 -> IO (DynFlags, FilePath) -- (final flags, output filename)
358 runPipeline stop_phase mode_flag_string dflags keep_output
359 maybe_output_filename input_fn maybe_loc
361 let (basename, suffix) = splitFilename input_fn
362 start_phase = startPhase suffix
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 when (not (start_phase `happensBefore` stop_phase)) $
373 ("flag `" ++ mode_flag_string
374 ++ "' is incompatible with source file `"
377 -- generate a function which will be used to calculate output file names
379 get_output_fn <- genOutputFilenameFunc stop_phase keep_output
380 maybe_output_filename basename
382 -- Execute the pipeline...
383 (dflags', output_fn, maybe_loc) <- pipeLoop dflags start_phase stop_phase input_fn
384 basename suffix get_output_fn maybe_loc
386 -- Sometimes, a compilation phase doesn't actually generate any output
387 -- (eg. the CPP phase when -fcpp is not turned on). If we end on this
388 -- stage, but we wanted to keep the output, then we have to explicitly
391 then do final_fn <- get_output_fn stop_phase maybe_loc
392 when (final_fn /= output_fn) $
393 copy dflags ("Copying `" ++ output_fn ++ "' to `" ++ final_fn
394 ++ "'") output_fn final_fn
395 return (dflags', final_fn)
397 return (dflags', output_fn)
400 pipeLoop :: DynFlags -> Phase -> Phase
401 -> FilePath -> String -> Suffix
402 -> (Phase -> Maybe ModLocation -> IO FilePath)
404 -> IO (DynFlags, FilePath, Maybe ModLocation)
406 pipeLoop dflags phase stop_phase
407 input_fn orig_basename orig_suff
408 orig_get_output_fn maybe_loc
410 | phase `eqPhase` stop_phase -- All done
411 = return (dflags, input_fn, maybe_loc)
413 | not (phase `happensBefore` stop_phase)
414 -- Something has gone wrong. We'll try to cover all the cases when
415 -- this could happen, so if we reach here it is a panic.
416 -- eg. it might happen if the -C flag is used on a source file that
417 -- has {-# OPTIONS -fasm #-}.
418 = panic ("pipeLoop: at phase " ++ show phase ++
419 " but I wanted to stop at phase " ++ show stop_phase)
422 = do { (next_phase, dflags', maybe_loc, output_fn)
423 <- runPhase phase stop_phase dflags orig_basename
424 orig_suff input_fn orig_get_output_fn maybe_loc
425 ; pipeLoop dflags' next_phase stop_phase output_fn
426 orig_basename orig_suff orig_get_output_fn maybe_loc }
428 genOutputFilenameFunc :: Phase -> Bool -> Maybe FilePath -> String
429 -> IO (Phase{-next phase-} -> Maybe ModLocation -> IO FilePath)
430 genOutputFilenameFunc stop_phase keep_final_output maybe_output_filename basename
432 hcsuf <- readIORef v_HC_suf
433 odir <- readIORef v_Output_dir
434 osuf <- readIORef v_Object_suf
435 keep_hc <- readIORef v_Keep_hc_files
437 keep_il <- readIORef v_Keep_il_files
438 keep_ilx <- readIORef v_Keep_ilx_files
440 keep_raw_s <- readIORef v_Keep_raw_s_files
441 keep_s <- readIORef v_Keep_s_files
443 myPhaseInputExt HCc = hcsuf
444 myPhaseInputExt StopLn = osuf
445 myPhaseInputExt other = phaseInputExt other
447 func next_phase maybe_location
448 | is_last_phase, Just f <- maybe_output_filename = return f
449 | is_last_phase && keep_final_output = persistent_fn
450 | keep_this_output = persistent_fn
451 | otherwise = newTempName suffix
454 is_last_phase = next_phase `eqPhase` stop_phase
456 -- sometimes, we keep output from intermediate stages
460 Mangle | keep_raw_s -> True
462 HCc | keep_hc -> True
465 suffix = myPhaseInputExt next_phase
467 -- persistent object files get put in odir
469 | StopLn <- next_phase = return odir_persistent
470 | otherwise = return persistent
472 persistent = basename ++ '.':suffix
475 | Just loc <- maybe_location = ml_obj_file loc
476 | Just d <- odir = replaceFilenameDirectory persistent d
477 | otherwise = persistent
482 -- -----------------------------------------------------------------------------
483 -- Each phase in the pipeline returns the next phase to execute, and the
484 -- name of the file in which the output was placed.
486 -- We must do things dynamically this way, because we often don't know
487 -- what the rest of the phases will be until part-way through the
488 -- compilation: for example, an {-# OPTIONS -fasm #-} at the beginning
489 -- of a source file can change the latter stages of the pipeline from
490 -- taking the via-C route to using the native code generator.
492 runPhase :: Phase -- Do this phase first
493 -> Phase -- Stop just before this phase
495 -> String -- basename of original input source
496 -> String -- its extension
497 -> FilePath -- name of file which contains the input to this phase.
498 -> (Phase -> Maybe ModLocation -> IO FilePath)
499 -- how to calculate the output filename
500 -> Maybe ModLocation -- the ModLocation, if we have one
501 -> IO (Phase, -- next phase
502 DynFlags, -- new dynamic flags
503 Maybe ModLocation, -- the ModLocation, if we have one
504 FilePath) -- output filename
506 -- Invariant: the output filename always contains the output
507 -- Interesting case: Hsc when there is no recompilation to do
508 -- Then the output filename is still a .o file
510 -------------------------------------------------------------------------------
513 runPhase (Unlit sf) _stop dflags _basename _suff input_fn get_output_fn maybe_loc
514 = do let unlit_flags = getOpts dflags opt_L
515 -- The -h option passes the file name for unlit to put in a #line directive
516 output_fn <- get_output_fn (Cpp sf) maybe_loc
518 SysTools.runUnlit dflags
519 (map SysTools.Option unlit_flags ++
520 [ SysTools.Option "-h"
521 , SysTools.Option input_fn
522 , SysTools.FileOption "" input_fn
523 , SysTools.FileOption "" output_fn
526 return (Cpp sf, dflags, maybe_loc, output_fn)
528 -------------------------------------------------------------------------------
529 -- Cpp phase : (a) gets OPTIONS out of file
530 -- (b) runs cpp if necessary
532 runPhase (Cpp sf) _stop dflags basename suff input_fn get_output_fn maybe_loc
533 = do src_opts <- getOptionsFromSource input_fn
534 (dflags,unhandled_flags) <- processDynamicFlags src_opts dflags
535 checkProcessArgsResult unhandled_flags (basename++'.':suff)
537 if not (cppFlag dflags) then
538 -- no need to preprocess CPP, just pass input file along
539 -- to the next phase of the pipeline.
540 return (HsPp sf, dflags, maybe_loc, input_fn)
542 output_fn <- get_output_fn (HsPp sf) maybe_loc
543 doCpp dflags True{-raw-} False{-no CC opts-} input_fn output_fn
544 return (HsPp sf, dflags, maybe_loc, output_fn)
546 -------------------------------------------------------------------------------
549 runPhase (HsPp sf) _stop dflags basename suff input_fn get_output_fn maybe_loc
550 = do if not (ppFlag dflags) then
551 -- no need to preprocess, just pass input file along
552 -- to the next phase of the pipeline.
553 return (Hsc sf, dflags, maybe_loc, input_fn)
555 let hspp_opts = getOpts dflags opt_F
556 hs_src_pp_opts <- readIORef v_Hs_source_pp_opts
557 let orig_fn = basename ++ '.':suff
558 output_fn <- get_output_fn (Hsc sf) maybe_loc
559 SysTools.runPp dflags
560 ( [ SysTools.Option orig_fn
561 , SysTools.Option input_fn
562 , SysTools.FileOption "" output_fn
564 map SysTools.Option hs_src_pp_opts ++
565 map SysTools.Option hspp_opts
567 return (Hsc sf, dflags, maybe_loc, output_fn)
569 -----------------------------------------------------------------------------
572 -- Compilation of a single module, in "legacy" mode (_not_ under
573 -- the direction of the compilation manager).
574 runPhase (Hsc src_flavour) stop dflags basename suff input_fn get_output_fn _maybe_loc
575 = do -- normal Hsc mode, not mkdependHS
577 -- we add the current directory (i.e. the directory in which
578 -- the .hs files resides) to the import path, since this is
579 -- what gcc does, and it's probably what you want.
580 let current_dir = directoryOf basename
582 paths <- readIORef v_Include_paths
583 writeIORef v_Include_paths (current_dir : paths)
585 -- gather the imports and module name
586 (hspp_buf,mod_name) <-
588 ExtCoreFile -> do { -- no explicit imports in ExtCore input.
589 ; m <- getCoreModuleName input_fn
590 ; return (Nothing, mkModule m) }
592 other -> do { buf <- hGetStringBuffer input_fn
593 ; (_,_,mod_name) <- getImports dflags buf input_fn
594 ; return (Just buf, mod_name) }
596 -- Build a ModLocation to pass to hscMain.
597 -- The source filename is rather irrelevant by now, but it's used
598 -- by hscMain for messages. hscMain also needs
599 -- the .hi and .o filenames, and this is as good a way
600 -- as any to generate them, and better than most. (e.g. takes
601 -- into accout the -osuf flags)
602 location1 <- mkHomeModLocation2 mod_name basename suff
604 -- Boot-ify it if necessary
605 let location2 | isHsBoot src_flavour = addBootSuffixLocn location1
606 | otherwise = location1
609 -- Take -ohi into account if present
610 -- This can't be done in mkHomeModuleLocation because
611 -- it only applies to the module being compiles
612 ohi <- readIORef v_Output_hi
613 let location3 | Just fn <- ohi = location2{ ml_hi_file = fn }
614 | otherwise = location2
616 -- Take -o into account if present
617 -- Very like -ohi, but we must *only* do this if we aren't linking
618 -- (If we're linking then the -o applies to the linked thing, not to
619 -- the object file for one module.)
620 -- Note the nasty duplication with the same computation in compileFile above
621 expl_o_file <- readIORef v_Output_file
622 ghc_link <- readIORef v_GhcLink
623 let location4 | Just ofile <- expl_o_file
625 = location3 { ml_obj_file = ofile }
626 | otherwise = location3
628 -- Tell the finder cache about this module
629 addHomeModuleToFinder mod_name location4
631 -- Make the ModSummary to hand to hscMain
632 src_timestamp <- getModificationTime (basename ++ '.':suff)
634 unused_field = panic "runPhase:ModSummary field"
635 -- Some fields are not looked at by hscMain
636 mod_summary = ModSummary { ms_mod = mod_name,
637 ms_hsc_src = src_flavour,
638 ms_hspp_file = Just input_fn,
639 ms_hspp_buf = hspp_buf,
640 ms_location = location4,
641 ms_hs_date = src_timestamp,
642 ms_imps = unused_field,
643 ms_srcimps = unused_field }
645 o_file = ml_obj_file location4 -- The real object file
648 -- Figure out if the source has changed, for recompilation avoidance.
650 -- Setting source_unchanged to True means that M.o seems
651 -- to be up to date wrt M.hs; so no need to recompile unless imports have
652 -- changed (which the compiler itself figures out).
653 -- Setting source_unchanged to False tells the compiler that M.o is out of
654 -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
655 let do_recomp = recompFlag dflags
657 if not do_recomp || not (isStopLn stop)
658 -- Set source_unchanged to False unconditionally if
659 -- (a) recompilation checker is off, or
660 -- (b) we aren't going all the way to .o file (e.g. ghc -S)
662 -- Otherwise look at file modification dates
663 else do o_file_exists <- doesFileExist o_file
665 then return False -- Need to recompile
666 else do t2 <- getModificationTime o_file
667 if t2 > src_timestamp
672 hsc_lang <- hscMaybeAdjustTarget stop src_flavour (hscTarget dflags)
673 next_phase <- hscNextPhase src_flavour hsc_lang
674 output_fn <- get_output_fn next_phase (Just location4)
676 let dflags' = dflags { hscTarget = hsc_lang,
677 hscOutName = output_fn,
678 hscStubCOutName = basename ++ "_stub.c",
679 hscStubHOutName = basename ++ "_stub.h",
680 extCoreName = basename ++ ".hcr" }
682 hsc_env <- newHscEnv OneShot dflags'
685 result <- hscMain hsc_env printErrorsAndWarnings
686 mod_summary source_unchanged
687 False -- No object file
692 HscFail -> throwDyn (PhaseFailed "hsc" (ExitFailure 1))
694 HscNoRecomp details iface -> do
695 SysTools.touch dflags' "Touching object file" o_file
696 return (StopLn, dflags', Just location4, o_file)
698 HscRecomp _details _iface
699 stub_h_exists stub_c_exists
700 _maybe_interpreted_code -> do
703 maybe_stub_o <- compileStub dflags' stub_c_exists
706 Just stub_o -> add v_Ld_inputs stub_o
708 -- In the case of hs-boot files, generate a dummy .o-boot
709 -- stamp file for the benefit of Make
711 HsBootFile -> SysTools.touch dflags' "Touching object file" o_file
714 return (next_phase, dflags', Just location4, output_fn)
716 -----------------------------------------------------------------------------
719 runPhase CmmCpp stop dflags basename suff input_fn get_output_fn maybe_loc
721 output_fn <- get_output_fn Cmm maybe_loc
722 doCpp dflags False{-not raw-} True{-include CC opts-} input_fn output_fn
723 return (Cmm, dflags, maybe_loc, output_fn)
725 runPhase Cmm stop dflags basename suff input_fn get_output_fn maybe_loc
727 hsc_lang <- hscMaybeAdjustTarget stop HsSrcFile (hscTarget dflags)
728 next_phase <- hscNextPhase HsSrcFile hsc_lang
729 output_fn <- get_output_fn next_phase maybe_loc
731 let dflags' = dflags { hscTarget = hsc_lang,
732 hscOutName = output_fn,
733 hscStubCOutName = basename ++ "_stub.c",
734 hscStubHOutName = basename ++ "_stub.h",
735 extCoreName = basename ++ ".hcr" }
737 ok <- hscCmmFile dflags' input_fn
739 when (not ok) $ throwDyn (PhaseFailed "cmm" (ExitFailure 1))
741 return (next_phase, dflags, maybe_loc, output_fn)
743 -----------------------------------------------------------------------------
746 -- we don't support preprocessing .c files (with -E) now. Doing so introduces
747 -- way too many hacks, and I can't say I've ever used it anyway.
749 runPhase cc_phase stop dflags basename suff input_fn get_output_fn maybe_loc
750 | cc_phase `eqPhase` Cc || cc_phase `eqPhase` HCc
751 = do let cc_opts = getOpts dflags opt_c
752 hcc = cc_phase `eqPhase` HCc
754 cmdline_include_paths <- readIORef v_Include_paths
756 -- HC files have the dependent packages stamped into them
757 pkgs <- if hcc then getHCFilePackages input_fn else return []
759 -- add package include paths even if we're just compiling .c
760 -- files; this is the Value Add(TM) that using ghc instead of
762 pkg_include_dirs <- getPackageIncludePath dflags pkgs
763 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
764 (cmdline_include_paths ++ pkg_include_dirs)
766 (md_c_flags, md_regd_c_flags) <- machdepCCOpts dflags
767 pic_c_flags <- picCCOpts dflags
769 let verb = getVerbFlag dflags
771 pkg_extra_cc_opts <- getPackageExtraCcOpts dflags pkgs
773 split_objs <- readIORef v_Split_object_files
774 let split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
777 excessPrecision <- readIORef v_Excess_precision
780 mangle <- readIORef v_Do_asm_mangling
782 | hcc && mangle = Mangle
784 output_fn <- get_output_fn next_phase maybe_loc
786 -- force the C compiler to interpret this file as C when
787 -- compiling .hc files, by adding the -x c option.
788 let langopt | hcc = [ SysTools.Option "-x", SysTools.Option "c"]
791 SysTools.runCc dflags (langopt ++
792 [ SysTools.FileOption "" input_fn
793 , SysTools.Option "-o"
794 , SysTools.FileOption "" output_fn
796 ++ map SysTools.Option (
802 ++ [ verb, "-S", "-Wimplicit", "-O" ]
803 ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
806 ++ (if excessPrecision then [] else [ "-ffloat-store" ])
811 return (next_phase, dflags, maybe_loc, output_fn)
813 -- ToDo: postprocess the output from gcc
815 -----------------------------------------------------------------------------
818 runPhase Mangle stop dflags _basename _suff input_fn get_output_fn maybe_loc
819 = do let mangler_opts = getOpts dflags opt_m
822 machdep_opts <- return [ show (stolen_x86_regs dflags) ]
824 machdep_opts <- return []
827 split <- readIORef v_Split_object_files
829 | split = SplitMangle
831 output_fn <- get_output_fn next_phase maybe_loc
833 SysTools.runMangle dflags (map SysTools.Option mangler_opts
834 ++ [ SysTools.FileOption "" input_fn
835 , SysTools.FileOption "" output_fn
837 ++ map SysTools.Option machdep_opts)
839 return (next_phase, dflags, maybe_loc, output_fn)
841 -----------------------------------------------------------------------------
844 runPhase SplitMangle stop dflags _basename _suff input_fn get_output_fn maybe_loc
845 = do -- tmp_pfx is the prefix used for the split .s files
846 -- We also use it as the file to contain the no. of split .s files (sigh)
847 split_s_prefix <- SysTools.newTempName "split"
848 let n_files_fn = split_s_prefix
850 SysTools.runSplit dflags
851 [ SysTools.FileOption "" input_fn
852 , SysTools.FileOption "" split_s_prefix
853 , SysTools.FileOption "" n_files_fn
856 -- Save the number of split files for future references
857 s <- readFile n_files_fn
858 let n_files = read s :: Int
859 writeIORef v_Split_info (split_s_prefix, n_files)
861 -- Remember to delete all these files
862 addFilesToClean [ split_s_prefix ++ "__" ++ show n ++ ".s"
865 return (SplitAs, dflags, maybe_loc, "**splitmangle**")
866 -- we don't use the filename
868 -----------------------------------------------------------------------------
871 runPhase As stop dflags _basename _suff input_fn get_output_fn maybe_loc
872 = do let as_opts = getOpts dflags opt_a
873 cmdline_include_paths <- readIORef v_Include_paths
875 output_fn <- get_output_fn StopLn maybe_loc
877 -- we create directories for the object file, because it
878 -- might be a hierarchical module.
879 createDirectoryHierarchy (directoryOf output_fn)
881 SysTools.runAs dflags
882 (map SysTools.Option as_opts
883 ++ [ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ]
884 ++ [ SysTools.Option "-c"
885 , SysTools.FileOption "" input_fn
886 , SysTools.Option "-o"
887 , SysTools.FileOption "" output_fn
890 return (StopLn, dflags, maybe_loc, output_fn)
893 runPhase SplitAs stop dflags basename _suff _input_fn get_output_fn maybe_loc
894 = do let as_opts = getOpts dflags opt_a
896 (split_s_prefix, n) <- readIORef v_Split_info
898 odir <- readIORef v_Output_dir
899 let real_odir = case odir of
900 Nothing -> basename ++ "_split"
904 = do let input_s = split_s_prefix ++ "__" ++ show n ++ ".s"
905 let output_o = replaceFilenameDirectory
906 (basename ++ "__" ++ show n ++ ".o")
908 real_o <- osuf_ify output_o
909 SysTools.runAs dflags
910 (map SysTools.Option as_opts ++
911 [ SysTools.Option "-c"
912 , SysTools.Option "-o"
913 , SysTools.FileOption "" real_o
914 , SysTools.FileOption "" input_s
917 mapM_ assemble_file [1..n]
919 output_fn <- get_output_fn StopLn maybe_loc
920 return (StopLn, dflags, maybe_loc, output_fn)
923 -----------------------------------------------------------------------------
925 -- Run ilx2il over the ILX output, getting an IL file
927 runPhase Ilx2Il stop dflags _basename _suff input_fn get_output_fn maybe_loc
928 = do let ilx2il_opts = getOpts dflags opt_I
929 SysTools.runIlx2il (map SysTools.Option ilx2il_opts
930 ++ [ SysTools.Option "--no-add-suffix-to-assembly",
931 SysTools.Option "mscorlib",
932 SysTools.Option "-o",
933 SysTools.FileOption "" output_fn,
934 SysTools.FileOption "" input_fn ])
937 -----------------------------------------------------------------------------
939 -- Run ilasm over the IL, getting a DLL
941 runPhase Ilasm stop dflags _basename _suff input_fn get_output_fn maybe_loc
942 = do let ilasm_opts = getOpts dflags opt_i
943 SysTools.runIlasm (map SysTools.Option ilasm_opts
944 ++ [ SysTools.Option "/QUIET",
945 SysTools.Option "/DLL",
946 SysTools.FileOption "/OUT=" output_fn,
947 SysTools.FileOption "" input_fn ])
952 -----------------------------------------------------------------------------
953 -- MoveBinary sort-of-phase
954 -- After having produced a binary, move it somewhere else and generate a
955 -- wrapper script calling the binary. Currently, we need this only in
956 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
957 -- central directory.
958 -- This is called from staticLink below, after linking. I haven't made it
959 -- a separate phase to minimise interfering with other modules, and
960 -- we don't need the generality of a phase (MoveBinary is always
961 -- done after linking and makes only sense in a parallel setup) -- HWL
963 runPhase_MoveBinary input_fn
966 pvm_root <- getEnv "PVM_ROOT"
967 pvm_arch <- getEnv "PVM_ARCH"
969 pvm_executable_base = "=" ++ input_fn
970 pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
971 -- nuke old binary; maybe use configur'ed names for cp and rm?
972 system ("rm -f " ++ pvm_executable)
973 -- move the newly created binary into PVM land
974 system ("cp -p " ++ input_fn ++ " " ++ pvm_executable)
975 -- generate a wrapper script for running a parallel prg under PVM
976 writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
979 -- generates a Perl skript starting a parallel prg under PVM
980 mk_pvm_wrapper_script :: String -> String -> String -> String
981 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
983 "eval 'exec perl -S $0 ${1+\"$@\"}'",
984 " if $running_under_some_shell;",
985 "# =!=!=!=!=!=!=!=!=!=!=!",
986 "# This script is automatically generated: DO NOT EDIT!!!",
987 "# Generated by Glasgow Haskell Compiler",
988 "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
990 "$pvm_executable = '" ++ pvm_executable ++ "';",
991 "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
992 "$SysMan = '" ++ sysMan ++ "';",
994 {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
995 "# first, some magical shortcuts to run "commands" on the binary",
996 "# (which is hidden)",
997 "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
998 " local($cmd) = $1;",
999 " system("$cmd $pvm_executable");",
1000 " exit(0); # all done",
1003 "# Now, run the real binary; process the args first",
1004 "$ENV{'PE'} = $pvm_executable_base;", -- ++ pvm_executable_base,
1006 "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
1007 "@nonPVM_args = ();",
1008 "$in_RTS_args = 0;",
1010 "args: while ($a = shift(@ARGV)) {",
1011 " if ( $a eq '+RTS' ) {",
1012 " $in_RTS_args = 1;",
1013 " } elsif ( $a eq '-RTS' ) {",
1014 " $in_RTS_args = 0;",
1016 " if ( $a eq '-d' && $in_RTS_args ) {",
1018 " } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
1019 " $nprocessors = $1;",
1020 " } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
1021 " $nprocessors = $1;",
1023 " push(@nonPVM_args, $a);",
1027 "local($return_val) = 0;",
1028 "# Start the parallel execution by calling SysMan",
1029 "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
1030 "$return_val = $?;",
1031 "# ToDo: fix race condition moving files and flushing them!!",
1032 "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
1033 "exit($return_val);"
1036 -----------------------------------------------------------------------------
1037 -- Complain about non-dynamic flags in OPTIONS pragmas
1039 checkProcessArgsResult flags filename
1040 = do when (notNull flags) (throwDyn (ProgramError (
1041 showSDoc (hang (text filename <> char ':')
1042 4 (text "unknown flags in {-# OPTIONS #-} pragma:" <+>
1043 hsep (map text flags)))
1046 -----------------------------------------------------------------------------
1047 -- Look for the /* GHC_PACKAGES ... */ comment at the top of a .hc file
1049 getHCFilePackages :: FilePath -> IO [PackageId]
1050 getHCFilePackages filename =
1051 EXCEPTION.bracket (openFile filename ReadMode) hClose $ \h -> do
1054 '/':'*':' ':'G':'H':'C':'_':'P':'A':'C':'K':'A':'G':'E':'S':rest ->
1055 return (map stringToPackageId (words rest))
1059 -----------------------------------------------------------------------------
1060 -- Static linking, of .o files
1062 -- The list of packages passed to link is the list of packages on
1063 -- which this program depends, as discovered by the compilation
1064 -- manager. It is combined with the list of packages that the user
1065 -- specifies on the command line with -package flags.
1067 -- In one-shot linking mode, we can't discover the package
1068 -- dependencies (because we haven't actually done any compilation or
1069 -- read any interface files), so the user must explicitly specify all
1072 staticLink :: DynFlags -> [FilePath] -> [PackageId] -> IO ()
1073 staticLink dflags o_files dep_packages = do
1074 let verb = getVerbFlag dflags
1075 static <- readIORef v_Static
1076 no_hs_main <- readIORef v_NoHsMain
1078 -- get the full list of packages to link with, by combining the
1079 -- explicit packages with the auto packages and all of their
1080 -- dependencies, and eliminating duplicates.
1082 o_file <- readIORef v_Output_file
1083 #if defined(mingw32_HOST_OS)
1084 let output_fn = case o_file of { Just s -> s; Nothing -> "main.exe"; }
1086 let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
1089 pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1090 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1092 lib_paths <- readIORef v_Library_paths
1093 let lib_path_opts = map ("-L"++) lib_paths
1095 pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1097 #ifdef darwin_TARGET_OS
1098 pkg_framework_paths <- getPackageFrameworkPath dflags dep_packages
1099 let pkg_framework_path_opts = map ("-F"++) pkg_framework_paths
1101 framework_paths <- readIORef v_Framework_paths
1102 let framework_path_opts = map ("-F"++) framework_paths
1104 pkg_frameworks <- getPackageFrameworks dflags dep_packages
1105 let pkg_framework_opts = concat [ ["-framework", fw] | fw <- pkg_frameworks ]
1106 frameworks <- readIORef v_Cmdline_frameworks
1107 let framework_opts = concat [ ["-framework", fw] | fw <- reverse frameworks ]
1108 -- reverse because they're added in reverse order from the cmd line
1111 -- probably _stub.o files
1112 extra_ld_inputs <- readIORef v_Ld_inputs
1114 -- opts from -optl-<blah> (including -l<blah> options)
1115 extra_ld_opts <- getStaticOpts v_Opt_l
1117 ways <- readIORef v_Ways
1119 -- Here are some libs that need to be linked at the *end* of
1120 -- the command line, because they contain symbols that are referred to
1121 -- by the RTS. We can't therefore use the ordinary way opts for these.
1123 debug_opts | WayDebug `elem` ways = [
1124 #if defined(HAVE_LIBBFD)
1131 thread_opts | WayThreaded `elem` ways = [
1132 #if !defined(mingw32_TARGET_OS) && !defined(freebsd_TARGET_OS)
1135 #if defined(osf3_TARGET_OS)
1141 (md_c_flags, _) <- machdepCCOpts dflags
1142 SysTools.runLink dflags (
1143 [ SysTools.Option verb
1144 , SysTools.Option "-o"
1145 , SysTools.FileOption "" output_fn
1147 ++ map SysTools.Option (
1153 #ifdef darwin_TARGET_OS
1154 ++ framework_path_opts
1157 ++ pkg_lib_path_opts
1159 #ifdef darwin_TARGET_OS
1160 ++ pkg_framework_path_opts
1161 ++ pkg_framework_opts
1167 -- parallel only: move binary to another dir -- HWL
1168 ways_ <- readIORef v_Ways
1169 when (WayPar `elem` ways_)
1170 (do success <- runPhase_MoveBinary output_fn
1171 if success then return ()
1172 else throwDyn (InstallationError ("cannot move binary to PVM dir")))
1174 -----------------------------------------------------------------------------
1175 -- Making a DLL (only for Win32)
1177 doMkDLL :: DynFlags -> [String] -> [PackageId] -> IO ()
1178 doMkDLL dflags o_files dep_packages = do
1179 let verb = getVerbFlag dflags
1180 static <- readIORef v_Static
1181 no_hs_main <- readIORef v_NoHsMain
1183 o_file <- readIORef v_Output_file
1184 let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
1186 pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1187 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1189 lib_paths <- readIORef v_Library_paths
1190 let lib_path_opts = map ("-L"++) lib_paths
1192 pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1194 -- probably _stub.o files
1195 extra_ld_inputs <- readIORef v_Ld_inputs
1197 -- opts from -optdll-<blah>
1198 extra_ld_opts <- getStaticOpts v_Opt_dll
1200 let pstate = pkgState dflags
1201 rts_id | ExtPackage id <- rtsPackageId pstate = id
1202 | otherwise = panic "staticLink: rts package missing"
1203 base_id | ExtPackage id <- basePackageId pstate = id
1204 | otherwise = panic "staticLink: base package missing"
1205 rts_pkg = getPackageDetails pstate rts_id
1206 base_pkg = getPackageDetails pstate base_id
1208 let extra_os = if static || no_hs_main
1210 else [ head (libraryDirs rts_pkg) ++ "/Main.dll_o",
1211 head (libraryDirs base_pkg) ++ "/PrelMain.dll_o" ]
1213 (md_c_flags, _) <- machdepCCOpts dflags
1214 SysTools.runMkDLL dflags
1215 ([ SysTools.Option verb
1216 , SysTools.Option "-o"
1217 , SysTools.FileOption "" output_fn
1219 ++ map SysTools.Option (
1223 ++ [ "--target=i386-mingw32" ]
1227 ++ pkg_lib_path_opts
1229 ++ (if "--def" `elem` (concatMap words extra_ld_opts)
1231 else [ "--export-all" ])
1234 -- -----------------------------------------------------------------------------
1237 doCpp :: DynFlags -> Bool -> Bool -> FilePath -> FilePath -> IO ()
1238 doCpp dflags raw include_cc_opts input_fn output_fn = do
1239 let hscpp_opts = getOpts dflags opt_P
1241 cmdline_include_paths <- readIORef v_Include_paths
1243 pkg_include_dirs <- getPackageIncludePath dflags []
1244 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
1245 (cmdline_include_paths ++ pkg_include_dirs)
1247 let verb = getVerbFlag dflags
1249 cc_opts <- if not include_cc_opts
1251 else do let optc = getOpts dflags opt_c
1252 (md_c_flags, _) <- machdepCCOpts dflags
1253 return (optc ++ md_c_flags)
1255 let cpp_prog args | raw = SysTools.runCpp dflags args
1256 | otherwise = SysTools.runCc dflags (SysTools.Option "-E" : args)
1259 [ "-D" ++ HOST_OS ++ "_BUILD_OS=1",
1260 "-D" ++ HOST_ARCH ++ "_BUILD_ARCH=1",
1261 "-D" ++ TARGET_OS ++ "_HOST_OS=1",
1262 "-D" ++ TARGET_ARCH ++ "_HOST_ARCH=1" ]
1263 -- remember, in code we *compile*, the HOST is the same our TARGET,
1264 -- and BUILD is the same as our HOST.
1266 cpp_prog ([SysTools.Option verb]
1267 ++ map SysTools.Option include_paths
1268 ++ map SysTools.Option hsSourceCppOpts
1269 ++ map SysTools.Option hscpp_opts
1270 ++ map SysTools.Option cc_opts
1271 ++ map SysTools.Option target_defs
1272 ++ [ SysTools.Option "-x"
1273 , SysTools.Option "c"
1274 , SysTools.Option input_fn
1275 -- We hackily use Option instead of FileOption here, so that the file
1276 -- name is not back-slashed on Windows. cpp is capable of
1277 -- dealing with / in filenames, so it works fine. Furthermore
1278 -- if we put in backslashes, cpp outputs #line directives
1279 -- with *double* backslashes. And that in turn means that
1280 -- our error messages get double backslashes in them.
1281 -- In due course we should arrange that the lexer deals
1282 -- with these \\ escapes properly.
1283 , SysTools.Option "-o"
1284 , SysTools.FileOption "" output_fn
1287 -- -----------------------------------------------------------------------------
1290 hscNextPhase :: HscSource -> HscTarget -> IO Phase
1291 hscNextPhase HsBootFile hsc_lang
1294 hscNextPhase other hsc_lang = do
1295 split <- readIORef v_Split_object_files
1296 return (case hsc_lang of
1298 HscAsm | split -> SplitMangle
1300 HscNothing -> StopLn
1301 HscInterpreted -> StopLn
1305 hscMaybeAdjustTarget :: Phase -> HscSource -> HscTarget -> IO HscTarget
1306 hscMaybeAdjustTarget stop HsBootFile current_hsc_lang
1307 = return HscNothing -- No output (other than Foo.hi-boot) for hs-boot files
1308 hscMaybeAdjustTarget stop other current_hsc_lang
1309 = do { keep_hc <- readIORef v_Keep_hc_files
1311 -- don't change the lang if we're interpreting
1312 | current_hsc_lang == HscInterpreted = current_hsc_lang
1314 -- force -fvia-C if we are being asked for a .hc file
1315 | HCc <- stop = HscC
1317 -- otherwise, stick to the plan
1318 | otherwise = current_hsc_lang