1 -----------------------------------------------------------------------------
5 -- (c) Simon Marlow 2000
7 -----------------------------------------------------------------------------
9 #include "../includes/config.h"
11 module DriverPipeline (
13 -- interfaces for the batch-mode driver
14 GhcMode(..), getGhcMode, v_GhcMode,
15 genPipeline, runPipeline, pipeLoop,
17 -- interfaces for the compilation manager (interpreted/batch-mode)
18 preprocess, compile, CompResult(..),
20 -- batch-mode linking interface
26 #include "HsVersions.h"
36 import SysTools ( newTempName, addFilesToClean, getSysMan, copy )
37 import qualified SysTools
49 import Time ( getClockTime )
62 -----------------------------------------------------------------------------
63 -- GHC modes of operation
65 modeFlag :: String -> Maybe GhcMode
66 modeFlag "-M" = Just $ DoMkDependHS
67 modeFlag "--mk-dll" = Just $ DoMkDLL
68 modeFlag "-E" = Just $ StopBefore Hsc
69 modeFlag "-C" = Just $ StopBefore HCc
70 modeFlag "-S" = Just $ StopBefore As
71 modeFlag "-c" = Just $ StopBefore Ln
72 modeFlag "--make" = Just $ DoMake
73 modeFlag "--interactive" = Just $ DoInteractive
76 getGhcMode :: [String]
77 -> IO ( [String] -- rest of command line
79 , String -- "GhcMode" flag
82 = case my_partition modeFlag flags of
83 ([] , rest) -> return (rest, DoLink, "") -- default is to do linking
84 ([(flag,one)], rest) -> return (rest, one, flag)
87 "only one of the flags -M, -E, -C, -S, -c, --make, --interactive, -mk-dll is allowed")
89 -----------------------------------------------------------------------------
92 -- Herein is all the magic about which phases to run in which order, whether
93 -- the intermediate files should be in TMPDIR or in the current directory,
94 -- what the suffix of the intermediate files should be, etc.
96 -- The following compilation pipeline algorithm is fairly hacky. A
97 -- better way to do this would be to express the whole compilation as a
98 -- data flow DAG, where the nodes are the intermediate files and the
99 -- edges are the compilation phases. This framework would also work
100 -- nicely if a haskell dependency generator was included in the
103 -- It would also deal much more cleanly with compilation phases that
104 -- generate multiple intermediates, (eg. hsc generates .hc, .hi, and
105 -- possibly stub files), where some of the output files need to be
106 -- processed further (eg. the stub files need to be compiled by the C
109 -- A cool thing to do would then be to execute the data flow graph
110 -- concurrently, automatically taking advantage of extra processors on
111 -- the host machine. For example, when compiling two Haskell files
112 -- where one depends on the other, the data flow graph would determine
113 -- that the C compiler from the first compilation can be overlapped
114 -- with the hsc compilation for the second file.
116 data IntermediateFileType
122 :: GhcMode -- when to stop
123 -> String -- "stop after" flag (for error messages)
124 -> Bool -- True => output is persistent
125 -> HscLang -- preferred output language for hsc
126 -> (FilePath, String) -- original filename & its suffix
127 -> IO [ -- list of phases to run for this file
129 IntermediateFileType, -- keep the output from this phase?
130 String) -- output file suffix
133 genPipeline todo stop_flag persistent_output lang (filename,suffix)
135 split <- readIORef v_Split_object_files
136 mangle <- readIORef v_Do_asm_mangling
137 keep_hc <- readIORef v_Keep_hc_files
138 keep_il <- readIORef v_Keep_il_files
139 keep_raw_s <- readIORef v_Keep_raw_s_files
140 keep_s <- readIORef v_Keep_s_files
141 osuf <- readIORef v_Object_suf
142 hcsuf <- readIORef v_HC_suf
145 ----------- ----- ---- --- -- -- - - -
146 start = startPhase suffix
148 -- special case for mkdependHS: .hspp files go through MkDependHS
149 start_phase | todo == DoMkDependHS && start == Hsc = MkDependHS
152 haskellish = haskellish_suffix suffix
153 cish = cish_suffix suffix
155 -- for a .hc file we need to force lang to HscC
156 real_lang | start_phase == HCc || start_phase == Mangle = HscC
160 ----------- ----- ---- --- -- -- - - -
162 | todo == DoMkDependHS = [ Unlit, Cpp, HsPp, MkDependHS ]
166 HscC | split && mangle -> [ Unlit, Cpp, HsPp, Hsc, HCc, Mangle,
167 SplitMangle, SplitAs ]
168 | mangle -> [ Unlit, Cpp, HsPp, Hsc, HCc, Mangle, As ]
170 | otherwise -> [ Unlit, Cpp, HsPp, Hsc, HCc, As ]
172 HscAsm | split -> [ Unlit, Cpp, HsPp, Hsc, SplitMangle, SplitAs ]
173 | otherwise -> [ Unlit, Cpp, HsPp, Hsc, As ]
175 HscJava | split -> not_valid
176 | otherwise -> error "not implemented: compiling via Java"
178 HscILX | split -> not_valid
179 | otherwise -> [ Unlit, Cpp, HsPp, Hsc, Ilx2Il, Ilasm ]
181 HscNothing -> [ Unlit, Cpp, HsPp, Hsc ]
185 | otherwise = [ ] -- just pass this file through to the linker
187 -- ToDo: this is somewhat cryptic
188 not_valid = throwDyn (UsageError ("invalid option combination"))
190 stop_phase = case todo of
191 StopBefore As | split -> SplitAs
193 | real_lang == HscILX -> Ilasm
195 StopBefore phase -> phase
198 ----------- ----- ---- --- -- -- - - -
200 -- this shouldn't happen.
201 when (start_phase /= Ln && start_phase `notElem` pipeline)
202 (throwDyn (CmdLineError ("can't find starting phase for "
204 -- if we can't find the phase we're supposed to stop before,
205 -- something has gone wrong. This test carefully avoids the
206 -- case where we aren't supposed to do any compilation, because the file
207 -- is already in linkable form (for example).
208 when (start_phase `elem` pipeline &&
209 (stop_phase /= Ln && stop_phase `notElem` pipeline))
210 (throwDyn (UsageError
211 ("flag " ++ stop_flag
212 ++ " is incompatible with source file `" ++ filename ++ "'")))
214 -- .o and .hc suffixes can be overriden by command-line options:
215 myPhaseInputExt Ln | Just s <- osuf = s
216 myPhaseInputExt HCc | Just s <- hcsuf = s
217 myPhaseInputExt other = phaseInputExt other
220 :: [Phase] -- raw pipeline
221 -> Phase -- phase to stop before
222 -> [(Phase, IntermediateFileType, String{-file extension-})]
223 annotatePipeline [] _ = []
224 annotatePipeline (Ln:_) _ = []
225 annotatePipeline (phase:next_phase:ps) stop =
226 (phase, keep_this_output, myPhaseInputExt next_phase)
227 : annotatePipeline (next_phase:ps) stop
231 = if persistent_output then Persistent else Temporary
235 Mangle | keep_raw_s -> Persistent
236 As | keep_s -> Persistent
237 HCc | keep_hc -> Persistent
239 Ilasm | keep_il -> Persistent
243 -- add information about output files to the pipeline
244 -- the suffix on an output file is determined by the next phase
245 -- in the pipeline, so we add linking to the end of the pipeline
246 -- to force the output from the final phase to be a .o file.
248 annotated_pipeline = annotatePipeline (pipeline ++ [Ln]) stop_phase
250 phase_ne p (p1,_,_) = (p1 /= p)
251 ----------- ----- ---- --- -- -- - - -
254 takeWhile (phase_ne stop_phase ) $
255 dropWhile (phase_ne start_phase) $
261 :: [ (Phase, IntermediateFileType, String) ] -- phases to run
262 -> (String,String) -- input file
263 -> Bool -- doing linking afterward?
264 -> Bool -- take into account -o when generating output?
265 -> IO (String, String) -- return final filename
267 runPipeline pipeline (input_fn,suffix) do_linking use_ofile
268 = pipeLoop pipeline (input_fn,suffix) do_linking use_ofile basename suffix
269 where (basename, _) = splitFilename input_fn
271 pipeLoop [] input_fn _ _ _ _ = return input_fn
272 pipeLoop (all_phases@((phase, keep, o_suffix):phases))
273 (input_fn,real_suff) do_linking use_ofile orig_basename orig_suffix
276 output_fn <- outputFileName (null phases) keep o_suffix
278 mbCarryOn <- run_phase phase orig_basename orig_suffix
280 -- sometimes we bail out early, eg. when the compiler's recompilation
281 -- checker has determined that recompilation isn't necessary.
284 let (_,keep,final_suffix) = last all_phases
285 ofile <- outputFileName True keep final_suffix
286 return (ofile, final_suffix)
290 Check to see whether we've reached the end of the
291 pipeline, but did so with an ineffective last stage.
292 (i.e., it returned the input_fn as the output filename).
294 If we did and the output is persistent, copy the contents
295 of input_fn into the file where the pipeline's output is
298 atEnd <- finalStage (null phases)
299 when (atEnd && fn == input_fn)
300 (copy "Saving away compilation pipeline's output"
304 Notice that in order to keep the invariant that we can
305 determine a compilation pipeline's 'start phase' just
306 by looking at the input filename, the input filename
307 to the next stage/phase is associated here with the suffix
308 of the output file, *even* if it does not have that
311 Why is this important? Because we may run a compilation
312 pipeline in stages (cf. Main.main.compileFile's two stages),
313 so when generating the next stage we need to be precise
314 about what kind of file (=> suffix) is given as input.
316 [Not having to generate a pipeline in stages seems like
317 the right way to go, but I've punted on this for now --sof]
320 pipeLoop phases (fn, o_suffix) do_linking use_ofile
321 orig_basename orig_suffix
323 finalStage lastPhase = do
324 o_file <- readIORef v_Output_file
325 return (lastPhase && not do_linking && use_ofile && isJust o_file)
327 outputFileName last_phase keep suffix
328 = do o_file <- readIORef v_Output_file
329 atEnd <- finalStage last_phase
333 Nothing -> error "outputFileName"
334 else if keep == Persistent
335 then odir_ify (orig_basename ++ '.':suffix)
336 else newTempName suffix
339 -> String -- basename of original input source
340 -> String -- its extension
341 -> FilePath -- name of file which contains the input to this phase.
342 -> FilePath -- where to stick the result.
343 -> IO (Maybe FilePath)
344 -- Nothing => stop the compilation pipeline
345 -- Just fn => the result of this phase can be found in 'fn'
346 -- (this can either be 'input_fn' or 'output_fn').
347 -------------------------------------------------------------------------------
350 run_phase Unlit _basename _suff input_fn output_fn
351 = do unlit_flags <- getOpts opt_L
352 -- The -h option passes the file name for unlit to put in a #line directive
353 SysTools.runUnlit (map SysTools.Option unlit_flags ++
354 [ SysTools.Option "-h"
355 , SysTools.Option input_fn
356 , SysTools.FileOption "" input_fn
357 , SysTools.FileOption "" output_fn
359 return (Just output_fn)
361 -------------------------------------------------------------------------------
364 run_phase Cpp basename suff input_fn output_fn
365 = do src_opts <- getOptionsFromSource input_fn
366 unhandled_flags <- processArgs dynamic_flags src_opts []
367 checkProcessArgsResult unhandled_flags basename suff
369 do_cpp <- dynFlag cppFlag
371 -- no need to preprocess CPP, just pass input file along
372 -- to the next phase of the pipeline.
373 return (Just input_fn)
375 hscpp_opts <- getOpts opt_P
376 hs_src_cpp_opts <- readIORef v_Hs_source_cpp_opts
378 cmdline_include_paths <- readIORef v_Include_paths
379 pkg_include_dirs <- getPackageIncludePath
380 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
381 (cmdline_include_paths ++ pkg_include_dirs)
384 (md_c_flags, _) <- machdepCCOpts
386 SysTools.runCpp ([SysTools.Option verb]
387 ++ map SysTools.Option include_paths
388 ++ map SysTools.Option hs_src_cpp_opts
389 ++ map SysTools.Option hscpp_opts
390 ++ map SysTools.Option md_c_flags
391 ++ [ SysTools.Option "-x"
392 , SysTools.Option "c"
393 , SysTools.Option input_fn
394 -- We hackily use Option instead of FileOption here, so that the file
395 -- name is not back-slashed on Windows. cpp is capable of
396 -- dealing with / in filenames, so it works fine. Furthermore
397 -- if we put in backslashes, cpp outputs #line directives
398 -- with *double* backslashes. And that in turn means that
399 -- our error messages get double backslashes in them.
400 -- In due course we should arrange that the lexer deals
401 -- with these \\ escapes properly.
402 , SysTools.Option "-o"
403 , SysTools.FileOption "" output_fn
405 return (Just output_fn)
407 -------------------------------------------------------------------------------
409 run_phase HsPp basename suff input_fn output_fn
410 = do src_opts <- getOptionsFromSource input_fn
411 unhandled_flags <- processArgs dynamic_flags src_opts []
412 checkProcessArgsResult unhandled_flags basename suff
414 let orig_fn = basename ++ '.':suff
415 do_pp <- dynFlag ppFlag
417 -- no need to preprocess, just pass input file along
418 -- to the next phase of the pipeline.
419 return (Just input_fn)
421 hspp_opts <- getOpts opt_F
422 hs_src_pp_opts <- readIORef v_Hs_source_pp_opts
423 SysTools.runPp ( [ SysTools.Option orig_fn
424 , SysTools.Option input_fn
425 , SysTools.FileOption "" output_fn
427 map SysTools.Option hs_src_pp_opts ++
428 map SysTools.Option hspp_opts
430 return (Just output_fn)
432 -----------------------------------------------------------------------------
435 run_phase MkDependHS basename suff input_fn output_fn
436 = do src <- readFile input_fn
437 let (import_sources, import_normals, _) = getImports src
438 let orig_fn = basename ++ '.':suff
439 deps_sources <- mapM (findDependency True orig_fn) import_sources
440 deps_normals <- mapM (findDependency False orig_fn) import_normals
441 let deps = deps_sources ++ deps_normals
443 osuf_opt <- readIORef v_Object_suf
444 let osuf = case osuf_opt of
445 Nothing -> phaseInputExt Ln
448 extra_suffixes <- readIORef v_Dep_suffixes
449 let suffixes = osuf : map (++ ('_':osuf)) extra_suffixes
450 ofiles = map (\suf -> basename ++ '.':suf) suffixes
452 objs <- mapM odir_ify ofiles
454 -- Handle for file that accumulates dependencies
455 hdl <- readIORef v_Dep_tmp_hdl
457 -- std dependency of the object(s) on the source file
458 hPutStrLn hdl (unwords objs ++ " : " ++ basename ++ '.':suff)
460 let genDep (dep, False {- not an hi file -}) =
461 hPutStrLn hdl (unwords objs ++ " : " ++ dep)
462 genDep (dep, True {- is an hi file -}) = do
463 hisuf <- readIORef v_Hi_suf
464 let dep_base = remove_suffix '.' dep
465 deps = (dep_base ++ hisuf)
466 : map (\suf -> dep_base ++ suf ++ '_':hisuf) extra_suffixes
467 -- length objs should be == length deps
468 sequence_ (zipWith (\o d -> hPutStrLn hdl (o ++ " : " ++ d)) objs deps)
470 sequence_ (map genDep [ d | Just d <- deps ])
471 return (Just output_fn)
473 -- add the lines to dep_makefile:
477 -- if the dependency is on something other than a .hi file:
478 -- this.o this.p_o ... : dep
480 -- if the import is {-# SOURCE #-}
481 -- this.o this.p_o ... : dep.hi-boot[-$vers]
484 -- this.o ... : dep.hi
485 -- this.p_o ... : dep.p_hi
488 -- (where .o is $osuf, and the other suffixes come from
489 -- the cmdline -s options).
491 -----------------------------------------------------------------------------
494 -- Compilation of a single module, in "legacy" mode (_not_ under
495 -- the direction of the compilation manager).
496 run_phase Hsc basename suff input_fn output_fn
499 -- we add the current directory (i.e. the directory in which
500 -- the .hs files resides) to the import path, since this is
501 -- what gcc does, and it's probably what you want.
502 let current_dir = getdir basename
504 paths <- readIORef v_Include_paths
505 writeIORef v_Include_paths (current_dir : paths)
507 -- figure out which header files to #include in a generated .hc file
508 c_includes <- getPackageCIncludes
509 cmdline_includes <- dynFlag cmdlineHcIncludes -- -#include options
511 let cc_injects = unlines (map mk_include
512 (c_includes ++ reverse cmdline_includes))
515 '"':_{-"-} -> "#include "++h_file
516 '<':_ -> "#include "++h_file
517 _ -> "#include \""++h_file++"\""
519 writeIORef v_HCHeader cc_injects
521 -- gather the imports and module name
522 (srcimps,imps,mod_name) <- getImportsFromFile input_fn
524 -- build a ModuleLocation to pass to hscMain.
526 <- mkHomeModuleLocn mod_name basename (basename ++ '.':suff)
528 -- take -ohi into account if present
529 ohi <- readIORef v_Output_hi
530 let location | Just fn <- ohi = location'{ ml_hi_file = fn }
531 | otherwise = location'
533 -- figure out if the source has changed, for recompilation avoidance.
534 -- only do this if we're eventually going to generate a .o file.
535 -- (ToDo: do when generating .hc files too?)
537 -- Setting source_unchanged to True means that M.o seems
538 -- to be up to date wrt M.hs; so no need to recompile unless imports have
539 -- changed (which the compiler itself figures out).
540 -- Setting source_unchanged to False tells the compiler that M.o is out of
541 -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
542 do_recomp <- readIORef v_Recomp
543 todo <- readIORef v_GhcMode
544 expl_o_file <- readIORef v_Output_file
547 Nothing -> unJust "source_unchanged" (ml_obj_file location)
550 if not (do_recomp && ( todo == DoLink || todo == StopBefore Ln ))
552 else do t1 <- getModificationTime (basename ++ '.':suff)
553 o_file_exists <- doesFileExist o_file
555 then return False -- Need to recompile
556 else do t2 <- getModificationTime o_file
562 dyn_flags <- getDynFlags
564 let dyn_flags' = dyn_flags { hscOutName = output_fn,
565 hscStubCOutName = basename ++ "_stub.c",
566 hscStubHOutName = basename ++ "_stub.h",
567 extCoreName = basename ++ ".hcr" }
570 pcs <- initPersistentCompilerState
571 result <- hscMain OneShot
573 location{ ml_hspp_file=Just input_fn }
577 emptyModuleEnv -- HomeSymbolTable
578 emptyModuleEnv -- HomeIfaceTable
583 HscFail pcs -> throwDyn (PhaseFailed "hsc" (ExitFailure 1));
585 HscNoRecomp pcs details iface -> do { SysTools.touch "Touching object file" o_file
588 HscRecomp pcs details iface stub_h_exists stub_c_exists
589 _maybe_interpreted_code -> do
592 maybe_stub_o <- compileStub dyn_flags' stub_c_exists
595 Just stub_o -> add v_Ld_inputs stub_o
596 case hscLang dyn_flags of
597 HscNothing -> return Nothing
598 _ -> return (Just output_fn)
601 -----------------------------------------------------------------------------
604 -- we don't support preprocessing .c files (with -E) now. Doing so introduces
605 -- way too many hacks, and I can't say I've ever used it anyway.
607 run_phase cc_phase basename suff input_fn output_fn
608 | cc_phase == Cc || cc_phase == HCc
609 = do cc_opts <- getOpts opt_c
610 cmdline_include_paths <- readIORef v_Include_paths
612 let hcc = cc_phase == HCc
614 -- add package include paths even if we're just compiling
615 -- .c files; this is the Value Add(TM) that using
616 -- ghc instead of gcc gives you :)
617 pkg_include_dirs <- getPackageIncludePath
618 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
619 (cmdline_include_paths ++ pkg_include_dirs)
621 mangle <- readIORef v_Do_asm_mangling
622 (md_c_flags, md_regd_c_flags) <- machdepCCOpts
626 o2 <- readIORef v_minus_o2_for_C
627 let opt_flag | o2 = "-O2"
630 pkg_extra_cc_opts <- getPackageExtraCcOpts
632 split_objs <- readIORef v_Split_object_files
633 let split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
636 excessPrecision <- readIORef v_Excess_precision
637 SysTools.runCc ([ SysTools.Option "-x", SysTools.Option "c"
638 , SysTools.FileOption "" input_fn
639 , SysTools.Option "-o"
640 , SysTools.FileOption "" output_fn
642 ++ map SysTools.Option (
644 ++ (if cc_phase == HCc && mangle
647 ++ [ verb, "-S", "-Wimplicit", opt_flag ]
648 ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
651 ++ (if excessPrecision then [] else [ "-ffloat-store" ])
655 return (Just output_fn)
657 -- ToDo: postprocess the output from gcc
659 -----------------------------------------------------------------------------
662 run_phase Mangle _basename _suff input_fn output_fn
663 = do mangler_opts <- getOpts opt_m
664 machdep_opts <- if (prefixMatch "i386" cTARGETPLATFORM)
665 then do n_regs <- dynFlag stolen_x86_regs
666 return [ show n_regs ]
669 SysTools.runMangle (map SysTools.Option mangler_opts
670 ++ [ SysTools.FileOption "" input_fn
671 , SysTools.FileOption "" output_fn
673 ++ map SysTools.Option machdep_opts)
674 return (Just output_fn)
676 -----------------------------------------------------------------------------
679 run_phase SplitMangle _basename _suff input_fn output_fn
680 = do -- tmp_pfx is the prefix used for the split .s files
681 -- We also use it as the file to contain the no. of split .s files (sigh)
682 split_s_prefix <- SysTools.newTempName "split"
683 let n_files_fn = split_s_prefix
685 SysTools.runSplit [ SysTools.FileOption "" input_fn
686 , SysTools.FileOption "" split_s_prefix
687 , SysTools.FileOption "" n_files_fn
690 -- Save the number of split files for future references
691 s <- readFile n_files_fn
692 let n_files = read s :: Int
693 writeIORef v_Split_info (split_s_prefix, n_files)
695 -- Remember to delete all these files
696 addFilesToClean [ split_s_prefix ++ "__" ++ show n ++ ".s"
699 return (Just output_fn)
701 -----------------------------------------------------------------------------
704 run_phase As _basename _suff input_fn output_fn
705 = do as_opts <- getOpts opt_a
706 cmdline_include_paths <- readIORef v_Include_paths
708 SysTools.runAs (map SysTools.Option as_opts
709 ++ [ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ]
710 ++ [ SysTools.Option "-c"
711 , SysTools.FileOption "" input_fn
712 , SysTools.Option "-o"
713 , SysTools.FileOption "" output_fn
715 return (Just output_fn)
717 run_phase SplitAs basename _suff _input_fn output_fn
718 = do as_opts <- getOpts opt_a
720 (split_s_prefix, n) <- readIORef v_Split_info
722 odir <- readIORef v_Output_dir
723 let real_odir = case odir of
728 = do let input_s = split_s_prefix ++ "__" ++ show n ++ ".s"
729 let output_o = newdir real_odir
730 (basename ++ "__" ++ show n ++ ".o")
731 real_o <- osuf_ify output_o
732 SysTools.runAs (map SysTools.Option as_opts ++
733 [ SysTools.Option "-c"
734 , SysTools.Option "-o"
735 , SysTools.FileOption "" real_o
736 , SysTools.FileOption "" input_s
739 mapM_ assemble_file [1..n]
740 return (Just output_fn)
743 -----------------------------------------------------------------------------
745 -- Run ilx2il over the ILX output, getting an IL file
747 run_phase Ilx2Il _basename _suff input_fn output_fn
748 = do ilx2il_opts <- getOpts opt_I
749 SysTools.runIlx2il (map SysTools.Option ilx2il_opts
750 ++ [ SysTools.Option "--no-add-suffix-to-assembly",
751 SysTools.Option "mscorlib",
752 SysTools.Option "-o",
753 SysTools.FileOption "" output_fn,
754 SysTools.FileOption "" input_fn ])
755 return (Just output_fn)
757 -----------------------------------------------------------------------------
759 -- Run ilasm over the IL, getting a DLL
761 run_phase Ilasm _basename _suff input_fn output_fn
762 = do ilasm_opts <- getOpts opt_i
763 SysTools.runIlasm (map SysTools.Option ilasm_opts
764 ++ [ SysTools.Option "/QUIET",
765 SysTools.Option "/DLL",
766 SysTools.FileOption "/OUT=" output_fn,
767 SysTools.FileOption "" input_fn ])
768 return (Just output_fn)
772 -----------------------------------------------------------------------------
773 -- MoveBinary sort-of-phase
774 -- After having produced a binary, move it somewhere else and generate a
775 -- wrapper script calling the binary. Currently, we need this only in
776 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
777 -- central directory.
778 -- This is called from doLink below, after linking. I haven't made it
779 -- a separate phase to minimise interfering with other modules, and
780 -- we don't need the generality of a phase (MoveBinary is always
781 -- done after linking and makes only sense in a parallel setup) -- HWL
783 run_phase_MoveBinary input_fn
786 pvm_root <- getEnv "PVM_ROOT"
787 pvm_arch <- getEnv "PVM_ARCH"
789 pvm_executable_base = "=" ++ input_fn
790 pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
791 -- nuke old binary; maybe use configur'ed names for cp and rm?
792 system ("rm -f " ++ pvm_executable)
793 -- move the newly created binary into PVM land
794 system ("cp -p " ++ input_fn ++ " " ++ pvm_executable)
795 -- generate a wrapper script for running a parallel prg under PVM
796 writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
799 -- generates a Perl skript starting a parallel prg under PVM
800 mk_pvm_wrapper_script :: String -> String -> String -> String
801 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
803 "eval 'exec perl -S $0 ${1+\"$@\"}'",
804 " if $running_under_some_shell;",
805 "# =!=!=!=!=!=!=!=!=!=!=!",
806 "# This script is automatically generated: DO NOT EDIT!!!",
807 "# Generated by Glasgow Haskell Compiler",
808 "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
810 "$pvm_executable = '" ++ pvm_executable ++ "';",
811 "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
812 "$SysMan = '" ++ sysMan ++ "';",
814 {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
815 "# first, some magical shortcuts to run "commands" on the binary",
816 "# (which is hidden)",
817 "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
818 " local($cmd) = $1;",
819 " system("$cmd $pvm_executable");",
820 " exit(0); # all done",
823 "# Now, run the real binary; process the args first",
824 "$ENV{'PE'} = $pvm_executable_base;", -- ++ pvm_executable_base,
826 "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
827 "@nonPVM_args = ();",
830 "args: while ($a = shift(@ARGV)) {",
831 " if ( $a eq '+RTS' ) {",
832 " $in_RTS_args = 1;",
833 " } elsif ( $a eq '-RTS' ) {",
834 " $in_RTS_args = 0;",
836 " if ( $a eq '-d' && $in_RTS_args ) {",
838 " } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
839 " $nprocessors = $1;",
840 " } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
841 " $nprocessors = $1;",
843 " push(@nonPVM_args, $a);",
847 "local($return_val) = 0;",
848 "# Start the parallel execution by calling SysMan",
849 "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
851 "# ToDo: fix race condition moving files and flushing them!!",
852 "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
856 -----------------------------------------------------------------------------
857 -- Complain about non-dynamic flags in OPTIONS pragmas
859 checkProcessArgsResult flags basename suff
860 = do when (not (null flags)) (throwDyn (ProgramError (
861 basename ++ "." ++ suff
862 ++ ": static flags are not allowed in {-# OPTIONS #-} pragmas:\n\t"
863 ++ unwords flags)) (ExitFailure 1))
865 -----------------------------------------------------------------------------
868 doLink :: [String] -> IO ()
871 static <- readIORef v_Static
872 no_hs_main <- readIORef v_NoHsMain
874 o_file <- readIORef v_Output_file
875 let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
877 pkg_lib_paths <- getPackageLibraryPath
878 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
880 lib_paths <- readIORef v_Library_paths
881 let lib_path_opts = map ("-L"++) lib_paths
883 pkg_libs <- getPackageLibraries
884 let imp = if static then "" else "_imp"
885 pkg_lib_opts = map (\lib -> "-l" ++ lib ++ imp) pkg_libs
887 libs <- readIORef v_Cmdline_libraries
888 let lib_opts = map ("-l"++) (reverse libs)
889 -- reverse because they're added in reverse order from the cmd line
891 pkg_extra_ld_opts <- getPackageExtraLdOpts
893 -- probably _stub.o files
894 extra_ld_inputs <- readIORef v_Ld_inputs
896 -- opts from -optl-<blah>
897 extra_ld_opts <- getStaticOpts v_Opt_l
899 rts_pkg <- getPackageDetails ["rts"]
900 std_pkg <- getPackageDetails ["std"]
901 let extra_os = if static || no_hs_main
903 else [ head (library_dirs (head rts_pkg)) ++ "/Main.dll_o",
904 head (library_dirs (head std_pkg)) ++ "/PrelMain.dll_o" ]
906 (md_c_flags, _) <- machdepCCOpts
907 SysTools.runLink ( [ SysTools.Option verb
908 , SysTools.Option "-o"
909 , SysTools.FileOption "" output_fn
911 ++ map SysTools.Option (
922 ++ if static && not no_hs_main then
923 [ "-u", prefixUnderscore "PrelMain_mainIO_closure",
924 "-u", prefixUnderscore "__stginit_PrelMain"]
927 -- parallel only: move binary to another dir -- HWL
928 ways_ <- readIORef v_Ways
929 when (WayPar `elem` ways_)
930 (do success <- run_phase_MoveBinary output_fn
931 if success then return ()
932 else throwDyn (InstallationError ("cannot move binary to PVM dir")))
934 -----------------------------------------------------------------------------
935 -- Making a DLL (only for Win32)
937 doMkDLL :: [String] -> IO ()
940 static <- readIORef v_Static
941 no_hs_main <- readIORef v_NoHsMain
943 o_file <- readIORef v_Output_file
944 let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
946 pkg_lib_paths <- getPackageLibraryPath
947 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
949 lib_paths <- readIORef v_Library_paths
950 let lib_path_opts = map ("-L"++) lib_paths
952 pkg_libs <- getPackageLibraries
953 let imp = if static then "" else "_imp"
954 pkg_lib_opts = map (\lib -> "-l" ++ lib ++ imp) pkg_libs
956 libs <- readIORef v_Cmdline_libraries
957 let lib_opts = map ("-l"++) (reverse libs)
958 -- reverse because they're added in reverse order from the cmd line
960 pkg_extra_ld_opts <- getPackageExtraLdOpts
962 -- probably _stub.o files
963 extra_ld_inputs <- readIORef v_Ld_inputs
965 -- opts from -optdll-<blah>
966 extra_ld_opts <- getStaticOpts v_Opt_dll
968 rts_pkg <- getPackageDetails ["rts"]
969 std_pkg <- getPackageDetails ["std"]
971 let extra_os = if static || no_hs_main
973 else [ head (library_dirs (head rts_pkg)) ++ "/Main.dll_o",
974 head (library_dirs (head std_pkg)) ++ "/PrelMain.dll_o" ]
976 (md_c_flags, _) <- machdepCCOpts
978 ([ SysTools.Option verb
979 , SysTools.Option "-o"
980 , SysTools.FileOption "" output_fn
982 ++ map SysTools.Option (
986 ++ [ "--target=i386-mingw32" ]
993 ++ (case findPS (packString (concat extra_ld_opts)) (packString "--def") of
994 Nothing -> [ "--export-all" ]
999 -----------------------------------------------------------------------------
1000 -- Just preprocess a file, put the result in a temp. file (used by the
1001 -- compilation manager during the summary phase).
1003 preprocess :: FilePath -> IO FilePath
1004 preprocess filename =
1005 ASSERT(haskellish_src_file filename)
1006 do restoreDynFlags -- Restore to state of last save
1007 let fInfo = (filename, getFileSuffix filename)
1008 pipeline <- genPipeline (StopBefore Hsc) ("preprocess") False
1009 defaultHscLang fInfo
1010 (fn,_) <- runPipeline pipeline fInfo
1011 False{-no linking-} False{-no -o flag-}
1014 -----------------------------------------------------------------------------
1015 -- Compile a single module, under the control of the compilation manager.
1017 -- This is the interface between the compilation manager and the
1018 -- compiler proper (hsc), where we deal with tedious details like
1019 -- reading the OPTIONS pragma from the source file, and passing the
1020 -- output of hsc through the C compiler.
1022 -- The driver sits between 'compile' and 'hscMain', translating calls
1023 -- to the former into calls to the latter, and results from the latter
1024 -- into results from the former. It does things like preprocessing
1025 -- the .hs file if necessary, and compiling up the .stub_c files to
1026 -- generate Linkables.
1028 -- NB. No old interface can also mean that the source has changed.
1030 compile :: GhciMode -- distinguish batch from interactive
1031 -> ModSummary -- summary, including source
1032 -> Bool -- True <=> source unchanged
1033 -> Bool -- True <=> have object
1034 -> Maybe ModIface -- old interface, if available
1035 -> HomeSymbolTable -- for home module ModDetails
1036 -> HomeIfaceTable -- for home module Ifaces
1037 -> PersistentCompilerState -- persistent compiler state
1041 = CompOK PersistentCompilerState -- updated PCS
1042 ModDetails -- new details (HST additions)
1043 ModIface -- new iface (HIT additions)
1045 -- new code; Nothing => compilation was not reqd
1046 -- (old code is still valid)
1048 | CompErrs PersistentCompilerState -- updated PCS
1051 compile ghci_mode summary source_unchanged have_object
1052 old_iface hst hit pcs = do
1053 dyn_flags <- restoreDynFlags -- Restore to the state of the last save
1057 (showSDoc (text "Compiling" <+> ppr (name_of_summary summary)))
1059 let verb = verbosity dyn_flags
1060 let location = ms_location summary
1061 let input_fn = unJust "compile:hs" (ml_hs_file location)
1062 let input_fnpp = unJust "compile:hspp" (ml_hspp_file location)
1064 when (verb >= 2) (hPutStrLn stderr ("compile: input file " ++ input_fnpp))
1066 opts <- getOptionsFromSource input_fnpp
1067 processArgs dynamic_flags opts []
1068 dyn_flags <- getDynFlags
1070 let hsc_lang = hscLang dyn_flags
1071 (basename, _) = splitFilename input_fn
1073 keep_hc <- readIORef v_Keep_hc_files
1074 keep_il <- readIORef v_Keep_il_files
1075 keep_s <- readIORef v_Keep_s_files
1079 HscAsm | keep_s -> return (basename ++ '.':phaseInputExt As)
1080 | otherwise -> newTempName (phaseInputExt As)
1081 HscC | keep_hc -> return (basename ++ '.':phaseInputExt HCc)
1082 | otherwise -> newTempName (phaseInputExt HCc)
1083 HscJava -> newTempName "java" -- ToDo
1085 HscILX | keep_il -> return (basename ++ '.':phaseInputExt Ilasm)
1086 | otherwise -> newTempName (phaseInputExt Ilx2Il)
1088 HscInterpreted -> return (error "no output file")
1089 HscNothing -> return (error "no output file")
1091 let dyn_flags' = dyn_flags { hscOutName = output_fn,
1092 hscStubCOutName = basename ++ "_stub.c",
1093 hscStubHOutName = basename ++ "_stub.h",
1094 extCoreName = basename ++ ".hcr" }
1096 -- figure out which header files to #include in a generated .hc file
1097 c_includes <- getPackageCIncludes
1098 cmdline_includes <- dynFlag cmdlineHcIncludes -- -#include options
1100 let cc_injects = unlines (map mk_include
1101 (c_includes ++ reverse cmdline_includes))
1104 '"':_{-"-} -> "#include "++h_file
1105 '<':_ -> "#include "++h_file
1106 _ -> "#include \""++h_file++"\""
1108 writeIORef v_HCHeader cc_injects
1110 -- -no-recomp should also work with --make
1111 do_recomp <- readIORef v_Recomp
1112 let source_unchanged' = source_unchanged && do_recomp
1115 hsc_result <- hscMain ghci_mode dyn_flags'
1116 (ms_mod summary) location
1117 source_unchanged' have_object old_iface hst hit pcs
1120 HscFail pcs -> return (CompErrs pcs)
1122 HscNoRecomp pcs details iface -> return (CompOK pcs details iface Nothing)
1124 HscRecomp pcs details iface
1125 stub_h_exists stub_c_exists maybe_interpreted_code -> do
1128 maybe_stub_o <- compileStub dyn_flags' stub_c_exists
1129 let stub_unlinked = case maybe_stub_o of
1131 Just stub_o -> [ DotO stub_o ]
1133 (hs_unlinked, unlinked_time) <-
1136 -- in interpreted mode, just return the compiled code
1137 -- as our "unlinked" object.
1139 case maybe_interpreted_code of
1141 Just (bcos,itbl_env) -> do tm <- getClockTime
1142 return ([BCOs bcos itbl_env], tm)
1144 Nothing -> panic "compile: no interpreted code"
1146 -- we're in batch mode: finish the compilation pipeline.
1147 _other -> do pipe <- genPipeline (StopBefore Ln) "" True
1148 hsc_lang (output_fn, getFileSuffix output_fn)
1149 -- runPipeline takes input_fn so it can split off
1150 -- the base name and use it as the base of
1151 -- the output object file.
1152 let (basename, suffix) = splitFilename input_fn
1154 pipeLoop pipe (output_fn, getFileSuffix output_fn)
1157 o_time <- getModificationTime o_file
1158 return ([DotO o_file], o_time)
1160 let linkable = LM unlinked_time (moduleName (ms_mod summary))
1161 (hs_unlinked ++ stub_unlinked)
1163 return (CompOK pcs details iface (Just linkable))
1166 -----------------------------------------------------------------------------
1167 -- stub .h and .c files (for foreign export support)
1169 compileStub dflags stub_c_exists
1170 | not stub_c_exists = return Nothing
1171 | stub_c_exists = do
1172 -- compile the _stub.c file w/ gcc
1173 let stub_c = hscStubCOutName dflags
1174 pipeline <- genPipeline (StopBefore Ln) "" True defaultHscLang (stub_c,"c")
1175 (stub_o,_) <- runPipeline pipeline (stub_c,"c") False{-no linking-}
1176 False{-no -o option-}
1177 return (Just stub_o)