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 runPipeline, staticLink,
16 -- Interfaces for the compilation manager (interpreted/batch-mode)
18 compile, CompResult(..),
25 #include "HsVersions.h"
34 import SysTools ( newTempName, addFilesToClean, getSysMan, copy )
35 import qualified SysTools
44 import RdrName ( GlobalRdrEnv )
47 import BasicTypes ( SuccessFlag(..) )
48 import Maybes ( expectJust )
50 import ParserCoreUtils ( getCoreModuleName )
53 import DATA_IOREF ( readIORef, writeIORef )
55 import Time ( ClockTime )
63 -- ---------------------------------------------------------------------------
66 -- Just preprocess a file, put the result in a temp. file (used by the
67 -- compilation manager during the summary phase).
69 preprocess :: FilePath -> IO FilePath
71 ASSERT(isHaskellSrcFilename filename)
72 do restoreDynFlags -- Restore to state of last save
73 runPipeline (StopBefore Hsc) ("preprocess")
74 False{-temporary output file-}
75 Nothing{-no specific output file-}
77 Nothing{-no ModLocation-}
79 -- ---------------------------------------------------------------------------
82 -- Compile a single module, under the control of the compilation manager.
84 -- This is the interface between the compilation manager and the
85 -- compiler proper (hsc), where we deal with tedious details like
86 -- reading the OPTIONS pragma from the source file, and passing the
87 -- output of hsc through the C compiler.
89 -- The driver sits between 'compile' and 'hscMain', translating calls
90 -- to the former into calls to the latter, and results from the latter
91 -- into results from the former. It does things like preprocessing
92 -- the .hs file if necessary, and compiling up the .stub_c files to
93 -- generate Linkables.
95 -- NB. No old interface can also mean that the source has changed.
100 -> ClockTime -- timestamp of original source file
101 -> Bool -- True <=> source unchanged
102 -> Bool -- True <=> have object
103 -> Maybe ModIface -- old interface, if available
107 = CompOK ModDetails -- New details
108 (Maybe GlobalRdrEnv) -- Lexical environment for the module
109 -- (Maybe because we may have loaded it from
110 -- its precompiled interface)
111 ModIface -- New iface
112 (Maybe Linkable) -- New code; Nothing => compilation was not reqd
113 -- (old code is still valid)
118 compile hsc_env this_mod location src_timestamp
119 source_unchanged have_object
122 dyn_flags <- restoreDynFlags -- Restore to the state of the last save
125 (showSDoc (text "Compiling" <+> ppr this_mod))
127 let verb = verbosity dyn_flags
128 let input_fn = expectJust "compile:hs" (ml_hs_file location)
129 let input_fnpp = expectJust "compile:hspp" (ml_hspp_file location)
130 let mod_name = moduleName this_mod
132 when (verb >= 2) (hPutStrLn stderr ("compile: input file " ++ input_fnpp))
134 opts <- getOptionsFromSource input_fnpp
135 processArgs dynamic_flags opts []
136 dyn_flags <- getDynFlags
138 let (basename, _) = splitFilename input_fn
140 -- figure out what lang we're generating
141 hsc_lang <- hscMaybeAdjustLang (hscLang dyn_flags)
142 -- figure out what the next phase should be
143 next_phase <- hscNextPhase hsc_lang
144 -- figure out what file to generate the output into
145 get_output_fn <- genOutputFilenameFunc False Nothing next_phase basename
146 output_fn <- get_output_fn next_phase (Just location)
148 let dyn_flags' = dyn_flags { hscLang = hsc_lang,
149 hscOutName = output_fn,
150 hscStubCOutName = basename ++ "_stub.c",
151 hscStubHOutName = basename ++ "_stub.h",
152 extCoreName = basename ++ ".hcr" }
154 -- -no-recomp should also work with --make
155 do_recomp <- readIORef v_Recomp
156 let source_unchanged' = source_unchanged && do_recomp
157 hsc_env' = hsc_env { hsc_dflags = dyn_flags' }
160 hsc_result <- hscMain hsc_env' printErrorsAndWarnings this_mod location
161 source_unchanged' have_object old_iface
164 HscFail -> return CompErrs
166 HscNoRecomp details iface -> return (CompOK details Nothing iface Nothing)
168 HscRecomp details rdr_env iface
169 stub_h_exists stub_c_exists maybe_interpreted_code -> do
171 maybe_stub_o <- compileStub dyn_flags' stub_c_exists
172 let stub_unlinked = case maybe_stub_o of
174 Just stub_o -> [ DotO stub_o ]
176 (hs_unlinked, unlinked_time) <-
179 -- in interpreted mode, just return the compiled code
180 -- as our "unlinked" object.
182 case maybe_interpreted_code of
184 Just comp_bc -> return ([BCOs comp_bc], src_timestamp)
185 -- Why do we use the timestamp of the source file here,
186 -- rather than the current time? This works better in
187 -- the case where the local clock is out of sync
188 -- with the filesystem's clock. It's just as accurate:
189 -- if the source is modified, then the linkable will
192 Nothing -> panic "compile: no interpreted code"
194 -- we're in batch mode: finish the compilation pipeline.
196 let object_filename = ml_obj_file location
198 runPipeline (StopBefore Ln) ""
199 True Nothing output_fn (Just location)
200 -- the object filename comes from the ModLocation
202 o_time <- getModificationTime object_filename
203 return ([DotO object_filename], o_time)
205 let linkable = LM unlinked_time mod_name
206 (hs_unlinked ++ stub_unlinked)
208 return (CompOK details rdr_env iface (Just linkable))
210 -----------------------------------------------------------------------------
211 -- stub .h and .c files (for foreign export support)
213 compileStub dflags stub_c_exists
214 | not stub_c_exists = return Nothing
216 -- compile the _stub.c file w/ gcc
217 let stub_c = hscStubCOutName dflags
218 stub_o <- runPipeline (StopBefore Ln) "stub-compile"
219 True{-persistent output-}
220 Nothing{-no specific output file-}
222 Nothing{-no ModLocation-}
226 -- ---------------------------------------------------------------------------
229 link :: GhciMode -- interactive or batch
230 -> DynFlags -- dynamic flags
231 -> Bool -- attempt linking in batch mode?
232 -> HomePackageTable -- what to link
235 -- For the moment, in the batch linker, we don't bother to tell doLink
236 -- which packages to link -- it just tries all that are available.
237 -- batch_attempt_linking should only be *looked at* in batch mode. It
238 -- should only be True if the upsweep was successful and someone
239 -- exports main, i.e., we have good reason to believe that linking
243 link Interactive dflags batch_attempt_linking hpt
244 = do -- Not Linking...(demand linker will do the job)
248 link Batch dflags batch_attempt_linking hpt
249 | batch_attempt_linking
252 home_mod_infos = moduleEnvElts hpt
254 -- the packages we depend on
255 pkg_deps = concatMap (dep_pkgs . mi_deps . hm_iface) home_mod_infos
257 -- the linkables to link
258 linkables = map hm_linkable home_mod_infos
260 when (verb >= 3) $ do
261 hPutStrLn stderr "link: linkables are ..."
262 hPutStrLn stderr (showSDoc (vcat (map ppr linkables)))
264 -- check for the -no-link flag
265 omit_linking <- readIORef v_NoLink
267 then do when (verb >= 3) $
268 hPutStrLn stderr "link(batch): linking omitted (-no-link flag given)."
273 hPutStrLn stderr "Linking ..."
275 let getOfiles (LM _ _ us) = map nameOfObject (filter isObject us)
276 obj_files = concatMap getOfiles linkables
278 -- Don't showPass in Batch mode; doLink will do that for us.
279 staticLink obj_files pkg_deps
281 when (verb >= 3) (hPutStrLn stderr "link: done")
283 -- staticLink only returns if it succeeds
287 = do when (verb >= 3) $ do
288 hPutStrLn stderr "link(batch): upsweep (partially) failed OR"
289 hPutStrLn stderr " Main.main not exported; not linking."
292 verb = verbosity dflags
294 -- ---------------------------------------------------------------------------
295 -- Run a compilation pipeline, consisting of multiple phases.
298 :: GhcMode -- when to stop
299 -> String -- "stop after" flag
300 -> Bool -- final output is persistent?
301 -> Maybe FilePath -- where to put the output, optionally
302 -> FilePath -- input filename
303 -> Maybe ModLocation -- a ModLocation for this module, if we have one
304 -> IO FilePath -- output filename
306 runPipeline todo stop_flag keep_output maybe_output_filename input_fn maybe_loc
308 split <- readIORef v_Split_object_files
309 let (basename, suffix) = splitFilename input_fn
310 start_phase = startPhase suffix
312 stop_phase = case todo of
313 StopBefore As | split -> SplitAs
314 StopBefore phase -> phase
319 -- We want to catch cases of "you can't get there from here" before
320 -- we start the pipeline, because otherwise it will just run off the
323 -- There is a partial ordering on phases, where A < B iff A occurs
324 -- before B in a normal compilation pipeline.
326 when (not (start_phase `happensBefore` stop_phase)) $
328 ("flag `" ++ stop_flag
329 ++ "' is incompatible with source file `"
332 -- generate a function which will be used to calculate output file names
334 get_output_fn <- genOutputFilenameFunc keep_output maybe_output_filename
337 -- and execute the pipeline...
338 (output_fn, maybe_loc) <-
339 pipeLoop start_phase stop_phase input_fn basename suffix
340 get_output_fn maybe_loc
342 -- sometimes, a compilation phase doesn't actually generate any output
343 -- (eg. the CPP phase when -fcpp is not turned on). If we end on this
344 -- stage, but we wanted to keep the output, then we have to explicitly
347 then do final_fn <- get_output_fn stop_phase maybe_loc
348 when (final_fn /= output_fn) $
349 copy ("Copying `" ++ output_fn ++ "' to `" ++ final_fn
350 ++ "'") output_fn final_fn
356 pipeLoop :: Phase -> Phase -> FilePath -> String -> Suffix
357 -> (Phase -> Maybe ModLocation -> IO FilePath)
358 -> Maybe ModLocation -> IO (FilePath, Maybe ModLocation)
360 pipeLoop phase stop_phase input_fn orig_basename orig_suff
361 get_output_fn maybe_loc
363 | phase == stop_phase = return (input_fn, maybe_loc) -- all done
365 | not (phase `happensBefore` stop_phase) =
366 -- Something has gone wrong. We'll try to cover all the cases when
367 -- this could happen, so if we reach here it is a panic.
368 -- eg. it might happen if the -C flag is used on a source file that
369 -- has {-# OPTIONS -fasm #-}.
370 panic ("pipeLoop: at phase " ++ show phase ++
371 " but I wanted to stop at phase " ++ show stop_phase)
374 maybe_next_phase <- runPhase phase orig_basename orig_suff input_fn
375 get_output_fn maybe_loc
376 case maybe_next_phase of
377 (Nothing, maybe_loc, output_fn) -> do
378 -- we stopped early, but return the *final* filename
379 -- (it presumably already exists)
380 final_fn <- get_output_fn stop_phase maybe_loc
381 return (final_fn, maybe_loc)
382 (Just next_phase, maybe_loc, output_fn) ->
383 pipeLoop next_phase stop_phase output_fn
384 orig_basename orig_suff get_output_fn maybe_loc
387 genOutputFilenameFunc :: Bool -> Maybe FilePath -> Phase -> String
388 -> IO (Phase{-next phase-} -> Maybe ModLocation -> IO FilePath)
389 genOutputFilenameFunc keep_final_output maybe_output_filename
392 hcsuf <- readIORef v_HC_suf
393 odir <- readIORef v_Output_dir
394 osuf <- readIORef v_Object_suf
395 keep_hc <- readIORef v_Keep_hc_files
397 keep_il <- readIORef v_Keep_il_files
398 keep_ilx <- readIORef v_Keep_ilx_files
400 keep_raw_s <- readIORef v_Keep_raw_s_files
401 keep_s <- readIORef v_Keep_s_files
403 myPhaseInputExt HCc | Just s <- hcsuf = s
404 myPhaseInputExt Ln = osuf
405 myPhaseInputExt other = phaseInputExt other
407 func next_phase maybe_location
408 | is_last_phase, Just f <- maybe_output_filename = return f
409 | is_last_phase && keep_final_output = persistent_fn
410 | keep_this_output = persistent_fn
411 | otherwise = newTempName suffix
414 is_last_phase = next_phase == stop_phase
416 -- sometimes, we keep output from intermediate stages
420 Mangle | keep_raw_s -> True
422 HCc | keep_hc -> True
425 suffix = myPhaseInputExt next_phase
427 -- persistent object files get put in odir
429 | Ln <- next_phase = return odir_persistent
430 | otherwise = return persistent
432 persistent = basename ++ '.':suffix
435 | Just loc <- maybe_location = ml_obj_file loc
436 | Just d <- odir = replaceFilenameDirectory persistent d
437 | otherwise = persistent
442 -- -----------------------------------------------------------------------------
443 -- Each phase in the pipeline returns the next phase to execute, and the
444 -- name of the file in which the output was placed.
446 -- We must do things dynamically this way, because we often don't know
447 -- what the rest of the phases will be until part-way through the
448 -- compilation: for example, an {-# OPTIONS -fasm #-} at the beginning
449 -- of a source file can change the latter stages of the pipeline from
450 -- taking the via-C route to using the native code generator.
453 -> String -- basename of original input source
454 -> String -- its extension
455 -> FilePath -- name of file which contains the input to this phase.
456 -> (Phase -> Maybe ModLocation -> IO FilePath)
457 -- how to calculate the output filename
458 -> Maybe ModLocation -- the ModLocation, if we have one
459 -> IO (Maybe Phase, -- next phase
460 Maybe ModLocation, -- the ModLocation, if we have one
461 FilePath) -- output filename
463 -------------------------------------------------------------------------------
466 runPhase Unlit _basename _suff input_fn get_output_fn maybe_loc
467 = do unlit_flags <- getOpts opt_L
468 -- The -h option passes the file name for unlit to put in a #line directive
469 output_fn <- get_output_fn Cpp maybe_loc
471 SysTools.runUnlit (map SysTools.Option unlit_flags ++
472 [ SysTools.Option "-h"
473 , SysTools.Option input_fn
474 , SysTools.FileOption "" input_fn
475 , SysTools.FileOption "" output_fn
478 return (Just Cpp, maybe_loc, output_fn)
480 -------------------------------------------------------------------------------
483 runPhase Cpp basename suff input_fn get_output_fn maybe_loc
484 = do src_opts <- getOptionsFromSource input_fn
485 unhandled_flags <- processArgs dynamic_flags src_opts []
486 checkProcessArgsResult unhandled_flags basename suff
488 do_cpp <- dynFlag cppFlag
490 -- no need to preprocess CPP, just pass input file along
491 -- to the next phase of the pipeline.
492 return (Just HsPp, maybe_loc, input_fn)
494 output_fn <- get_output_fn HsPp maybe_loc
495 doCpp True{-raw-} False{-no CC opts-} input_fn output_fn
496 return (Just HsPp, maybe_loc, output_fn)
498 -------------------------------------------------------------------------------
501 runPhase HsPp basename suff input_fn get_output_fn maybe_loc
502 = do do_pp <- dynFlag ppFlag
504 -- no need to preprocess, just pass input file along
505 -- to the next phase of the pipeline.
506 return (Just Hsc, maybe_loc, input_fn)
508 hspp_opts <- getOpts opt_F
509 hs_src_pp_opts <- readIORef v_Hs_source_pp_opts
510 let orig_fn = basename ++ '.':suff
511 output_fn <- get_output_fn Hsc maybe_loc
512 SysTools.runPp ( [ SysTools.Option orig_fn
513 , SysTools.Option input_fn
514 , SysTools.FileOption "" output_fn
516 map SysTools.Option hs_src_pp_opts ++
517 map SysTools.Option hspp_opts
519 return (Just Hsc, maybe_loc, output_fn)
521 -----------------------------------------------------------------------------
524 -- Compilation of a single module, in "legacy" mode (_not_ under
525 -- the direction of the compilation manager).
526 runPhase Hsc basename suff input_fn get_output_fn _maybe_loc = do
527 todo <- readIORef v_GhcMode
528 if todo == DoMkDependHS then do
529 locn <- doMkDependHSPhase basename suff input_fn
530 return (Nothing, Just locn, input_fn) -- Ln is a dummy stop phase
533 -- normal Hsc mode, not mkdependHS
535 -- we add the current directory (i.e. the directory in which
536 -- the .hs files resides) to the import path, since this is
537 -- what gcc does, and it's probably what you want.
538 let current_dir = directoryOf basename
540 paths <- readIORef v_Include_paths
541 writeIORef v_Include_paths (current_dir : paths)
543 -- gather the imports and module name
545 if isExtCoreFilename ('.':suff)
547 -- no explicit imports in ExtCore input.
548 m <- getCoreModuleName input_fn
549 return ([], [], mkModuleName m)
551 getImportsFromFile input_fn
553 -- build a ModLocation to pass to hscMain.
554 (mod, location') <- mkHomeModLocation mod_name (basename ++ '.':suff)
556 -- take -ohi into account if present
557 ohi <- readIORef v_Output_hi
558 let location | Just fn <- ohi = location'{ ml_hi_file = fn }
559 | otherwise = location'
561 -- figure out if the source has changed, for recompilation avoidance.
562 -- only do this if we're eventually going to generate a .o file.
563 -- (ToDo: do when generating .hc files too?)
565 -- Setting source_unchanged to True means that M.o seems
566 -- to be up to date wrt M.hs; so no need to recompile unless imports have
567 -- changed (which the compiler itself figures out).
568 -- Setting source_unchanged to False tells the compiler that M.o is out of
569 -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
570 do_recomp <- readIORef v_Recomp
571 expl_o_file <- readIORef v_Output_file
573 let o_file -- if the -o option is given and IT IS THE OBJECT FILE FOR
574 -- THIS COMPILATION, then use that to determine if the
575 -- source is unchanged.
576 | Just x <- expl_o_file, todo == StopBefore Ln = x
577 | otherwise = ml_obj_file location
580 if not (do_recomp && ( todo == DoLink || todo == StopBefore Ln ))
582 else do t1 <- getModificationTime (basename ++ '.':suff)
583 o_file_exists <- doesFileExist o_file
585 then return False -- Need to recompile
586 else do t2 <- getModificationTime o_file
592 dyn_flags <- getDynFlags
593 hsc_lang <- hscMaybeAdjustLang (hscLang dyn_flags)
594 next_phase <- hscNextPhase hsc_lang
595 output_fn <- get_output_fn next_phase (Just location)
597 let dyn_flags' = dyn_flags { hscLang = hsc_lang,
598 hscOutName = output_fn,
599 hscStubCOutName = basename ++ "_stub.c",
600 hscStubHOutName = basename ++ "_stub.h",
601 extCoreName = basename ++ ".hcr" }
602 hsc_env <- newHscEnv OneShot dyn_flags'
605 result <- hscMain hsc_env printErrorsAndWarnings mod
606 location{ ml_hspp_file=Just input_fn }
613 HscFail -> throwDyn (PhaseFailed "hsc" (ExitFailure 1))
615 HscNoRecomp details iface -> do
616 SysTools.touch "Touching object file" o_file
617 return (Nothing, Just location, output_fn)
619 HscRecomp _details _rdr_env _iface
620 stub_h_exists stub_c_exists
621 _maybe_interpreted_code -> do
624 maybe_stub_o <- compileStub dyn_flags' stub_c_exists
627 Just stub_o -> add v_Ld_inputs stub_o
628 case hscLang dyn_flags of
629 HscNothing -> return (Nothing, Just location, output_fn)
630 _ -> return (Just next_phase, Just location, output_fn)
632 -----------------------------------------------------------------------------
635 runPhase CmmCpp basename suff input_fn get_output_fn maybe_loc
637 output_fn <- get_output_fn Cmm maybe_loc
638 doCpp False{-not raw-} True{-include CC opts-} input_fn output_fn
639 return (Just Cmm, maybe_loc, output_fn)
641 runPhase Cmm basename suff input_fn get_output_fn maybe_loc
643 dyn_flags <- getDynFlags
644 hsc_lang <- hscMaybeAdjustLang (hscLang dyn_flags)
645 next_phase <- hscNextPhase hsc_lang
646 output_fn <- get_output_fn next_phase maybe_loc
648 let dyn_flags' = dyn_flags { hscLang = hsc_lang,
649 hscOutName = output_fn,
650 hscStubCOutName = basename ++ "_stub.c",
651 hscStubHOutName = basename ++ "_stub.h",
652 extCoreName = basename ++ ".hcr" }
654 ok <- hscCmmFile dyn_flags' input_fn
656 when (not ok) $ throwDyn (PhaseFailed "cmm" (ExitFailure 1))
658 return (Just next_phase, maybe_loc, output_fn)
660 -----------------------------------------------------------------------------
663 -- we don't support preprocessing .c files (with -E) now. Doing so introduces
664 -- way too many hacks, and I can't say I've ever used it anyway.
666 runPhase cc_phase basename suff input_fn get_output_fn maybe_loc
667 | cc_phase == Cc || cc_phase == HCc
668 = do cc_opts <- getOpts opt_c
669 cmdline_include_paths <- readIORef v_Include_paths
671 split <- readIORef v_Split_object_files
672 mangle <- readIORef v_Do_asm_mangling
674 let hcc = cc_phase == HCc
677 | hcc && mangle = Mangle
680 output_fn <- get_output_fn next_phase maybe_loc
682 -- HC files have the dependent packages stamped into them
683 pkgs <- if hcc then getHCFilePackages input_fn else return []
685 -- add package include paths even if we're just compiling .c
686 -- files; this is the Value Add(TM) that using ghc instead of
688 pkg_include_dirs <- getPackageIncludePath pkgs
689 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
690 (cmdline_include_paths ++ pkg_include_dirs)
692 -- We add the flag -I- after all the include paths.
693 -- According to the gcc docs, this causes all -I paths
694 -- up to this point apply only to #include "..."
695 -- style includes. This prevents accidentally
696 -- shadowing a system include (eg. #include <stdio.h>)
697 -- by putting a file of the same name in the current
698 -- directory, for example.
700 mangle <- readIORef v_Do_asm_mangling
701 (md_c_flags, md_regd_c_flags) <- machdepCCOpts
705 pkg_extra_cc_opts <- getPackageExtraCcOpts pkgs
707 split_objs <- readIORef v_Split_object_files
708 let split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
711 excessPrecision <- readIORef v_Excess_precision
713 -- force the C compiler to interpret this file as C when
714 -- compiling .hc files, by adding the -x c option.
716 | cc_phase == HCc = [ SysTools.Option "-x", SysTools.Option "c"]
719 SysTools.runCc (langopt ++
720 [ SysTools.FileOption "" input_fn
721 , SysTools.Option "-o"
722 , SysTools.FileOption "" output_fn
724 ++ map SysTools.Option (
726 ++ (if cc_phase == HCc && mangle
729 ++ [ verb, "-S", "-Wimplicit", "-O" ]
730 ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
733 ++ (if excessPrecision then [] else [ "-ffloat-store" ])
738 return (Just next_phase, maybe_loc, output_fn)
740 -- ToDo: postprocess the output from gcc
742 -----------------------------------------------------------------------------
745 runPhase Mangle _basename _suff input_fn get_output_fn maybe_loc
746 = do mangler_opts <- getOpts opt_m
747 machdep_opts <- if (prefixMatch "i386" cTARGETPLATFORM)
748 then do n_regs <- dynFlag stolen_x86_regs
749 return [ show n_regs ]
752 split <- readIORef v_Split_object_files
754 | split = SplitMangle
756 output_fn <- get_output_fn next_phase maybe_loc
758 SysTools.runMangle (map SysTools.Option mangler_opts
759 ++ [ SysTools.FileOption "" input_fn
760 , SysTools.FileOption "" output_fn
762 ++ map SysTools.Option machdep_opts)
764 return (Just next_phase, maybe_loc, output_fn)
766 -----------------------------------------------------------------------------
769 runPhase SplitMangle _basename _suff input_fn get_output_fn maybe_loc
770 = do -- tmp_pfx is the prefix used for the split .s files
771 -- We also use it as the file to contain the no. of split .s files (sigh)
772 split_s_prefix <- SysTools.newTempName "split"
773 let n_files_fn = split_s_prefix
775 SysTools.runSplit [ SysTools.FileOption "" input_fn
776 , SysTools.FileOption "" split_s_prefix
777 , SysTools.FileOption "" n_files_fn
780 -- Save the number of split files for future references
781 s <- readFile n_files_fn
782 let n_files = read s :: Int
783 writeIORef v_Split_info (split_s_prefix, n_files)
785 -- Remember to delete all these files
786 addFilesToClean [ split_s_prefix ++ "__" ++ show n ++ ".s"
789 return (Just SplitAs, maybe_loc, "**splitmangle**")
790 -- we don't use the filename
792 -----------------------------------------------------------------------------
795 runPhase As _basename _suff input_fn get_output_fn maybe_loc
796 = do as_opts <- getOpts opt_a
797 cmdline_include_paths <- readIORef v_Include_paths
799 output_fn <- get_output_fn Ln maybe_loc
801 -- we create directories for the object file, because it
802 -- might be a hierarchical module.
803 createDirectoryHierarchy (directoryOf output_fn)
805 SysTools.runAs (map SysTools.Option as_opts
806 ++ [ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ]
807 ++ [ SysTools.Option "-c"
808 , SysTools.FileOption "" input_fn
809 , SysTools.Option "-o"
810 , SysTools.FileOption "" output_fn
813 return (Just Ln, maybe_loc, output_fn)
816 runPhase SplitAs basename _suff _input_fn get_output_fn maybe_loc
817 = do as_opts <- getOpts opt_a
819 (split_s_prefix, n) <- readIORef v_Split_info
821 odir <- readIORef v_Output_dir
822 let real_odir = case odir of
823 Nothing -> basename ++ "_split"
827 = do let input_s = split_s_prefix ++ "__" ++ show n ++ ".s"
828 let output_o = replaceFilenameDirectory
829 (basename ++ "__" ++ show n ++ ".o")
831 real_o <- osuf_ify output_o
832 SysTools.runAs (map SysTools.Option as_opts ++
833 [ SysTools.Option "-c"
834 , SysTools.Option "-o"
835 , SysTools.FileOption "" real_o
836 , SysTools.FileOption "" input_s
839 mapM_ assemble_file [1..n]
841 output_fn <- get_output_fn Ln maybe_loc
842 return (Just Ln, maybe_loc, output_fn)
845 -----------------------------------------------------------------------------
847 -- Run ilx2il over the ILX output, getting an IL file
849 runPhase Ilx2Il _basename _suff input_fn get_output_fn maybe_loc
850 = do ilx2il_opts <- getOpts opt_I
851 SysTools.runIlx2il (map SysTools.Option ilx2il_opts
852 ++ [ SysTools.Option "--no-add-suffix-to-assembly",
853 SysTools.Option "mscorlib",
854 SysTools.Option "-o",
855 SysTools.FileOption "" output_fn,
856 SysTools.FileOption "" input_fn ])
859 -----------------------------------------------------------------------------
861 -- Run ilasm over the IL, getting a DLL
863 runPhase Ilasm _basename _suff input_fn get_output_fn maybe_loc
864 = do ilasm_opts <- getOpts opt_i
865 SysTools.runIlasm (map SysTools.Option ilasm_opts
866 ++ [ SysTools.Option "/QUIET",
867 SysTools.Option "/DLL",
868 SysTools.FileOption "/OUT=" output_fn,
869 SysTools.FileOption "" input_fn ])
874 -----------------------------------------------------------------------------
875 -- MoveBinary sort-of-phase
876 -- After having produced a binary, move it somewhere else and generate a
877 -- wrapper script calling the binary. Currently, we need this only in
878 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
879 -- central directory.
880 -- This is called from staticLink below, after linking. I haven't made it
881 -- a separate phase to minimise interfering with other modules, and
882 -- we don't need the generality of a phase (MoveBinary is always
883 -- done after linking and makes only sense in a parallel setup) -- HWL
885 runPhase_MoveBinary input_fn
888 pvm_root <- getEnv "PVM_ROOT"
889 pvm_arch <- getEnv "PVM_ARCH"
891 pvm_executable_base = "=" ++ input_fn
892 pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
893 -- nuke old binary; maybe use configur'ed names for cp and rm?
894 system ("rm -f " ++ pvm_executable)
895 -- move the newly created binary into PVM land
896 system ("cp -p " ++ input_fn ++ " " ++ pvm_executable)
897 -- generate a wrapper script for running a parallel prg under PVM
898 writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
901 -- generates a Perl skript starting a parallel prg under PVM
902 mk_pvm_wrapper_script :: String -> String -> String -> String
903 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
905 "eval 'exec perl -S $0 ${1+\"$@\"}'",
906 " if $running_under_some_shell;",
907 "# =!=!=!=!=!=!=!=!=!=!=!",
908 "# This script is automatically generated: DO NOT EDIT!!!",
909 "# Generated by Glasgow Haskell Compiler",
910 "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
912 "$pvm_executable = '" ++ pvm_executable ++ "';",
913 "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
914 "$SysMan = '" ++ sysMan ++ "';",
916 {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
917 "# first, some magical shortcuts to run "commands" on the binary",
918 "# (which is hidden)",
919 "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
920 " local($cmd) = $1;",
921 " system("$cmd $pvm_executable");",
922 " exit(0); # all done",
925 "# Now, run the real binary; process the args first",
926 "$ENV{'PE'} = $pvm_executable_base;", -- ++ pvm_executable_base,
928 "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
929 "@nonPVM_args = ();",
932 "args: while ($a = shift(@ARGV)) {",
933 " if ( $a eq '+RTS' ) {",
934 " $in_RTS_args = 1;",
935 " } elsif ( $a eq '-RTS' ) {",
936 " $in_RTS_args = 0;",
938 " if ( $a eq '-d' && $in_RTS_args ) {",
940 " } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
941 " $nprocessors = $1;",
942 " } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
943 " $nprocessors = $1;",
945 " push(@nonPVM_args, $a);",
949 "local($return_val) = 0;",
950 "# Start the parallel execution by calling SysMan",
951 "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
953 "# ToDo: fix race condition moving files and flushing them!!",
954 "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
958 -----------------------------------------------------------------------------
959 -- Complain about non-dynamic flags in OPTIONS pragmas
961 checkProcessArgsResult flags basename suff
962 = do when (notNull flags) (throwDyn (ProgramError (
963 showSDoc (hang (text basename <> text ('.':suff) <> char ':')
964 4 (text "unknown flags in {-# OPTIONS #-} pragma:" <+>
965 hsep (map text flags)))
968 -----------------------------------------------------------------------------
969 -- Look for the /* GHC_PACKAGES ... */ comment at the top of a .hc file
971 getHCFilePackages :: FilePath -> IO [PackageName]
972 getHCFilePackages filename =
973 EXCEPTION.bracket (openFile filename ReadMode) hClose $ \h -> do
976 '/':'*':' ':'G':'H':'C':'_':'P':'A':'C':'K':'A':'G':'E':'S':rest ->
977 return (map mkPackageName (words rest))
981 -----------------------------------------------------------------------------
982 -- Static linking, of .o files
984 -- The list of packages passed to link is the list of packages on
985 -- which this program depends, as discovered by the compilation
986 -- manager. It is combined with the list of packages that the user
987 -- specifies on the command line with -package flags.
989 -- In one-shot linking mode, we can't discover the package
990 -- dependencies (because we haven't actually done any compilation or
991 -- read any interface files), so the user must explicitly specify all
994 staticLink :: [FilePath] -> [PackageName] -> IO ()
995 staticLink o_files dep_packages = do
997 static <- readIORef v_Static
998 no_hs_main <- readIORef v_NoHsMain
1000 -- get the full list of packages to link with, by combining the
1001 -- explicit packages with the auto packages and all of their
1002 -- dependencies, and eliminating duplicates.
1004 o_file <- readIORef v_Output_file
1005 #if defined(mingw32_HOST_OS)
1006 let output_fn = case o_file of { Just s -> s; Nothing -> "main.exe"; }
1008 let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
1011 pkg_lib_paths <- getPackageLibraryPath dep_packages
1012 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1014 lib_paths <- readIORef v_Library_paths
1015 let lib_path_opts = map ("-L"++) lib_paths
1017 pkg_link_opts <- getPackageLinkOpts dep_packages
1019 #ifdef darwin_TARGET_OS
1020 pkg_framework_paths <- getPackageFrameworkPath dep_packages
1021 let pkg_framework_path_opts = map ("-F"++) pkg_framework_paths
1023 framework_paths <- readIORef v_Framework_paths
1024 let framework_path_opts = map ("-F"++) framework_paths
1026 pkg_frameworks <- getPackageFrameworks dep_packages
1027 let pkg_framework_opts = concat [ ["-framework", fw] | fw <- pkg_frameworks ]
1029 frameworks <- readIORef v_Cmdline_frameworks
1030 let framework_opts = concat [ ["-framework", fw] | fw <- reverse frameworks ]
1031 -- reverse because they're added in reverse order from the cmd line
1034 -- probably _stub.o files
1035 extra_ld_inputs <- readIORef v_Ld_inputs
1037 -- opts from -optl-<blah> (including -l<blah> options)
1038 extra_ld_opts <- getStaticOpts v_Opt_l
1040 [rts_pkg, std_pkg] <- getPackageDetails [rtsPackage, basePackage]
1042 ways <- readIORef v_Ways
1044 -- Here are some libs that need to be linked at the *end* of
1045 -- the command line, because they contain symbols that are referred to
1046 -- by the RTS. We can't therefore use the ordinary way opts for these.
1048 debug_opts | WayDebug `elem` ways = [
1049 #if defined(HAVE_LIBBFD)
1056 thread_opts | WayThreaded `elem` ways = [
1057 #if !defined(mingw32_TARGET_OS) && !defined(freebsd_TARGET_OS)
1060 #if defined(osf3_TARGET_OS)
1066 let extra_os = if static || no_hs_main
1068 else [ head (library_dirs rts_pkg) ++ "/Main.dll_o",
1069 head (library_dirs std_pkg) ++ "/PrelMain.dll_o" ]
1071 (md_c_flags, _) <- machdepCCOpts
1072 SysTools.runLink ( [ SysTools.Option verb
1073 , SysTools.Option "-o"
1074 , SysTools.FileOption "" output_fn
1076 ++ map SysTools.Option (
1083 #ifdef darwin_TARGET_OS
1084 ++ framework_path_opts
1087 ++ pkg_lib_path_opts
1089 #ifdef darwin_TARGET_OS
1090 ++ pkg_framework_path_opts
1091 ++ pkg_framework_opts
1097 -- parallel only: move binary to another dir -- HWL
1098 ways_ <- readIORef v_Ways
1099 when (WayPar `elem` ways_)
1100 (do success <- runPhase_MoveBinary output_fn
1101 if success then return ()
1102 else throwDyn (InstallationError ("cannot move binary to PVM dir")))
1104 -----------------------------------------------------------------------------
1105 -- Making a DLL (only for Win32)
1107 doMkDLL :: [String] -> [PackageName] -> IO ()
1108 doMkDLL o_files dep_packages = do
1110 static <- readIORef v_Static
1111 no_hs_main <- readIORef v_NoHsMain
1113 o_file <- readIORef v_Output_file
1114 let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
1116 pkg_lib_paths <- getPackageLibraryPath dep_packages
1117 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1119 lib_paths <- readIORef v_Library_paths
1120 let lib_path_opts = map ("-L"++) lib_paths
1122 pkg_link_opts <- getPackageLinkOpts dep_packages
1124 -- probably _stub.o files
1125 extra_ld_inputs <- readIORef v_Ld_inputs
1127 -- opts from -optdll-<blah>
1128 extra_ld_opts <- getStaticOpts v_Opt_dll
1130 [rts_pkg, std_pkg] <- getPackageDetails [rtsPackage, basePackage]
1132 let extra_os = if static || no_hs_main
1134 else [ head (library_dirs rts_pkg) ++ "/Main.dll_o",
1135 head (library_dirs std_pkg) ++ "/PrelMain.dll_o" ]
1137 (md_c_flags, _) <- machdepCCOpts
1139 ([ SysTools.Option verb
1140 , SysTools.Option "-o"
1141 , SysTools.FileOption "" output_fn
1143 ++ map SysTools.Option (
1147 ++ [ "--target=i386-mingw32" ]
1151 ++ pkg_lib_path_opts
1153 ++ (if "--def" `elem` (concatMap words extra_ld_opts)
1155 else [ "--export-all" ])
1158 -- -----------------------------------------------------------------------------
1161 doCpp :: Bool -> Bool -> FilePath -> FilePath -> IO ()
1162 doCpp raw include_cc_opts input_fn output_fn = do
1163 hscpp_opts <- getOpts opt_P
1165 cmdline_include_paths <- readIORef v_Include_paths
1167 pkg_include_dirs <- getPackageIncludePath []
1168 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
1169 (cmdline_include_paths ++ pkg_include_dirs)
1173 cc_opts <- if not include_cc_opts
1175 else do optc <- getOpts opt_c
1176 (md_c_flags, _) <- machdepCCOpts
1177 return (optc ++ md_c_flags)
1179 let cpp_prog args | raw = SysTools.runCpp args
1180 | otherwise = SysTools.runCc (SysTools.Option "-E" : args)
1183 [ "-D" ++ cTARGETOS ++ "_TARGET_OS=1",
1184 "-D" ++ cTARGETARCH ++ "_TARGET_ARCH=1" ]
1186 cpp_prog ([SysTools.Option verb]
1187 ++ map SysTools.Option include_paths
1188 ++ map SysTools.Option hsSourceCppOpts
1189 ++ map SysTools.Option hscpp_opts
1190 ++ map SysTools.Option cc_opts
1191 ++ map SysTools.Option target_defs
1192 ++ [ SysTools.Option "-x"
1193 , SysTools.Option "c"
1194 , SysTools.Option input_fn
1195 -- We hackily use Option instead of FileOption here, so that the file
1196 -- name is not back-slashed on Windows. cpp is capable of
1197 -- dealing with / in filenames, so it works fine. Furthermore
1198 -- if we put in backslashes, cpp outputs #line directives
1199 -- with *double* backslashes. And that in turn means that
1200 -- our error messages get double backslashes in them.
1201 -- In due course we should arrange that the lexer deals
1202 -- with these \\ escapes properly.
1203 , SysTools.Option "-o"
1204 , SysTools.FileOption "" output_fn
1207 -- -----------------------------------------------------------------------------
1210 hscNextPhase :: HscLang -> IO Phase
1211 hscNextPhase hsc_lang = do
1212 split <- readIORef v_Split_object_files
1213 return (case hsc_lang of
1215 HscAsm | split -> SplitMangle
1217 HscNothing -> HCc -- dummy (no output will be generated)
1218 HscInterpreted -> HCc -- "" ""
1219 _other -> HCc -- "" ""
1222 hscMaybeAdjustLang :: HscLang -> IO HscLang
1223 hscMaybeAdjustLang current_hsc_lang = do
1224 todo <- readIORef v_GhcMode
1225 keep_hc <- readIORef v_Keep_hc_files
1227 -- don't change the lang if we're interpreting
1228 | current_hsc_lang == HscInterpreted = current_hsc_lang
1229 -- force -fvia-C if we are being asked for a .hc file
1230 | todo == StopBefore HCc || keep_hc = HscC
1231 -- otherwise, stick to the plan
1232 | otherwise = current_hsc_lang