1 -----------------------------------------------------------------------------
2 -- $Id: DriverPipeline.hs,v 1.82 2001/06/26 16:30:50 rrt Exp $
6 -- (c) Simon Marlow 2000
8 -----------------------------------------------------------------------------
10 #include "../includes/config.h"
12 module DriverPipeline (
14 -- interfaces for the batch-mode driver
15 GhcMode(..), getGhcMode, v_GhcMode,
16 genPipeline, runPipeline, pipeLoop,
18 -- interfaces for the compilation manager (interpreted/batch-mode)
19 preprocess, compile, CompResult(..),
21 -- batch-mode linking interface
27 #include "HsVersions.h"
37 import SysTools ( newTempName, addFilesToClean, getSysMan )
38 import qualified SysTools
50 import Time ( getClockTime )
63 -----------------------------------------------------------------------------
64 -- GHC modes of operation
67 = DoMkDependHS -- ghc -M
68 | DoMkDLL -- ghc --mk-dll
69 | StopBefore Phase -- ghc -E | -C | -S | -c
70 | DoMake -- ghc --make
71 | DoInteractive -- ghc --interactive
72 | DoLink -- [ the default ]
75 GLOBAL_VAR(v_GhcMode, error "todo", GhcMode)
77 modeFlag :: String -> Maybe GhcMode
78 modeFlag "-M" = Just $ DoMkDependHS
79 modeFlag "--mk-dll" = Just $ DoMkDLL
80 modeFlag "-E" = Just $ StopBefore Hsc
81 modeFlag "-C" = Just $ StopBefore HCc
82 modeFlag "-S" = Just $ StopBefore As
83 modeFlag "-c" = Just $ StopBefore Ln
84 modeFlag "--make" = Just $ DoMake
85 modeFlag "--interactive" = Just $ DoInteractive
88 getGhcMode :: [String]
89 -> IO ( [String] -- rest of command line
91 , String -- "GhcMode" flag
94 = case my_partition modeFlag flags of
95 ([] , rest) -> return (rest, DoLink, "") -- default is to do linking
96 ([(flag,one)], rest) -> return (rest, one, flag)
99 "only one of the flags -M, -E, -C, -S, -c, --make, --interactive, -mk-dll is allowed")
101 -----------------------------------------------------------------------------
104 -- Herein is all the magic about which phases to run in which order, whether
105 -- the intermediate files should be in TMPDIR or in the current directory,
106 -- what the suffix of the intermediate files should be, etc.
108 -- The following compilation pipeline algorithm is fairly hacky. A
109 -- better way to do this would be to express the whole compilation as a
110 -- data flow DAG, where the nodes are the intermediate files and the
111 -- edges are the compilation phases. This framework would also work
112 -- nicely if a haskell dependency generator was included in the
115 -- It would also deal much more cleanly with compilation phases that
116 -- generate multiple intermediates, (eg. hsc generates .hc, .hi, and
117 -- possibly stub files), where some of the output files need to be
118 -- processed further (eg. the stub files need to be compiled by the C
121 -- A cool thing to do would then be to execute the data flow graph
122 -- concurrently, automatically taking advantage of extra processors on
123 -- the host machine. For example, when compiling two Haskell files
124 -- where one depends on the other, the data flow graph would determine
125 -- that the C compiler from the first compilation can be overlapped
126 -- with the hsc compilation for the second file.
128 data IntermediateFileType
134 :: GhcMode -- when to stop
135 -> String -- "stop after" flag (for error messages)
136 -> Bool -- True => output is persistent
137 -> HscLang -- preferred output language for hsc
138 -> String -- original filename
139 -> IO [ -- list of phases to run for this file
141 IntermediateFileType, -- keep the output from this phase?
142 String) -- output file suffix
145 genPipeline todo stop_flag persistent_output lang filename
147 split <- readIORef v_Split_object_files
148 mangle <- readIORef v_Do_asm_mangling
149 keep_hc <- readIORef v_Keep_hc_files
150 keep_raw_s <- readIORef v_Keep_raw_s_files
151 keep_s <- readIORef v_Keep_s_files
152 osuf <- readIORef v_Object_suf
153 hcsuf <- readIORef v_HC_suf
156 ----------- ----- ---- --- -- -- - - -
157 (_basename, suffix) = splitFilename filename
159 start = startPhase suffix
161 -- special case for mkdependHS: .hspp files go through MkDependHS
162 start_phase | todo == DoMkDependHS && start == Hsc = MkDependHS
165 haskellish = haskellish_suffix suffix
166 cish = cish_suffix suffix
168 -- for a .hc file we need to force lang to HscC
169 real_lang | start_phase == HCc || start_phase == Mangle = HscC
173 ----------- ----- ---- --- -- -- - - -
175 | todo == DoMkDependHS = [ Unlit, Cpp, MkDependHS ]
179 HscC | split && mangle -> [ Unlit, Cpp, Hsc, HCc, Mangle,
180 SplitMangle, SplitAs ]
181 | mangle -> [ Unlit, Cpp, Hsc, HCc, Mangle, As ]
183 | otherwise -> [ Unlit, Cpp, Hsc, HCc, As ]
185 HscAsm | split -> [ Unlit, Cpp, Hsc, SplitMangle, SplitAs ]
186 | otherwise -> [ Unlit, Cpp, Hsc, As ]
188 HscJava | split -> not_valid
189 | otherwise -> error "not implemented: compiling via Java"
190 HscILX | split -> not_valid
191 | otherwise -> [ Unlit, Cpp, Hsc ]
195 | otherwise = [ ] -- just pass this file through to the linker
197 -- ToDo: this is somewhat cryptic
198 not_valid = throwDyn (UsageError ("invalid option combination"))
200 stop_phase = case todo of
201 StopBefore As | split -> SplitAs
202 StopBefore phase -> phase
205 ----------- ----- ---- --- -- -- - - -
207 -- this shouldn't happen.
208 if start_phase /= Ln && start_phase `notElem` pipeline
209 then throwDyn (CmdLineError ("can't find starting phase for "
213 -- if we can't find the phase we're supposed to stop before,
214 -- something has gone wrong. This test carefully avoids the
215 -- case where we aren't supposed to do any compilation, because the file
216 -- is already in linkable form (for example).
217 if start_phase `elem` pipeline &&
218 (stop_phase /= Ln && stop_phase `notElem` pipeline)
219 then throwDyn (UsageError
220 ("flag " ++ stop_flag
221 ++ " is incompatible with source file `" ++ filename ++ "'"))
225 -- .o and .hc suffixes can be overriden by command-line options:
226 myPhaseInputExt Ln | Just s <- osuf = s
227 myPhaseInputExt HCc | Just s <- hcsuf = s
228 myPhaseInputExt other = phaseInputExt other
231 :: [Phase] -- raw pipeline
232 -> Phase -- phase to stop before
233 -> [(Phase, IntermediateFileType, String{-file extension-})]
234 annotatePipeline [] _ = []
235 annotatePipeline (Ln:_) _ = []
236 annotatePipeline (phase:next_phase:ps) stop =
237 (phase, keep_this_output, myPhaseInputExt next_phase)
238 : annotatePipeline (next_phase:ps) stop
242 = if persistent_output then Persistent else Temporary
246 Mangle | keep_raw_s -> Persistent
247 As | keep_s -> Persistent
248 HCc | keep_hc -> Persistent
251 -- add information about output files to the pipeline
252 -- the suffix on an output file is determined by the next phase
253 -- in the pipeline, so we add linking to the end of the pipeline
254 -- to force the output from the final phase to be a .o file.
256 annotated_pipeline = annotatePipeline (pipeline ++ [Ln]) stop_phase
258 phase_ne p (p1,_,_) = (p1 /= p)
259 ----------- ----- ---- --- -- -- - - -
262 takeWhile (phase_ne stop_phase ) $
263 dropWhile (phase_ne start_phase) $
269 :: [ (Phase, IntermediateFileType, String) ] -- phases to run
270 -> String -- input file
271 -> Bool -- doing linking afterward?
272 -> Bool -- take into account -o when generating output?
273 -> IO String -- return final filename
275 runPipeline pipeline input_fn do_linking use_ofile
276 = pipeLoop pipeline input_fn do_linking use_ofile basename suffix
277 where (basename, suffix) = splitFilename input_fn
279 pipeLoop [] input_fn _ _ _ _ = return input_fn
280 pipeLoop ((phase, keep, o_suffix):phases)
281 input_fn do_linking use_ofile orig_basename orig_suffix
284 output_fn <- outputFileName (null phases) keep o_suffix
286 carry_on <- run_phase phase orig_basename orig_suffix input_fn output_fn
287 -- sometimes we bail out early, eg. when the compiler's recompilation
288 -- checker has determined that recompilation isn't necessary.
290 then do let (_,keep,final_suffix) = last phases
291 ofile <- outputFileName True keep final_suffix
293 else do -- carry on ...
295 pipeLoop phases output_fn do_linking use_ofile orig_basename orig_suffix
298 outputFileName last_phase keep suffix
299 = do o_file <- readIORef v_Output_file
300 if last_phase && not do_linking && use_ofile && isJust o_file
303 Nothing -> error "outputFileName"
304 else if keep == Persistent
305 then odir_ify (orig_basename ++ '.':suffix)
306 else newTempName suffix
308 -------------------------------------------------------------------------------
311 run_phase Unlit _basename _suff input_fn output_fn
312 = do unlit_flags <- getOpts opt_L
313 SysTools.runUnlit (unlit_flags ++ ["-h", input_fn, input_fn, output_fn])
316 -------------------------------------------------------------------------------
319 run_phase Cpp basename suff input_fn output_fn
320 = do src_opts <- getOptionsFromSource input_fn
321 unhandled_flags <- processArgs dynamic_flags src_opts []
322 checkProcessArgsResult unhandled_flags basename suff
324 do_cpp <- dynFlag cppFlag
327 hscpp_opts <- getOpts opt_P
328 hs_src_cpp_opts <- readIORef v_Hs_source_cpp_opts
330 cmdline_include_paths <- readIORef v_Include_paths
331 pkg_include_dirs <- getPackageIncludePath
332 let include_paths = map (\p -> "-I"++p) (cmdline_include_paths
336 (md_c_flags, _) <- machdepCCOpts
338 SysTools.runCpp ([verb]
343 ++ [ "-x", "c", input_fn, "-o", output_fn ])
345 -- ToDo: switch away from using 'echo' altogether (but need
346 -- a faster alternative than what's done below).
347 #if defined(mingw32_TARGET_OS) && defined(MINIMAL_UNIX_DEPS)
349 h <- openFile output_fn WriteMode
350 hPutStrLn h ("{-# LINE 1 \"" ++ input_fn ++ "\" #-}")
351 ls <- readFile input_fn -- inefficient, but it'll do for now.
352 -- ToDo: speed up via slurping.
354 hClose h) `catchAllIO`
355 (\_ -> throwDyn (PhaseFailed "Ineffective C pre-processor" (ExitFailure 1)))
358 SysTools.runSomething "Ineffective C pre-processor"
359 ("echo '{-# LINE 1 \"" ++ input_fn ++ "\" #-}' > "
360 ++ output_fn ++ " && cat " ++ input_fn
361 ++ " >> " ++ output_fn) []
365 -----------------------------------------------------------------------------
368 run_phase MkDependHS basename suff input_fn _output_fn = do
369 src <- readFile input_fn
370 let (import_sources, import_normals, _) = getImports src
372 let orig_fn = basename ++ '.':suff
373 deps_sources <- mapM (findDependency True orig_fn) import_sources
374 deps_normals <- mapM (findDependency False orig_fn) import_normals
375 let deps = deps_sources ++ deps_normals
377 osuf_opt <- readIORef v_Object_suf
378 let osuf = case osuf_opt of
379 Nothing -> phaseInputExt Ln
382 extra_suffixes <- readIORef v_Dep_suffixes
383 let suffixes = osuf : map (++ ('_':osuf)) extra_suffixes
384 ofiles = map (\suf -> basename ++ '.':suf) suffixes
386 objs <- mapM odir_ify ofiles
388 hdl <- readIORef v_Dep_tmp_hdl
390 -- std dependency of the object(s) on the source file
391 hPutStrLn hdl (unwords objs ++ " : " ++ basename ++ '.':suff)
393 let genDep (dep, False {- not an hi file -}) =
394 hPutStrLn hdl (unwords objs ++ " : " ++ dep)
395 genDep (dep, True {- is an hi file -}) = do
396 hisuf <- readIORef v_Hi_suf
397 let dep_base = remove_suffix '.' dep
398 deps = (dep_base ++ hisuf)
399 : map (\suf -> dep_base ++ suf ++ '_':hisuf) extra_suffixes
400 -- length objs should be == length deps
401 sequence_ (zipWith (\o d -> hPutStrLn hdl (o ++ " : " ++ d)) objs deps)
403 mapM genDep [ d | Just d <- deps ]
407 -- add the lines to dep_makefile:
411 -- if the dependency is on something other than a .hi file:
412 -- this.o this.p_o ... : dep
414 -- if the import is {-# SOURCE #-}
415 -- this.o this.p_o ... : dep.hi-boot[-$vers]
418 -- this.o ... : dep.hi
419 -- this.p_o ... : dep.p_hi
422 -- (where .o is $osuf, and the other suffixes come from
423 -- the cmdline -s options).
425 -----------------------------------------------------------------------------
428 -- Compilation of a single module, in "legacy" mode (_not_ under
429 -- the direction of the compilation manager).
430 run_phase Hsc basename suff input_fn output_fn
433 -- we add the current directory (i.e. the directory in which
434 -- the .hs files resides) to the import path, since this is
435 -- what gcc does, and it's probably what you want.
436 let current_dir = getdir basename
438 paths <- readIORef v_Include_paths
439 writeIORef v_Include_paths (current_dir : paths)
441 -- figure out which header files to #include in a generated .hc file
442 c_includes <- getPackageCIncludes
443 cmdline_includes <- dynFlag cmdlineHcIncludes -- -#include options
445 let cc_injects = unlines (map mk_include
446 (c_includes ++ reverse cmdline_includes))
449 '"':_{-"-} -> "#include "++h_file
450 '<':_ -> "#include "++h_file
451 _ -> "#include \""++h_file++"\""
453 writeIORef v_HCHeader cc_injects
455 -- gather the imports and module name
456 (srcimps,imps,mod_name) <- getImportsFromFile input_fn
458 -- build a ModuleLocation to pass to hscMain.
459 Just (mod, location')
460 <- mkHomeModuleLocn mod_name basename (Just (basename ++ '.':suff))
462 -- take -ohi into account if present
463 ohi <- readIORef v_Output_hi
464 let location | Just fn <- ohi = location'{ ml_hi_file = fn }
465 | otherwise = location'
467 -- figure out if the source has changed, for recompilation avoidance.
468 -- only do this if we're eventually going to generate a .o file.
469 -- (ToDo: do when generating .hc files too?)
471 -- Setting source_unchanged to True means that M.o seems
472 -- to be up to date wrt M.hs; so no need to recompile unless imports have
473 -- changed (which the compiler itself figures out).
474 -- Setting source_unchanged to False tells the compiler that M.o is out of
475 -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
476 do_recomp <- readIORef v_Recomp
477 todo <- readIORef v_GhcMode
478 expl_o_file <- readIORef v_Output_file
481 Nothing -> unJust "source_unchanged" (ml_obj_file location)
484 if not (do_recomp && ( todo == DoLink || todo == StopBefore Ln ))
486 else do t1 <- getModificationTime (basename ++ '.':suff)
487 o_file_exists <- doesFileExist o_file
489 then return False -- Need to recompile
490 else do t2 <- getModificationTime o_file
496 dyn_flags <- getDynFlags
498 let dyn_flags' = dyn_flags { hscOutName = output_fn,
499 hscStubCOutName = basename ++ "_stub.c",
500 hscStubHOutName = basename ++ "_stub.h",
501 extCoreName = basename ++ ".core" }
504 pcs <- initPersistentCompilerState
505 result <- hscMain OneShot
507 location{ ml_hspp_file=Just input_fn }
511 emptyModuleEnv -- HomeSymbolTable
512 emptyModuleEnv -- HomeIfaceTable
517 HscFail pcs -> throwDyn (PhaseFailed "hsc" (ExitFailure 1));
519 HscNoRecomp pcs details iface -> do { SysTools.touch "Touching object file" o_file
522 HscRecomp pcs details iface stub_h_exists stub_c_exists
523 _maybe_interpreted_code -> do
526 maybe_stub_o <- compileStub dyn_flags' stub_c_exists
529 Just stub_o -> add v_Ld_inputs stub_o
534 -----------------------------------------------------------------------------
537 -- we don't support preprocessing .c files (with -E) now. Doing so introduces
538 -- way too many hacks, and I can't say I've ever used it anyway.
540 run_phase cc_phase basename suff input_fn output_fn
541 | cc_phase == Cc || cc_phase == HCc
542 = do cc_opts <- getOpts opt_c
543 cmdline_include_dirs <- readIORef v_Include_paths
545 let hcc = cc_phase == HCc
547 -- add package include paths even if we're just compiling
548 -- .c files; this is the Value Add(TM) that using
549 -- ghc instead of gcc gives you :)
550 pkg_include_dirs <- getPackageIncludePath
551 let include_paths = map (\p -> "-I"++p) (cmdline_include_dirs
554 mangle <- readIORef v_Do_asm_mangling
555 (md_c_flags, md_regd_c_flags) <- machdepCCOpts
559 o2 <- readIORef v_minus_o2_for_C
560 let opt_flag | o2 = "-O2"
563 pkg_extra_cc_opts <- getPackageExtraCcOpts
565 split_objs <- readIORef v_Split_object_files
566 let split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
569 excessPrecision <- readIORef v_Excess_precision
570 SysTools.runCc ([ "-x", "c", input_fn, "-o", output_fn ]
572 ++ (if cc_phase == HCc && mangle
575 ++ [ verb, "-S", "-Wimplicit", opt_flag ]
576 ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
579 ++ (if excessPrecision then [] else [ "-ffloat-store" ])
585 -- ToDo: postprocess the output from gcc
587 -----------------------------------------------------------------------------
590 run_phase Mangle _basename _suff input_fn output_fn
591 = do mangler_opts <- getOpts opt_m
592 machdep_opts <- if (prefixMatch "i386" cTARGETPLATFORM)
593 then do n_regs <- dynFlag stolen_x86_regs
594 return [ show n_regs ]
597 SysTools.runMangle (mangler_opts
598 ++ [ input_fn, output_fn ]
602 -----------------------------------------------------------------------------
605 run_phase SplitMangle _basename _suff input_fn _output_fn
606 = do -- tmp_pfx is the prefix used for the split .s files
607 -- We also use it as the file to contain the no. of split .s files (sigh)
608 split_s_prefix <- SysTools.newTempName "split"
609 let n_files_fn = split_s_prefix
611 SysTools.runSplit [input_fn, split_s_prefix, n_files_fn]
613 -- Save the number of split files for future references
614 s <- readFile n_files_fn
615 let n_files = read s :: Int
616 writeIORef v_Split_info (split_s_prefix, n_files)
618 -- Remember to delete all these files
619 addFilesToClean [ split_s_prefix ++ "__" ++ show n ++ ".s"
624 -----------------------------------------------------------------------------
627 run_phase As _basename _suff input_fn output_fn
628 = do as_opts <- getOpts opt_a
629 cmdline_include_paths <- readIORef v_Include_paths
631 SysTools.runAs (as_opts
632 ++ [ "-I" ++ p | p <- cmdline_include_paths ]
633 ++ [ "-c", input_fn, "-o", output_fn ])
636 run_phase SplitAs basename _suff _input_fn _output_fn
637 = do as_opts <- getOpts opt_a
639 (split_s_prefix, n) <- readIORef v_Split_info
641 odir <- readIORef v_Output_dir
642 let real_odir = case odir of
647 = do let input_s = split_s_prefix ++ "__" ++ show n ++ ".s"
648 let output_o = newdir real_odir
649 (basename ++ "__" ++ show n ++ ".o")
650 real_o <- osuf_ify output_o
651 SysTools.runAs (as_opts ++ ["-c", "-o", real_o, input_s])
653 mapM_ assemble_file [1..n]
656 -----------------------------------------------------------------------------
657 -- MoveBinary sort-of-phase
658 -- After having produced a binary, move it somewhere else and generate a
659 -- wrapper script calling the binary. Currently, we need this only in
660 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
661 -- central directory.
662 -- This is called from doLink below, after linking. I haven't made it
663 -- a separate phase to minimise interfering with other modules, and
664 -- we don't need the generality of a phase (MoveBinary is always
665 -- done after linking and makes only sense in a parallel setup) -- HWL
667 run_phase_MoveBinary input_fn
670 pvm_root <- getEnv "PVM_ROOT"
671 pvm_arch <- getEnv "PVM_ARCH"
673 pvm_executable_base = "=" ++ input_fn
674 pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
675 -- nuke old binary; maybe use configur'ed names for cp and rm?
676 system ("rm -f " ++ pvm_executable)
677 -- move the newly created binary into PVM land
678 system ("cp -p " ++ input_fn ++ " " ++ pvm_executable)
679 -- generate a wrapper script for running a parallel prg under PVM
680 writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
683 -- generates a Perl skript starting a parallel prg under PVM
684 mk_pvm_wrapper_script :: String -> String -> String -> String
685 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
687 "eval 'exec perl -S $0 ${1+\"$@\"}'",
688 " if $running_under_some_shell;",
689 "# =!=!=!=!=!=!=!=!=!=!=!",
690 "# This script is automatically generated: DO NOT EDIT!!!",
691 "# Generated by Glasgow Haskell Compiler",
692 "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
694 "$pvm_executable = '" ++ pvm_executable ++ "';",
695 "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
696 "$SysMan = '" ++ sysMan ++ "';",
698 {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
699 "# first, some magical shortcuts to run "commands" on the binary",
700 "# (which is hidden)",
701 "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
702 " local($cmd) = $1;",
703 " system("$cmd $pvm_executable");",
704 " exit(0); # all done",
707 "# Now, run the real binary; process the args first",
708 "$ENV{'PE'} = $pvm_executable_base;", -- ++ pvm_executable_base,
710 "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
711 "@nonPVM_args = ();",
714 "args: while ($a = shift(@ARGV)) {",
715 " if ( $a eq '+RTS' ) {",
716 " $in_RTS_args = 1;",
717 " } elsif ( $a eq '-RTS' ) {",
718 " $in_RTS_args = 0;",
720 " if ( $a eq '-d' && $in_RTS_args ) {",
722 " } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
723 " $nprocessors = $1;",
724 " } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
725 " $nprocessors = $1;",
727 " push(@nonPVM_args, $a);",
731 "local($return_val) = 0;",
732 "# Start the parallel execution by calling SysMan",
733 "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
735 "# ToDo: fix race condition moving files and flushing them!!",
736 "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
740 -----------------------------------------------------------------------------
741 -- Complain about non-dynamic flags in OPTIONS pragmas
743 checkProcessArgsResult flags basename suff
744 = do when (not (null flags)) (throwDyn (ProgramError (
745 basename ++ "." ++ suff
746 ++ ": static flags are not allowed in {-# OPTIONS #-} pragmas:\n\t"
747 ++ unwords flags)) (ExitFailure 1))
749 -----------------------------------------------------------------------------
752 doLink :: [String] -> IO ()
755 static <- readIORef v_Static
756 no_hs_main <- readIORef v_NoHsMain
758 o_file <- readIORef v_Output_file
759 let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
761 pkg_lib_paths <- getPackageLibraryPath
762 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
764 lib_paths <- readIORef v_Library_paths
765 let lib_path_opts = map ("-L"++) lib_paths
767 pkg_libs <- getPackageLibraries
768 let imp = if static then "" else "_imp"
769 pkg_lib_opts = map (\lib -> "-l" ++ lib ++ imp) pkg_libs
771 libs <- readIORef v_Cmdline_libraries
772 let lib_opts = map ("-l"++) (reverse libs)
773 -- reverse because they're added in reverse order from the cmd line
775 pkg_extra_ld_opts <- getPackageExtraLdOpts
777 -- probably _stub.o files
778 extra_ld_inputs <- readIORef v_Ld_inputs
780 -- opts from -optl-<blah>
781 extra_ld_opts <- getStaticOpts v_Opt_l
783 rts_pkg <- getPackageDetails ["rts"]
784 std_pkg <- getPackageDetails ["std"]
785 let extra_os = if static || no_hs_main
787 else [ head (library_dirs (head rts_pkg)) ++ "/Main.dll_o",
788 head (library_dirs (head std_pkg)) ++ "/PrelMain.dll_o" ]
790 (md_c_flags, _) <- machdepCCOpts
791 SysTools.runLink ( [verb, "-o", output_fn]
802 ++ if static && not no_hs_main then
803 #ifdef LEADING_UNDERSCORE
804 [ "-u _PrelMain_mainIO_closure" ,
805 "-u ___init_PrelMain"]
807 [ "-u PrelMain_mainIO_closure" ,
808 "-u __init_PrelMain"]
812 -- parallel only: move binary to another dir -- HWL
813 ways_ <- readIORef v_Ways
814 when (WayPar `elem` ways_)
815 (do success <- run_phase_MoveBinary output_fn
816 if success then return ()
817 else throwDyn (InstallationError ("cannot move binary to PVM dir")))
819 -----------------------------------------------------------------------------
820 -- Making a DLL (only for Win32)
822 doMkDLL :: [String] -> IO ()
825 static <- readIORef v_Static
826 no_hs_main <- readIORef v_NoHsMain
828 o_file <- readIORef v_Output_file
829 let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
831 pkg_lib_paths <- getPackageLibraryPath
832 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
834 lib_paths <- readIORef v_Library_paths
835 let lib_path_opts = map ("-L"++) lib_paths
837 pkg_libs <- getPackageLibraries
838 let imp = if static then "" else "_imp"
839 pkg_lib_opts = map (\lib -> "-l" ++ lib ++ imp) pkg_libs
841 libs <- readIORef v_Cmdline_libraries
842 let lib_opts = map ("-l"++) (reverse libs)
843 -- reverse because they're added in reverse order from the cmd line
845 pkg_extra_ld_opts <- getPackageExtraLdOpts
847 -- probably _stub.o files
848 extra_ld_inputs <- readIORef v_Ld_inputs
850 -- opts from -optdll-<blah>
851 extra_ld_opts <- getStaticOpts v_Opt_dll
853 rts_pkg <- getPackageDetails ["rts"]
854 std_pkg <- getPackageDetails ["std"]
856 let extra_os = if static || no_hs_main
858 else [ head (library_dirs (head rts_pkg)) ++ "/Main.dll_o",
859 head (library_dirs (head std_pkg)) ++ "/PrelMain.dll_o" ]
861 (md_c_flags, _) <- machdepCCOpts
863 ([ verb, "-o", output_fn ]
867 ++ [ "--target=i386-mingw32" ]
874 ++ (case findPS (packString (concat extra_ld_opts)) (packString "--def") of
875 Nothing -> [ "--export-all" ]
880 -----------------------------------------------------------------------------
881 -- Just preprocess a file, put the result in a temp. file (used by the
882 -- compilation manager during the summary phase).
884 preprocess :: FilePath -> IO FilePath
885 preprocess filename =
886 ASSERT(haskellish_src_file filename)
887 do restoreDynFlags -- Restore to state of last save
888 pipeline <- genPipeline (StopBefore Hsc) ("preprocess") False
889 defaultHscLang filename
890 runPipeline pipeline filename False{-no linking-} False{-no -o flag-}
892 -----------------------------------------------------------------------------
893 -- Compile a single module, under the control of the compilation manager.
895 -- This is the interface between the compilation manager and the
896 -- compiler proper (hsc), where we deal with tedious details like
897 -- reading the OPTIONS pragma from the source file, and passing the
898 -- output of hsc through the C compiler.
900 -- The driver sits between 'compile' and 'hscMain', translating calls
901 -- to the former into calls to the latter, and results from the latter
902 -- into results from the former. It does things like preprocessing
903 -- the .hs file if necessary, and compiling up the .stub_c files to
904 -- generate Linkables.
906 -- NB. No old interface can also mean that the source has changed.
908 compile :: GhciMode -- distinguish batch from interactive
909 -> ModSummary -- summary, including source
910 -> Bool -- True <=> source unchanged
911 -> Bool -- True <=> have object
912 -> Maybe ModIface -- old interface, if available
913 -> HomeSymbolTable -- for home module ModDetails
914 -> HomeIfaceTable -- for home module Ifaces
915 -> PersistentCompilerState -- persistent compiler state
919 = CompOK PersistentCompilerState -- updated PCS
920 ModDetails -- new details (HST additions)
921 ModIface -- new iface (HIT additions)
923 -- new code; Nothing => compilation was not reqd
924 -- (old code is still valid)
926 | CompErrs PersistentCompilerState -- updated PCS
929 compile ghci_mode summary source_unchanged have_object
930 old_iface hst hit pcs = do
931 dyn_flags <- restoreDynFlags -- Restore to the state of the last save
935 (showSDoc (text "Compiling" <+> ppr (name_of_summary summary)))
937 let verb = verbosity dyn_flags
938 let location = ms_location summary
939 let input_fn = unJust "compile:hs" (ml_hs_file location)
940 let input_fnpp = unJust "compile:hspp" (ml_hspp_file location)
942 when (verb >= 2) (hPutStrLn stderr ("compile: input file " ++ input_fnpp))
944 opts <- getOptionsFromSource input_fnpp
945 processArgs dynamic_flags opts []
946 dyn_flags <- getDynFlags
948 let hsc_lang = hscLang dyn_flags
949 (basename, _) = splitFilename input_fn
951 output_fn <- case hsc_lang of
952 HscAsm -> newTempName (phaseInputExt As)
953 HscC -> newTempName (phaseInputExt HCc)
954 HscJava -> newTempName "java" -- ToDo
955 HscILX -> return (basename ++ ".ilx") -- newTempName "ilx" -- ToDo
956 HscInterpreted -> return (error "no output file")
958 let dyn_flags' = dyn_flags { hscOutName = output_fn,
959 hscStubCOutName = basename ++ "_stub.c",
960 hscStubHOutName = basename ++ "_stub.h",
961 extCoreName = basename ++ ".core" }
963 -- figure out which header files to #include in a generated .hc file
964 c_includes <- getPackageCIncludes
965 cmdline_includes <- dynFlag cmdlineHcIncludes -- -#include options
967 let cc_injects = unlines (map mk_include
968 (c_includes ++ reverse cmdline_includes))
971 '"':_{-"-} -> "#include "++h_file
972 '<':_ -> "#include "++h_file
973 _ -> "#include \""++h_file++"\""
975 writeIORef v_HCHeader cc_injects
978 hsc_result <- hscMain ghci_mode dyn_flags'
979 (ms_mod summary) location
980 source_unchanged have_object old_iface hst hit pcs
983 HscFail pcs -> return (CompErrs pcs)
985 HscNoRecomp pcs details iface -> return (CompOK pcs details iface Nothing)
987 HscRecomp pcs details iface
988 stub_h_exists stub_c_exists maybe_interpreted_code -> do
991 maybe_stub_o <- compileStub dyn_flags' stub_c_exists
992 let stub_unlinked = case maybe_stub_o of
994 Just stub_o -> [ DotO stub_o ]
996 (hs_unlinked, unlinked_time) <-
999 -- in interpreted mode, just return the compiled code
1000 -- as our "unlinked" object.
1002 case maybe_interpreted_code of
1003 Just (bcos,itbl_env) -> do tm <- getClockTime
1004 return ([BCOs bcos itbl_env], tm)
1005 Nothing -> panic "compile: no interpreted code"
1007 -- we're in batch mode: finish the compilation pipeline.
1008 _other -> do pipe <- genPipeline (StopBefore Ln) "" True
1010 -- runPipeline takes input_fn so it can split off
1011 -- the base name and use it as the base of
1012 -- the output object file.
1013 let (basename, suffix) = splitFilename input_fn
1014 o_file <- pipeLoop pipe output_fn False False
1016 o_time <- getModificationTime o_file
1017 return ([DotO o_file], o_time)
1019 let linkable = LM unlinked_time (moduleName (ms_mod summary))
1020 (hs_unlinked ++ stub_unlinked)
1022 return (CompOK pcs details iface (Just linkable))
1025 -----------------------------------------------------------------------------
1026 -- stub .h and .c files (for foreign export support)
1028 compileStub dflags stub_c_exists
1029 | not stub_c_exists = return Nothing
1030 | stub_c_exists = do
1031 -- compile the _stub.c file w/ gcc
1032 let stub_c = hscStubCOutName dflags
1033 pipeline <- genPipeline (StopBefore Ln) "" True defaultHscLang stub_c
1034 stub_o <- runPipeline pipeline stub_c False{-no linking-}
1035 False{-no -o option-}
1037 return (Just stub_o)