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{stop_phase,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 next_phase <- maybeMergeStub
1182 output_fn <- phaseOutputFilename next_phase
1184 let base_o = dropExtension output_fn
1185 osuf = objectSuf dflags
1186 split_odir = base_o ++ "_" ++ osuf ++ "_split"
1188 io $ createDirectoryHierarchy split_odir
1190 -- remove M_split/ *.o, because we're going to archive M_split/ *.o
1191 -- later and we don't want to pick up any old objects.
1192 fs <- io $ getDirectoryContents split_odir
1193 io $ mapM_ removeFile $
1194 map (split_odir </>) $ filter (osuf `isSuffixOf`) fs
1196 let as_opts = getOpts dflags opt_a
1198 let (split_s_prefix, n) = case splitInfo dflags of
1199 Nothing -> panic "No split info"
1202 let split_s n = split_s_prefix ++ "__" ++ show n <.> "s"
1203 split_obj n = split_odir </>
1204 takeFileName base_o ++ "__" ++ show n <.> osuf
1206 let md_c_flags = machdepCCOpts dflags
1208 = SysTools.runAs dflags
1209 (map SysTools.Option as_opts ++
1210 #ifdef sparc_TARGET_ARCH
1211 -- We only support SparcV9 and better because V8 lacks an atomic CAS
1212 -- instruction so we have to make sure that the assembler accepts the
1213 -- instruction set. Note that the user can still override this
1214 -- (e.g., -mcpu=ultrasparc). GCC picks the "best" -mcpu flag
1215 -- regardless of the ordering.
1217 -- This is a temporary hack.
1218 [ SysTools.Option "-mcpu=v9" ] ++
1220 [ SysTools.Option "-c"
1221 , SysTools.Option "-o"
1222 , SysTools.FileOption "" (split_obj n)
1223 , SysTools.FileOption "" (split_s n)
1225 ++ map SysTools.Option md_c_flags)
1227 io $ mapM_ assemble_file [1..n]
1229 -- join them into a single .o file
1230 io $ joinObjectFiles dflags (map split_obj [1..n]) output_fn
1232 return (next_phase, output_fn)
1234 -----------------------------------------------------------------------------
1237 runPhase LlvmOpt input_fn dflags
1239 let lo_opts = getOpts dflags opt_lo
1240 let opt_lvl = max 0 (min 2 $ optLevel dflags)
1241 -- don't specify anything if user has specified commands. We do this for
1242 -- opt but not llc since opt is very specifically for optimisation passes
1243 -- only, so if the user is passing us extra options we assume they know
1244 -- what they are doing and don't get in the way.
1245 let optFlag = if null lo_opts
1246 then [SysTools.Option (llvmOpts !! opt_lvl)]
1249 output_fn <- phaseOutputFilename LlvmLlc
1251 io $ SysTools.runLlvmOpt dflags
1252 ([ SysTools.FileOption "" input_fn,
1253 SysTools.Option "-o",
1254 SysTools.FileOption "" output_fn]
1256 ++ map SysTools.Option lo_opts)
1258 return (LlvmLlc, output_fn)
1260 -- we always (unless -optlo specified) run Opt since we rely on it to
1261 -- fix up some pretty big deficiencies in the code we generate
1262 llvmOpts = ["-mem2reg", "-O1", "-O2"]
1265 -----------------------------------------------------------------------------
1268 runPhase LlvmLlc input_fn dflags
1270 let lc_opts = getOpts dflags opt_lc
1271 let opt_lvl = max 0 (min 2 $ optLevel dflags)
1272 #if darwin_TARGET_OS
1273 let nphase = LlvmMangle
1277 let rmodel | opt_PIC = "pic"
1278 | not opt_Static = "dynamic-no-pic"
1279 | otherwise = "static"
1281 output_fn <- phaseOutputFilename nphase
1283 io $ SysTools.runLlvmLlc dflags
1284 ([ SysTools.Option (llvmOpts !! opt_lvl),
1285 SysTools.Option $ "-relocation-model=" ++ rmodel,
1286 SysTools.FileOption "" input_fn,
1287 SysTools.Option "-o", SysTools.FileOption "" output_fn]
1288 ++ map SysTools.Option lc_opts)
1290 return (nphase, output_fn)
1292 #if darwin_TARGET_OS
1293 llvmOpts = ["-O1", "-O2", "-O2"]
1295 llvmOpts = ["-O1", "-O2", "-O3"]
1299 -----------------------------------------------------------------------------
1302 runPhase LlvmMangle input_fn _dflags
1304 output_fn <- phaseOutputFilename As
1305 io $ llvmFixupAsm input_fn output_fn
1306 return (As, output_fn)
1308 -----------------------------------------------------------------------------
1309 -- merge in stub objects
1311 runPhase MergeStub input_fn dflags
1313 PipeState{maybe_stub_o} <- getPipeState
1314 output_fn <- phaseOutputFilename StopLn
1315 case maybe_stub_o of
1317 panic "runPhase(MergeStub): no stub"
1319 io $ joinObjectFiles dflags [input_fn, stub_o] output_fn
1320 return (StopLn, output_fn)
1322 -- warning suppression
1323 runPhase other _input_fn _dflags =
1324 panic ("runPhase: don't know how to run phase " ++ show other)
1326 maybeMergeStub :: CompPipeline Phase
1329 PipeState{maybe_stub_o} <- getPipeState
1330 if isJust maybe_stub_o then return MergeStub else return StopLn
1332 -----------------------------------------------------------------------------
1333 -- MoveBinary sort-of-phase
1334 -- After having produced a binary, move it somewhere else and generate a
1335 -- wrapper script calling the binary. Currently, we need this only in
1336 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
1337 -- central directory.
1338 -- This is called from linkBinary below, after linking. I haven't made it
1339 -- a separate phase to minimise interfering with other modules, and
1340 -- we don't need the generality of a phase (MoveBinary is always
1341 -- done after linking and makes only sense in a parallel setup) -- HWL
1343 runPhase_MoveBinary :: DynFlags -> FilePath -> IO Bool
1344 runPhase_MoveBinary dflags input_fn
1345 | WayPar `elem` (wayNames dflags) && not opt_Static =
1346 panic ("Don't know how to combine PVM wrapper and dynamic wrapper")
1347 | WayPar `elem` (wayNames dflags) = do
1348 let sysMan = pgm_sysman dflags
1349 pvm_root <- getEnv "PVM_ROOT"
1350 pvm_arch <- getEnv "PVM_ARCH"
1352 pvm_executable_base = "=" ++ input_fn
1353 pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
1354 -- nuke old binary; maybe use configur'ed names for cp and rm?
1355 _ <- tryIO (removeFile pvm_executable)
1356 -- move the newly created binary into PVM land
1357 copy dflags "copying PVM executable" input_fn pvm_executable
1358 -- generate a wrapper script for running a parallel prg under PVM
1359 writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
1361 | otherwise = return True
1363 mkExtraCObj :: DynFlags -> [String] -> IO FilePath
1364 mkExtraCObj dflags xs
1365 = do cFile <- newTempName dflags "c"
1366 oFile <- newTempName dflags "o"
1367 writeFile cFile $ unlines xs
1368 let rtsDetails = getPackageDetails (pkgState dflags) rtsPackageId
1369 md_c_flags = machdepCCOpts dflags
1370 SysTools.runCc dflags
1372 FileOption "" cFile,
1374 FileOption "" oFile] ++
1375 map (FileOption "-I") (includeDirs rtsDetails) ++
1376 map Option md_c_flags)
1379 mkRtsOptionsLevelObj :: DynFlags -> IO [FilePath]
1380 mkRtsOptionsLevelObj dflags
1381 = do let mkRtsEnabledObj val
1382 = do fn <- mkExtraCObj dflags
1383 ["#include \"Rts.h\"",
1384 "#include \"RtsOpts.h\"",
1385 "const rtsOptsEnabledEnum rtsOptsEnabled = "
1388 case rtsOptsEnabled dflags of
1389 RtsOptsNone -> mkRtsEnabledObj "rtsOptsNone"
1390 RtsOptsSafeOnly -> return [] -- The default
1391 RtsOptsAll -> mkRtsEnabledObj "rtsOptsAll"
1393 -- generates a Perl skript starting a parallel prg under PVM
1394 mk_pvm_wrapper_script :: String -> String -> String -> String
1395 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
1397 "eval 'exec perl -S $0 ${1+\"$@\"}'",
1398 " if $running_under_some_shell;",
1399 "# =!=!=!=!=!=!=!=!=!=!=!",
1400 "# This script is automatically generated: DO NOT EDIT!!!",
1401 "# Generated by Glasgow Haskell Compiler",
1402 "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
1404 "$pvm_executable = '" ++ pvm_executable ++ "';",
1405 "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
1406 "$SysMan = '" ++ sysMan ++ "';",
1408 {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
1409 "# first, some magical shortcuts to run "commands" on the binary",
1410 "# (which is hidden)",
1411 "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
1412 " local($cmd) = $1;",
1413 " system("$cmd $pvm_executable");",
1414 " exit(0); # all done",
1417 "# Now, run the real binary; process the args first",
1418 "$ENV{'PE'} = $pvm_executable_base;", -- ++ pvm_executable_base,
1420 "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
1421 "@nonPVM_args = ();",
1422 "$in_RTS_args = 0;",
1424 "args: while ($a = shift(@ARGV)) {",
1425 " if ( $a eq '+RTS' ) {",
1426 " $in_RTS_args = 1;",
1427 " } elsif ( $a eq '-RTS' ) {",
1428 " $in_RTS_args = 0;",
1430 " if ( $a eq '-d' && $in_RTS_args ) {",
1432 " } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
1433 " $nprocessors = $1;",
1434 " } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
1435 " $nprocessors = $1;",
1437 " push(@nonPVM_args, $a);",
1441 "local($return_val) = 0;",
1442 "# Start the parallel execution by calling SysMan",
1443 "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
1444 "$return_val = $?;",
1445 "# ToDo: fix race condition moving files and flushing them!!",
1446 "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
1447 "exit($return_val);"
1450 -----------------------------------------------------------------------------
1451 -- Look for the /* GHC_PACKAGES ... */ comment at the top of a .hc file
1453 getHCFilePackages :: FilePath -> IO [PackageId]
1454 getHCFilePackages filename =
1455 Exception.bracket (openFile filename ReadMode) hClose $ \h -> do
1458 '/':'*':' ':'G':'H':'C':'_':'P':'A':'C':'K':'A':'G':'E':'S':rest ->
1459 return (map stringToPackageId (words rest))
1463 -----------------------------------------------------------------------------
1464 -- Static linking, of .o files
1466 -- The list of packages passed to link is the list of packages on
1467 -- which this program depends, as discovered by the compilation
1468 -- manager. It is combined with the list of packages that the user
1469 -- specifies on the command line with -package flags.
1471 -- In one-shot linking mode, we can't discover the package
1472 -- dependencies (because we haven't actually done any compilation or
1473 -- read any interface files), so the user must explicitly specify all
1476 linkBinary :: DynFlags -> [FilePath] -> [PackageId] -> IO ()
1477 linkBinary dflags o_files dep_packages = do
1478 let verb = getVerbFlag dflags
1479 output_fn = exeFileName dflags
1481 -- get the full list of packages to link with, by combining the
1482 -- explicit packages with the auto packages and all of their
1483 -- dependencies, and eliminating duplicates.
1485 pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1486 let pkg_lib_path_opts = concat (map get_pkg_lib_path_opts pkg_lib_paths)
1487 #ifdef elf_OBJ_FORMAT
1488 get_pkg_lib_path_opts l | (dynLibLoader dflags)==SystemDependent && not opt_Static = ["-L" ++ l, "-Wl,-rpath", "-Wl," ++ l]
1489 | otherwise = ["-L" ++ l]
1491 get_pkg_lib_path_opts l = ["-L" ++ l]
1494 let lib_paths = libraryPaths dflags
1495 let lib_path_opts = map ("-L"++) lib_paths
1497 -- The C "main" function is not in the rts but in a separate static
1498 -- library libHSrtsmain.a that sits next to the rts lib files. Assuming
1499 -- we're using a Haskell main function then we need to link it in.
1500 let no_hs_main = dopt Opt_NoHsMain dflags
1501 let main_lib | no_hs_main = []
1502 | otherwise = [ "-lHSrtsmain" ]
1503 rtsEnabledObj <- mkRtsOptionsLevelObj dflags
1504 rtsOptsObj <- case rtsOpts dflags of
1506 do fn <- mkExtraCObj dflags
1507 -- We assume that the Haskell "show" does
1508 -- the right thing here
1509 ["char *ghc_rts_opts = " ++ show opts ++ ";"]
1511 Nothing -> return []
1513 pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1515 #ifdef darwin_TARGET_OS
1516 pkg_framework_paths <- getPackageFrameworkPath dflags dep_packages
1517 let pkg_framework_path_opts = map ("-F"++) pkg_framework_paths
1519 let framework_paths = frameworkPaths dflags
1520 framework_path_opts = map ("-F"++) framework_paths
1522 pkg_frameworks <- getPackageFrameworks dflags dep_packages
1523 let pkg_framework_opts = concat [ ["-framework", fw] | fw <- pkg_frameworks ]
1525 let frameworks = cmdlineFrameworks dflags
1526 framework_opts = concat [ ["-framework", fw] | fw <- reverse frameworks ]
1527 -- reverse because they're added in reverse order from the cmd line
1529 -- probably _stub.o files
1530 extra_ld_inputs <- readIORef v_Ld_inputs
1532 -- opts from -optl-<blah> (including -l<blah> options)
1533 let extra_ld_opts = getOpts dflags opt_l
1535 let ways = wayNames dflags
1537 -- Here are some libs that need to be linked at the *end* of
1538 -- the command line, because they contain symbols that are referred to
1539 -- by the RTS. We can't therefore use the ordinary way opts for these.
1541 debug_opts | WayDebug `elem` ways = [
1542 #if defined(HAVE_LIBBFD)
1549 thread_opts | WayThreaded `elem` ways = [
1550 #if !defined(mingw32_TARGET_OS) && !defined(freebsd_TARGET_OS) && !defined(openbsd_TARGET_OS) && !defined(haiku_TARGET_OS)
1553 #if defined(osf3_TARGET_OS)
1559 rc_objs <- maybeCreateManifest dflags output_fn
1561 let md_c_flags = machdepCCOpts dflags
1562 SysTools.runLink dflags (
1563 [ SysTools.Option verb
1564 , SysTools.Option "-o"
1565 , SysTools.FileOption "" output_fn
1567 ++ map SysTools.Option (
1570 #ifdef mingw32_TARGET_OS
1571 -- Permit the linker to auto link _symbol to _imp_symbol.
1572 -- This lets us link against DLLs without needing an "import library".
1573 ++ ["-Wl,--enable-auto-import"]
1580 #ifdef darwin_TARGET_OS
1581 ++ framework_path_opts
1584 ++ pkg_lib_path_opts
1589 #ifdef darwin_TARGET_OS
1590 ++ pkg_framework_path_opts
1591 ++ pkg_framework_opts
1597 -- parallel only: move binary to another dir -- HWL
1598 success <- runPhase_MoveBinary dflags output_fn
1599 if success then return ()
1600 else ghcError (InstallationError ("cannot move binary"))
1603 exeFileName :: DynFlags -> FilePath
1605 | Just s <- outputFile dflags =
1606 #if defined(mingw32_HOST_OS)
1607 if null (takeExtension s)
1614 #if defined(mingw32_HOST_OS)
1622 -> FilePath -- filename of executable
1623 -> IO [FilePath] -- extra objects to embed, maybe
1624 #ifndef mingw32_TARGET_OS
1625 maybeCreateManifest _ _ = do
1628 maybeCreateManifest dflags exe_filename = do
1629 if not (dopt Opt_GenManifest dflags) then return [] else do
1631 let manifest_filename = exe_filename <.> "manifest"
1633 writeFile manifest_filename $
1634 "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"++
1635 " <assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">\n"++
1636 " <assemblyIdentity version=\"1.0.0.0\"\n"++
1637 " processorArchitecture=\"X86\"\n"++
1638 " name=\"" ++ dropExtension exe_filename ++ "\"\n"++
1639 " type=\"win32\"/>\n\n"++
1640 " <trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v3\">\n"++
1642 " <requestedPrivileges>\n"++
1643 " <requestedExecutionLevel level=\"asInvoker\" uiAccess=\"false\"/>\n"++
1644 " </requestedPrivileges>\n"++
1649 -- Windows will find the manifest file if it is named foo.exe.manifest.
1650 -- However, for extra robustness, and so that we can move the binary around,
1651 -- we can embed the manifest in the binary itself using windres:
1652 if not (dopt Opt_EmbedManifest dflags) then return [] else do
1654 rc_filename <- newTempName dflags "rc"
1655 rc_obj_filename <- newTempName dflags (objectSuf dflags)
1657 writeFile rc_filename $
1658 "1 24 MOVEABLE PURE " ++ show manifest_filename ++ "\n"
1659 -- magic numbers :-)
1660 -- show is a bit hackish above, but we need to escape the
1661 -- backslashes in the path.
1663 let wr_opts = getOpts dflags opt_windres
1664 runWindres dflags $ map SysTools.Option $
1665 ["--input="++rc_filename,
1666 "--output="++rc_obj_filename,
1667 "--output-format=coff"]
1669 -- no FileOptions here: windres doesn't like seeing
1670 -- backslashes, apparently
1672 removeFile manifest_filename
1674 return [rc_obj_filename]
1678 linkDynLib :: DynFlags -> [String] -> [PackageId] -> IO ()
1679 linkDynLib dflags o_files dep_packages = do
1680 let verb = getVerbFlag dflags
1681 let o_file = outputFile dflags
1683 pkgs <- getPreloadPackagesAnd dflags dep_packages
1685 let pkg_lib_paths = collectLibraryPaths pkgs
1686 let pkg_lib_path_opts = concatMap get_pkg_lib_path_opts pkg_lib_paths
1687 #ifdef elf_OBJ_FORMAT
1688 get_pkg_lib_path_opts l | (dynLibLoader dflags)==SystemDependent && not opt_Static = ["-L" ++ l, "-Wl,-rpath", "-Wl," ++ l]
1689 | otherwise = ["-L" ++ l]
1691 get_pkg_lib_path_opts l = ["-L" ++ l]
1694 let lib_paths = libraryPaths dflags
1695 let lib_path_opts = map ("-L"++) lib_paths
1697 -- We don't want to link our dynamic libs against the RTS package,
1698 -- because the RTS lib comes in several flavours and we want to be
1699 -- able to pick the flavour when a binary is linked.
1700 -- On Windows we need to link the RTS import lib as Windows does
1701 -- not allow undefined symbols.
1702 -- The RTS library path is still added to the library search path
1703 -- above in case the RTS is being explicitly linked in (see #3807).
1704 #if !defined(mingw32_HOST_OS)
1705 let pkgs_no_rts = filter ((/= rtsPackageId) . packageConfigId) pkgs
1707 let pkgs_no_rts = pkgs
1709 let pkg_link_opts = collectLinkOpts dflags pkgs_no_rts
1711 -- probably _stub.o files
1712 extra_ld_inputs <- readIORef v_Ld_inputs
1714 let md_c_flags = machdepCCOpts dflags
1715 let extra_ld_opts = getOpts dflags opt_l
1717 rtsEnabledObj <- mkRtsOptionsLevelObj dflags
1719 #if defined(mingw32_HOST_OS)
1720 -----------------------------------------------------------------------------
1722 -----------------------------------------------------------------------------
1723 let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
1725 SysTools.runLink dflags
1726 ([ SysTools.Option verb
1727 , SysTools.Option "-o"
1728 , SysTools.FileOption "" output_fn
1729 , SysTools.Option "-shared"
1731 [ SysTools.FileOption "-Wl,--out-implib=" (output_fn ++ ".a")
1732 | dopt Opt_SharedImplib dflags
1734 ++ map (SysTools.FileOption "") o_files
1735 ++ map SysTools.Option (
1738 -- Permit the linker to auto link _symbol to _imp_symbol
1739 -- This lets us link against DLLs without needing an "import library"
1740 ++ ["-Wl,--enable-auto-import"]
1745 ++ pkg_lib_path_opts
1749 #elif defined(darwin_TARGET_OS)
1750 -----------------------------------------------------------------------------
1751 -- Making a darwin dylib
1752 -----------------------------------------------------------------------------
1753 -- About the options used for Darwin:
1755 -- Apple's way of saying -shared
1756 -- -undefined dynamic_lookup:
1757 -- Without these options, we'd have to specify the correct dependencies
1758 -- for each of the dylibs. Note that we could (and should) do without this
1759 -- for all libraries except the RTS; all we need to do is to pass the
1760 -- correct HSfoo_dyn.dylib files to the link command.
1761 -- This feature requires Mac OS X 10.3 or later; there is a similar feature,
1762 -- -flat_namespace -undefined suppress, which works on earlier versions,
1763 -- but it has other disadvantages.
1765 -- Build the dynamic library as a single "module", i.e. no dynamic binding
1766 -- nonsense when referring to symbols from within the library. The NCG
1767 -- assumes that this option is specified (on i386, at least).
1769 -- Mac OS/X stores the path where a dynamic library is (to be) installed
1770 -- in the library itself. It's called the "install name" of the library.
1771 -- Then any library or executable that links against it before it's
1772 -- installed will search for it in its ultimate install location. By
1773 -- default we set the install name to the absolute path at build time, but
1774 -- it can be overridden by the -dylib-install-name option passed to ghc.
1776 -----------------------------------------------------------------------------
1778 let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
1780 instName <- case dylibInstallName dflags of
1783 pwd <- getCurrentDirectory
1784 return $ pwd `combine` output_fn
1785 SysTools.runLink dflags
1786 ([ SysTools.Option verb
1787 , SysTools.Option "-dynamiclib"
1788 , SysTools.Option "-o"
1789 , SysTools.FileOption "" output_fn
1791 ++ map SysTools.Option (
1794 ++ [ "-undefined", "dynamic_lookup", "-single_module",
1795 #if !defined(x86_64_TARGET_ARCH)
1796 "-Wl,-read_only_relocs,suppress",
1798 "-install_name", instName ]
1802 ++ pkg_lib_path_opts
1807 -----------------------------------------------------------------------------
1809 -----------------------------------------------------------------------------
1811 let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
1812 let buildingRts = thisPackage dflags == rtsPackageId
1813 let bsymbolicFlag = if buildingRts
1814 then -- -Bsymbolic breaks the way we implement
1817 else -- we need symbolic linking to resolve
1818 -- non-PIC intra-package-relocations
1821 SysTools.runLink dflags
1822 ([ SysTools.Option verb
1823 , SysTools.Option "-o"
1824 , SysTools.FileOption "" output_fn
1826 ++ map SysTools.Option (
1831 -- Set the library soname. We use -h rather than -soname as
1832 -- Solaris 10 doesn't support the latter:
1833 ++ [ "-Wl,-h," ++ takeFileName output_fn ]
1837 ++ pkg_lib_path_opts
1842 -- -----------------------------------------------------------------------------
1845 doCpp :: DynFlags -> Bool -> Bool -> FilePath -> FilePath -> IO ()
1846 doCpp dflags raw include_cc_opts input_fn output_fn = do
1847 let hscpp_opts = getOpts dflags opt_P
1848 let cmdline_include_paths = includePaths dflags
1850 pkg_include_dirs <- getPackageIncludePath dflags []
1851 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
1852 (cmdline_include_paths ++ pkg_include_dirs)
1854 let verb = getVerbFlag dflags
1857 | not include_cc_opts = []
1858 | otherwise = (optc ++ md_c_flags)
1860 optc = getOpts dflags opt_c
1861 md_c_flags = machdepCCOpts dflags
1863 let cpp_prog args | raw = SysTools.runCpp dflags args
1864 | otherwise = SysTools.runCc dflags (SysTools.Option "-E" : args)
1867 [ "-D" ++ HOST_OS ++ "_BUILD_OS=1",
1868 "-D" ++ HOST_ARCH ++ "_BUILD_ARCH=1",
1869 "-D" ++ TARGET_OS ++ "_HOST_OS=1",
1870 "-D" ++ TARGET_ARCH ++ "_HOST_ARCH=1" ]
1871 -- remember, in code we *compile*, the HOST is the same our TARGET,
1872 -- and BUILD is the same as our HOST.
1874 cpp_prog ([SysTools.Option verb]
1875 ++ map SysTools.Option include_paths
1876 ++ map SysTools.Option hsSourceCppOpts
1877 ++ map SysTools.Option target_defs
1878 ++ map SysTools.Option hscpp_opts
1879 ++ map SysTools.Option cc_opts
1880 ++ [ SysTools.Option "-x"
1881 , SysTools.Option "c"
1882 , SysTools.Option input_fn
1883 -- We hackily use Option instead of FileOption here, so that the file
1884 -- name is not back-slashed on Windows. cpp is capable of
1885 -- dealing with / in filenames, so it works fine. Furthermore
1886 -- if we put in backslashes, cpp outputs #line directives
1887 -- with *double* backslashes. And that in turn means that
1888 -- our error messages get double backslashes in them.
1889 -- In due course we should arrange that the lexer deals
1890 -- with these \\ escapes properly.
1891 , SysTools.Option "-o"
1892 , SysTools.FileOption "" output_fn
1895 hsSourceCppOpts :: [String]
1896 -- Default CPP defines in Haskell source
1898 [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
1900 -- ---------------------------------------------------------------------------
1901 -- join object files into a single relocatable object file, using ld -r
1903 joinObjectFiles :: DynFlags -> [FilePath] -> FilePath -> IO ()
1904 joinObjectFiles dflags o_files output_fn = do
1905 let ld_r args = SysTools.runLink dflags ([
1906 SysTools.Option "-nostdlib",
1907 SysTools.Option "-nodefaultlibs",
1908 SysTools.Option "-Wl,-r",
1909 SysTools.Option ld_x_flag,
1910 SysTools.Option "-o",
1911 SysTools.FileOption "" output_fn ]
1912 ++ map SysTools.Option md_c_flags
1914 ld_x_flag | null cLD_X = ""
1915 | otherwise = "-Wl,-x"
1917 md_c_flags = machdepCCOpts dflags
1919 if cLdIsGNULd == "YES"
1921 script <- newTempName dflags "ldscript"
1922 writeFile script $ "INPUT(" ++ unwords o_files ++ ")"
1923 ld_r [SysTools.FileOption "" script]
1925 ld_r (map (SysTools.FileOption "") o_files)
1927 -- -----------------------------------------------------------------------------
1930 hscNextPhase :: DynFlags -> HscSource -> HscTarget -> Phase
1931 hscNextPhase _ HsBootFile _ = StopLn
1932 hscNextPhase dflags _ hsc_lang =
1935 HscAsm | dopt Opt_SplitObjs dflags -> SplitMangle
1938 HscNothing -> StopLn
1939 HscInterpreted -> StopLn