1 -----------------------------------------------------------------------------
5 -- (c) The University of Glasgow 2005
7 -----------------------------------------------------------------------------
9 module DriverPipeline (
10 -- Run a series of compilation steps in a pipeline, for a
11 -- collection of source files.
14 -- Interfaces for the batch-mode driver
17 -- Interfaces for the compilation manager (interpreted/batch-mode)
19 compile, CompResult(..),
25 matchOptions, -- used in module GHC
28 #include "HsVersions.h"
33 import SysTools ( newTempName, addFilesToClean, getSysMan, copy )
34 import qualified SysTools
42 import StaticFlags ( v_Ld_inputs, opt_Static, WayName(..) )
44 import RdrName ( GlobalRdrEnv )
47 import StringBuffer ( hGetStringBuffer )
48 import BasicTypes ( SuccessFlag(..) )
49 import Maybes ( expectJust )
50 import Ctype ( is_ident )
52 import ParserCoreUtils ( getCoreModuleName )
55 import DATA_IOREF ( readIORef, writeIORef, IORef )
64 -- ---------------------------------------------------------------------------
67 -- Just preprocess a file, put the result in a temp. file (used by the
68 -- compilation manager during the summary phase).
70 -- We return the augmented DynFlags, because they contain the result
71 -- of slurping in the OPTIONS pragmas
73 preprocess :: DynFlags -> FilePath -> IO (DynFlags, FilePath)
74 preprocess dflags filename =
75 ASSERT2(isHaskellSrcFilename filename, text filename)
76 runPipeline anyHsc dflags filename Temporary Nothing{-no ModLocation-}
78 -- ---------------------------------------------------------------------------
81 -- Compile a single module, under the control of the compilation manager.
83 -- This is the interface between the compilation manager and the
84 -- compiler proper (hsc), where we deal with tedious details like
85 -- reading the OPTIONS pragma from the source file, and passing the
86 -- output of hsc through the C compiler.
88 -- NB. No old interface can also mean that the source has changed.
92 -> Maybe Linkable -- Just linkable <=> source unchanged
93 -> Maybe ModIface -- Old interface, if available
97 = CompOK ModDetails -- New details
99 (Maybe Linkable) -- a Maybe, for the same reasons as hm_linkable
104 compile hsc_env mod_summary maybe_old_linkable old_iface = do
106 let dflags0 = hsc_dflags hsc_env
107 this_mod = ms_mod mod_summary
108 src_flavour = ms_hsc_src mod_summary
111 | Just l <- maybe_old_linkable, isObjectLinkable l = True
114 showPass dflags0 ("Compiling " ++ showModMsg have_object mod_summary)
116 let verb = verbosity dflags0
117 let location = ms_location mod_summary
118 let input_fn = expectJust "compile:hs" (ml_hs_file location)
119 let input_fnpp = expectJust "compile:hspp" (ms_hspp_file mod_summary)
121 when (verb >= 2) (hPutStrLn stderr ("compile: input file " ++ input_fnpp))
123 -- Add in the OPTIONS from the source file
124 -- This is nasty: we've done this once already, in the compilation manager
125 -- It might be better to cache the flags in the ml_hspp_file field,say
126 opts <- getOptionsFromSource input_fnpp
127 (dflags1,unhandled_flags) <- parseDynamicFlags dflags0 opts
128 checkProcessArgsResult unhandled_flags input_fn
130 let (basename, _) = splitFilename input_fn
132 -- We add the directory in which the .hs files resides) to the import path.
133 -- This is needed when we try to compile the .hc file later, if it
134 -- imports a _stub.h file that we created here.
135 let current_dir = directoryOf basename
136 old_paths = includePaths dflags1
137 dflags = dflags1 { includePaths = current_dir : old_paths }
139 -- Figure out what lang we're generating
140 let hsc_lang = hscMaybeAdjustTarget dflags StopLn src_flavour (hscTarget dflags)
141 -- ... and what the next phase should be
142 let next_phase = hscNextPhase dflags src_flavour hsc_lang
143 -- ... and what file to generate the output into
144 output_fn <- getOutputFilename dflags next_phase
145 Temporary basename next_phase (Just location)
147 let dflags' = dflags { hscTarget = hsc_lang,
148 hscOutName = output_fn,
149 hscStubCOutName = basename ++ "_stub.c",
150 hscStubHOutName = basename ++ "_stub.h",
151 extCoreName = basename ++ ".hcr" }
153 -- -no-recomp should also work with --make
154 let do_recomp = dopt Opt_RecompChecking dflags
155 source_unchanged = isJust maybe_old_linkable && do_recomp
156 hsc_env' = hsc_env { hsc_dflags = dflags' }
159 hsc_result <- hscMain hsc_env' printErrorsAndWarnings mod_summary
160 source_unchanged have_object old_iface
163 HscFail -> return CompErrs
165 HscNoRecomp details iface ->
166 ASSERT(isJust maybe_old_linkable)
167 return (CompOK details iface maybe_old_linkable)
169 HscRecomp details iface
170 stub_h_exists stub_c_exists maybe_interpreted_code
172 | isHsBoot src_flavour -- No further compilation to do
173 -> return (CompOK details iface Nothing)
175 | otherwise -- Normal Haskell source files
177 maybe_stub_o <- compileStub dflags' stub_c_exists
178 let stub_unlinked = case maybe_stub_o of
180 Just stub_o -> [ DotO stub_o ]
182 (hs_unlinked, unlinked_time) <-
185 -- in interpreted mode, just return the compiled code
186 -- as our "unlinked" object.
188 case maybe_interpreted_code of
190 Just comp_bc -> return ([BCOs comp_bc], ms_hs_date mod_summary)
191 -- Why do we use the timestamp of the source file here,
192 -- rather than the current time? This works better in
193 -- the case where the local clock is out of sync
194 -- with the filesystem's clock. It's just as accurate:
195 -- if the source is modified, then the linkable will
198 Nothing -> panic "compile: no interpreted code"
200 -- we're in batch mode: finish the compilation pipeline.
202 let object_filename = ml_obj_file location
204 runPipeline StopLn dflags output_fn Persistent
206 -- the object filename comes from the ModLocation
208 o_time <- getModificationTime object_filename
209 return ([DotO object_filename], o_time)
211 let linkable = LM unlinked_time this_mod
212 (hs_unlinked ++ stub_unlinked)
214 return (CompOK details iface (Just linkable))
216 -----------------------------------------------------------------------------
217 -- stub .h and .c files (for foreign export support)
219 compileStub dflags stub_c_exists
220 | not stub_c_exists = return Nothing
222 -- compile the _stub.c file w/ gcc
223 let stub_c = hscStubCOutName dflags
224 (_, stub_o) <- runPipeline StopLn dflags
225 stub_c Persistent Nothing{-no ModLocation-}
229 -- ---------------------------------------------------------------------------
232 link :: GhcMode -- interactive or batch
233 -> DynFlags -- dynamic flags
234 -> Bool -- attempt linking in batch mode?
235 -> HomePackageTable -- what to link
238 -- For the moment, in the batch linker, we don't bother to tell doLink
239 -- which packages to link -- it just tries all that are available.
240 -- batch_attempt_linking should only be *looked at* in batch mode. It
241 -- should only be True if the upsweep was successful and someone
242 -- exports main, i.e., we have good reason to believe that linking
246 link Interactive dflags batch_attempt_linking hpt
247 = do -- Not Linking...(demand linker will do the job)
251 link BatchCompile dflags batch_attempt_linking hpt
252 | batch_attempt_linking
255 home_mod_infos = moduleEnvElts hpt
257 -- the packages we depend on
258 pkg_deps = concatMap (dep_pkgs . mi_deps . hm_iface) home_mod_infos
260 -- the linkables to link
261 linkables = map (fromJust.hm_linkable) home_mod_infos
263 when (verb >= 3) $ do
264 hPutStrLn stderr "link: linkables are ..."
265 hPutStrLn stderr (showSDoc (vcat (map ppr linkables)))
267 -- check for the -no-link flag
268 if isNoLink (ghcLink dflags)
269 then do when (verb >= 3) $
270 hPutStrLn stderr "link(batch): linking omitted (-c flag given)."
275 hPutStrLn stderr "Linking ..."
277 let getOfiles (LM _ _ us) = map nameOfObject (filter isObject us)
278 obj_files = concatMap getOfiles linkables
280 -- Don't showPass in Batch mode; doLink will do that for us.
281 staticLink dflags obj_files pkg_deps
283 when (verb >= 3) (hPutStrLn stderr "link: done")
285 -- staticLink only returns if it succeeds
289 = do when (verb >= 3) $ do
290 hPutStrLn stderr "link(batch): upsweep (partially) failed OR"
291 hPutStrLn stderr " Main.main not exported; not linking."
294 verb = verbosity dflags
297 -- -----------------------------------------------------------------------------
298 -- Compile files in one-shot mode.
300 oneShot :: DynFlags -> Phase -> [String] -> IO ()
301 oneShot dflags stop_phase srcs = do
302 o_files <- mapM (compileFile dflags stop_phase) srcs
303 doLink dflags stop_phase o_files
305 compileFile :: DynFlags -> Phase -> FilePath -> IO FilePath
306 compileFile dflags stop_phase src = do
307 exists <- doesFileExist src
309 throwDyn (CmdLineError ("does not exist: " ++ src))
312 split = dopt Opt_SplitObjs dflags
313 mb_o_file = outputFile dflags
314 ghc_link = ghcLink dflags -- Set by -c or -no-link
316 -- When linking, the -o argument refers to the linker's output.
317 -- otherwise, we use it as the name for the pipeline's output.
319 | StopLn <- stop_phase, not (isNoLink ghc_link) = Persistent
320 -- -o foo applies to linker
321 | Just o_file <- mb_o_file = SpecificFile o_file
322 -- -o foo applies to the file we are compiling now
323 | otherwise = Persistent
325 stop_phase' = case stop_phase of
326 As | split -> SplitAs
329 (_, out_file) <- runPipeline stop_phase' dflags
330 src output Nothing{-no ModLocation-}
334 doLink :: DynFlags -> Phase -> [FilePath] -> IO ()
335 doLink dflags stop_phase o_files
336 | not (isStopLn stop_phase)
337 = return () -- We stopped before the linking phase
340 = case ghcLink dflags of
342 StaticLink -> staticLink dflags o_files link_pkgs
343 MkDLL -> doMkDLL dflags o_files link_pkgs
345 -- Always link in the haskell98 package for static linking. Other
346 -- packages have to be specified via the -package flag.
348 | ExtPackage h98_id <- haskell98PackageId (pkgState dflags) = [h98_id]
352 -- ---------------------------------------------------------------------------
353 -- Run a compilation pipeline, consisting of multiple phases.
355 -- This is the interface to the compilation pipeline, which runs
356 -- a series of compilation steps on a single source file, specifying
357 -- at which stage to stop.
359 -- The DynFlags can be modified by phases in the pipeline (eg. by
360 -- GHC_OPTIONS pragmas), and the changes affect later phases in the
365 -- output should be to a temporary file: we're going to
366 -- run more compilation steps on this output later
368 -- we want a persistent file, i.e. a file in the current directory
369 -- derived from the input filename, but with the appropriate extension.
370 -- eg. in "ghc -c Foo.hs" the output goes into ./Foo.o.
371 | SpecificFile FilePath
372 -- the output must go into the specified file.
375 :: Phase -- When to stop
376 -> DynFlags -- Dynamic flags
377 -> FilePath -- Input filename
378 -> PipelineOutput -- Output filename
379 -> Maybe ModLocation -- A ModLocation, if this is a Haskell module
380 -> IO (DynFlags, FilePath) -- (final flags, output filename)
382 runPipeline stop_phase dflags input_fn output maybe_loc
384 let (basename, suffix) = splitFilename input_fn
385 start_phase = startPhase suffix
387 -- We want to catch cases of "you can't get there from here" before
388 -- we start the pipeline, because otherwise it will just run off the
391 -- There is a partial ordering on phases, where A < B iff A occurs
392 -- before B in a normal compilation pipeline.
394 when (not (start_phase `happensBefore` stop_phase)) $
396 ("cannot compile this file to desired target: "
399 -- this is a function which will be used to calculate output file names
400 -- as we go along (we partially apply it to some of its inputs here)
401 let get_output_fn = getOutputFilename dflags stop_phase output basename
403 -- Execute the pipeline...
404 (dflags', output_fn, maybe_loc) <-
405 pipeLoop dflags start_phase stop_phase input_fn
406 basename suffix get_output_fn maybe_loc
408 -- Sometimes, a compilation phase doesn't actually generate any output
409 -- (eg. the CPP phase when -fcpp is not turned on). If we end on this
410 -- stage, but we wanted to keep the output, then we have to explicitly
414 return (dflags', output_fn)
416 do final_fn <- get_output_fn stop_phase maybe_loc
417 when (final_fn /= output_fn) $
418 copy dflags ("Copying `" ++ output_fn ++ "' to `" ++ final_fn
419 ++ "'") output_fn final_fn
420 return (dflags', final_fn)
424 pipeLoop :: DynFlags -> Phase -> Phase
425 -> FilePath -> String -> Suffix
426 -> (Phase -> Maybe ModLocation -> IO FilePath)
428 -> IO (DynFlags, FilePath, Maybe ModLocation)
430 pipeLoop dflags phase stop_phase
431 input_fn orig_basename orig_suff
432 orig_get_output_fn maybe_loc
434 | phase `eqPhase` stop_phase -- All done
435 = return (dflags, input_fn, maybe_loc)
437 | not (phase `happensBefore` stop_phase)
438 -- Something has gone wrong. We'll try to cover all the cases when
439 -- this could happen, so if we reach here it is a panic.
440 -- eg. it might happen if the -C flag is used on a source file that
441 -- has {-# OPTIONS -fasm #-}.
442 = panic ("pipeLoop: at phase " ++ show phase ++
443 " but I wanted to stop at phase " ++ show stop_phase)
446 = do { (next_phase, dflags', maybe_loc, output_fn)
447 <- runPhase phase stop_phase dflags orig_basename
448 orig_suff input_fn orig_get_output_fn maybe_loc
449 ; pipeLoop dflags' next_phase stop_phase output_fn
450 orig_basename orig_suff orig_get_output_fn maybe_loc }
453 :: DynFlags -> Phase -> PipelineOutput -> String
454 -> Phase{-next phase-} -> Maybe ModLocation -> IO FilePath
455 getOutputFilename dflags stop_phase output basename
459 odir = outputDir dflags
460 osuf = objectSuf dflags
461 keep_hc = dopt Opt_KeepHcFiles dflags
462 keep_raw_s = dopt Opt_KeepRawSFiles dflags
463 keep_s = dopt Opt_KeepSFiles dflags
465 myPhaseInputExt HCc = hcsuf
466 myPhaseInputExt StopLn = osuf
467 myPhaseInputExt other = phaseInputExt other
469 func next_phase maybe_location
470 | is_last_phase, Persistent <- output = persistent_fn
471 | is_last_phase, SpecificFile f <- output = return f
472 | keep_this_output = persistent_fn
473 | otherwise = newTempName dflags suffix
475 is_last_phase = next_phase `eqPhase` stop_phase
477 -- sometimes, we keep output from intermediate stages
481 Mangle | keep_raw_s -> True
483 HCc | keep_hc -> True
486 suffix = myPhaseInputExt next_phase
488 -- persistent object files get put in odir
490 | StopLn <- next_phase = return odir_persistent
491 | otherwise = return persistent
493 persistent = basename ++ '.':suffix
496 | Just loc <- maybe_location = ml_obj_file loc
497 | Just d <- odir = replaceFilenameDirectory persistent d
498 | otherwise = persistent
501 -- -----------------------------------------------------------------------------
502 -- Each phase in the pipeline returns the next phase to execute, and the
503 -- name of the file in which the output was placed.
505 -- We must do things dynamically this way, because we often don't know
506 -- what the rest of the phases will be until part-way through the
507 -- compilation: for example, an {-# OPTIONS -fasm #-} at the beginning
508 -- of a source file can change the latter stages of the pipeline from
509 -- taking the via-C route to using the native code generator.
511 runPhase :: Phase -- Do this phase first
512 -> Phase -- Stop just before this phase
514 -> String -- basename of original input source
515 -> String -- its extension
516 -> FilePath -- name of file which contains the input to this phase.
517 -> (Phase -> Maybe ModLocation -> IO FilePath)
518 -- how to calculate the output filename
519 -> Maybe ModLocation -- the ModLocation, if we have one
520 -> IO (Phase, -- next phase
521 DynFlags, -- new dynamic flags
522 Maybe ModLocation, -- the ModLocation, if we have one
523 FilePath) -- output filename
525 -- Invariant: the output filename always contains the output
526 -- Interesting case: Hsc when there is no recompilation to do
527 -- Then the output filename is still a .o file
529 -------------------------------------------------------------------------------
532 runPhase (Unlit sf) _stop dflags _basename _suff input_fn get_output_fn maybe_loc
533 = do let unlit_flags = getOpts dflags opt_L
534 -- The -h option passes the file name for unlit to put in a #line directive
535 output_fn <- get_output_fn (Cpp sf) maybe_loc
537 SysTools.runUnlit dflags
538 (map SysTools.Option unlit_flags ++
539 [ SysTools.Option "-h"
540 , SysTools.Option input_fn
541 , SysTools.FileOption "" input_fn
542 , SysTools.FileOption "" output_fn
545 return (Cpp sf, dflags, maybe_loc, output_fn)
547 -------------------------------------------------------------------------------
548 -- Cpp phase : (a) gets OPTIONS out of file
549 -- (b) runs cpp if necessary
551 runPhase (Cpp sf) _stop dflags0 basename suff input_fn get_output_fn maybe_loc
552 = do src_opts <- getOptionsFromSource input_fn
553 (dflags,unhandled_flags) <- parseDynamicFlags dflags0 src_opts
554 checkProcessArgsResult unhandled_flags (basename++'.':suff)
556 if not (dopt Opt_Cpp dflags) then
557 -- no need to preprocess CPP, just pass input file along
558 -- to the next phase of the pipeline.
559 return (HsPp sf, dflags, maybe_loc, input_fn)
561 output_fn <- get_output_fn (HsPp sf) maybe_loc
562 doCpp dflags True{-raw-} False{-no CC opts-} input_fn output_fn
563 return (HsPp sf, dflags, maybe_loc, output_fn)
565 -------------------------------------------------------------------------------
568 runPhase (HsPp sf) _stop dflags basename suff input_fn get_output_fn maybe_loc
569 = do if not (dopt Opt_Pp dflags) then
570 -- no need to preprocess, just pass input file along
571 -- to the next phase of the pipeline.
572 return (Hsc sf, dflags, maybe_loc, input_fn)
574 let hspp_opts = getOpts dflags opt_F
575 let orig_fn = basename ++ '.':suff
576 output_fn <- get_output_fn (Hsc sf) maybe_loc
577 SysTools.runPp dflags
578 ( [ SysTools.Option orig_fn
579 , SysTools.Option input_fn
580 , SysTools.FileOption "" output_fn
582 map SysTools.Option hspp_opts
584 return (Hsc sf, dflags, maybe_loc, output_fn)
586 -----------------------------------------------------------------------------
589 -- Compilation of a single module, in "legacy" mode (_not_ under
590 -- the direction of the compilation manager).
591 runPhase (Hsc src_flavour) stop dflags0 basename suff input_fn get_output_fn _maybe_loc
592 = do -- normal Hsc mode, not mkdependHS
594 -- we add the current directory (i.e. the directory in which
595 -- the .hs files resides) to the import path, since this is
596 -- what gcc does, and it's probably what you want.
597 let current_dir = directoryOf basename
599 paths = includePaths dflags0
600 dflags = dflags0 { includePaths = current_dir : paths }
602 -- gather the imports and module name
603 (hspp_buf,mod_name) <-
605 ExtCoreFile -> do { -- no explicit imports in ExtCore input.
606 ; m <- getCoreModuleName input_fn
607 ; return (Nothing, mkModule m) }
609 other -> do { buf <- hGetStringBuffer input_fn
610 ; (_,_,mod_name) <- getImports dflags buf input_fn
611 ; return (Just buf, mod_name) }
613 -- Build a ModLocation to pass to hscMain.
614 -- The source filename is rather irrelevant by now, but it's used
615 -- by hscMain for messages. hscMain also needs
616 -- the .hi and .o filenames, and this is as good a way
617 -- as any to generate them, and better than most. (e.g. takes
618 -- into accout the -osuf flags)
619 location1 <- mkHomeModLocation2 dflags mod_name basename suff
621 -- Boot-ify it if necessary
622 let location2 | isHsBoot src_flavour = addBootSuffixLocn location1
623 | otherwise = location1
626 -- Take -ohi into account if present
627 -- This can't be done in mkHomeModuleLocation because
628 -- it only applies to the module being compiles
629 let ohi = outputHi dflags
630 location3 | Just fn <- ohi = location2{ ml_hi_file = fn }
631 | otherwise = location2
633 -- Take -o into account if present
634 -- Very like -ohi, but we must *only* do this if we aren't linking
635 -- (If we're linking then the -o applies to the linked thing, not to
636 -- the object file for one module.)
637 -- Note the nasty duplication with the same computation in compileFile above
638 let expl_o_file = outputFile dflags
639 location4 | Just ofile <- expl_o_file
640 , isNoLink (ghcLink dflags)
641 = location3 { ml_obj_file = ofile }
642 | otherwise = location3
644 -- Make the ModSummary to hand to hscMain
645 src_timestamp <- getModificationTime (basename ++ '.':suff)
647 unused_field = panic "runPhase:ModSummary field"
648 -- Some fields are not looked at by hscMain
649 mod_summary = ModSummary { ms_mod = mod_name,
650 ms_hsc_src = src_flavour,
651 ms_hspp_file = Just input_fn,
652 ms_hspp_buf = hspp_buf,
653 ms_location = location4,
654 ms_hs_date = src_timestamp,
655 ms_obj_date = Nothing,
656 ms_imps = unused_field,
657 ms_srcimps = unused_field }
659 o_file = ml_obj_file location4 -- The real object file
662 -- Figure out if the source has changed, for recompilation avoidance.
664 -- Setting source_unchanged to True means that M.o seems
665 -- to be up to date wrt M.hs; so no need to recompile unless imports have
666 -- changed (which the compiler itself figures out).
667 -- Setting source_unchanged to False tells the compiler that M.o is out of
668 -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
669 let do_recomp = dopt Opt_RecompChecking dflags
671 if not do_recomp || not (isStopLn stop)
672 -- Set source_unchanged to False unconditionally if
673 -- (a) recompilation checker is off, or
674 -- (b) we aren't going all the way to .o file (e.g. ghc -S)
676 -- Otherwise look at file modification dates
677 else do o_file_exists <- doesFileExist o_file
679 then return False -- Need to recompile
680 else do t2 <- getModificationTime o_file
681 if t2 > src_timestamp
686 let hsc_lang = hscMaybeAdjustTarget dflags stop src_flavour (hscTarget dflags)
687 let next_phase = hscNextPhase dflags src_flavour hsc_lang
688 output_fn <- get_output_fn next_phase (Just location4)
690 let dflags' = dflags { hscTarget = hsc_lang,
691 hscOutName = output_fn,
692 hscStubCOutName = basename ++ "_stub.c",
693 hscStubHOutName = basename ++ "_stub.h",
694 extCoreName = basename ++ ".hcr" }
696 hsc_env <- newHscEnv dflags'
698 -- Tell the finder cache about this module
699 addHomeModuleToFinder hsc_env mod_name location4
702 result <- hscMain hsc_env printErrorsAndWarnings
703 mod_summary source_unchanged
704 False -- No object file
709 HscFail -> throwDyn (PhaseFailed "hsc" (ExitFailure 1))
711 HscNoRecomp details iface -> do
712 SysTools.touch dflags' "Touching object file" o_file
713 return (StopLn, dflags', Just location4, o_file)
715 HscRecomp _details _iface
716 stub_h_exists stub_c_exists
717 _maybe_interpreted_code -> do
720 maybe_stub_o <- compileStub dflags' stub_c_exists
723 Just stub_o -> consIORef v_Ld_inputs stub_o
725 -- In the case of hs-boot files, generate a dummy .o-boot
726 -- stamp file for the benefit of Make
728 HsBootFile -> SysTools.touch dflags' "Touching object file" o_file
731 return (next_phase, dflags', Just location4, output_fn)
733 -----------------------------------------------------------------------------
736 runPhase CmmCpp stop dflags basename suff input_fn get_output_fn maybe_loc
738 output_fn <- get_output_fn Cmm maybe_loc
739 doCpp dflags False{-not raw-} True{-include CC opts-} input_fn output_fn
740 return (Cmm, dflags, maybe_loc, output_fn)
742 runPhase Cmm stop dflags basename suff input_fn get_output_fn maybe_loc
744 let hsc_lang = hscMaybeAdjustTarget dflags stop HsSrcFile (hscTarget dflags)
745 let next_phase = hscNextPhase dflags HsSrcFile hsc_lang
746 output_fn <- get_output_fn next_phase maybe_loc
748 let dflags' = dflags { hscTarget = hsc_lang,
749 hscOutName = output_fn,
750 hscStubCOutName = basename ++ "_stub.c",
751 hscStubHOutName = basename ++ "_stub.h",
752 extCoreName = basename ++ ".hcr" }
754 ok <- hscCmmFile dflags' input_fn
756 when (not ok) $ throwDyn (PhaseFailed "cmm" (ExitFailure 1))
758 return (next_phase, dflags, maybe_loc, output_fn)
760 -----------------------------------------------------------------------------
763 -- we don't support preprocessing .c files (with -E) now. Doing so introduces
764 -- way too many hacks, and I can't say I've ever used it anyway.
766 runPhase cc_phase stop dflags basename suff input_fn get_output_fn maybe_loc
767 | cc_phase `eqPhase` Cc || cc_phase `eqPhase` HCc
768 = do let cc_opts = getOpts dflags opt_c
769 hcc = cc_phase `eqPhase` HCc
771 let cmdline_include_paths = includePaths dflags
773 -- HC files have the dependent packages stamped into them
774 pkgs <- if hcc then getHCFilePackages input_fn else return []
776 -- add package include paths even if we're just compiling .c
777 -- files; this is the Value Add(TM) that using ghc instead of
779 pkg_include_dirs <- getPackageIncludePath dflags pkgs
780 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
781 (cmdline_include_paths ++ pkg_include_dirs)
783 let (md_c_flags, md_regd_c_flags) = machdepCCOpts dflags
784 let pic_c_flags = picCCOpts dflags
786 let verb = getVerbFlag dflags
788 pkg_extra_cc_opts <- getPackageExtraCcOpts dflags pkgs
790 let split_objs = dopt Opt_SplitObjs dflags
791 split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
794 let excessPrecision = dopt Opt_ExcessPrecision dflags
798 let mangle = dopt Opt_DoAsmMangling dflags
800 | hcc && mangle = Mangle
802 output_fn <- get_output_fn next_phase maybe_loc
804 -- force the C compiler to interpret this file as C when
805 -- compiling .hc files, by adding the -x c option.
806 let langopt | hcc = [ SysTools.Option "-x", SysTools.Option "c"]
809 SysTools.runCc dflags (langopt ++
810 [ SysTools.FileOption "" input_fn
811 , SysTools.Option "-o"
812 , SysTools.FileOption "" output_fn
814 ++ map SysTools.Option (
820 ++ [ verb, "-S", "-Wimplicit", "-O" ]
821 ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
824 ++ (if excessPrecision then [] else [ "-ffloat-store" ])
829 return (next_phase, dflags, maybe_loc, output_fn)
831 -- ToDo: postprocess the output from gcc
833 -----------------------------------------------------------------------------
836 runPhase Mangle stop dflags _basename _suff input_fn get_output_fn maybe_loc
837 = do let mangler_opts = getOpts dflags opt_m
840 machdep_opts <- return [ show (stolen_x86_regs dflags) ]
842 machdep_opts <- return []
845 let split = dopt Opt_SplitObjs dflags
847 | split = SplitMangle
849 output_fn <- get_output_fn next_phase maybe_loc
851 SysTools.runMangle dflags (map SysTools.Option mangler_opts
852 ++ [ SysTools.FileOption "" input_fn
853 , SysTools.FileOption "" output_fn
855 ++ map SysTools.Option machdep_opts)
857 return (next_phase, dflags, maybe_loc, output_fn)
859 -----------------------------------------------------------------------------
862 runPhase SplitMangle stop dflags _basename _suff input_fn get_output_fn maybe_loc
863 = do -- tmp_pfx is the prefix used for the split .s files
864 -- We also use it as the file to contain the no. of split .s files (sigh)
865 split_s_prefix <- SysTools.newTempName dflags "split"
866 let n_files_fn = split_s_prefix
868 SysTools.runSplit dflags
869 [ SysTools.FileOption "" input_fn
870 , SysTools.FileOption "" split_s_prefix
871 , SysTools.FileOption "" n_files_fn
874 -- Save the number of split files for future references
875 s <- readFile n_files_fn
876 let n_files = read s :: Int
877 writeIORef v_Split_info (split_s_prefix, n_files)
879 -- Remember to delete all these files
880 addFilesToClean [ split_s_prefix ++ "__" ++ show n ++ ".s"
883 return (SplitAs, dflags, maybe_loc, "**splitmangle**")
884 -- we don't use the filename
886 -----------------------------------------------------------------------------
889 runPhase As stop dflags _basename _suff input_fn get_output_fn maybe_loc
890 = do let as_opts = getOpts dflags opt_a
891 let cmdline_include_paths = includePaths dflags
893 output_fn <- get_output_fn StopLn maybe_loc
895 -- we create directories for the object file, because it
896 -- might be a hierarchical module.
897 createDirectoryHierarchy (directoryOf output_fn)
899 SysTools.runAs dflags
900 (map SysTools.Option as_opts
901 ++ [ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ]
902 ++ [ SysTools.Option "-c"
903 , SysTools.FileOption "" input_fn
904 , SysTools.Option "-o"
905 , SysTools.FileOption "" output_fn
908 return (StopLn, dflags, maybe_loc, output_fn)
911 runPhase SplitAs stop dflags basename _suff _input_fn get_output_fn maybe_loc
912 = do let as_opts = getOpts dflags opt_a
914 (split_s_prefix, n) <- readIORef v_Split_info
917 | Just d <- outputDir dflags = d
918 | otherwise = basename ++ "_split"
921 = do let input_s = split_s_prefix ++ "__" ++ show n ++ ".s"
922 let output_o = replaceFilenameDirectory
923 (basename ++ "__" ++ show n ++ ".o")
925 let osuf = objectSuf dflags
926 let real_o = replaceFilenameSuffix output_o osuf
927 SysTools.runAs dflags
928 (map SysTools.Option as_opts ++
929 [ SysTools.Option "-c"
930 , SysTools.Option "-o"
931 , SysTools.FileOption "" real_o
932 , SysTools.FileOption "" input_s
935 mapM_ assemble_file [1..n]
937 output_fn <- get_output_fn StopLn maybe_loc
938 return (StopLn, dflags, maybe_loc, output_fn)
940 -----------------------------------------------------------------------------
941 -- MoveBinary sort-of-phase
942 -- After having produced a binary, move it somewhere else and generate a
943 -- wrapper script calling the binary. Currently, we need this only in
944 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
945 -- central directory.
946 -- This is called from staticLink below, after linking. I haven't made it
947 -- a separate phase to minimise interfering with other modules, and
948 -- we don't need the generality of a phase (MoveBinary is always
949 -- done after linking and makes only sense in a parallel setup) -- HWL
951 runPhase_MoveBinary input_fn
954 pvm_root <- getEnv "PVM_ROOT"
955 pvm_arch <- getEnv "PVM_ARCH"
957 pvm_executable_base = "=" ++ input_fn
958 pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
959 -- nuke old binary; maybe use configur'ed names for cp and rm?
960 system ("rm -f " ++ pvm_executable)
961 -- move the newly created binary into PVM land
962 system ("cp -p " ++ input_fn ++ " " ++ pvm_executable)
963 -- generate a wrapper script for running a parallel prg under PVM
964 writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
967 -- generates a Perl skript starting a parallel prg under PVM
968 mk_pvm_wrapper_script :: String -> String -> String -> String
969 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
971 "eval 'exec perl -S $0 ${1+\"$@\"}'",
972 " if $running_under_some_shell;",
973 "# =!=!=!=!=!=!=!=!=!=!=!",
974 "# This script is automatically generated: DO NOT EDIT!!!",
975 "# Generated by Glasgow Haskell Compiler",
976 "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
978 "$pvm_executable = '" ++ pvm_executable ++ "';",
979 "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
980 "$SysMan = '" ++ sysMan ++ "';",
982 {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
983 "# first, some magical shortcuts to run "commands" on the binary",
984 "# (which is hidden)",
985 "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
986 " local($cmd) = $1;",
987 " system("$cmd $pvm_executable");",
988 " exit(0); # all done",
991 "# Now, run the real binary; process the args first",
992 "$ENV{'PE'} = $pvm_executable_base;", -- ++ pvm_executable_base,
994 "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
995 "@nonPVM_args = ();",
998 "args: while ($a = shift(@ARGV)) {",
999 " if ( $a eq '+RTS' ) {",
1000 " $in_RTS_args = 1;",
1001 " } elsif ( $a eq '-RTS' ) {",
1002 " $in_RTS_args = 0;",
1004 " if ( $a eq '-d' && $in_RTS_args ) {",
1006 " } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
1007 " $nprocessors = $1;",
1008 " } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
1009 " $nprocessors = $1;",
1011 " push(@nonPVM_args, $a);",
1015 "local($return_val) = 0;",
1016 "# Start the parallel execution by calling SysMan",
1017 "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
1018 "$return_val = $?;",
1019 "# ToDo: fix race condition moving files and flushing them!!",
1020 "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
1021 "exit($return_val);"
1024 -----------------------------------------------------------------------------
1025 -- Complain about non-dynamic flags in OPTIONS pragmas
1027 checkProcessArgsResult flags filename
1028 = do when (notNull flags) (throwDyn (ProgramError (
1029 showSDoc (hang (text filename <> char ':')
1030 4 (text "unknown flags in {-# OPTIONS #-} pragma:" <+>
1031 hsep (map text flags)))
1034 -----------------------------------------------------------------------------
1035 -- Look for the /* GHC_PACKAGES ... */ comment at the top of a .hc file
1037 getHCFilePackages :: FilePath -> IO [PackageId]
1038 getHCFilePackages filename =
1039 EXCEPTION.bracket (openFile filename ReadMode) hClose $ \h -> do
1042 '/':'*':' ':'G':'H':'C':'_':'P':'A':'C':'K':'A':'G':'E':'S':rest ->
1043 return (map stringToPackageId (words rest))
1047 -----------------------------------------------------------------------------
1048 -- Static linking, of .o files
1050 -- The list of packages passed to link is the list of packages on
1051 -- which this program depends, as discovered by the compilation
1052 -- manager. It is combined with the list of packages that the user
1053 -- specifies on the command line with -package flags.
1055 -- In one-shot linking mode, we can't discover the package
1056 -- dependencies (because we haven't actually done any compilation or
1057 -- read any interface files), so the user must explicitly specify all
1060 staticLink :: DynFlags -> [FilePath] -> [PackageId] -> IO ()
1061 staticLink dflags o_files dep_packages = do
1062 let verb = getVerbFlag dflags
1064 -- get the full list of packages to link with, by combining the
1065 -- explicit packages with the auto packages and all of their
1066 -- dependencies, and eliminating duplicates.
1068 let o_file = outputFile dflags
1069 #if defined(mingw32_HOST_OS)
1070 let output_fn = case o_file of { Just s -> s; Nothing -> "main.exe"; }
1072 let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
1075 pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1076 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1078 let lib_paths = libraryPaths dflags
1079 let lib_path_opts = map ("-L"++) lib_paths
1081 pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1083 #ifdef darwin_TARGET_OS
1084 pkg_framework_paths <- getPackageFrameworkPath dflags dep_packages
1085 let pkg_framework_path_opts = map ("-F"++) pkg_framework_paths
1087 let framework_paths = frameworkPaths dflags
1088 framework_path_opts = map ("-F"++) framework_paths
1090 pkg_frameworks <- getPackageFrameworks dflags dep_packages
1091 let pkg_framework_opts = concat [ ["-framework", fw] | fw <- pkg_frameworks ]
1093 let frameworks = cmdlineFrameworks dflags
1094 framework_opts = concat [ ["-framework", fw] | fw <- reverse frameworks ]
1095 -- reverse because they're added in reverse order from the cmd line
1098 -- probably _stub.o files
1099 extra_ld_inputs <- readIORef v_Ld_inputs
1101 -- opts from -optl-<blah> (including -l<blah> options)
1102 let extra_ld_opts = getOpts dflags opt_l
1104 let ways = wayNames dflags
1106 -- Here are some libs that need to be linked at the *end* of
1107 -- the command line, because they contain symbols that are referred to
1108 -- by the RTS. We can't therefore use the ordinary way opts for these.
1110 debug_opts | WayDebug `elem` ways = [
1111 #if defined(HAVE_LIBBFD)
1118 thread_opts | WayThreaded `elem` ways = [
1119 #if !defined(mingw32_TARGET_OS) && !defined(freebsd_TARGET_OS)
1122 #if defined(osf3_TARGET_OS)
1128 let (md_c_flags, _) = machdepCCOpts dflags
1129 SysTools.runLink dflags (
1130 [ SysTools.Option verb
1131 , SysTools.Option "-o"
1132 , SysTools.FileOption "" output_fn
1134 ++ map SysTools.Option (
1140 #ifdef darwin_TARGET_OS
1141 ++ framework_path_opts
1144 ++ pkg_lib_path_opts
1146 #ifdef darwin_TARGET_OS
1147 ++ pkg_framework_path_opts
1148 ++ pkg_framework_opts
1154 -- parallel only: move binary to another dir -- HWL
1155 when (WayPar `elem` ways)
1156 (do success <- runPhase_MoveBinary output_fn
1157 if success then return ()
1158 else throwDyn (InstallationError ("cannot move binary to PVM dir")))
1160 -----------------------------------------------------------------------------
1161 -- Making a DLL (only for Win32)
1163 doMkDLL :: DynFlags -> [String] -> [PackageId] -> IO ()
1164 doMkDLL dflags o_files dep_packages = do
1165 let verb = getVerbFlag dflags
1166 let static = opt_Static
1167 let no_hs_main = dopt Opt_NoHsMain dflags
1168 let o_file = outputFile dflags
1169 let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
1171 pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1172 let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1174 let lib_paths = libraryPaths dflags
1175 let lib_path_opts = map ("-L"++) lib_paths
1177 pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1179 -- probably _stub.o files
1180 extra_ld_inputs <- readIORef v_Ld_inputs
1182 -- opts from -optdll-<blah>
1183 let extra_ld_opts = getOpts dflags opt_dll
1185 let pstate = pkgState dflags
1186 rts_id | ExtPackage id <- rtsPackageId pstate = id
1187 | otherwise = panic "staticLink: rts package missing"
1188 base_id | ExtPackage id <- basePackageId pstate = id
1189 | otherwise = panic "staticLink: base package missing"
1190 rts_pkg = getPackageDetails pstate rts_id
1191 base_pkg = getPackageDetails pstate base_id
1193 let extra_os = if static || no_hs_main
1195 else [ head (libraryDirs rts_pkg) ++ "/Main.dll_o",
1196 head (libraryDirs base_pkg) ++ "/PrelMain.dll_o" ]
1198 let (md_c_flags, _) = machdepCCOpts dflags
1199 SysTools.runMkDLL dflags
1200 ([ SysTools.Option verb
1201 , SysTools.Option "-o"
1202 , SysTools.FileOption "" output_fn
1204 ++ map SysTools.Option (
1208 ++ [ "--target=i386-mingw32" ]
1212 ++ pkg_lib_path_opts
1214 ++ (if "--def" `elem` (concatMap words extra_ld_opts)
1216 else [ "--export-all" ])
1219 -- -----------------------------------------------------------------------------
1222 doCpp :: DynFlags -> Bool -> Bool -> FilePath -> FilePath -> IO ()
1223 doCpp dflags raw include_cc_opts input_fn output_fn = do
1224 let hscpp_opts = getOpts dflags opt_P
1225 let cmdline_include_paths = includePaths dflags
1227 pkg_include_dirs <- getPackageIncludePath dflags []
1228 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
1229 (cmdline_include_paths ++ pkg_include_dirs)
1231 let verb = getVerbFlag dflags
1234 | not include_cc_opts = []
1235 | otherwise = (optc ++ md_c_flags)
1237 optc = getOpts dflags opt_c
1238 (md_c_flags, _) = machdepCCOpts dflags
1240 let cpp_prog args | raw = SysTools.runCpp dflags args
1241 | otherwise = SysTools.runCc dflags (SysTools.Option "-E" : args)
1244 [ "-D" ++ HOST_OS ++ "_BUILD_OS=1",
1245 "-D" ++ HOST_ARCH ++ "_BUILD_ARCH=1",
1246 "-D" ++ TARGET_OS ++ "_HOST_OS=1",
1247 "-D" ++ TARGET_ARCH ++ "_HOST_ARCH=1" ]
1248 -- remember, in code we *compile*, the HOST is the same our TARGET,
1249 -- and BUILD is the same as our HOST.
1251 cpp_prog ([SysTools.Option verb]
1252 ++ map SysTools.Option include_paths
1253 ++ map SysTools.Option hsSourceCppOpts
1254 ++ map SysTools.Option hscpp_opts
1255 ++ map SysTools.Option cc_opts
1256 ++ map SysTools.Option target_defs
1257 ++ [ SysTools.Option "-x"
1258 , SysTools.Option "c"
1259 , SysTools.Option input_fn
1260 -- We hackily use Option instead of FileOption here, so that the file
1261 -- name is not back-slashed on Windows. cpp is capable of
1262 -- dealing with / in filenames, so it works fine. Furthermore
1263 -- if we put in backslashes, cpp outputs #line directives
1264 -- with *double* backslashes. And that in turn means that
1265 -- our error messages get double backslashes in them.
1266 -- In due course we should arrange that the lexer deals
1267 -- with these \\ escapes properly.
1268 , SysTools.Option "-o"
1269 , SysTools.FileOption "" output_fn
1272 cHaskell1Version = "5" -- i.e., Haskell 98
1274 -- Default CPP defines in Haskell source
1276 [ "-D__HASKELL1__="++cHaskell1Version
1277 , "-D__GLASGOW_HASKELL__="++cProjectVersionInt
1279 , "-D__CONCURRENT_HASKELL__"
1282 -----------------------------------------------------------------------------
1283 -- Reading OPTIONS pragmas
1285 getOptionsFromSource
1286 :: String -- input file
1287 -> IO [String] -- options, if any
1288 getOptionsFromSource file
1289 = do h <- openFile file ReadMode
1290 look h `finally` hClose h
1293 r <- tryJust ioErrors (hGetLine h)
1295 Left e | isEOFError e -> return []
1296 | otherwise -> ioError e
1298 let l = removeSpaces l'
1300 () | null l -> look h
1301 | prefixMatch "#" l -> look h
1302 | prefixMatch "{-# LINE" l -> look h -- -}
1303 | Just opts <- matchOptions l
1304 -> do rest <- look h
1305 return (opts ++ rest)
1306 | otherwise -> return []
1308 -- detect {-# OPTIONS_GHC ... #-}. For the time being, we accept OPTIONS
1309 -- instead of OPTIONS_GHC, but that is deprecated.
1311 | Just s1 <- maybePrefixMatch "{-#" s -- -}
1312 = matchOptions1 (removeSpaces s1)
1317 | Just s2 <- maybePrefixMatch "OPTIONS" s
1319 _ | Just s3 <- maybePrefixMatch "_GHC" s2, not (is_ident (head s3))
1321 | not (is_ident (head s2))
1324 -> Just [] -- OPTIONS_anything is ignored, not treated as start of source
1325 | Just s2 <- maybePrefixMatch "INCLUDE" s, not (is_ident (head s2)),
1326 Just s3 <- maybePrefixMatch "}-#" (reverse s2)
1327 = Just ["-#include", removeSpaces (reverse s3)]
1328 | otherwise = Nothing
1330 | Just s3 <- maybePrefixMatch "}-#" (reverse s) = Just (words (reverse s3))
1331 | otherwise = Nothing
1334 -- -----------------------------------------------------------------------------
1337 hscNextPhase :: DynFlags -> HscSource -> HscTarget -> Phase
1338 hscNextPhase dflags HsBootFile hsc_lang = StopLn
1339 hscNextPhase dflags other hsc_lang =
1342 HscAsm | dopt Opt_SplitObjs dflags -> SplitMangle
1344 HscNothing -> StopLn
1345 HscInterpreted -> StopLn
1349 hscMaybeAdjustTarget :: DynFlags -> Phase -> HscSource -> HscTarget -> HscTarget
1350 hscMaybeAdjustTarget dflags stop HsBootFile current_hsc_lang
1351 = HscNothing -- No output (other than Foo.hi-boot) for hs-boot files
1352 hscMaybeAdjustTarget dflags stop other current_hsc_lang
1355 keep_hc = dopt Opt_KeepHcFiles dflags
1357 -- don't change the lang if we're interpreting
1358 | current_hsc_lang == HscInterpreted = current_hsc_lang
1360 -- force -fvia-C if we are being asked for a .hc file
1361 | HCc <- stop = HscC
1363 -- otherwise, stick to the plan
1364 | otherwise = current_hsc_lang
1366 GLOBAL_VAR(v_Split_info, ("",0), (String,Int))
1367 -- The split prefix and number of files