1 {-# OPTIONS -fno-cse #-}
2 {-# LANGUAGE NamedFieldPuns #-}
3 -- -fno-cse is needed for GLOBAL_VAR's to behave properly
5 -----------------------------------------------------------------------------
9 -- (c) The University of Glasgow 2005
11 -----------------------------------------------------------------------------
13 module DriverPipeline (
14 -- Run a series of compilation steps in a pipeline, for a
15 -- collection of source files.
18 -- Interfaces for the batch-mode driver
21 -- Interfaces for the compilation manager (interpreted/batch-mode)
28 #include "HsVersions.h"
39 import UniqFM ( eltsUFM )
42 import StaticFlags ( v_Ld_inputs, opt_PIC, opt_Static, WayName(..) )
46 import StringBuffer ( hGetStringBuffer )
47 import BasicTypes ( SuccessFlag(..) )
48 import Maybes ( expectJust )
49 import ParserCoreUtils ( getCoreModuleName )
52 import LlvmCodeGen ( llvmFixupAsm )
57 import Data.IORef ( readIORef )
58 -- import GHC.Exts ( Int(..) )
59 import System.Directory
60 import System.FilePath
63 import Data.List ( isSuffixOf )
65 import System.Environment
67 -- ---------------------------------------------------------------------------
70 -- | Just preprocess a file, put the result in a temp. file (used by the
71 -- compilation manager during the summary phase).
73 -- We return the augmented DynFlags, because they contain the result
74 -- of slurping in the OPTIONS pragmas
77 -> (FilePath, Maybe Phase) -- ^ filename and starting phase
78 -> IO (DynFlags, FilePath)
79 preprocess hsc_env (filename, mb_phase) =
80 ASSERT2(isJust mb_phase || isHaskellSrcFilename filename, text filename)
81 runPipeline anyHsc hsc_env (filename, mb_phase)
82 Nothing Temporary Nothing{-no ModLocation-} Nothing{-no stub-}
84 -- ---------------------------------------------------------------------------
88 -- Compile a single module, under the control of the compilation manager.
90 -- This is the interface between the compilation manager and the
91 -- compiler proper (hsc), where we deal with tedious details like
92 -- reading the OPTIONS pragma from the source file, converting the
93 -- C or assembly that GHC produces into an object file, and compiling
96 -- NB. No old interface can also mean that the source has changed.
99 -> ModSummary -- ^ summary for module being compiled
100 -> Int -- ^ module N ...
102 -> Maybe ModIface -- ^ old interface, if we have one
103 -> Maybe Linkable -- ^ old linkable, if we have one
104 -> IO HomeModInfo -- ^ the complete HomeModInfo, if successful
106 compile = compile' (hscCompileNothing, hscCompileInteractive, hscCompileBatch)
109 (Compiler (HscStatus, ModIface, ModDetails),
110 Compiler (InteractiveStatus, ModIface, ModDetails),
111 Compiler (HscStatus, ModIface, ModDetails))
113 -> ModSummary -- ^ summary for module being compiled
114 -> Int -- ^ module N ...
116 -> Maybe ModIface -- ^ old interface, if we have one
117 -> Maybe Linkable -- ^ old linkable, if we have one
118 -> IO HomeModInfo -- ^ the complete HomeModInfo, if successful
120 compile' (nothingCompiler, interactiveCompiler, batchCompiler)
121 hsc_env0 summary mod_index nmods mb_old_iface maybe_old_linkable
123 let dflags0 = ms_hspp_opts summary
124 this_mod = ms_mod summary
125 src_flavour = ms_hsc_src summary
126 location = ms_location summary
127 input_fn = expectJust "compile:hs" (ml_hs_file location)
128 input_fnpp = ms_hspp_file summary
130 debugTraceMsg dflags0 2 (text "compile: input file" <+> text input_fnpp)
132 let basename = dropExtension input_fn
134 -- We add the directory in which the .hs files resides) to the import path.
135 -- This is needed when we try to compile the .hc file later, if it
136 -- imports a _stub.h file that we created here.
137 let current_dir = case takeDirectory basename of
138 "" -> "." -- XXX Hack
140 old_paths = includePaths dflags0
141 dflags = dflags0 { includePaths = current_dir : old_paths }
142 hsc_env = hsc_env0 {hsc_dflags = dflags}
144 -- Figure out what lang we're generating
145 let hsc_lang = hscTarget dflags
146 -- ... and what the next phase should be
147 let next_phase = hscNextPhase dflags src_flavour hsc_lang
148 -- ... and what file to generate the output into
149 output_fn <- getOutputFilename next_phase
150 Temporary basename dflags next_phase (Just location)
152 let dflags' = dflags { hscTarget = hsc_lang,
153 hscOutName = output_fn,
154 extCoreName = basename ++ ".hcr" }
155 let hsc_env' = hsc_env { hsc_dflags = dflags' }
157 -- -fforce-recomp should also work with --make
158 let force_recomp = dopt Opt_ForceRecomp dflags
159 source_unchanged = isJust maybe_old_linkable && not force_recomp
160 object_filename = ml_obj_file location
162 let handleBatch HscNoRecomp
163 = ASSERT (isJust maybe_old_linkable)
164 return maybe_old_linkable
166 handleBatch (HscRecomp hasStub _)
167 | isHsBoot src_flavour
168 = do when (isObjectTarget hsc_lang) $ -- interpreted reaches here too
169 liftIO $ SysTools.touch dflags' "Touching object file"
171 return maybe_old_linkable
174 = do (hs_unlinked, unlinked_time) <-
177 return ([], ms_hs_date summary)
178 -- We're in --make mode: finish the compilation pipeline.
180 maybe_stub_o <- case hasStub of
181 Nothing -> return Nothing
183 stub_o <- compileStub hsc_env' stub_c
185 _ <- runPipeline StopLn hsc_env' (output_fn,Nothing)
190 -- The object filename comes from the ModLocation
191 o_time <- getModificationTime object_filename
192 return ([DotO object_filename], o_time)
194 let linkable = LM unlinked_time this_mod hs_unlinked
195 return (Just linkable)
197 handleInterpreted HscNoRecomp
198 = ASSERT (isJust maybe_old_linkable)
199 return maybe_old_linkable
200 handleInterpreted (HscRecomp _hasStub Nothing)
201 = ASSERT (isHsBoot src_flavour)
202 return maybe_old_linkable
203 handleInterpreted (HscRecomp hasStub (Just (comp_bc, modBreaks)))
204 = do stub_o <- case hasStub of
207 stub_o <- compileStub hsc_env' stub_c
210 let hs_unlinked = [BCOs comp_bc modBreaks]
211 unlinked_time = ms_hs_date summary
212 -- Why do we use the timestamp of the source file here,
213 -- rather than the current time? This works better in
214 -- the case where the local clock is out of sync
215 -- with the filesystem's clock. It's just as accurate:
216 -- if the source is modified, then the linkable will
218 let linkable = LM unlinked_time this_mod
219 (hs_unlinked ++ stub_o)
220 return (Just linkable)
222 let -- runCompiler :: Compiler result -> (result -> Maybe Linkable)
224 runCompiler compiler handle
225 = do (result, iface, details)
226 <- compiler hsc_env' summary source_unchanged mb_old_iface
227 (Just (mod_index, nmods))
228 linkable <- handle result
229 return (HomeModInfo{ hm_details = details,
231 hm_linkable = linkable })
234 HscInterpreted -> runCompiler interactiveCompiler handleInterpreted
235 HscNothing -> runCompiler nothingCompiler handleBatch
236 _other -> runCompiler batchCompiler handleBatch
238 -----------------------------------------------------------------------------
239 -- stub .h and .c files (for foreign export support)
241 -- The _stub.c file is derived from the haskell source file, possibly taking
242 -- into account the -stubdir option.
244 -- The object file created by compiling the _stub.c file is put into a
245 -- temporary file, which will be later combined with the main .o file
246 -- (see the MergeStubs phase).
248 compileStub :: HscEnv -> FilePath -> IO FilePath
249 compileStub hsc_env stub_c = do
250 (_, stub_o) <- runPipeline StopLn hsc_env (stub_c,Nothing) Nothing
251 Temporary Nothing{-no ModLocation-} Nothing
255 -- ---------------------------------------------------------------------------
258 link :: GhcLink -- interactive or batch
259 -> DynFlags -- dynamic flags
260 -> Bool -- attempt linking in batch mode?
261 -> HomePackageTable -- what to link
264 -- For the moment, in the batch linker, we don't bother to tell doLink
265 -- which packages to link -- it just tries all that are available.
266 -- batch_attempt_linking should only be *looked at* in batch mode. It
267 -- should only be True if the upsweep was successful and someone
268 -- exports main, i.e., we have good reason to believe that linking
272 link LinkInMemory _ _ _
273 = do -- Not Linking...(demand linker will do the job)
280 link LinkBinary dflags batch_attempt_linking hpt
281 = link' dflags batch_attempt_linking hpt
283 link LinkDynLib dflags batch_attempt_linking hpt
284 = link' dflags batch_attempt_linking hpt
287 -- warning suppression
288 link other _ _ _ = panicBadLink other
291 panicBadLink :: GhcLink -> a
292 panicBadLink other = panic ("link: GHC not built to link this way: " ++
295 link' :: DynFlags -- dynamic flags
296 -> Bool -- attempt linking in batch mode?
297 -> HomePackageTable -- what to link
300 link' dflags batch_attempt_linking hpt
301 | batch_attempt_linking
304 home_mod_infos = eltsUFM hpt
306 -- the packages we depend on
307 pkg_deps = concatMap (dep_pkgs . mi_deps . hm_iface) home_mod_infos
309 -- the linkables to link
310 linkables = map (expectJust "link".hm_linkable) home_mod_infos
312 debugTraceMsg dflags 3 (text "link: linkables are ..." $$ vcat (map ppr linkables))
314 -- check for the -no-link flag
315 if isNoLink (ghcLink dflags)
316 then do debugTraceMsg dflags 3 (text "link(batch): linking omitted (-c flag given).")
320 let getOfiles (LM _ _ us) = map nameOfObject (filter isObject us)
321 obj_files = concatMap getOfiles linkables
323 exe_file = exeFileName dflags
325 linking_needed <- linkingNeeded dflags linkables pkg_deps
327 if not (dopt Opt_ForceRecomp dflags) && not linking_needed
328 then do debugTraceMsg dflags 2 (text exe_file <+> ptext (sLit "is up to date, linking not required."))
332 debugTraceMsg dflags 1 (ptext (sLit "Linking") <+> text exe_file
335 -- Don't showPass in Batch mode; doLink will do that for us.
336 let link = case ghcLink dflags of
337 LinkBinary -> linkBinary
338 LinkDynLib -> linkDynLib
339 other -> panicBadLink other
340 link dflags obj_files pkg_deps
342 debugTraceMsg dflags 3 (text "link: done")
344 -- linkBinary only returns if it succeeds
348 = do debugTraceMsg dflags 3 (text "link(batch): upsweep (partially) failed OR" $$
349 text " Main.main not exported; not linking.")
353 linkingNeeded :: DynFlags -> [Linkable] -> [PackageId] -> IO Bool
354 linkingNeeded dflags linkables pkg_deps = do
355 -- if the modification time on the executable is later than the
356 -- modification times on all of the objects and libraries, then omit
357 -- linking (unless the -fforce-recomp flag was given).
358 let exe_file = exeFileName dflags
359 e_exe_time <- tryIO $ getModificationTime exe_file
361 Left _ -> return True
363 -- first check object files and extra_ld_inputs
364 extra_ld_inputs <- readIORef v_Ld_inputs
365 e_extra_times <- mapM (tryIO . getModificationTime) extra_ld_inputs
366 let (errs,extra_times) = splitEithers e_extra_times
367 let obj_times = map linkableTime linkables ++ extra_times
368 if not (null errs) || any (t <) obj_times
372 -- next, check libraries. XXX this only checks Haskell libraries,
373 -- not extra_libraries or -l things from the command line.
374 let pkg_map = pkgIdMap (pkgState dflags)
375 pkg_hslibs = [ (libraryDirs c, lib)
376 | Just c <- map (lookupPackage pkg_map) pkg_deps,
377 lib <- packageHsLibs dflags c ]
379 pkg_libfiles <- mapM (uncurry findHSLib) pkg_hslibs
380 if any isNothing pkg_libfiles then return True else do
381 e_lib_times <- mapM (tryIO . getModificationTime)
382 (catMaybes pkg_libfiles)
383 let (lib_errs,lib_times) = splitEithers e_lib_times
384 if not (null lib_errs) || any (t <) lib_times
388 findHSLib :: [String] -> String -> IO (Maybe FilePath)
389 findHSLib dirs lib = do
390 let batch_lib_file = "lib" ++ lib <.> "a"
391 found <- filterM doesFileExist (map (</> batch_lib_file) dirs)
394 (x:_) -> return (Just x)
396 -- -----------------------------------------------------------------------------
397 -- Compile files in one-shot mode.
399 oneShot :: HscEnv -> Phase -> [(String, Maybe Phase)] -> IO ()
400 oneShot hsc_env stop_phase srcs = do
401 o_files <- mapM (compileFile hsc_env stop_phase) srcs
402 doLink (hsc_dflags hsc_env) stop_phase o_files
404 compileFile :: HscEnv -> Phase -> (FilePath, Maybe Phase) -> IO FilePath
405 compileFile hsc_env stop_phase (src, mb_phase) = do
406 exists <- doesFileExist src
408 ghcError (CmdLineError ("does not exist: " ++ src))
411 dflags = hsc_dflags hsc_env
412 split = dopt Opt_SplitObjs dflags
413 mb_o_file = outputFile dflags
414 ghc_link = ghcLink dflags -- Set by -c or -no-link
416 -- When linking, the -o argument refers to the linker's output.
417 -- otherwise, we use it as the name for the pipeline's output.
419 | StopLn <- stop_phase, not (isNoLink ghc_link) = Persistent
420 -- -o foo applies to linker
421 | Just o_file <- mb_o_file = SpecificFile o_file
422 -- -o foo applies to the file we are compiling now
423 | otherwise = Persistent
425 stop_phase' = case stop_phase of
426 As | split -> SplitAs
429 ( _, out_file) <- runPipeline stop_phase' hsc_env
430 (src, mb_phase) Nothing output
431 Nothing{-no ModLocation-} Nothing
435 doLink :: DynFlags -> Phase -> [FilePath] -> IO ()
436 doLink dflags stop_phase o_files
437 | not (isStopLn stop_phase)
438 = return () -- We stopped before the linking phase
441 = case ghcLink dflags of
443 LinkBinary -> linkBinary dflags o_files []
444 LinkDynLib -> linkDynLib dflags o_files []
445 other -> panicBadLink other
448 -- ---------------------------------------------------------------------------
452 -- ^ Output should be to a temporary file: we're going to
453 -- run more compilation steps on this output later.
455 -- ^ We want a persistent file, i.e. a file in the current directory
456 -- derived from the input filename, but with the appropriate extension.
457 -- eg. in "ghc -c Foo.hs" the output goes into ./Foo.o.
458 | SpecificFile FilePath
459 -- ^ The output must go into the specified file.
461 -- | Run a compilation pipeline, consisting of multiple phases.
463 -- This is the interface to the compilation pipeline, which runs
464 -- a series of compilation steps on a single source file, specifying
465 -- at which stage to stop.
467 -- The DynFlags can be modified by phases in the pipeline (eg. by
468 -- OPTIONS_GHC pragmas), and the changes affect later phases in the
471 :: Phase -- ^ When to stop
472 -> HscEnv -- ^ Compilation environment
473 -> (FilePath,Maybe Phase) -- ^ Input filename (and maybe -x suffix)
474 -> Maybe FilePath -- ^ original basename (if different from ^^^)
475 -> PipelineOutput -- ^ Output filename
476 -> Maybe ModLocation -- ^ A ModLocation, if this is a Haskell module
477 -> Maybe FilePath -- ^ stub object, if we have one
478 -> IO (DynFlags, FilePath) -- ^ (final flags, output filename)
480 runPipeline stop_phase hsc_env0 (input_fn, mb_phase)
481 mb_basename output maybe_loc maybe_stub_o
483 let dflags0 = hsc_dflags hsc_env0
484 (input_basename, suffix) = splitExtension input_fn
485 suffix' = drop 1 suffix -- strip off the .
486 basename | Just b <- mb_basename = b
487 | otherwise = input_basename
489 -- Decide where dump files should go based on the pipeline output
490 dflags = dflags0 { dumpPrefix = Just (basename ++ ".") }
491 hsc_env = hsc_env0 {hsc_dflags = dflags}
493 -- If we were given a -x flag, then use that phase to start from
494 start_phase = fromMaybe (startPhase suffix') mb_phase
496 -- We want to catch cases of "you can't get there from here" before
497 -- we start the pipeline, because otherwise it will just run off the
500 -- There is a partial ordering on phases, where A < B iff A occurs
501 -- before B in a normal compilation pipeline.
503 when (not (start_phase `happensBefore` stop_phase)) $
505 ("cannot compile this file to desired target: "
508 -- this is a function which will be used to calculate output file names
509 -- as we go along (we partially apply it to some of its inputs here)
510 let get_output_fn = getOutputFilename stop_phase output basename
512 -- Execute the pipeline...
513 let env = PipeEnv{ stop_phase,
514 src_basename = basename,
515 src_suffix = suffix',
516 output_spec = output }
518 state = PipeState{ hsc_env, maybe_loc, maybe_stub_o = maybe_stub_o }
520 (state', output_fn) <- unP (pipeLoop start_phase input_fn) env state
522 let PipeState{ hsc_env=hsc_env', maybe_loc } = state'
523 dflags' = hsc_dflags hsc_env'
525 -- Sometimes, a compilation phase doesn't actually generate any output
526 -- (eg. the CPP phase when -fcpp is not turned on). If we end on this
527 -- stage, but we wanted to keep the output, then we have to explicitly
528 -- copy the file, remembering to prepend a {-# LINE #-} pragma so that
529 -- further compilation stages can tell what the original filename was.
532 return (dflags', output_fn)
534 do final_fn <- get_output_fn dflags' stop_phase maybe_loc
535 when (final_fn /= output_fn) $ do
536 let msg = ("Copying `" ++ output_fn ++"' to `" ++ final_fn ++ "'")
537 line_prag = Just ("{-# LINE 1 \"" ++ input_fn ++ "\" #-}\n")
538 copyWithHeader dflags msg line_prag output_fn final_fn
539 return (dflags', final_fn)
541 -- -----------------------------------------------------------------------------
542 -- The pipeline uses a monad to carry around various bits of information
544 -- PipeEnv: invariant information passed down
545 data PipeEnv = PipeEnv {
546 stop_phase :: Phase, -- ^ Stop just before this phase
547 src_basename :: String, -- ^ basename of original input source
548 src_suffix :: String, -- ^ its extension
549 output_spec :: PipelineOutput -- ^ says where to put the pipeline output
552 -- PipeState: information that might change during a pipeline run
553 data PipeState = PipeState {
555 -- ^ only the DynFlags change in the HscEnv. The DynFlags change
556 -- at various points, for example when we read the OPTIONS_GHC
557 -- pragmas in the Cpp phase.
558 maybe_loc :: Maybe ModLocation,
559 -- ^ the ModLocation. This is discovered during compilation,
560 -- in the Hsc phase where we read the module header.
561 maybe_stub_o :: Maybe FilePath
562 -- ^ the stub object. This is set by the Hsc phase if a stub
563 -- object was created. The stub object will be joined with
564 -- the main compilation object using "ld -r" at the end.
567 getPipeEnv :: CompPipeline PipeEnv
568 getPipeEnv = P $ \env state -> return (state, env)
570 getPipeState :: CompPipeline PipeState
571 getPipeState = P $ \_env state -> return (state, state)
573 getDynFlags :: CompPipeline DynFlags
574 getDynFlags = P $ \_env state -> return (state, hsc_dflags (hsc_env state))
576 setDynFlags :: DynFlags -> CompPipeline ()
577 setDynFlags dflags = P $ \_env state ->
578 return (state{hsc_env= (hsc_env state){ hsc_dflags = dflags }}, ())
580 setModLocation :: ModLocation -> CompPipeline ()
581 setModLocation loc = P $ \_env state ->
582 return (state{ maybe_loc = Just loc }, ())
584 setStubO :: FilePath -> CompPipeline ()
585 setStubO stub_o = P $ \_env state ->
586 return (state{ maybe_stub_o = Just stub_o }, ())
588 newtype CompPipeline a = P { unP :: PipeEnv -> PipeState -> IO (PipeState, a) }
590 instance Monad CompPipeline where
591 return a = P $ \_env state -> return (state, a)
592 P m >>= k = P $ \env state -> do (state',a) <- m env state
595 io :: IO a -> CompPipeline a
596 io m = P $ \_env state -> do a <- m; return (state, a)
598 phaseOutputFilename :: Phase{-next phase-} -> CompPipeline FilePath
599 phaseOutputFilename next_phase = do
600 PipeEnv{stop_phase, src_basename, output_spec} <- getPipeEnv
601 PipeState{maybe_loc, hsc_env} <- getPipeState
602 let dflags = hsc_dflags hsc_env
603 io $ getOutputFilename stop_phase output_spec
604 src_basename dflags next_phase maybe_loc
606 -- ---------------------------------------------------------------------------
607 -- outer pipeline loop
609 -- | pipeLoop runs phases until we reach the stop phase
610 pipeLoop :: Phase -> FilePath -> CompPipeline FilePath
611 pipeLoop phase input_fn = do
612 PipeEnv{stop_phase} <- getPipeEnv
613 PipeState{hsc_env} <- getPipeState
615 _ | phase `eqPhase` stop_phase -- All done
618 | not (phase `happensBefore` stop_phase)
619 -- Something has gone wrong. We'll try to cover all the cases when
620 -- this could happen, so if we reach here it is a panic.
621 -- eg. it might happen if the -C flag is used on a source file that
622 -- has {-# OPTIONS -fasm #-}.
623 -> panic ("pipeLoop: at phase " ++ show phase ++
624 " but I wanted to stop at phase " ++ show stop_phase)
627 -> do io $ debugTraceMsg (hsc_dflags hsc_env) 4
628 (ptext (sLit "Running phase") <+> ppr phase)
629 dflags <- getDynFlags
630 (next_phase, output_fn) <- runPhase phase input_fn dflags
631 pipeLoop next_phase output_fn
633 -- -----------------------------------------------------------------------------
634 -- In each phase, we need to know into what filename to generate the
635 -- output. All the logic about which filenames we generate output
636 -- into is embodied in the following function.
639 :: Phase -> PipelineOutput -> String
640 -> DynFlags -> Phase{-next phase-} -> Maybe ModLocation -> IO FilePath
641 getOutputFilename stop_phase output basename
644 func dflags next_phase maybe_location
645 | is_last_phase, Persistent <- output = persistent_fn
646 | is_last_phase, SpecificFile f <- output = return f
647 | keep_this_output = persistent_fn
648 | otherwise = newTempName dflags suffix
651 odir = objectDir dflags
652 osuf = objectSuf dflags
653 keep_hc = dopt Opt_KeepHcFiles dflags
654 keep_s = dopt Opt_KeepSFiles dflags
655 keep_bc = dopt Opt_KeepLlvmFiles dflags
657 myPhaseInputExt HCc = hcsuf
658 myPhaseInputExt MergeStub = osuf
659 myPhaseInputExt StopLn = osuf
660 myPhaseInputExt other = phaseInputExt other
662 is_last_phase = next_phase `eqPhase` stop_phase
664 -- sometimes, we keep output from intermediate stages
668 LlvmOpt | keep_bc -> True
669 HCc | keep_hc -> True
672 suffix = myPhaseInputExt next_phase
674 -- persistent object files get put in odir
676 | StopLn <- next_phase = return odir_persistent
677 | otherwise = return persistent
679 persistent = basename <.> suffix
682 | Just loc <- maybe_location = ml_obj_file loc
683 | Just d <- odir = d </> persistent
684 | otherwise = persistent
687 -- -----------------------------------------------------------------------------
688 -- | Each phase in the pipeline returns the next phase to execute, and the
689 -- name of the file in which the output was placed.
691 -- We must do things dynamically this way, because we often don't know
692 -- what the rest of the phases will be until part-way through the
693 -- compilation: for example, an {-# OPTIONS -fasm #-} at the beginning
694 -- of a source file can change the latter stages of the pipeline from
695 -- taking the via-C route to using the native code generator.
697 runPhase :: Phase -- ^ Run this phase
698 -> FilePath -- ^ name of the input file
699 -> DynFlags -- ^ for convenience, we pass the current dflags in
700 -> CompPipeline (Phase, -- next phase to run
701 FilePath) -- output filename
703 -- Invariant: the output filename always contains the output
704 -- Interesting case: Hsc when there is no recompilation to do
705 -- Then the output filename is still a .o file
708 -------------------------------------------------------------------------------
711 runPhase (Unlit sf) input_fn dflags
713 output_fn <- phaseOutputFilename (Cpp sf)
715 let unlit_flags = getOpts dflags opt_L
716 flags = map SysTools.Option unlit_flags ++
717 [ -- The -h option passes the file name for unlit to
718 -- put in a #line directive
720 -- cpp interprets \b etc as escape sequences,
721 -- so we use / for filenames in pragmas
722 , SysTools.Option $ reslash Forwards $ normalise input_fn
723 , SysTools.FileOption "" input_fn
724 , SysTools.FileOption "" output_fn
727 io $ SysTools.runUnlit dflags flags
729 return (Cpp sf, output_fn)
731 -------------------------------------------------------------------------------
732 -- Cpp phase : (a) gets OPTIONS out of file
733 -- (b) runs cpp if necessary
735 runPhase (Cpp sf) input_fn dflags0
737 src_opts <- io $ getOptionsFromFile dflags0 input_fn
738 (dflags1, unhandled_flags, warns)
739 <- io $ parseDynamicNoPackageFlags dflags0 src_opts
741 io $ checkProcessArgsResult unhandled_flags
743 if not (xopt Opt_Cpp dflags1) then do
744 -- we have to be careful to emit warnings only once.
745 unless (dopt Opt_Pp dflags1) $ io $ handleFlagWarnings dflags1 warns
747 -- no need to preprocess CPP, just pass input file along
748 -- to the next phase of the pipeline.
749 return (HsPp sf, input_fn)
751 output_fn <- phaseOutputFilename (HsPp sf)
752 io $ doCpp dflags1 True{-raw-} False{-no CC opts-} input_fn output_fn
753 -- re-read the pragmas now that we've preprocessed the file
755 src_opts <- io $ getOptionsFromFile dflags0 output_fn
756 (dflags2, unhandled_flags, warns)
757 <- io $ parseDynamicNoPackageFlags dflags0 src_opts
758 unless (dopt Opt_Pp dflags2) $ io $ handleFlagWarnings dflags2 warns
759 -- the HsPp pass below will emit warnings
760 io $ checkProcessArgsResult unhandled_flags
764 return (HsPp sf, output_fn)
766 -------------------------------------------------------------------------------
769 runPhase (HsPp sf) input_fn dflags
771 if not (dopt Opt_Pp dflags) then
772 -- no need to preprocess, just pass input file along
773 -- to the next phase of the pipeline.
774 return (Hsc sf, input_fn)
776 let hspp_opts = getOpts dflags opt_F
777 PipeEnv{src_basename, src_suffix} <- getPipeEnv
778 let orig_fn = src_basename <.> src_suffix
779 output_fn <- phaseOutputFilename (Hsc sf)
780 io $ SysTools.runPp dflags
781 ( [ SysTools.Option orig_fn
782 , SysTools.Option input_fn
783 , SysTools.FileOption "" output_fn
785 map SysTools.Option hspp_opts
788 -- re-read pragmas now that we've parsed the file (see #3674)
789 src_opts <- io $ getOptionsFromFile dflags output_fn
790 (dflags1, unhandled_flags, warns)
791 <- io $ parseDynamicNoPackageFlags dflags src_opts
793 io $ handleFlagWarnings dflags1 warns
794 io $ checkProcessArgsResult unhandled_flags
796 return (Hsc sf, output_fn)
798 -----------------------------------------------------------------------------
801 -- Compilation of a single module, in "legacy" mode (_not_ under
802 -- the direction of the compilation manager).
803 runPhase (Hsc src_flavour) input_fn dflags0
804 = do -- normal Hsc mode, not mkdependHS
806 PipeEnv{ stop_phase=stop,
807 src_basename=basename,
808 src_suffix=suff } <- getPipeEnv
810 -- we add the current directory (i.e. the directory in which
811 -- the .hs files resides) to the include path, since this is
812 -- what gcc does, and it's probably what you want.
813 let current_dir = case takeDirectory basename of
814 "" -> "." -- XXX Hack
817 paths = includePaths dflags0
818 dflags = dflags0 { includePaths = current_dir : paths }
822 -- gather the imports and module name
823 (hspp_buf,mod_name,imps,src_imps) <- io $
825 ExtCoreFile -> do -- no explicit imports in ExtCore input.
826 m <- getCoreModuleName input_fn
827 return (Nothing, mkModuleName m, [], [])
830 buf <- hGetStringBuffer input_fn
831 (src_imps,imps,L _ mod_name) <- getImports dflags buf input_fn (basename <.> suff)
832 return (Just buf, mod_name, imps, src_imps)
834 -- Build a ModLocation to pass to hscMain.
835 -- The source filename is rather irrelevant by now, but it's used
836 -- by hscMain for messages. hscMain also needs
837 -- the .hi and .o filenames, and this is as good a way
838 -- as any to generate them, and better than most. (e.g. takes
839 -- into accout the -osuf flags)
840 location1 <- io $ mkHomeModLocation2 dflags mod_name basename suff
842 -- Boot-ify it if necessary
843 let location2 | isHsBoot src_flavour = addBootSuffixLocn location1
844 | otherwise = location1
847 -- Take -ohi into account if present
848 -- This can't be done in mkHomeModuleLocation because
849 -- it only applies to the module being compiles
850 let ohi = outputHi dflags
851 location3 | Just fn <- ohi = location2{ ml_hi_file = fn }
852 | otherwise = location2
854 -- Take -o into account if present
855 -- Very like -ohi, but we must *only* do this if we aren't linking
856 -- (If we're linking then the -o applies to the linked thing, not to
857 -- the object file for one module.)
858 -- Note the nasty duplication with the same computation in compileFile above
859 let expl_o_file = outputFile dflags
860 location4 | Just ofile <- expl_o_file
861 , isNoLink (ghcLink dflags)
862 = location3 { ml_obj_file = ofile }
863 | otherwise = location3
865 o_file = ml_obj_file location4 -- The real object file
867 setModLocation location4
869 -- Figure out if the source has changed, for recompilation avoidance.
871 -- Setting source_unchanged to True means that M.o seems
872 -- to be up to date wrt M.hs; so no need to recompile unless imports have
873 -- changed (which the compiler itself figures out).
874 -- Setting source_unchanged to False tells the compiler that M.o is out of
875 -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
876 src_timestamp <- io $ getModificationTime (basename <.> suff)
878 let force_recomp = dopt Opt_ForceRecomp dflags
879 hsc_lang = hscTarget dflags
880 source_unchanged <- io $
881 if force_recomp || not (isStopLn stop)
882 -- Set source_unchanged to False unconditionally if
883 -- (a) recompilation checker is off, or
884 -- (b) we aren't going all the way to .o file (e.g. ghc -S)
886 -- Otherwise look at file modification dates
887 else do o_file_exists <- doesFileExist o_file
889 then return False -- Need to recompile
890 else do t2 <- getModificationTime o_file
891 if t2 > src_timestamp
896 let next_phase = hscNextPhase dflags src_flavour hsc_lang
897 output_fn <- phaseOutputFilename next_phase
899 let dflags' = dflags { hscTarget = hsc_lang,
900 hscOutName = output_fn,
901 extCoreName = basename ++ ".hcr" }
904 PipeState{hsc_env=hsc_env'} <- getPipeState
906 -- Tell the finder cache about this module
907 mod <- io $ addHomeModuleToFinder hsc_env' mod_name location4
909 -- Make the ModSummary to hand to hscMain
911 mod_summary = ModSummary { ms_mod = mod,
912 ms_hsc_src = src_flavour,
913 ms_hspp_file = input_fn,
914 ms_hspp_opts = dflags,
915 ms_hspp_buf = hspp_buf,
916 ms_location = location4,
917 ms_hs_date = src_timestamp,
918 ms_obj_date = Nothing,
920 ms_srcimps = src_imps }
923 result <- io $ hscCompileOneShot hsc_env'
924 mod_summary source_unchanged
926 Nothing -- No "module i of n" progress info
930 -> do io $ SysTools.touch dflags' "Touching object file" o_file
931 -- The .o file must have a later modification date
932 -- than the source file (else we wouldn't be in HscNoRecomp)
933 -- but we touch it anyway, to keep 'make' happy (we think).
934 return (StopLn, o_file)
935 (HscRecomp hasStub _)
936 -> do case hasStub of
939 do stub_o <- io $ compileStub hsc_env' stub_c
941 -- In the case of hs-boot files, generate a dummy .o-boot
942 -- stamp file for the benefit of Make
943 when (isHsBoot src_flavour) $
944 io $ SysTools.touch dflags' "Touching object file" o_file
945 return (next_phase, output_fn)
947 -----------------------------------------------------------------------------
950 runPhase CmmCpp input_fn dflags
952 output_fn <- phaseOutputFilename Cmm
953 io $ doCpp dflags False{-not raw-} True{-include CC opts-}
955 return (Cmm, output_fn)
957 runPhase Cmm input_fn dflags
959 PipeEnv{src_basename} <- getPipeEnv
960 let hsc_lang = hscTarget dflags
962 let next_phase = hscNextPhase dflags HsSrcFile hsc_lang
964 output_fn <- phaseOutputFilename next_phase
966 let dflags' = dflags { hscTarget = hsc_lang,
967 hscOutName = output_fn,
968 extCoreName = src_basename ++ ".hcr" }
971 PipeState{hsc_env} <- getPipeState
973 io $ hscCompileCmmFile hsc_env input_fn
975 -- XXX: catch errors above and convert them into ghcError? Original
978 --when (not ok) $ ghcError (PhaseFailed "cmm" (ExitFailure 1))
980 return (next_phase, output_fn)
982 -----------------------------------------------------------------------------
985 -- we don't support preprocessing .c files (with -E) now. Doing so introduces
986 -- way too many hacks, and I can't say I've ever used it anyway.
988 runPhase cc_phase input_fn dflags
989 | cc_phase `eqPhase` Cc || cc_phase `eqPhase` Ccpp || cc_phase `eqPhase` HCc
991 let cc_opts = getOpts dflags opt_c
992 hcc = cc_phase `eqPhase` HCc
994 let cmdline_include_paths = includePaths dflags
996 -- HC files have the dependent packages stamped into them
997 pkgs <- if hcc then io $ getHCFilePackages input_fn else return []
999 -- add package include paths even if we're just compiling .c
1000 -- files; this is the Value Add(TM) that using ghc instead of
1002 pkg_include_dirs <- io $ getPackageIncludePath dflags pkgs
1003 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
1004 (cmdline_include_paths ++ pkg_include_dirs)
1006 let md_c_flags = machdepCCOpts dflags
1007 gcc_extra_viac_flags <- io $ getExtraViaCOpts dflags
1008 let pic_c_flags = picCCOpts dflags
1010 let verb = getVerbFlag dflags
1012 -- cc-options are not passed when compiling .hc files. Our
1013 -- hc code doesn't not #include any header files anyway, so these
1014 -- options aren't necessary.
1015 pkg_extra_cc_opts <- io $
1016 if cc_phase `eqPhase` HCc
1018 else getPackageExtraCcOpts dflags pkgs
1020 #ifdef darwin_TARGET_OS
1021 pkg_framework_paths <- io $ getPackageFrameworkPath dflags pkgs
1022 let cmdline_framework_paths = frameworkPaths dflags
1023 let framework_paths = map ("-F"++)
1024 (cmdline_framework_paths ++ pkg_framework_paths)
1027 let split_objs = dopt Opt_SplitObjs dflags
1028 split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
1031 let cc_opt | optLevel dflags >= 2 = "-O2"
1034 -- Decide next phase
1037 output_fn <- phaseOutputFilename next_phase
1041 #if i386_TARGET_ARCH
1042 -- on x86 the floating point regs have greater precision
1043 -- than a double, which leads to unpredictable results.
1044 -- By default, we turn this off with -ffloat-store unless
1045 -- the user specified -fexcess-precision.
1046 (if dopt Opt_ExcessPrecision dflags
1048 else [ "-ffloat-store" ]) ++
1051 -- gcc's -fstrict-aliasing allows two accesses to memory
1052 -- to be considered non-aliasing if they have different types.
1053 -- This interacts badly with the C code we generate, which is
1054 -- very weakly typed, being derived from C--.
1055 ["-fno-strict-aliasing"]
1057 io $ SysTools.runCc dflags (
1058 -- force the C compiler to interpret this file as C when
1059 -- compiling .hc files, by adding the -x c option.
1060 -- Also useful for plain .c files, just in case GHC saw a
1062 [ SysTools.Option "-x", if cc_phase `eqPhase` Ccpp
1063 then SysTools.Option "c++"
1064 else SysTools.Option "c"] ++
1065 [ SysTools.FileOption "" input_fn
1066 , SysTools.Option "-o"
1067 , SysTools.FileOption "" output_fn
1069 ++ map SysTools.Option (
1073 #if defined(mingw32_TARGET_OS)
1074 -- Stub files generated for foreign exports references the runIO_closure
1075 -- and runNonIO_closure symbols, which are defined in the base package.
1076 -- These symbols are imported into the stub.c file via RtsAPI.h, and the
1077 -- way we do the import depends on whether we're currently compiling
1078 -- the base package or not.
1079 ++ (if thisPackage dflags == basePackageId
1080 then [ "-DCOMPILING_BASE_PACKAGE" ]
1084 #ifdef sparc_TARGET_ARCH
1085 -- We only support SparcV9 and better because V8 lacks an atomic CAS
1086 -- instruction. Note that the user can still override this
1087 -- (e.g., -mcpu=ultrasparc) as GCC picks the "best" -mcpu flag
1088 -- regardless of the ordering.
1090 -- This is a temporary hack.
1094 then gcc_extra_viac_flags ++ more_hcc_opts
1096 ++ [ verb, "-S", "-Wimplicit", cc_opt ]
1097 ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
1098 #ifdef darwin_TARGET_OS
1104 ++ pkg_extra_cc_opts
1107 return (next_phase, output_fn)
1109 -- ToDo: postprocess the output from gcc
1111 -----------------------------------------------------------------------------
1114 runPhase SplitMangle input_fn dflags
1115 = do -- tmp_pfx is the prefix used for the split .s files
1117 split_s_prefix <- io $ SysTools.newTempName dflags "split"
1118 let n_files_fn = split_s_prefix
1120 io $ SysTools.runSplit dflags
1121 [ SysTools.FileOption "" input_fn
1122 , SysTools.FileOption "" split_s_prefix
1123 , SysTools.FileOption "" n_files_fn
1126 -- Save the number of split files for future references
1127 s <- io $ readFile n_files_fn
1128 let n_files = read s :: Int
1129 dflags' = dflags { splitInfo = Just (split_s_prefix, n_files) }
1133 -- Remember to delete all these files
1134 io $ addFilesToClean dflags' [ split_s_prefix ++ "__" ++ show n ++ ".s"
1135 | n <- [1..n_files]]
1137 return (SplitAs, "**splitmangle**")
1138 -- we don't use the filename
1140 -----------------------------------------------------------------------------
1143 runPhase As input_fn dflags
1145 let as_opts = getOpts dflags opt_a
1146 let cmdline_include_paths = includePaths dflags
1148 next_phase <- maybeMergeStub
1149 output_fn <- phaseOutputFilename next_phase
1151 -- we create directories for the object file, because it
1152 -- might be a hierarchical module.
1153 io $ createDirectoryHierarchy (takeDirectory output_fn)
1155 let md_c_flags = machdepCCOpts dflags
1156 io $ SysTools.runAs dflags
1157 (map SysTools.Option as_opts
1158 ++ [ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ]
1159 #ifdef sparc_TARGET_ARCH
1160 -- We only support SparcV9 and better because V8 lacks an atomic CAS
1161 -- instruction so we have to make sure that the assembler accepts the
1162 -- instruction set. Note that the user can still override this
1163 -- (e.g., -mcpu=ultrasparc). GCC picks the "best" -mcpu flag
1164 -- regardless of the ordering.
1166 -- This is a temporary hack.
1167 ++ [ SysTools.Option "-mcpu=v9" ]
1169 ++ [ SysTools.Option "-c"
1170 , SysTools.FileOption "" input_fn
1171 , SysTools.Option "-o"
1172 , SysTools.FileOption "" output_fn
1174 ++ map SysTools.Option md_c_flags)
1176 return (next_phase, output_fn)
1179 runPhase SplitAs _input_fn dflags
1181 -- we'll handle the stub_o file in this phase, so don't MergeStub,
1182 -- just jump straight to StopLn afterwards.
1183 let next_phase = StopLn
1184 output_fn <- phaseOutputFilename next_phase
1186 let base_o = dropExtension output_fn
1187 osuf = objectSuf dflags
1188 split_odir = base_o ++ "_" ++ osuf ++ "_split"
1190 io $ createDirectoryHierarchy split_odir
1192 -- remove M_split/ *.o, because we're going to archive M_split/ *.o
1193 -- later and we don't want to pick up any old objects.
1194 fs <- io $ getDirectoryContents split_odir
1195 io $ mapM_ removeFile $
1196 map (split_odir </>) $ filter (osuf `isSuffixOf`) fs
1198 let as_opts = getOpts dflags opt_a
1200 let (split_s_prefix, n) = case splitInfo dflags of
1201 Nothing -> panic "No split info"
1204 let split_s n = split_s_prefix ++ "__" ++ show n <.> "s"
1205 split_obj n = split_odir </>
1206 takeFileName base_o ++ "__" ++ show n <.> osuf
1208 let md_c_flags = machdepCCOpts dflags
1210 = SysTools.runAs dflags
1211 (map SysTools.Option as_opts ++
1212 #ifdef sparc_TARGET_ARCH
1213 -- We only support SparcV9 and better because V8 lacks an atomic CAS
1214 -- instruction so we have to make sure that the assembler accepts the
1215 -- instruction set. Note that the user can still override this
1216 -- (e.g., -mcpu=ultrasparc). GCC picks the "best" -mcpu flag
1217 -- regardless of the ordering.
1219 -- This is a temporary hack.
1220 [ SysTools.Option "-mcpu=v9" ] ++
1222 [ SysTools.Option "-c"
1223 , SysTools.Option "-o"
1224 , SysTools.FileOption "" (split_obj n)
1225 , SysTools.FileOption "" (split_s n)
1227 ++ map SysTools.Option md_c_flags)
1229 io $ mapM_ assemble_file [1..n]
1231 -- If there's a stub_o file, then we make it the n+1th split object.
1232 PipeState{maybe_stub_o} <- getPipeState
1233 n' <- case maybe_stub_o of
1235 Just stub_o -> do io $ copyFile stub_o (split_obj (n+1))
1238 -- join them into a single .o file
1239 io $ joinObjectFiles dflags (map split_obj [1..n']) output_fn
1241 return (next_phase, output_fn)
1243 -----------------------------------------------------------------------------
1246 runPhase LlvmOpt input_fn dflags
1248 let lo_opts = getOpts dflags opt_lo
1249 let opt_lvl = max 0 (min 2 $ optLevel dflags)
1250 -- don't specify anything if user has specified commands. We do this for
1251 -- opt but not llc since opt is very specifically for optimisation passes
1252 -- only, so if the user is passing us extra options we assume they know
1253 -- what they are doing and don't get in the way.
1254 let optFlag = if null lo_opts
1255 then [SysTools.Option (llvmOpts !! opt_lvl)]
1258 output_fn <- phaseOutputFilename LlvmLlc
1260 io $ SysTools.runLlvmOpt dflags
1261 ([ SysTools.FileOption "" input_fn,
1262 SysTools.Option "-o",
1263 SysTools.FileOption "" output_fn]
1265 ++ map SysTools.Option lo_opts)
1267 return (LlvmLlc, output_fn)
1269 -- we always (unless -optlo specified) run Opt since we rely on it to
1270 -- fix up some pretty big deficiencies in the code we generate
1271 llvmOpts = ["-mem2reg", "-O1", "-O2"]
1274 -----------------------------------------------------------------------------
1277 runPhase LlvmLlc input_fn dflags
1279 let lc_opts = getOpts dflags opt_lc
1280 let opt_lvl = max 0 (min 2 $ optLevel dflags)
1281 #if darwin_TARGET_OS
1282 let nphase = LlvmMangle
1286 let rmodel | opt_PIC = "pic"
1287 | not opt_Static = "dynamic-no-pic"
1288 | otherwise = "static"
1290 output_fn <- phaseOutputFilename nphase
1292 io $ SysTools.runLlvmLlc dflags
1293 ([ SysTools.Option (llvmOpts !! opt_lvl),
1294 SysTools.Option $ "-relocation-model=" ++ rmodel,
1295 SysTools.FileOption "" input_fn,
1296 SysTools.Option "-o", SysTools.FileOption "" output_fn]
1297 ++ map SysTools.Option lc_opts)
1299 return (nphase, output_fn)
1301 #if darwin_TARGET_OS
1302 llvmOpts = ["-O1", "-O2", "-O2"]
1304 llvmOpts = ["-O1", "-O2", "-O3"]
1308 -----------------------------------------------------------------------------
1311 runPhase LlvmMangle input_fn _dflags
1313 output_fn <- phaseOutputFilename As
1314 io $ llvmFixupAsm input_fn output_fn
1315 return (As, output_fn)
1317 -----------------------------------------------------------------------------
1318 -- merge in stub objects
1320 runPhase MergeStub input_fn dflags
1322 PipeState{maybe_stub_o} <- getPipeState
1323 output_fn <- phaseOutputFilename StopLn
1324 case maybe_stub_o of
1326 panic "runPhase(MergeStub): no stub"
1328 io $ joinObjectFiles dflags [input_fn, stub_o] output_fn
1329 return (StopLn, output_fn)
1331 -- warning suppression
1332 runPhase other _input_fn _dflags =
1333 panic ("runPhase: don't know how to run phase " ++ show other)
1335 maybeMergeStub :: CompPipeline Phase
1338 PipeState{maybe_stub_o} <- getPipeState
1339 if isJust maybe_stub_o then return MergeStub else return StopLn
1341 -----------------------------------------------------------------------------
1342 -- MoveBinary sort-of-phase
1343 -- After having produced a binary, move it somewhere else and generate a
1344 -- wrapper script calling the binary. Currently, we need this only in
1345 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
1346 -- central directory.
1347 -- This is called from linkBinary below, after linking. I haven't made it
1348 -- a separate phase to minimise interfering with other modules, and
1349 -- we don't need the generality of a phase (MoveBinary is always
1350 -- done after linking and makes only sense in a parallel setup) -- HWL
1352 runPhase_MoveBinary :: DynFlags -> FilePath -> IO Bool
1353 runPhase_MoveBinary dflags input_fn
1354 | WayPar `elem` (wayNames dflags) && not opt_Static =
1355 panic ("Don't know how to combine PVM wrapper and dynamic wrapper")
1356 | WayPar `elem` (wayNames dflags) = do
1357 let sysMan = pgm_sysman dflags
1358 pvm_root <- getEnv "PVM_ROOT"
1359 pvm_arch <- getEnv "PVM_ARCH"
1361 pvm_executable_base = "=" ++ input_fn
1362 pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
1363 -- nuke old binary; maybe use configur'ed names for cp and rm?
1364 _ <- tryIO (removeFile pvm_executable)
1365 -- move the newly created binary into PVM land
1366 copy dflags "copying PVM executable" input_fn pvm_executable
1367 -- generate a wrapper script for running a parallel prg under PVM
1368 writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
1370 | otherwise = return True
1372 mkExtraCObj :: DynFlags -> [String] -> IO FilePath
1373 mkExtraCObj dflags xs
1374 = do cFile <- newTempName dflags "c"
1375 oFile <- newTempName dflags "o"
1376 writeFile cFile $ unlines xs
1377 let rtsDetails = getPackageDetails (pkgState dflags) rtsPackageId
1378 md_c_flags = machdepCCOpts dflags
1379 SysTools.runCc dflags
1381 FileOption "" cFile,
1383 FileOption "" oFile] ++
1384 map (FileOption "-I") (includeDirs rtsDetails) ++
1385 map Option md_c_flags)
1388 mkRtsOptionsLevelObj :: DynFlags -> IO [FilePath]
1389 mkRtsOptionsLevelObj dflags
1390 = do let mkRtsEnabledObj val
1391 = do fn <- mkExtraCObj dflags
1392 ["#include \"Rts.h\"",
1393 "#include \"RtsOpts.h\"",
1394 "const rtsOptsEnabledEnum rtsOptsEnabled = "
1397 case rtsOptsEnabled dflags of
1398 RtsOptsNone -> mkRtsEnabledObj "rtsOptsNone"
1399 RtsOptsSafeOnly -> return [] -- The default
1400 RtsOptsAll -> mkRtsEnabledObj "rtsOptsAll"
1402 -- generates a Perl skript starting a parallel prg under PVM
1403 mk_pvm_wrapper_script :: String -> String -> String -> String
1404 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
1406 "eval 'exec perl -S $0 ${1+\"$@\"}'",
1407 " if $running_under_some_shell;",
1408 "# =!=!=!=!=!=!=!=!=!=!=!",
1409 "# This script is automatically generated: DO NOT EDIT!!!",
1410 "# Generated by Glasgow Haskell Compiler",
1411 "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
1413 "$pvm_executable = '" ++ pvm_executable ++ "';",
1414 "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
1415 "$SysMan = '" ++ sysMan ++ "';",
1417 {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
1418 "# first, some magical shortcuts to run "commands" on the binary",
1419 "# (which is hidden)",
1420 "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
1421 " local($cmd) = $1;",
1422 " system("$cmd $pvm_executable");",
1423 " exit(0); # all done",
1426 "# Now, run the real binary; process the args first",
1427 "$ENV{'PE'} = $pvm_executable_base;", -- ++ pvm_executable_base,
1429 "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
1430 "@nonPVM_args = ();",
1431 "$in_RTS_args = 0;",
1433 "args: while ($a = shift(@ARGV)) {",
1434 " if ( $a eq '+RTS' ) {",
1435 " $in_RTS_args = 1;",
1436 " } elsif ( $a eq '-RTS' ) {",
1437 " $in_RTS_args = 0;",
1439 " if ( $a eq '-d' && $in_RTS_args ) {",
1441 " } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
1442 " $nprocessors = $1;",
1443 " } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
1444 " $nprocessors = $1;",
1446 " push(@nonPVM_args, $a);",
1450 "local($return_val) = 0;",
1451 "# Start the parallel execution by calling SysMan",
1452 "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
1453 "$return_val = $?;",
1454 "# ToDo: fix race condition moving files and flushing them!!",
1455 "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
1456 "exit($return_val);"
1459 -----------------------------------------------------------------------------
1460 -- Look for the /* GHC_PACKAGES ... */ comment at the top of a .hc file
1462 getHCFilePackages :: FilePath -> IO [PackageId]
1463 getHCFilePackages filename =
1464 Exception.bracket (openFile filename ReadMode) hClose $ \h -> do
1467 '/':'*':' ':'G':'H':'C':'_':'P':'A':'C':'K':'A':'G':'E':'S':rest ->
1468 return (map stringToPackageId (words rest))
1472 -----------------------------------------------------------------------------
1473 -- Static linking, of .o files
1475 -- The list of packages passed to link is the list of packages on
1476 -- which this program depends, as discovered by the compilation
1477 -- manager. It is combined with the list of packages that the user
1478 -- specifies on the command line with -package flags.
1480 -- In one-shot linking mode, we can't discover the package
1481 -- dependencies (because we haven't actually done any compilation or
1482 -- read any interface files), so the user must explicitly specify all
1485 linkBinary :: DynFlags -> [FilePath] -> [PackageId] -> IO ()
1486 linkBinary dflags o_files dep_packages = do
1487 let verb = getVerbFlag dflags
1488 output_fn = exeFileName dflags
1490 -- get the full list of packages to link with, by combining the
1491 -- explicit packages with the auto packages and all of their
1492 -- dependencies, and eliminating duplicates.
1494 pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1495 let pkg_lib_path_opts = concat (map get_pkg_lib_path_opts pkg_lib_paths)
1496 #ifdef elf_OBJ_FORMAT
1497 get_pkg_lib_path_opts l | (dynLibLoader dflags)==SystemDependent && not opt_Static = ["-L" ++ l, "-Wl,-rpath", "-Wl," ++ l]
1498 | otherwise = ["-L" ++ l]
1500 get_pkg_lib_path_opts l = ["-L" ++ l]
1503 let lib_paths = libraryPaths dflags
1504 let lib_path_opts = map ("-L"++) lib_paths
1506 -- The C "main" function is not in the rts but in a separate static
1507 -- library libHSrtsmain.a that sits next to the rts lib files. Assuming
1508 -- we're using a Haskell main function then we need to link it in.
1509 let no_hs_main = dopt Opt_NoHsMain dflags
1510 let main_lib | no_hs_main = []
1511 | otherwise = [ "-lHSrtsmain" ]
1512 rtsEnabledObj <- mkRtsOptionsLevelObj dflags
1513 rtsOptsObj <- case rtsOpts dflags of
1515 do fn <- mkExtraCObj dflags
1516 -- We assume that the Haskell "show" does
1517 -- the right thing here
1518 ["char *ghc_rts_opts = " ++ show opts ++ ";"]
1520 Nothing -> return []
1522 pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1524 #ifdef darwin_TARGET_OS
1525 pkg_framework_paths <- getPackageFrameworkPath dflags dep_packages
1526 let pkg_framework_path_opts = map ("-F"++) pkg_framework_paths
1528 let framework_paths = frameworkPaths dflags
1529 framework_path_opts = map ("-F"++) framework_paths
1531 pkg_frameworks <- getPackageFrameworks dflags dep_packages
1532 let pkg_framework_opts = concat [ ["-framework", fw] | fw <- pkg_frameworks ]
1534 let frameworks = cmdlineFrameworks dflags
1535 framework_opts = concat [ ["-framework", fw] | fw <- reverse frameworks ]
1536 -- reverse because they're added in reverse order from the cmd line
1538 -- probably _stub.o files
1539 extra_ld_inputs <- readIORef v_Ld_inputs
1541 -- opts from -optl-<blah> (including -l<blah> options)
1542 let extra_ld_opts = getOpts dflags opt_l
1544 let ways = wayNames dflags
1546 -- Here are some libs that need to be linked at the *end* of
1547 -- the command line, because they contain symbols that are referred to
1548 -- by the RTS. We can't therefore use the ordinary way opts for these.
1550 debug_opts | WayDebug `elem` ways = [
1551 #if defined(HAVE_LIBBFD)
1558 thread_opts | WayThreaded `elem` ways = [
1559 #if !defined(mingw32_TARGET_OS) && !defined(freebsd_TARGET_OS) && !defined(openbsd_TARGET_OS) && !defined(haiku_TARGET_OS)
1562 #if defined(osf3_TARGET_OS)
1568 rc_objs <- maybeCreateManifest dflags output_fn
1570 let md_c_flags = machdepCCOpts dflags
1571 SysTools.runLink dflags (
1572 [ SysTools.Option verb
1573 , SysTools.Option "-o"
1574 , SysTools.FileOption "" output_fn
1576 ++ map SysTools.Option (
1579 #ifdef mingw32_TARGET_OS
1580 -- Permit the linker to auto link _symbol to _imp_symbol.
1581 -- This lets us link against DLLs without needing an "import library".
1582 ++ ["-Wl,--enable-auto-import"]
1589 #ifdef darwin_TARGET_OS
1590 ++ framework_path_opts
1593 ++ pkg_lib_path_opts
1598 #ifdef darwin_TARGET_OS
1599 ++ pkg_framework_path_opts
1600 ++ pkg_framework_opts
1606 -- parallel only: move binary to another dir -- HWL
1607 success <- runPhase_MoveBinary dflags output_fn
1608 if success then return ()
1609 else ghcError (InstallationError ("cannot move binary"))
1612 exeFileName :: DynFlags -> FilePath
1614 | Just s <- outputFile dflags =
1615 #if defined(mingw32_HOST_OS)
1616 if null (takeExtension s)
1623 #if defined(mingw32_HOST_OS)
1631 -> FilePath -- filename of executable
1632 -> IO [FilePath] -- extra objects to embed, maybe
1633 #ifndef mingw32_TARGET_OS
1634 maybeCreateManifest _ _ = do
1637 maybeCreateManifest dflags exe_filename = do
1638 if not (dopt Opt_GenManifest dflags) then return [] else do
1640 let manifest_filename = exe_filename <.> "manifest"
1642 writeFile manifest_filename $
1643 "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"++
1644 " <assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">\n"++
1645 " <assemblyIdentity version=\"1.0.0.0\"\n"++
1646 " processorArchitecture=\"X86\"\n"++
1647 " name=\"" ++ dropExtension exe_filename ++ "\"\n"++
1648 " type=\"win32\"/>\n\n"++
1649 " <trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v3\">\n"++
1651 " <requestedPrivileges>\n"++
1652 " <requestedExecutionLevel level=\"asInvoker\" uiAccess=\"false\"/>\n"++
1653 " </requestedPrivileges>\n"++
1658 -- Windows will find the manifest file if it is named foo.exe.manifest.
1659 -- However, for extra robustness, and so that we can move the binary around,
1660 -- we can embed the manifest in the binary itself using windres:
1661 if not (dopt Opt_EmbedManifest dflags) then return [] else do
1663 rc_filename <- newTempName dflags "rc"
1664 rc_obj_filename <- newTempName dflags (objectSuf dflags)
1666 writeFile rc_filename $
1667 "1 24 MOVEABLE PURE " ++ show manifest_filename ++ "\n"
1668 -- magic numbers :-)
1669 -- show is a bit hackish above, but we need to escape the
1670 -- backslashes in the path.
1672 let wr_opts = getOpts dflags opt_windres
1673 runWindres dflags $ map SysTools.Option $
1674 ["--input="++rc_filename,
1675 "--output="++rc_obj_filename,
1676 "--output-format=coff"]
1678 -- no FileOptions here: windres doesn't like seeing
1679 -- backslashes, apparently
1681 removeFile manifest_filename
1683 return [rc_obj_filename]
1687 linkDynLib :: DynFlags -> [String] -> [PackageId] -> IO ()
1688 linkDynLib dflags o_files dep_packages = do
1689 let verb = getVerbFlag dflags
1690 let o_file = outputFile dflags
1692 pkgs <- getPreloadPackagesAnd dflags dep_packages
1694 let pkg_lib_paths = collectLibraryPaths pkgs
1695 let pkg_lib_path_opts = concatMap get_pkg_lib_path_opts pkg_lib_paths
1696 #ifdef elf_OBJ_FORMAT
1697 get_pkg_lib_path_opts l | (dynLibLoader dflags)==SystemDependent && not opt_Static = ["-L" ++ l, "-Wl,-rpath", "-Wl," ++ l]
1698 | otherwise = ["-L" ++ l]
1700 get_pkg_lib_path_opts l = ["-L" ++ l]
1703 let lib_paths = libraryPaths dflags
1704 let lib_path_opts = map ("-L"++) lib_paths
1706 -- We don't want to link our dynamic libs against the RTS package,
1707 -- because the RTS lib comes in several flavours and we want to be
1708 -- able to pick the flavour when a binary is linked.
1709 -- On Windows we need to link the RTS import lib as Windows does
1710 -- not allow undefined symbols.
1711 -- The RTS library path is still added to the library search path
1712 -- above in case the RTS is being explicitly linked in (see #3807).
1713 #if !defined(mingw32_HOST_OS)
1714 let pkgs_no_rts = filter ((/= rtsPackageId) . packageConfigId) pkgs
1716 let pkgs_no_rts = pkgs
1718 let pkg_link_opts = collectLinkOpts dflags pkgs_no_rts
1720 -- probably _stub.o files
1721 extra_ld_inputs <- readIORef v_Ld_inputs
1723 let md_c_flags = machdepCCOpts dflags
1724 let extra_ld_opts = getOpts dflags opt_l
1726 rtsEnabledObj <- mkRtsOptionsLevelObj dflags
1728 #if defined(mingw32_HOST_OS)
1729 -----------------------------------------------------------------------------
1731 -----------------------------------------------------------------------------
1732 let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
1734 SysTools.runLink dflags
1735 ([ SysTools.Option verb
1736 , SysTools.Option "-o"
1737 , SysTools.FileOption "" output_fn
1738 , SysTools.Option "-shared"
1740 [ SysTools.FileOption "-Wl,--out-implib=" (output_fn ++ ".a")
1741 | dopt Opt_SharedImplib dflags
1743 ++ map (SysTools.FileOption "") o_files
1744 ++ map SysTools.Option (
1747 -- Permit the linker to auto link _symbol to _imp_symbol
1748 -- This lets us link against DLLs without needing an "import library"
1749 ++ ["-Wl,--enable-auto-import"]
1754 ++ pkg_lib_path_opts
1758 #elif defined(darwin_TARGET_OS)
1759 -----------------------------------------------------------------------------
1760 -- Making a darwin dylib
1761 -----------------------------------------------------------------------------
1762 -- About the options used for Darwin:
1764 -- Apple's way of saying -shared
1765 -- -undefined dynamic_lookup:
1766 -- Without these options, we'd have to specify the correct dependencies
1767 -- for each of the dylibs. Note that we could (and should) do without this
1768 -- for all libraries except the RTS; all we need to do is to pass the
1769 -- correct HSfoo_dyn.dylib files to the link command.
1770 -- This feature requires Mac OS X 10.3 or later; there is a similar feature,
1771 -- -flat_namespace -undefined suppress, which works on earlier versions,
1772 -- but it has other disadvantages.
1774 -- Build the dynamic library as a single "module", i.e. no dynamic binding
1775 -- nonsense when referring to symbols from within the library. The NCG
1776 -- assumes that this option is specified (on i386, at least).
1778 -- Mac OS/X stores the path where a dynamic library is (to be) installed
1779 -- in the library itself. It's called the "install name" of the library.
1780 -- Then any library or executable that links against it before it's
1781 -- installed will search for it in its ultimate install location. By
1782 -- default we set the install name to the absolute path at build time, but
1783 -- it can be overridden by the -dylib-install-name option passed to ghc.
1785 -----------------------------------------------------------------------------
1787 let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
1789 instName <- case dylibInstallName dflags of
1792 pwd <- getCurrentDirectory
1793 return $ pwd `combine` output_fn
1794 SysTools.runLink dflags
1795 ([ SysTools.Option verb
1796 , SysTools.Option "-dynamiclib"
1797 , SysTools.Option "-o"
1798 , SysTools.FileOption "" output_fn
1800 ++ map SysTools.Option (
1803 ++ [ "-undefined", "dynamic_lookup", "-single_module",
1804 #if !defined(x86_64_TARGET_ARCH)
1805 "-Wl,-read_only_relocs,suppress",
1807 "-install_name", instName ]
1811 ++ pkg_lib_path_opts
1816 -----------------------------------------------------------------------------
1818 -----------------------------------------------------------------------------
1820 let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
1821 let buildingRts = thisPackage dflags == rtsPackageId
1822 let bsymbolicFlag = if buildingRts
1823 then -- -Bsymbolic breaks the way we implement
1826 else -- we need symbolic linking to resolve
1827 -- non-PIC intra-package-relocations
1830 SysTools.runLink dflags
1831 ([ SysTools.Option verb
1832 , SysTools.Option "-o"
1833 , SysTools.FileOption "" output_fn
1835 ++ map SysTools.Option (
1840 -- Set the library soname. We use -h rather than -soname as
1841 -- Solaris 10 doesn't support the latter:
1842 ++ [ "-Wl,-h," ++ takeFileName output_fn ]
1846 ++ pkg_lib_path_opts
1851 -- -----------------------------------------------------------------------------
1854 doCpp :: DynFlags -> Bool -> Bool -> FilePath -> FilePath -> IO ()
1855 doCpp dflags raw include_cc_opts input_fn output_fn = do
1856 let hscpp_opts = getOpts dflags opt_P
1857 let cmdline_include_paths = includePaths dflags
1859 pkg_include_dirs <- getPackageIncludePath dflags []
1860 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
1861 (cmdline_include_paths ++ pkg_include_dirs)
1863 let verb = getVerbFlag dflags
1866 | not include_cc_opts = []
1867 | otherwise = (optc ++ md_c_flags)
1869 optc = getOpts dflags opt_c
1870 md_c_flags = machdepCCOpts dflags
1872 let cpp_prog args | raw = SysTools.runCpp dflags args
1873 | otherwise = SysTools.runCc dflags (SysTools.Option "-E" : args)
1876 [ "-D" ++ HOST_OS ++ "_BUILD_OS=1",
1877 "-D" ++ HOST_ARCH ++ "_BUILD_ARCH=1",
1878 "-D" ++ TARGET_OS ++ "_HOST_OS=1",
1879 "-D" ++ TARGET_ARCH ++ "_HOST_ARCH=1" ]
1880 -- remember, in code we *compile*, the HOST is the same our TARGET,
1881 -- and BUILD is the same as our HOST.
1883 cpp_prog ([SysTools.Option verb]
1884 ++ map SysTools.Option include_paths
1885 ++ map SysTools.Option hsSourceCppOpts
1886 ++ map SysTools.Option target_defs
1887 ++ map SysTools.Option hscpp_opts
1888 ++ map SysTools.Option cc_opts
1889 ++ [ SysTools.Option "-x"
1890 , SysTools.Option "c"
1891 , SysTools.Option input_fn
1892 -- We hackily use Option instead of FileOption here, so that the file
1893 -- name is not back-slashed on Windows. cpp is capable of
1894 -- dealing with / in filenames, so it works fine. Furthermore
1895 -- if we put in backslashes, cpp outputs #line directives
1896 -- with *double* backslashes. And that in turn means that
1897 -- our error messages get double backslashes in them.
1898 -- In due course we should arrange that the lexer deals
1899 -- with these \\ escapes properly.
1900 , SysTools.Option "-o"
1901 , SysTools.FileOption "" output_fn
1904 hsSourceCppOpts :: [String]
1905 -- Default CPP defines in Haskell source
1907 [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
1909 -- ---------------------------------------------------------------------------
1910 -- join object files into a single relocatable object file, using ld -r
1912 joinObjectFiles :: DynFlags -> [FilePath] -> FilePath -> IO ()
1913 joinObjectFiles dflags o_files output_fn = do
1914 let ld_r args = SysTools.runLink dflags ([
1915 SysTools.Option "-nostdlib",
1916 SysTools.Option "-nodefaultlibs",
1917 SysTools.Option "-Wl,-r",
1918 SysTools.Option ld_x_flag,
1919 SysTools.Option "-o",
1920 SysTools.FileOption "" output_fn ]
1921 ++ map SysTools.Option md_c_flags
1923 ld_x_flag | null cLD_X = ""
1924 | otherwise = "-Wl,-x"
1926 md_c_flags = machdepCCOpts dflags
1928 if cLdIsGNULd == "YES"
1930 script <- newTempName dflags "ldscript"
1931 writeFile script $ "INPUT(" ++ unwords o_files ++ ")"
1932 ld_r [SysTools.FileOption "" script]
1934 ld_r (map (SysTools.FileOption "") o_files)
1936 -- -----------------------------------------------------------------------------
1939 hscNextPhase :: DynFlags -> HscSource -> HscTarget -> Phase
1940 hscNextPhase _ HsBootFile _ = StopLn
1941 hscNextPhase dflags _ hsc_lang =
1944 HscAsm | dopt Opt_SplitObjs dflags -> SplitMangle
1947 HscNothing -> StopLn
1948 HscInterpreted -> StopLn