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.
96 let maybe_o_file | isLinkMode mode && not (isNoLink ghc_link)
97 = Nothing -- -o foo applies to linker
99 = o_file -- -o foo applies to the file we are compiling now
101 stop_phase = case mode of
102 StopBefore As | split -> SplitAs
103 StopBefore phase -> phase
106 mode_flag_string <- readIORef v_GhcModeFlag
107 (_, out_file) <- runPipeline stop_phase mode_flag_string dflags True maybe_o_file
108 src Nothing{-no ModLocation-}
112 -- ---------------------------------------------------------------------------
115 -- Compile a single module, under the control of the compilation manager.
117 -- This is the interface between the compilation manager and the
118 -- compiler proper (hsc), where we deal with tedious details like
119 -- reading the OPTIONS pragma from the source file, and passing the
120 -- output of hsc through the C compiler.
122 -- The driver sits between 'compile' and 'hscMain', translating calls
123 -- to the former into calls to the latter, and results from the latter
124 -- into results from the former. It does things like preprocessing
125 -- the .hs file if necessary, and compiling up the .stub_c files to
126 -- generate Linkables.
128 -- NB. No old interface can also mean that the source has changed.
132 -> Bool -- True <=> source unchanged
133 -> Bool -- True <=> have object
134 -> Maybe ModIface -- Old interface, if available
138 = CompOK ModDetails -- New details
139 (Maybe GlobalRdrEnv) -- Lexical environment for the module
140 -- (Maybe because we may have loaded it from
141 -- its precompiled interface)
142 ModIface -- New iface
143 (Maybe Linkable) -- New code; Nothing => compilation was not reqd
144 -- (old code is still valid)
149 compile hsc_env mod_summary
150 source_unchanged have_object old_iface = do
152 let dyn_flags = hsc_dflags hsc_env
153 this_mod = ms_mod mod_summary
154 src_flavour = ms_hsc_src mod_summary
156 showPass dyn_flags ("Compiling " ++ showModMsg have_object mod_summary)
158 let verb = verbosity dyn_flags
159 let location = ms_location mod_summary
160 let input_fn = expectJust "compile:hs" (ml_hs_file location)
161 let input_fnpp = expectJust "compile:hspp" (ms_hspp_file mod_summary)
163 when (verb >= 2) (hPutStrLn stderr ("compile: input file " ++ input_fnpp))
165 -- Add in the OPTIONS from the source file
166 -- This is nasty: we've done this once already, in the compilation manager
167 -- It might be better to cache the flags in the ml_hspp_file field,say
168 opts <- getOptionsFromSource input_fnpp
169 (dyn_flags,unhandled_flags) <- processDynamicFlags opts dyn_flags
170 checkProcessArgsResult unhandled_flags input_fn
172 let (basename, _) = splitFilename input_fn
174 -- We add the directory in which the .hs files resides) to the import path.
175 -- This is needed when we try to compile the .hc file later, if it
176 -- imports a _stub.h file that we created here.
177 let current_dir = directoryOf basename
178 old_paths <- readIORef v_Include_paths
179 writeIORef v_Include_paths (current_dir : old_paths)
180 -- put back the old include paths afterward.
181 later (writeIORef v_Include_paths old_paths) $ do
183 -- Figure out what lang we're generating
184 hsc_lang <- hscMaybeAdjustTarget StopLn src_flavour (hscTarget dyn_flags)
185 -- ... and what the next phase should be
186 next_phase <- hscNextPhase src_flavour hsc_lang
187 -- ... and what file to generate the output into
188 get_output_fn <- genOutputFilenameFunc next_phase False Nothing basename
189 output_fn <- get_output_fn next_phase (Just location)
191 let dyn_flags' = dyn_flags { hscTarget = hsc_lang,
192 hscOutName = output_fn,
193 hscStubCOutName = basename ++ "_stub.c",
194 hscStubHOutName = basename ++ "_stub.h",
195 extCoreName = basename ++ ".hcr" }
197 -- -no-recomp should also work with --make
198 let do_recomp = recompFlag dyn_flags
199 source_unchanged' = source_unchanged && do_recomp
200 hsc_env' = hsc_env { hsc_dflags = dyn_flags' }
203 hsc_result <- hscMain hsc_env' printErrorsAndWarnings mod_summary
204 source_unchanged' have_object old_iface
207 HscFail -> return CompErrs
209 HscNoRecomp details iface -> return (CompOK details Nothing iface Nothing)
211 HscRecomp details rdr_env iface
212 stub_h_exists stub_c_exists maybe_interpreted_code
214 | isHsBoot src_flavour -- No further compilation to do
215 -> return (CompOK details rdr_env iface Nothing)
217 | otherwise -- Normal Haskell source files
220 maybe_stub_o <- compileStub dyn_flags' stub_c_exists
221 let stub_unlinked = case maybe_stub_o of
223 Just stub_o -> [ DotO stub_o ]
225 (hs_unlinked, unlinked_time) <-
228 -- in interpreted mode, just return the compiled code
229 -- as our "unlinked" object.
231 case maybe_interpreted_code of
233 Just comp_bc -> return ([BCOs comp_bc], ms_hs_date mod_summary)
234 -- Why do we use the timestamp of the source file here,
235 -- rather than the current time? This works better in
236 -- the case where the local clock is out of sync
237 -- with the filesystem's clock. It's just as accurate:
238 -- if the source is modified, then the linkable will
241 Nothing -> panic "compile: no interpreted code"
243 -- we're in batch mode: finish the compilation pipeline.
245 let object_filename = ml_obj_file location
247 runPipeline StopLn "" dyn_flags
248 True Nothing output_fn (Just location)
249 -- the object filename comes from the ModLocation
251 o_time <- getModificationTime object_filename
252 return ([DotO object_filename], o_time)
254 let linkable = LM unlinked_time this_mod
255 (hs_unlinked ++ stub_unlinked)
257 return (CompOK details rdr_env iface (Just linkable))
259 -----------------------------------------------------------------------------
260 -- stub .h and .c files (for foreign export support)
262 compileStub dflags stub_c_exists
263 | not stub_c_exists = return Nothing
265 -- compile the _stub.c file w/ gcc
266 let stub_c = hscStubCOutName dflags
267 (_, stub_o) <- runPipeline StopLn "stub-compile" dflags
268 True{-persistent output-}
269 Nothing{-no specific output file-}
271 Nothing{-no ModLocation-}
275 -- ---------------------------------------------------------------------------
278 link :: GhciMode -- interactive or batch
279 -> DynFlags -- dynamic flags
280 -> Bool -- attempt linking in batch mode?
281 -> HomePackageTable -- what to link
284 -- For the moment, in the batch linker, we don't bother to tell doLink
285 -- which packages to link -- it just tries all that are available.
286 -- batch_attempt_linking should only be *looked at* in batch mode. It
287 -- should only be True if the upsweep was successful and someone
288 -- exports main, i.e., we have good reason to believe that linking
292 link Interactive dflags batch_attempt_linking hpt
293 = do -- Not Linking...(demand linker will do the job)
297 link Batch dflags batch_attempt_linking hpt
298 | batch_attempt_linking
301 home_mod_infos = moduleEnvElts hpt
303 -- the packages we depend on
304 pkg_deps = concatMap (dep_pkgs . mi_deps . hm_iface) home_mod_infos
306 -- the linkables to link
307 linkables = map hm_linkable home_mod_infos
309 when (verb >= 3) $ do
310 hPutStrLn stderr "link: linkables are ..."
311 hPutStrLn stderr (showSDoc (vcat (map ppr linkables)))
313 -- check for the -no-link flag
314 ghc_link <- readIORef v_GhcLink
316 then do when (verb >= 3) $
317 hPutStrLn stderr "link(batch): linking omitted (-c flag given)."
322 hPutStrLn stderr "Linking ..."
324 let getOfiles (LM _ _ us) = map nameOfObject (filter isObject us)
325 obj_files = concatMap getOfiles linkables
327 -- Don't showPass in Batch mode; doLink will do that for us.
328 staticLink dflags obj_files pkg_deps
330 when (verb >= 3) (hPutStrLn stderr "link: done")
332 -- staticLink only returns if it succeeds
336 = do when (verb >= 3) $ do
337 hPutStrLn stderr "link(batch): upsweep (partially) failed OR"
338 hPutStrLn stderr " Main.main not exported; not linking."
341 verb = verbosity dflags
343 -- ---------------------------------------------------------------------------
344 -- Run a compilation pipeline, consisting of multiple phases.
346 -- The DynFlags can be modified by phases in the pipeline (eg. by
347 -- OPTIONS pragmas), and the changes affect later phases in the
348 -- pipeline, but we throw away the resulting DynFlags at the end.
351 :: Phase -- When to stop
352 -> String -- "GhcMode" flag as a string
353 -> DynFlags -- Dynamic flags
354 -> Bool -- Final output is persistent?
355 -> Maybe FilePath -- Where to put the output, optionally
356 -> FilePath -- Input filename
357 -> Maybe ModLocation -- A ModLocation for this module, if we have one
358 -> IO (DynFlags, FilePath) -- (final flags, output filename)
360 runPipeline stop_phase mode_flag_string dflags keep_output
361 maybe_output_filename input_fn maybe_loc
363 let (basename, suffix) = splitFilename input_fn
364 start_phase = startPhase suffix
366 -- We want to catch cases of "you can't get there from here" before
367 -- we start the pipeline, because otherwise it will just run off the
370 -- There is a partial ordering on phases, where A < B iff A occurs
371 -- before B in a normal compilation pipeline.
373 when (not (start_phase `happensBefore` stop_phase)) $
375 ("flag `" ++ mode_flag_string
376 ++ "' is incompatible with source file `"
379 -- generate a function which will be used to calculate output file names
381 get_output_fn <- genOutputFilenameFunc stop_phase keep_output
382 maybe_output_filename basename
384 -- Execute the pipeline...
385 (dflags', output_fn, maybe_loc) <- pipeLoop dflags start_phase stop_phase input_fn
386 basename suffix get_output_fn maybe_loc
388 -- Sometimes, a compilation phase doesn't actually generate any output
389 -- (eg. the CPP phase when -fcpp is not turned on). If we end on this
390 -- stage, but we wanted to keep the output, then we have to explicitly
393 then do final_fn <- get_output_fn stop_phase maybe_loc
394 when (final_fn /= output_fn) $
395 copy dflags ("Copying `" ++ output_fn ++ "' to `" ++ final_fn
396 ++ "'") output_fn final_fn
397 return (dflags', final_fn)
399 return (dflags', output_fn)
402 pipeLoop :: DynFlags -> Phase -> Phase
403 -> FilePath -> String -> Suffix
404 -> (Phase -> Maybe ModLocation -> IO FilePath)
406 -> IO (DynFlags, FilePath, Maybe ModLocation)
408 pipeLoop dflags phase stop_phase
409 input_fn orig_basename orig_suff
410 orig_get_output_fn maybe_loc
412 | phase `eqPhase` stop_phase -- All done
413 = return (dflags, input_fn, maybe_loc)
415 | not (phase `happensBefore` stop_phase)
416 -- Something has gone wrong. We'll try to cover all the cases when
417 -- this could happen, so if we reach here it is a panic.
418 -- eg. it might happen if the -C flag is used on a source file that
419 -- has {-# OPTIONS -fasm #-}.
420 = panic ("pipeLoop: at phase " ++ show phase ++
421 " but I wanted to stop at phase " ++ show stop_phase)
424 = do { (next_phase, dflags', maybe_loc, output_fn)
425 <- runPhase phase stop_phase dflags orig_basename
426 orig_suff input_fn orig_get_output_fn maybe_loc
427 ; pipeLoop dflags' next_phase stop_phase output_fn
428 orig_basename orig_suff orig_get_output_fn maybe_loc }
430 genOutputFilenameFunc :: Phase -> Bool -> Maybe FilePath -> String
431 -> IO (Phase{-next phase-} -> Maybe ModLocation -> IO FilePath)
432 genOutputFilenameFunc stop_phase keep_final_output maybe_output_filename basename
434 hcsuf <- readIORef v_HC_suf
435 odir <- readIORef v_Output_dir
436 osuf <- readIORef v_Object_suf
437 keep_hc <- readIORef v_Keep_hc_files
439 keep_il <- readIORef v_Keep_il_files
440 keep_ilx <- readIORef v_Keep_ilx_files
442 keep_raw_s <- readIORef v_Keep_raw_s_files
443 keep_s <- readIORef v_Keep_s_files
445 myPhaseInputExt HCc = hcsuf
446 myPhaseInputExt StopLn = osuf
447 myPhaseInputExt other = phaseInputExt other
449 func next_phase maybe_location
450 | is_last_phase, Just f <- maybe_output_filename = return f
451 | is_last_phase && keep_final_output = persistent_fn
452 | keep_this_output = persistent_fn
453 | otherwise = newTempName suffix
456 is_last_phase = next_phase `eqPhase` stop_phase
458 -- sometimes, we keep output from intermediate stages
462 Mangle | keep_raw_s -> True
464 HCc | keep_hc -> True
467 suffix = myPhaseInputExt next_phase
469 -- persistent object files get put in odir
471 | StopLn <- next_phase = return odir_persistent
472 | otherwise = return persistent
474 persistent = basename ++ '.':suffix
477 | Just loc <- maybe_location = ml_obj_file loc
478 | Just d <- odir = replaceFilenameDirectory persistent d
479 | otherwise = persistent
484 -- -----------------------------------------------------------------------------
485 -- Each phase in the pipeline returns the next phase to execute, and the
486 -- name of the file in which the output was placed.
488 -- We must do things dynamically this way, because we often don't know
489 -- what the rest of the phases will be until part-way through the
490 -- compilation: for example, an {-# OPTIONS -fasm #-} at the beginning
491 -- of a source file can change the latter stages of the pipeline from
492 -- taking the via-C route to using the native code generator.
494 runPhase :: Phase -- Do this phase first
495 -> Phase -- Stop just before this phase
497 -> String -- basename of original input source
498 -> String -- its extension
499 -> FilePath -- name of file which contains the input to this phase.
500 -> (Phase -> Maybe ModLocation -> IO FilePath)
501 -- how to calculate the output filename
502 -> Maybe ModLocation -- the ModLocation, if we have one
503 -> IO (Phase, -- next phase
504 DynFlags, -- new dynamic flags
505 Maybe ModLocation, -- the ModLocation, if we have one
506 FilePath) -- output filename
508 -- Invariant: the output filename always contains the output
509 -- Interesting case: Hsc when there is no recompilation to do
510 -- Then the output filename is still a .o file
512 -------------------------------------------------------------------------------
515 runPhase (Unlit sf) _stop dflags _basename _suff input_fn get_output_fn maybe_loc
516 = do let unlit_flags = getOpts dflags opt_L
517 -- The -h option passes the file name for unlit to put in a #line directive
518 output_fn <- get_output_fn (Cpp sf) maybe_loc
520 SysTools.runUnlit dflags
521 (map SysTools.Option unlit_flags ++
522 [ SysTools.Option "-h"
523 , SysTools.Option input_fn
524 , SysTools.FileOption "" input_fn
525 , SysTools.FileOption "" output_fn
528 return (Cpp sf, dflags, maybe_loc, output_fn)
530 -------------------------------------------------------------------------------
531 -- Cpp phase : (a) gets OPTIONS out of file
532 -- (b) runs cpp if necessary
534 runPhase (Cpp sf) _stop dflags basename suff input_fn get_output_fn maybe_loc
535 = do src_opts <- getOptionsFromSource input_fn
536 (dflags,unhandled_flags) <- processDynamicFlags src_opts dflags
537 checkProcessArgsResult unhandled_flags (basename++'.':suff)
539 if not (cppFlag dflags) then
540 -- no need to preprocess CPP, just pass input file along
541 -- to the next phase of the pipeline.
542 return (HsPp sf, dflags, maybe_loc, input_fn)
544 output_fn <- get_output_fn (HsPp sf) maybe_loc
545 doCpp dflags True{-raw-} False{-no CC opts-} input_fn output_fn
546 return (HsPp sf, dflags, maybe_loc, output_fn)
548 -------------------------------------------------------------------------------
551 runPhase (HsPp sf) _stop dflags basename suff input_fn get_output_fn maybe_loc
552 = do if not (ppFlag dflags) then
553 -- no need to preprocess, just pass input file along
554 -- to the next phase of the pipeline.
555 return (Hsc sf, dflags, maybe_loc, input_fn)
557 let hspp_opts = getOpts dflags opt_F
558 hs_src_pp_opts <- readIORef v_Hs_source_pp_opts
559 let orig_fn = basename ++ '.':suff
560 output_fn <- get_output_fn (Hsc sf) maybe_loc
561 SysTools.runPp dflags
562 ( [ SysTools.Option orig_fn
563 , SysTools.Option input_fn
564 , SysTools.FileOption "" output_fn
566 map SysTools.Option hs_src_pp_opts ++
567 map SysTools.Option hspp_opts
569 return (Hsc sf, dflags, maybe_loc, output_fn)
571 -----------------------------------------------------------------------------
574 -- Compilation of a single module, in "legacy" mode (_not_ under
575 -- the direction of the compilation manager).
576 runPhase (Hsc src_flavour) stop dflags basename suff input_fn get_output_fn _maybe_loc
577 = do -- normal Hsc mode, not mkdependHS
579 -- we add the current directory (i.e. the directory in which
580 -- the .hs files resides) to the import path, since this is
581 -- what gcc does, and it's probably what you want.
582 let current_dir = directoryOf basename
584 paths <- readIORef v_Include_paths
585 writeIORef v_Include_paths (current_dir : paths)
587 -- gather the imports and module name
588 (hspp_buf,mod_name) <-
590 ExtCoreFile -> do { -- no explicit imports in ExtCore input.
591 ; m <- getCoreModuleName input_fn
592 ; return (Nothing, mkModule m) }
594 other -> do { buf <- hGetStringBuffer input_fn
595 ; (_,_,mod_name) <- getImports dflags buf input_fn
596 ; return (Just buf, mod_name) }
598 -- Build a ModLocation to pass to hscMain.
599 -- The source filename is rather irrelevant by now, but it's used
600 -- by hscMain for messages. hscMain also needs
601 -- the .hi and .o filenames, and this is as good a way
602 -- as any to generate them, and better than most. (e.g. takes
603 -- into accout the -osuf flags)
604 location1 <- mkHomeModLocation2 mod_name basename suff
606 -- Boot-ify it if necessary
607 let location2 | isHsBoot src_flavour = addBootSuffixLocn location1
608 | otherwise = location1
611 -- Take -ohi into account if present
612 -- This can't be done in mkHomeModuleLocation because
613 -- it only applies to the module being compiles
614 ohi <- readIORef v_Output_hi
615 let location3 | Just fn <- ohi = location2{ ml_hi_file = fn }
616 | otherwise = location2
618 -- Take -o into account if present
619 -- Very like -ohi, but we must *only* do this if we aren't linking
620 -- (If we're linking then the -o applies to the linked thing, not to
621 -- the object file for one module.)
622 -- Note the nasty duplication with the same computation in compileFile above
623 expl_o_file <- readIORef v_Output_file
624 ghc_link <- readIORef v_GhcLink
625 let location4 | Just ofile <- expl_o_file
627 = location3 { ml_obj_file = ofile }
628 | otherwise = location3
630 -- Tell the finder cache about this module
631 addHomeModuleToFinder mod_name location4
633 -- Make the ModSummary to hand to hscMain
634 src_timestamp <- getModificationTime (basename ++ '.':suff)
636 unused_field = panic "runPhase:ModSummary field"
637 -- Some fields are not looked at by hscMain
638 mod_summary = ModSummary { ms_mod = mod_name,
639 ms_hsc_src = src_flavour,
640 ms_hspp_file = Just input_fn,
641 ms_hspp_buf = hspp_buf,
642 ms_location = location4,
643 ms_hs_date = src_timestamp,
644 ms_imps = unused_field,
645 ms_srcimps = unused_field }
647 o_file = ml_obj_file location4 -- The real object file
650 -- Figure out if the source has changed, for recompilation avoidance.
652 -- Setting source_unchanged to True means that M.o seems
653 -- to be up to date wrt M.hs; so no need to recompile unless imports have
654 -- changed (which the compiler itself figures out).
655 -- Setting source_unchanged to False tells the compiler that M.o is out of
656 -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
657 let do_recomp = recompFlag dflags
659 if not do_recomp || not (isStopLn stop)
660 -- Set source_unchanged to False unconditionally if
661 -- (a) recompilation checker is off, or
662 -- (b) we aren't going all the way to .o file (e.g. ghc -S)
664 -- Otherwise look at file modification dates
665 else do o_file_exists <- doesFileExist o_file
667 then return False -- Need to recompile
668 else do t2 <- getModificationTime o_file
669 if t2 > src_timestamp
674 hsc_lang <- hscMaybeAdjustTarget stop src_flavour (hscTarget dflags)
675 next_phase <- hscNextPhase src_flavour hsc_lang
676 output_fn <- get_output_fn next_phase (Just location4)
678 let dflags' = dflags { hscTarget = hsc_lang,
679 hscOutName = output_fn,
680 hscStubCOutName = basename ++ "_stub.c",
681 hscStubHOutName = basename ++ "_stub.h",
682 extCoreName = basename ++ ".hcr" }
684 hsc_env <- newHscEnv OneShot dflags'
687 result <- hscMain hsc_env printErrorsAndWarnings
688 mod_summary source_unchanged
689 False -- No object file
694 HscFail -> throwDyn (PhaseFailed "hsc" (ExitFailure 1))
696 HscNoRecomp details iface -> do
697 SysTools.touch dflags' "Touching object file" o_file
698 return (StopLn, dflags', Just location4, o_file)
700 HscRecomp _details _rdr_env _iface
701 stub_h_exists stub_c_exists
702 _maybe_interpreted_code -> do
705 maybe_stub_o <- compileStub dflags' stub_c_exists
708 Just stub_o -> add v_Ld_inputs stub_o
710 -- In the case of hs-boot files, generate a dummy .o-boot
711 -- stamp file for the benefit of Make
713 HsBootFile -> SysTools.touch dflags' "Touching object file" o_file
716 return (next_phase, dflags', Just location4, output_fn)
718 -----------------------------------------------------------------------------
721 runPhase CmmCpp stop dflags basename suff input_fn get_output_fn maybe_loc
723 output_fn <- get_output_fn Cmm maybe_loc
724 doCpp dflags False{-not raw-} True{-include CC opts-} input_fn output_fn
725 return (Cmm, dflags, maybe_loc, output_fn)
727 runPhase Cmm stop dflags basename suff input_fn get_output_fn maybe_loc
729 hsc_lang <- hscMaybeAdjustTarget stop HsSrcFile (hscTarget dflags)
730 next_phase <- hscNextPhase HsSrcFile hsc_lang
731 output_fn <- get_output_fn next_phase maybe_loc
733 let dflags' = dflags { hscTarget = hsc_lang,
734 hscOutName = output_fn,
735 hscStubCOutName = basename ++ "_stub.c",
736 hscStubHOutName = basename ++ "_stub.h",
737 extCoreName = basename ++ ".hcr" }
739 ok <- hscCmmFile dflags' input_fn
741 when (not ok) $ throwDyn (PhaseFailed "cmm" (ExitFailure 1))
743 return (next_phase, dflags, maybe_loc, output_fn)
745 -----------------------------------------------------------------------------
748 -- we don't support preprocessing .c files (with -E) now. Doing so introduces
749 -- way too many hacks, and I can't say I've ever used it anyway.
751 runPhase cc_phase stop dflags basename suff input_fn get_output_fn maybe_loc
752 | cc_phase `eqPhase` Cc || cc_phase `eqPhase` HCc
753 = do let cc_opts = getOpts dflags opt_c
754 hcc = cc_phase `eqPhase` HCc
756 cmdline_include_paths <- readIORef v_Include_paths
758 -- HC files have the dependent packages stamped into them
759 pkgs <- if hcc then getHCFilePackages input_fn else return []
761 -- add package include paths even if we're just compiling .c
762 -- files; this is the Value Add(TM) that using ghc instead of
764 pkg_include_dirs <- getPackageIncludePath dflags pkgs
765 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
766 (cmdline_include_paths ++ pkg_include_dirs)
768 (md_c_flags, md_regd_c_flags) <- machdepCCOpts dflags
769 pic_c_flags <- picCCOpts dflags
771 let verb = getVerbFlag dflags
773 pkg_extra_cc_opts <- getPackageExtraCcOpts dflags pkgs
775 split_objs <- readIORef v_Split_object_files
776 let split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
779 excessPrecision <- readIORef v_Excess_precision
782 mangle <- readIORef v_Do_asm_mangling
784 | hcc && mangle = Mangle
786 output_fn <- get_output_fn next_phase maybe_loc
788 -- force the C compiler to interpret this file as C when
789 -- compiling .hc files, by adding the -x c option.
790 let langopt | hcc = [ SysTools.Option "-x", SysTools.Option "c"]
793 SysTools.runCc dflags (langopt ++
794 [ SysTools.FileOption "" input_fn
795 , SysTools.Option "-o"
796 , SysTools.FileOption "" output_fn
798 ++ map SysTools.Option (
804 ++ [ verb, "-S", "-Wimplicit", "-O" ]
805 ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
808 ++ (if excessPrecision then [] else [ "-ffloat-store" ])
813 return (next_phase, dflags, maybe_loc, output_fn)
815 -- ToDo: postprocess the output from gcc
817 -----------------------------------------------------------------------------
820 runPhase Mangle stop dflags _basename _suff input_fn get_output_fn maybe_loc
821 = do let mangler_opts = getOpts dflags opt_m
824 machdep_opts <- return [ show (stolen_x86_regs dflags) ]
826 machdep_opts <- return []
829 split <- readIORef v_Split_object_files
831 | split = SplitMangle
833 output_fn <- get_output_fn next_phase maybe_loc
835 SysTools.runMangle dflags (map SysTools.Option mangler_opts
836 ++ [ SysTools.FileOption "" input_fn
837 , SysTools.FileOption "" output_fn
839 ++ map SysTools.Option machdep_opts)
841 return (next_phase, dflags, maybe_loc, output_fn)
843 -----------------------------------------------------------------------------
846 runPhase SplitMangle stop dflags _basename _suff input_fn get_output_fn maybe_loc
847 = do -- tmp_pfx is the prefix used for the split .s files
848 -- We also use it as the file to contain the no. of split .s files (sigh)
849 split_s_prefix <- SysTools.newTempName "split"
850 let n_files_fn = split_s_prefix
852 SysTools.runSplit dflags
853 [ SysTools.FileOption "" input_fn
854 , SysTools.FileOption "" split_s_prefix
855 , SysTools.FileOption "" n_files_fn
858 -- Save the number of split files for future references
859 s <- readFile n_files_fn
860 let n_files = read s :: Int
861 writeIORef v_Split_info (split_s_prefix, n_files)
863 -- Remember to delete all these files
864 addFilesToClean [ split_s_prefix ++ "__" ++ show n ++ ".s"
867 return (SplitAs, dflags, maybe_loc, "**splitmangle**")
868 -- we don't use the filename
870 -----------------------------------------------------------------------------
873 runPhase As stop dflags _basename _suff input_fn get_output_fn maybe_loc
874 = do let as_opts = getOpts dflags opt_a
875 cmdline_include_paths <- readIORef v_Include_paths
877 output_fn <- get_output_fn StopLn maybe_loc
879 -- we create directories for the object file, because it
880 -- might be a hierarchical module.
881 createDirectoryHierarchy (directoryOf output_fn)
883 SysTools.runAs dflags
884 (map SysTools.Option as_opts
885 ++ [ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ]
886 ++ [ SysTools.Option "-c"
887 , SysTools.FileOption "" input_fn
888 , SysTools.Option "-o"
889 , SysTools.FileOption "" output_fn
892 return (StopLn, dflags, maybe_loc, output_fn)
895 runPhase SplitAs stop dflags basename _suff _input_fn get_output_fn maybe_loc
896 = do let as_opts = getOpts dflags opt_a
898 (split_s_prefix, n) <- readIORef v_Split_info
900 odir <- readIORef v_Output_dir
901 let real_odir = case odir of
902 Nothing -> basename ++ "_split"
906 = do let input_s = split_s_prefix ++ "__" ++ show n ++ ".s"
907 let output_o = replaceFilenameDirectory
908 (basename ++ "__" ++ show n ++ ".o")
910 real_o <- osuf_ify output_o
911 SysTools.runAs dflags
912 (map SysTools.Option as_opts ++
913 [ SysTools.Option "-c"
914 , SysTools.Option "-o"
915 , SysTools.FileOption "" real_o
916 , SysTools.FileOption "" input_s
919 mapM_ assemble_file [1..n]
921 output_fn <- get_output_fn StopLn maybe_loc
922 return (StopLn, dflags, maybe_loc, output_fn)
925 -----------------------------------------------------------------------------
927 -- Run ilx2il over the ILX output, getting an IL file
929 runPhase Ilx2Il stop dflags _basename _suff input_fn get_output_fn maybe_loc
930 = do let ilx2il_opts = getOpts dflags opt_I
931 SysTools.runIlx2il (map SysTools.Option ilx2il_opts
932 ++ [ SysTools.Option "--no-add-suffix-to-assembly",
933 SysTools.Option "mscorlib",
934 SysTools.Option "-o",
935 SysTools.FileOption "" output_fn,
936 SysTools.FileOption "" input_fn ])
939 -----------------------------------------------------------------------------
941 -- Run ilasm over the IL, getting a DLL
943 runPhase Ilasm stop dflags _basename _suff input_fn get_output_fn maybe_loc
944 = do let ilasm_opts = getOpts dflags opt_i
945 SysTools.runIlasm (map SysTools.Option ilasm_opts
946 ++ [ SysTools.Option "/QUIET",
947 SysTools.Option "/DLL",
948 SysTools.FileOption "/OUT=" output_fn,
949 SysTools.FileOption "" input_fn ])
954 -----------------------------------------------------------------------------
955 -- MoveBinary sort-of-phase
956 -- After having produced a binary, move it somewhere else and generate a
957 -- wrapper script calling the binary. Currently, we need this only in
958 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
959 -- central directory.
960 -- This is called from staticLink below, after linking. I haven't made it
961 -- a separate phase to minimise interfering with other modules, and
962 -- we don't need the generality of a phase (MoveBinary is always
963 -- done after linking and makes only sense in a parallel setup) -- HWL
965 runPhase_MoveBinary input_fn
968 pvm_root <- getEnv "PVM_ROOT"
969 pvm_arch <- getEnv "PVM_ARCH"
971 pvm_executable_base = "=" ++ input_fn
972 pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
973 -- nuke old binary; maybe use configur'ed names for cp and rm?
974 system ("rm -f " ++ pvm_executable)
975 -- move the newly created binary into PVM land
976 system ("cp -p " ++ input_fn ++ " " ++ pvm_executable)
977 -- generate a wrapper script for running a parallel prg under PVM
978 writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
981 -- generates a Perl skript starting a parallel prg under PVM
982 mk_pvm_wrapper_script :: String -> String -> String -> String
983 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
985 "eval 'exec perl -S $0 ${1+\"$@\"}'",
986 " if $running_under_some_shell;",
987 "# =!=!=!=!=!=!=!=!=!=!=!",
988 "# This script is automatically generated: DO NOT EDIT!!!",
989 "# Generated by Glasgow Haskell Compiler",
990 "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
992 "$pvm_executable = '" ++ pvm_executable ++ "';",
993 "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
994 "$SysMan = '" ++ sysMan ++ "';",
996 {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
997 "# first, some magical shortcuts to run "commands" on the binary",
998 "# (which is hidden)",
999 "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
1000 " local($cmd) = $1;",
1001 " system("$cmd $pvm_executable");",
1002 " exit(0); # all done",
1005 "# Now, run the real binary; process the args first",
1006 "$ENV{'PE'} = $pvm_executable_base;", -- ++ pvm_executable_base,
1008 "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
1009 "@nonPVM_args = ();",
1010 "$in_RTS_args = 0;",
1012 "args: while ($a = shift(@ARGV)) {",
1013 " if ( $a eq '+RTS' ) {",
1014 " $in_RTS_args = 1;",
1015 " } elsif ( $a eq '-RTS' ) {",
1016 " $in_RTS_args = 0;",
1018 " if ( $a eq '-d' && $in_RTS_args ) {",
1020 " } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
1021 " $nprocessors = $1;",
1022 " } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
1023 " $nprocessors = $1;",
1025 " push(@nonPVM_args, $a);",
1029 "local($return_val) = 0;",
1030 "# Start the parallel execution by calling SysMan",
1031 "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
1032 "$return_val = $?;",
1033 "# ToDo: fix race condition moving files and flushing them!!",
1034 "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
1035 "exit($return_val);"
1038 -----------------------------------------------------------------------------
1039 -- Complain about non-dynamic flags in OPTIONS pragmas
1041 checkProcessArgsResult flags filename
1042 = do when (notNull flags) (throwDyn (ProgramError (
1043 showSDoc (hang (text filename <> char ':')
1044 4 (text "unknown flags in {-# OPTIONS #-} pragma:" <+>
1045 hsep (map text flags)))
1048 -----------------------------------------------------------------------------
1049 -- Look for the /* GHC_PACKAGES ... */ comment at the top of a .hc file
1051 getHCFilePackages :: FilePath -> IO [PackageId]
1052 getHCFilePackages filename =
1053 EXCEPTION.bracket (openFile filename ReadMode) hClose $ \h -> do
1056 '/':'*':' ':'G':'H':'C':'_':'P':'A':'C':'K':'A':'G':'E':'S':rest ->
1057 return (map stringToPackageId (words rest))
1061 -----------------------------------------------------------------------------
1062 -- Static linking, of .o files
1064 -- The list of packages passed to link is the list of packages on
1065 -- which this program depends, as discovered by the compilation
1066 -- manager. It is combined with the list of packages that the user
1067 -- specifies on the command line with -package flags.
1069 -- In one-shot linking mode, we can't discover the package
1070 -- dependencies (because we haven't actually done any compilation or
1071 -- read any interface files), so the user must explicitly specify all
1074 staticLink :: DynFlags -> [FilePath] -> [PackageId] -> IO ()
1075 staticLink dflags o_files dep_packages = do
1076 let verb = getVerbFlag dflags
1077 static <- readIORef v_Static
1078 no_hs_main <- readIORef v_NoHsMain
1080 -- get the full list of packages to link with, by combining the
1081 -- explicit packages with the auto packages and all of their
1082 -- dependencies, and eliminating duplicates.
1084 o_file <- readIORef v_Output_file
1085 #if defined(mingw32_HOST_OS)
1086 let output_fn = case o_file of { Just s -> s; Nothing -> "main.exe"; }
1088 let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
1091 pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1092 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1094 lib_paths <- readIORef v_Library_paths
1095 let lib_path_opts = map ("-L"++) lib_paths
1097 pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1099 #ifdef darwin_TARGET_OS
1100 pkg_framework_paths <- getPackageFrameworkPath dflags dep_packages
1101 let pkg_framework_path_opts = map ("-F"++) pkg_framework_paths
1103 framework_paths <- readIORef v_Framework_paths
1104 let framework_path_opts = map ("-F"++) framework_paths
1106 pkg_frameworks <- getPackageFrameworks dflags dep_packages
1107 let pkg_framework_opts = concat [ ["-framework", fw] | fw <- pkg_frameworks ]
1108 frameworks <- readIORef v_Cmdline_frameworks
1109 let framework_opts = concat [ ["-framework", fw] | fw <- reverse frameworks ]
1110 -- reverse because they're added in reverse order from the cmd line
1113 -- probably _stub.o files
1114 extra_ld_inputs <- readIORef v_Ld_inputs
1116 -- opts from -optl-<blah> (including -l<blah> options)
1117 extra_ld_opts <- getStaticOpts v_Opt_l
1119 ways <- readIORef v_Ways
1121 -- Here are some libs that need to be linked at the *end* of
1122 -- the command line, because they contain symbols that are referred to
1123 -- by the RTS. We can't therefore use the ordinary way opts for these.
1125 debug_opts | WayDebug `elem` ways = [
1126 #if defined(HAVE_LIBBFD)
1133 thread_opts | WayThreaded `elem` ways = [
1134 #if !defined(mingw32_TARGET_OS) && !defined(freebsd_TARGET_OS)
1137 #if defined(osf3_TARGET_OS)
1143 (md_c_flags, _) <- machdepCCOpts dflags
1144 SysTools.runLink dflags (
1145 [ SysTools.Option verb
1146 , SysTools.Option "-o"
1147 , SysTools.FileOption "" output_fn
1149 ++ map SysTools.Option (
1155 #ifdef darwin_TARGET_OS
1156 ++ framework_path_opts
1159 ++ pkg_lib_path_opts
1161 #ifdef darwin_TARGET_OS
1162 ++ pkg_framework_path_opts
1163 ++ pkg_framework_opts
1169 -- parallel only: move binary to another dir -- HWL
1170 ways_ <- readIORef v_Ways
1171 when (WayPar `elem` ways_)
1172 (do success <- runPhase_MoveBinary output_fn
1173 if success then return ()
1174 else throwDyn (InstallationError ("cannot move binary to PVM dir")))
1176 -----------------------------------------------------------------------------
1177 -- Making a DLL (only for Win32)
1179 doMkDLL :: DynFlags -> [String] -> [PackageId] -> IO ()
1180 doMkDLL dflags o_files dep_packages = do
1181 let verb = getVerbFlag dflags
1182 static <- readIORef v_Static
1183 no_hs_main <- readIORef v_NoHsMain
1185 o_file <- readIORef v_Output_file
1186 let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
1188 pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1189 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1191 lib_paths <- readIORef v_Library_paths
1192 let lib_path_opts = map ("-L"++) lib_paths
1194 pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1196 -- probably _stub.o files
1197 extra_ld_inputs <- readIORef v_Ld_inputs
1199 -- opts from -optdll-<blah>
1200 extra_ld_opts <- getStaticOpts v_Opt_dll
1202 let pstate = pkgState dflags
1203 rts_id | ExtPackage id <- rtsPackageId pstate = id
1204 | otherwise = panic "staticLink: rts package missing"
1205 base_id | ExtPackage id <- basePackageId pstate = id
1206 | otherwise = panic "staticLink: base package missing"
1207 rts_pkg = getPackageDetails pstate rts_id
1208 base_pkg = getPackageDetails pstate base_id
1210 let extra_os = if static || no_hs_main
1212 else [ head (libraryDirs rts_pkg) ++ "/Main.dll_o",
1213 head (libraryDirs base_pkg) ++ "/PrelMain.dll_o" ]
1215 (md_c_flags, _) <- machdepCCOpts dflags
1216 SysTools.runMkDLL dflags
1217 ([ SysTools.Option verb
1218 , SysTools.Option "-o"
1219 , SysTools.FileOption "" output_fn
1221 ++ map SysTools.Option (
1225 ++ [ "--target=i386-mingw32" ]
1229 ++ pkg_lib_path_opts
1231 ++ (if "--def" `elem` (concatMap words extra_ld_opts)
1233 else [ "--export-all" ])
1236 -- -----------------------------------------------------------------------------
1239 doCpp :: DynFlags -> Bool -> Bool -> FilePath -> FilePath -> IO ()
1240 doCpp dflags raw include_cc_opts input_fn output_fn = do
1241 let hscpp_opts = getOpts dflags opt_P
1243 cmdline_include_paths <- readIORef v_Include_paths
1245 pkg_include_dirs <- getPackageIncludePath dflags []
1246 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
1247 (cmdline_include_paths ++ pkg_include_dirs)
1249 let verb = getVerbFlag dflags
1251 cc_opts <- if not include_cc_opts
1253 else do let optc = getOpts dflags opt_c
1254 (md_c_flags, _) <- machdepCCOpts dflags
1255 return (optc ++ md_c_flags)
1257 let cpp_prog args | raw = SysTools.runCpp dflags args
1258 | otherwise = SysTools.runCc dflags (SysTools.Option "-E" : args)
1261 [ "-D" ++ HOST_OS ++ "_BUILD_OS=1",
1262 "-D" ++ HOST_ARCH ++ "_BUILD_ARCH=1",
1263 "-D" ++ TARGET_OS ++ "_HOST_OS=1",
1264 "-D" ++ TARGET_ARCH ++ "_HOST_ARCH=1" ]
1265 -- remember, in code we *compile*, the HOST is the same our TARGET,
1266 -- and BUILD is the same as our HOST.
1268 cpp_prog ([SysTools.Option verb]
1269 ++ map SysTools.Option include_paths
1270 ++ map SysTools.Option hsSourceCppOpts
1271 ++ map SysTools.Option hscpp_opts
1272 ++ map SysTools.Option cc_opts
1273 ++ map SysTools.Option target_defs
1274 ++ [ SysTools.Option "-x"
1275 , SysTools.Option "c"
1276 , SysTools.Option input_fn
1277 -- We hackily use Option instead of FileOption here, so that the file
1278 -- name is not back-slashed on Windows. cpp is capable of
1279 -- dealing with / in filenames, so it works fine. Furthermore
1280 -- if we put in backslashes, cpp outputs #line directives
1281 -- with *double* backslashes. And that in turn means that
1282 -- our error messages get double backslashes in them.
1283 -- In due course we should arrange that the lexer deals
1284 -- with these \\ escapes properly.
1285 , SysTools.Option "-o"
1286 , SysTools.FileOption "" output_fn
1289 -- -----------------------------------------------------------------------------
1292 hscNextPhase :: HscSource -> HscTarget -> IO Phase
1293 hscNextPhase HsBootFile hsc_lang
1296 hscNextPhase other hsc_lang = do
1297 split <- readIORef v_Split_object_files
1298 return (case hsc_lang of
1300 HscAsm | split -> SplitMangle
1302 HscNothing -> StopLn
1303 HscInterpreted -> StopLn
1307 hscMaybeAdjustTarget :: Phase -> HscSource -> HscTarget -> IO HscTarget
1308 hscMaybeAdjustTarget stop HsBootFile current_hsc_lang
1309 = return HscNothing -- No output (other than Foo.hi-boot) for hs-boot files
1310 hscMaybeAdjustTarget stop other current_hsc_lang
1311 = do { keep_hc <- readIORef v_Keep_hc_files
1313 -- don't change the lang if we're interpreting
1314 | current_hsc_lang == HscInterpreted = current_hsc_lang
1316 -- force -fvia-C if we are being asked for a .hc file
1317 | HCc <- stop = HscC
1319 -- otherwise, stick to the plan
1320 | otherwise = current_hsc_lang