Merge branch 'master' of /home/simonmar/ghc-git/.
[ghc.git] / compiler / main / DriverPipeline.hs
1 {-# OPTIONS -fno-cse #-}
2 {-# LANGUAGE NamedFieldPuns #-}
3 -- -fno-cse is needed for GLOBAL_VAR's to behave properly
4
5 -----------------------------------------------------------------------------
6 --
7 -- GHC Driver
8 --
9 -- (c) The University of Glasgow 2005
10 --
11 -----------------------------------------------------------------------------
12
13 module DriverPipeline (
14 -- Run a series of compilation steps in a pipeline, for a
15 -- collection of source files.
16 oneShot, compileFile,
17
18 -- Interfaces for the batch-mode driver
19 linkBinary,
20
21 -- Interfaces for the compilation manager (interpreted/batch-mode)
22 preprocess,
23 compile, compile',
24 link,
25
26 ) where
27
28 #include "HsVersions.h"
29
30 import Packages
31 import HeaderInfo
32 import DriverPhases
33 import SysTools
34 import HscMain
35 import Finder
36 import HscTypes
37 import Outputable
38 import Module
39 import UniqFM ( eltsUFM )
40 import ErrUtils
41 import DynFlags
42 import StaticFlags ( v_Ld_inputs, opt_PIC, opt_Static, WayName(..) )
43 import Config
44 import Panic
45 import Util
46 import StringBuffer ( hGetStringBuffer )
47 import BasicTypes ( SuccessFlag(..) )
48 import Maybes ( expectJust )
49 import ParserCoreUtils ( getCoreModuleName )
50 import SrcLoc
51 import FastString
52 import LlvmCodeGen ( llvmFixupAsm )
53 import MonadUtils
54
55 -- import Data.Either
56 import Exception
57 import Data.IORef ( readIORef )
58 -- import GHC.Exts ( Int(..) )
59 import System.Directory
60 import System.FilePath
61 import System.IO
62 import Control.Monad
63 import Data.List ( isSuffixOf )
64 import Data.Maybe
65 import System.Environment
66
67 -- ---------------------------------------------------------------------------
68 -- Pre-process
69
70 -- | Just preprocess a file, put the result in a temp. file (used by the
71 -- compilation manager during the summary phase).
72 --
73 -- We return the augmented DynFlags, because they contain the result
74 -- of slurping in the OPTIONS pragmas
75
76 preprocess :: HscEnv
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-}
83
84 -- ---------------------------------------------------------------------------
85
86 -- | Compile
87 --
88 -- Compile a single module, under the control of the compilation manager.
89 --
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
94 -- FFI stub files.
95 --
96 -- NB. No old interface can also mean that the source has changed.
97
98 compile :: HscEnv
99 -> ModSummary -- ^ summary for module being compiled
100 -> Int -- ^ module N ...
101 -> Int -- ^ ... of M
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
105
106 compile = compile' (hscCompileNothing, hscCompileInteractive, hscCompileBatch)
107
108 compile' ::
109 (Compiler (HscStatus, ModIface, ModDetails),
110 Compiler (InteractiveStatus, ModIface, ModDetails),
111 Compiler (HscStatus, ModIface, ModDetails))
112 -> HscEnv
113 -> ModSummary -- ^ summary for module being compiled
114 -> Int -- ^ module N ...
115 -> Int -- ^ ... of M
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
119
120 compile' (nothingCompiler, interactiveCompiler, batchCompiler)
121 hsc_env0 summary mod_index nmods mb_old_iface maybe_old_linkable
122 = do
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
129
130 debugTraceMsg dflags0 2 (text "compile: input file" <+> text input_fnpp)
131
132 let basename = dropExtension input_fn
133
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
139 d -> d
140 old_paths = includePaths dflags0
141 dflags = dflags0 { includePaths = current_dir : old_paths }
142 hsc_env = hsc_env0 {hsc_dflags = dflags}
143
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)
151
152 let dflags' = dflags { hscTarget = hsc_lang,
153 hscOutName = output_fn,
154 extCoreName = basename ++ ".hcr" }
155 let hsc_env' = hsc_env { hsc_dflags = dflags' }
156
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
161
162 let handleBatch HscNoRecomp
163 = ASSERT (isJust maybe_old_linkable)
164 return maybe_old_linkable
165
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"
170 object_filename
171 return maybe_old_linkable
172
173 | otherwise
174 = do (hs_unlinked, unlinked_time) <-
175 case hsc_lang of
176 HscNothing ->
177 return ([], ms_hs_date summary)
178 -- We're in --make mode: finish the compilation pipeline.
179 _other -> do
180 maybe_stub_o <- case hasStub of
181 Nothing -> return Nothing
182 Just stub_c -> do
183 stub_o <- compileStub hsc_env' stub_c
184 return (Just stub_o)
185 _ <- runPipeline StopLn hsc_env' (output_fn,Nothing)
186 (Just basename)
187 Persistent
188 (Just location)
189 maybe_stub_o
190 -- The object filename comes from the ModLocation
191 o_time <- getModificationTime object_filename
192 return ([DotO object_filename], o_time)
193
194 let linkable = LM unlinked_time this_mod hs_unlinked
195 return (Just linkable)
196
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
205 Nothing -> return []
206 Just stub_c -> do
207 stub_o <- compileStub hsc_env' stub_c
208 return [DotO stub_o]
209
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
217 -- be out of date.
218 let linkable = LM unlinked_time this_mod
219 (hs_unlinked ++ stub_o)
220 return (Just linkable)
221
222 let -- runCompiler :: Compiler result -> (result -> Maybe Linkable)
223 -- -> m HomeModInfo
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,
230 hm_iface = iface,
231 hm_linkable = linkable })
232 -- run the compiler
233 case hsc_lang of
234 HscInterpreted -> runCompiler interactiveCompiler handleInterpreted
235 HscNothing -> runCompiler nothingCompiler handleBatch
236 _other -> runCompiler batchCompiler handleBatch
237
238 -----------------------------------------------------------------------------
239 -- stub .h and .c files (for foreign export support)
240
241 -- The _stub.c file is derived from the haskell source file, possibly taking
242 -- into account the -stubdir option.
243 --
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).
247
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
252
253 return stub_o
254
255 -- ---------------------------------------------------------------------------
256 -- Link
257
258 link :: GhcLink -- interactive or batch
259 -> DynFlags -- dynamic flags
260 -> Bool -- attempt linking in batch mode?
261 -> HomePackageTable -- what to link
262 -> IO SuccessFlag
263
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
269 -- will succeed.
270
271 #ifdef GHCI
272 link LinkInMemory _ _ _
273 = do -- Not Linking...(demand linker will do the job)
274 return Succeeded
275 #endif
276
277 link NoLink _ _ _
278 = return Succeeded
279
280 link LinkBinary dflags batch_attempt_linking hpt
281 = link' dflags batch_attempt_linking hpt
282
283 link LinkDynLib dflags batch_attempt_linking hpt
284 = link' dflags batch_attempt_linking hpt
285
286 #ifndef GHCI
287 -- warning suppression
288 link other _ _ _ = panicBadLink other
289 #endif
290
291 panicBadLink :: GhcLink -> a
292 panicBadLink other = panic ("link: GHC not built to link this way: " ++
293 show other)
294
295 link' :: DynFlags -- dynamic flags
296 -> Bool -- attempt linking in batch mode?
297 -> HomePackageTable -- what to link
298 -> IO SuccessFlag
299
300 link' dflags batch_attempt_linking hpt
301 | batch_attempt_linking
302 = do
303 let
304 home_mod_infos = eltsUFM hpt
305
306 -- the packages we depend on
307 pkg_deps = concatMap (dep_pkgs . mi_deps . hm_iface) home_mod_infos
308
309 -- the linkables to link
310 linkables = map (expectJust "link".hm_linkable) home_mod_infos
311
312 debugTraceMsg dflags 3 (text "link: linkables are ..." $$ vcat (map ppr linkables))
313
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).")
317 return Succeeded
318 else do
319
320 let getOfiles (LM _ _ us) = map nameOfObject (filter isObject us)
321 obj_files = concatMap getOfiles linkables
322
323 exe_file = exeFileName dflags
324
325 linking_needed <- linkingNeeded dflags linkables pkg_deps
326
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."))
329 return Succeeded
330 else do
331
332 debugTraceMsg dflags 1 (ptext (sLit "Linking") <+> text exe_file
333 <+> text "...")
334
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
341
342 debugTraceMsg dflags 3 (text "link: done")
343
344 -- linkBinary only returns if it succeeds
345 return Succeeded
346
347 | otherwise
348 = do debugTraceMsg dflags 3 (text "link(batch): upsweep (partially) failed OR" $$
349 text " Main.main not exported; not linking.")
350 return Succeeded
351
352
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
360 case e_exe_time of
361 Left _ -> return True
362 Right t -> do
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
369 then return True
370 else do
371
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 ]
378
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
385 then return True
386 else return False
387
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)
392 case found of
393 [] -> return Nothing
394 (x:_) -> return (Just x)
395
396 -- -----------------------------------------------------------------------------
397 -- Compile files in one-shot mode.
398
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
403
404 compileFile :: HscEnv -> Phase -> (FilePath, Maybe Phase) -> IO FilePath
405 compileFile hsc_env stop_phase (src, mb_phase) = do
406 exists <- doesFileExist src
407 when (not exists) $
408 ghcError (CmdLineError ("does not exist: " ++ src))
409
410 let
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
415
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.
418 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
424
425 stop_phase' = case stop_phase of
426 As | split -> SplitAs
427 _ -> stop_phase
428
429 ( _, out_file) <- runPipeline stop_phase' hsc_env
430 (src, mb_phase) Nothing output
431 Nothing{-no ModLocation-} Nothing
432 return out_file
433
434
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
439
440 | otherwise
441 = case ghcLink dflags of
442 NoLink -> return ()
443 LinkBinary -> linkBinary dflags o_files []
444 LinkDynLib -> linkDynLib dflags o_files []
445 other -> panicBadLink other
446
447
448 -- ---------------------------------------------------------------------------
449
450 data PipelineOutput
451 = Temporary
452 -- ^ Output should be to a temporary file: we're going to
453 -- run more compilation steps on this output later.
454 | Persistent
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.
460
461 -- | Run a compilation pipeline, consisting of multiple phases.
462 --
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.
466 --
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
469 -- pipeline.
470 runPipeline
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)
479
480 runPipeline stop_phase hsc_env0 (input_fn, mb_phase)
481 mb_basename output maybe_loc maybe_stub_o
482 = do
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
488
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}
492
493 -- If we were given a -x flag, then use that phase to start from
494 start_phase = fromMaybe (startPhase suffix') mb_phase
495
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
498 -- end.
499 --
500 -- There is a partial ordering on phases, where A < B iff A occurs
501 -- before B in a normal compilation pipeline.
502
503 when (not (start_phase `happensBefore` stop_phase)) $
504 ghcError (UsageError
505 ("cannot compile this file to desired target: "
506 ++ input_fn))
507
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
511
512 -- Execute the pipeline...
513 let env = PipeEnv{ stop_phase,
514 src_basename = basename,
515 src_suffix = suffix',
516 output_spec = output }
517
518 state = PipeState{ hsc_env, maybe_loc, maybe_stub_o = maybe_stub_o }
519
520 (state', output_fn) <- unP (pipeLoop start_phase input_fn) env state
521
522 let PipeState{ hsc_env=hsc_env', maybe_loc } = state'
523 dflags' = hsc_dflags hsc_env'
524
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.
530 case output of
531 Temporary ->
532 return (dflags', output_fn)
533 _other ->
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)
540
541 -- -----------------------------------------------------------------------------
542 -- The pipeline uses a monad to carry around various bits of information
543
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
550 }
551
552 -- PipeState: information that might change during a pipeline run
553 data PipeState = PipeState {
554 hsc_env :: HscEnv,
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.
565 }
566
567 getPipeEnv :: CompPipeline PipeEnv
568 getPipeEnv = P $ \env state -> return (state, env)
569
570 getPipeState :: CompPipeline PipeState
571 getPipeState = P $ \_env state -> return (state, state)
572
573 getDynFlags :: CompPipeline DynFlags
574 getDynFlags = P $ \_env state -> return (state, hsc_dflags (hsc_env state))
575
576 setDynFlags :: DynFlags -> CompPipeline ()
577 setDynFlags dflags = P $ \_env state ->
578 return (state{hsc_env= (hsc_env state){ hsc_dflags = dflags }}, ())
579
580 setModLocation :: ModLocation -> CompPipeline ()
581 setModLocation loc = P $ \_env state ->
582 return (state{ maybe_loc = Just loc }, ())
583
584 setStubO :: FilePath -> CompPipeline ()
585 setStubO stub_o = P $ \_env state ->
586 return (state{ maybe_stub_o = Just stub_o }, ())
587
588 newtype CompPipeline a = P { unP :: PipeEnv -> PipeState -> IO (PipeState, a) }
589
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
593 unP (k a) env state'
594
595 io :: IO a -> CompPipeline a
596 io m = P $ \_env state -> do a <- m; return (state, a)
597
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
605
606 -- ---------------------------------------------------------------------------
607 -- outer pipeline loop
608
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
614 case () of
615 _ | phase `eqPhase` stop_phase -- All done
616 -> return input_fn
617
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)
625
626 | otherwise
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
632
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.
637
638 getOutputFilename
639 :: Phase -> PipelineOutput -> String
640 -> DynFlags -> Phase{-next phase-} -> Maybe ModLocation -> IO FilePath
641 getOutputFilename stop_phase output basename
642 = func
643 where
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
649 where
650 hcsuf = hcSuf dflags
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
656
657 myPhaseInputExt HCc = hcsuf
658 myPhaseInputExt MergeStub = osuf
659 myPhaseInputExt StopLn = osuf
660 myPhaseInputExt other = phaseInputExt other
661
662 is_last_phase = next_phase `eqPhase` stop_phase
663
664 -- sometimes, we keep output from intermediate stages
665 keep_this_output =
666 case next_phase of
667 As | keep_s -> True
668 LlvmOpt | keep_bc -> True
669 HCc | keep_hc -> True
670 _other -> False
671
672 suffix = myPhaseInputExt next_phase
673
674 -- persistent object files get put in odir
675 persistent_fn
676 | StopLn <- next_phase = return odir_persistent
677 | otherwise = return persistent
678
679 persistent = basename <.> suffix
680
681 odir_persistent
682 | Just loc <- maybe_location = ml_obj_file loc
683 | Just d <- odir = d </> persistent
684 | otherwise = persistent
685
686
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.
690 --
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.
696 --
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
702
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
706
707
708 -------------------------------------------------------------------------------
709 -- Unlit phase
710
711 runPhase (Unlit sf) input_fn dflags
712 = do
713 output_fn <- phaseOutputFilename (Cpp sf)
714
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
719 SysTools.Option "-h"
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
725 ]
726
727 io $ SysTools.runUnlit dflags flags
728
729 return (Cpp sf, output_fn)
730
731 -------------------------------------------------------------------------------
732 -- Cpp phase : (a) gets OPTIONS out of file
733 -- (b) runs cpp if necessary
734
735 runPhase (Cpp sf) input_fn dflags0
736 = do
737 src_opts <- io $ getOptionsFromFile dflags0 input_fn
738 (dflags1, unhandled_flags, warns)
739 <- io $ parseDynamicNoPackageFlags dflags0 src_opts
740 setDynFlags dflags1
741 io $ checkProcessArgsResult unhandled_flags
742
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
746
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)
750 else do
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
754 -- See #2464,#3457
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
761
762 setDynFlags dflags2
763
764 return (HsPp sf, output_fn)
765
766 -------------------------------------------------------------------------------
767 -- HsPp phase
768
769 runPhase (HsPp sf) input_fn dflags
770 = do
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)
775 else do
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
784 ] ++
785 map SysTools.Option hspp_opts
786 )
787
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
792 setDynFlags dflags1
793 io $ handleFlagWarnings dflags1 warns
794 io $ checkProcessArgsResult unhandled_flags
795
796 return (Hsc sf, output_fn)
797
798 -----------------------------------------------------------------------------
799 -- Hsc phase
800
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
805
806 PipeEnv{ stop_phase=stop,
807 src_basename=basename,
808 src_suffix=suff } <- getPipeEnv
809
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
815 d -> d
816
817 paths = includePaths dflags0
818 dflags = dflags0 { includePaths = current_dir : paths }
819
820 setDynFlags dflags
821
822 -- gather the imports and module name
823 (hspp_buf,mod_name,imps,src_imps) <- io $
824 case src_flavour of
825 ExtCoreFile -> do -- no explicit imports in ExtCore input.
826 m <- getCoreModuleName input_fn
827 return (Nothing, mkModuleName m, [], [])
828
829 _ -> do
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)
833
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
841
842 -- Boot-ify it if necessary
843 let location2 | isHsBoot src_flavour = addBootSuffixLocn location1
844 | otherwise = location1
845
846
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
853
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
864
865 o_file = ml_obj_file location4 -- The real object file
866
867 setModLocation location4
868
869 -- Figure out if the source has changed, for recompilation avoidance.
870 --
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)
877
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)
885 then return False
886 -- Otherwise look at file modification dates
887 else do o_file_exists <- doesFileExist o_file
888 if not o_file_exists
889 then return False -- Need to recompile
890 else do t2 <- getModificationTime o_file
891 if t2 > src_timestamp
892 then return True
893 else return False
894
895 -- get the DynFlags
896 let next_phase = hscNextPhase dflags src_flavour hsc_lang
897 output_fn <- phaseOutputFilename next_phase
898
899 let dflags' = dflags { hscTarget = hsc_lang,
900 hscOutName = output_fn,
901 extCoreName = basename ++ ".hcr" }
902
903 setDynFlags dflags'
904 PipeState{hsc_env=hsc_env'} <- getPipeState
905
906 -- Tell the finder cache about this module
907 mod <- io $ addHomeModuleToFinder hsc_env' mod_name location4
908
909 -- Make the ModSummary to hand to hscMain
910 let
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,
919 ms_imps = imps,
920 ms_srcimps = src_imps }
921
922 -- run the compiler!
923 result <- io $ hscCompileOneShot hsc_env'
924 mod_summary source_unchanged
925 Nothing -- No iface
926 Nothing -- No "module i of n" progress info
927
928 case result of
929 HscNoRecomp
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
937 Nothing -> return ()
938 Just stub_c ->
939 do stub_o <- io $ compileStub hsc_env' stub_c
940 setStubO stub_o
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)
946
947 -----------------------------------------------------------------------------
948 -- Cmm phase
949
950 runPhase CmmCpp input_fn dflags
951 = do
952 output_fn <- phaseOutputFilename Cmm
953 io $ doCpp dflags False{-not raw-} True{-include CC opts-}
954 input_fn output_fn
955 return (Cmm, output_fn)
956
957 runPhase Cmm input_fn dflags
958 = do
959 PipeEnv{src_basename} <- getPipeEnv
960 let hsc_lang = hscTarget dflags
961
962 let next_phase = hscNextPhase dflags HsSrcFile hsc_lang
963
964 output_fn <- phaseOutputFilename next_phase
965
966 let dflags' = dflags { hscTarget = hsc_lang,
967 hscOutName = output_fn,
968 extCoreName = src_basename ++ ".hcr" }
969
970 setDynFlags dflags'
971 PipeState{hsc_env} <- getPipeState
972
973 io $ hscCompileCmmFile hsc_env input_fn
974
975 -- XXX: catch errors above and convert them into ghcError? Original
976 -- code was:
977 --
978 --when (not ok) $ ghcError (PhaseFailed "cmm" (ExitFailure 1))
979
980 return (next_phase, output_fn)
981
982 -----------------------------------------------------------------------------
983 -- Cc phase
984
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.
987
988 runPhase cc_phase input_fn dflags
989 | cc_phase `eqPhase` Cc || cc_phase `eqPhase` Ccpp || cc_phase `eqPhase` HCc
990 = do
991 let cc_opts = getOpts dflags opt_c
992 hcc = cc_phase `eqPhase` HCc
993
994 let cmdline_include_paths = includePaths dflags
995
996 -- HC files have the dependent packages stamped into them
997 pkgs <- if hcc then io $ getHCFilePackages input_fn else return []
998
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
1001 -- gcc gives you :)
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)
1005
1006 let md_c_flags = machdepCCOpts dflags
1007 gcc_extra_viac_flags <- io $ getExtraViaCOpts dflags
1008 let pic_c_flags = picCCOpts dflags
1009
1010 let verb = getVerbFlag dflags
1011
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
1017 then return []
1018 else getPackageExtraCcOpts dflags pkgs
1019
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)
1025 #endif
1026
1027 let split_objs = dopt Opt_SplitObjs dflags
1028 split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
1029 | otherwise = [ ]
1030
1031 let cc_opt | optLevel dflags >= 2 = "-O2"
1032 | otherwise = "-O"
1033
1034 -- Decide next phase
1035
1036 let next_phase = As
1037 output_fn <- phaseOutputFilename next_phase
1038
1039 let
1040 more_hcc_opts =
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
1047 then []
1048 else [ "-ffloat-store" ]) ++
1049 #endif
1050
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"]
1056
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
1061 -- -x c option.
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
1068 ]
1069 ++ map SysTools.Option (
1070 md_c_flags
1071 ++ pic_c_flags
1072
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" ]
1081 else [])
1082 #endif
1083
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.
1089 --
1090 -- This is a temporary hack.
1091 ++ ["-mcpu=v9"]
1092 #endif
1093 ++ (if hcc
1094 then gcc_extra_viac_flags ++ more_hcc_opts
1095 else [])
1096 ++ [ verb, "-S", "-Wimplicit", cc_opt ]
1097 ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
1098 #ifdef darwin_TARGET_OS
1099 ++ framework_paths
1100 #endif
1101 ++ cc_opts
1102 ++ split_opt
1103 ++ include_paths
1104 ++ pkg_extra_cc_opts
1105 ))
1106
1107 return (next_phase, output_fn)
1108
1109 -- ToDo: postprocess the output from gcc
1110
1111 -----------------------------------------------------------------------------
1112 -- Splitting phase
1113
1114 runPhase SplitMangle input_fn dflags
1115 = do -- tmp_pfx is the prefix used for the split .s files
1116
1117 split_s_prefix <- io $ SysTools.newTempName dflags "split"
1118 let n_files_fn = split_s_prefix
1119
1120 io $ SysTools.runSplit dflags
1121 [ SysTools.FileOption "" input_fn
1122 , SysTools.FileOption "" split_s_prefix
1123 , SysTools.FileOption "" n_files_fn
1124 ]
1125
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) }
1130
1131 setDynFlags dflags'
1132
1133 -- Remember to delete all these files
1134 io $ addFilesToClean dflags' [ split_s_prefix ++ "__" ++ show n ++ ".s"
1135 | n <- [1..n_files]]
1136
1137 return (SplitAs, "**splitmangle**")
1138 -- we don't use the filename
1139
1140 -----------------------------------------------------------------------------
1141 -- As phase
1142
1143 runPhase As input_fn dflags
1144 = do
1145 let as_opts = getOpts dflags opt_a
1146 let cmdline_include_paths = includePaths dflags
1147
1148 next_phase <- maybeMergeStub
1149 output_fn <- phaseOutputFilename next_phase
1150
1151 -- we create directories for the object file, because it
1152 -- might be a hierarchical module.
1153 io $ createDirectoryHierarchy (takeDirectory output_fn)
1154
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.
1165 --
1166 -- This is a temporary hack.
1167 ++ [ SysTools.Option "-mcpu=v9" ]
1168 #endif
1169 ++ [ SysTools.Option "-c"
1170 , SysTools.FileOption "" input_fn
1171 , SysTools.Option "-o"
1172 , SysTools.FileOption "" output_fn
1173 ]
1174 ++ map SysTools.Option md_c_flags)
1175
1176 return (next_phase, output_fn)
1177
1178
1179 runPhase SplitAs _input_fn dflags
1180 = do
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
1185
1186 let base_o = dropExtension output_fn
1187 osuf = objectSuf dflags
1188 split_odir = base_o ++ "_" ++ osuf ++ "_split"
1189
1190 io $ createDirectoryHierarchy split_odir
1191
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
1197
1198 let as_opts = getOpts dflags opt_a
1199
1200 let (split_s_prefix, n) = case splitInfo dflags of
1201 Nothing -> panic "No split info"
1202 Just x -> x
1203
1204 let split_s n = split_s_prefix ++ "__" ++ show n <.> "s"
1205 split_obj n = split_odir </>
1206 takeFileName base_o ++ "__" ++ show n <.> osuf
1207
1208 let md_c_flags = machdepCCOpts dflags
1209 let assemble_file n
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.
1218 --
1219 -- This is a temporary hack.
1220 [ SysTools.Option "-mcpu=v9" ] ++
1221 #endif
1222 [ SysTools.Option "-c"
1223 , SysTools.Option "-o"
1224 , SysTools.FileOption "" (split_obj n)
1225 , SysTools.FileOption "" (split_s n)
1226 ]
1227 ++ map SysTools.Option md_c_flags)
1228
1229 io $ mapM_ assemble_file [1..n]
1230
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
1234 Nothing -> return n
1235 Just stub_o -> do io $ copyFile stub_o (split_obj (n+1))
1236 return (n+1)
1237
1238 -- join them into a single .o file
1239 io $ joinObjectFiles dflags (map split_obj [1..n']) output_fn
1240
1241 return (next_phase, output_fn)
1242
1243 -----------------------------------------------------------------------------
1244 -- LlvmOpt phase
1245
1246 runPhase LlvmOpt input_fn dflags
1247 = do
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)]
1256 else []
1257
1258 output_fn <- phaseOutputFilename LlvmLlc
1259
1260 io $ SysTools.runLlvmOpt dflags
1261 ([ SysTools.FileOption "" input_fn,
1262 SysTools.Option "-o",
1263 SysTools.FileOption "" output_fn]
1264 ++ optFlag
1265 ++ map SysTools.Option lo_opts)
1266
1267 return (LlvmLlc, output_fn)
1268 where
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"]
1272
1273
1274 -----------------------------------------------------------------------------
1275 -- LlvmLlc phase
1276
1277 runPhase LlvmLlc input_fn dflags
1278 = do
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
1283 #else
1284 let nphase = As
1285 #endif
1286 let rmodel | opt_PIC = "pic"
1287 | not opt_Static = "dynamic-no-pic"
1288 | otherwise = "static"
1289
1290 output_fn <- phaseOutputFilename nphase
1291
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)
1298
1299 return (nphase, output_fn)
1300 where
1301 #if darwin_TARGET_OS
1302 llvmOpts = ["-O1", "-O2", "-O2"]
1303 #else
1304 llvmOpts = ["-O1", "-O2", "-O3"]
1305 #endif
1306
1307
1308 -----------------------------------------------------------------------------
1309 -- LlvmMangle phase
1310
1311 runPhase LlvmMangle input_fn _dflags
1312 = do
1313 output_fn <- phaseOutputFilename As
1314 io $ llvmFixupAsm input_fn output_fn
1315 return (As, output_fn)
1316
1317 -----------------------------------------------------------------------------
1318 -- merge in stub objects
1319
1320 runPhase MergeStub input_fn dflags
1321 = do
1322 PipeState{maybe_stub_o} <- getPipeState
1323 output_fn <- phaseOutputFilename StopLn
1324 case maybe_stub_o of
1325 Nothing ->
1326 panic "runPhase(MergeStub): no stub"
1327 Just stub_o -> do
1328 io $ joinObjectFiles dflags [input_fn, stub_o] output_fn
1329 return (StopLn, output_fn)
1330
1331 -- warning suppression
1332 runPhase other _input_fn _dflags =
1333 panic ("runPhase: don't know how to run phase " ++ show other)
1334
1335 maybeMergeStub :: CompPipeline Phase
1336 maybeMergeStub
1337 = do
1338 PipeState{maybe_stub_o} <- getPipeState
1339 if isJust maybe_stub_o then return MergeStub else return StopLn
1340
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
1351
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"
1360 let
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)
1369 return True
1370 | otherwise = return True
1371
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
1380 ([Option "-c",
1381 FileOption "" cFile,
1382 Option "-o",
1383 FileOption "" oFile] ++
1384 map (FileOption "-I") (includeDirs rtsDetails) ++
1385 map Option md_c_flags)
1386 return oFile
1387
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 = "
1395 ++ val ++ ";"]
1396 return [fn]
1397 case rtsOptsEnabled dflags of
1398 RtsOptsNone -> mkRtsEnabledObj "rtsOptsNone"
1399 RtsOptsSafeOnly -> return [] -- The default
1400 RtsOptsAll -> mkRtsEnabledObj "rtsOptsAll"
1401
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 $
1405 [
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 !!!!",
1412 "#",
1413 "$pvm_executable = '" ++ pvm_executable ++ "';",
1414 "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
1415 "$SysMan = '" ++ sysMan ++ "';",
1416 "",
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",
1424 "}", -}
1425 "",
1426 "# Now, run the real binary; process the args first",
1427 "$ENV{'PE'} = $pvm_executable_base;", -- ++ pvm_executable_base,
1428 "$debug = '';",
1429 "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
1430 "@nonPVM_args = ();",
1431 "$in_RTS_args = 0;",
1432 "",
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;",
1438 " }",
1439 " if ( $a eq '-d' && $in_RTS_args ) {",
1440 " $debug = '-';",
1441 " } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
1442 " $nprocessors = $1;",
1443 " } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
1444 " $nprocessors = $1;",
1445 " } else {",
1446 " push(@nonPVM_args, $a);",
1447 " }",
1448 "}",
1449 "",
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);"
1457 ]
1458
1459 -----------------------------------------------------------------------------
1460 -- Look for the /* GHC_PACKAGES ... */ comment at the top of a .hc file
1461
1462 getHCFilePackages :: FilePath -> IO [PackageId]
1463 getHCFilePackages filename =
1464 Exception.bracket (openFile filename ReadMode) hClose $ \h -> do
1465 l <- hGetLine h
1466 case l of
1467 '/':'*':' ':'G':'H':'C':'_':'P':'A':'C':'K':'A':'G':'E':'S':rest ->
1468 return (map stringToPackageId (words rest))
1469 _other ->
1470 return []
1471
1472 -----------------------------------------------------------------------------
1473 -- Static linking, of .o files
1474
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.
1479 --
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
1483 -- the packages.
1484
1485 linkBinary :: DynFlags -> [FilePath] -> [PackageId] -> IO ()
1486 linkBinary dflags o_files dep_packages = do
1487 let verb = getVerbFlag dflags
1488 output_fn = exeFileName dflags
1489
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.
1493
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]
1499 #else
1500 get_pkg_lib_path_opts l = ["-L" ++ l]
1501 #endif
1502
1503 let lib_paths = libraryPaths dflags
1504 let lib_path_opts = map ("-L"++) lib_paths
1505
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
1514 Just opts ->
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 ++ ";"]
1519 return [fn]
1520 Nothing -> return []
1521
1522 pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1523
1524 #ifdef darwin_TARGET_OS
1525 pkg_framework_paths <- getPackageFrameworkPath dflags dep_packages
1526 let pkg_framework_path_opts = map ("-F"++) pkg_framework_paths
1527
1528 let framework_paths = frameworkPaths dflags
1529 framework_path_opts = map ("-F"++) framework_paths
1530
1531 pkg_frameworks <- getPackageFrameworks dflags dep_packages
1532 let pkg_framework_opts = concat [ ["-framework", fw] | fw <- pkg_frameworks ]
1533
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
1537 #endif
1538 -- probably _stub.o files
1539 extra_ld_inputs <- readIORef v_Ld_inputs
1540
1541 -- opts from -optl-<blah> (including -l<blah> options)
1542 let extra_ld_opts = getOpts dflags opt_l
1543
1544 let ways = wayNames dflags
1545
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.
1549 let
1550 debug_opts | WayDebug `elem` ways = [
1551 #if defined(HAVE_LIBBFD)
1552 "-lbfd", "-liberty"
1553 #endif
1554 ]
1555 | otherwise = []
1556
1557 let
1558 thread_opts | WayThreaded `elem` ways = [
1559 #if !defined(mingw32_TARGET_OS) && !defined(freebsd_TARGET_OS) && !defined(openbsd_TARGET_OS) && !defined(haiku_TARGET_OS)
1560 "-lpthread"
1561 #endif
1562 #if defined(osf3_TARGET_OS)
1563 , "-lexc"
1564 #endif
1565 ]
1566 | otherwise = []
1567
1568 rc_objs <- maybeCreateManifest dflags output_fn
1569
1570 let md_c_flags = machdepCCOpts dflags
1571 SysTools.runLink dflags (
1572 [ SysTools.Option verb
1573 , SysTools.Option "-o"
1574 , SysTools.FileOption "" output_fn
1575 ]
1576 ++ map SysTools.Option (
1577 md_c_flags
1578
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"]
1583 #endif
1584 ++ o_files
1585 ++ extra_ld_inputs
1586 ++ lib_path_opts
1587 ++ extra_ld_opts
1588 ++ rc_objs
1589 #ifdef darwin_TARGET_OS
1590 ++ framework_path_opts
1591 ++ framework_opts
1592 #endif
1593 ++ pkg_lib_path_opts
1594 ++ main_lib
1595 ++ rtsEnabledObj
1596 ++ rtsOptsObj
1597 ++ pkg_link_opts
1598 #ifdef darwin_TARGET_OS
1599 ++ pkg_framework_path_opts
1600 ++ pkg_framework_opts
1601 #endif
1602 ++ debug_opts
1603 ++ thread_opts
1604 ))
1605
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"))
1610
1611
1612 exeFileName :: DynFlags -> FilePath
1613 exeFileName dflags
1614 | Just s <- outputFile dflags =
1615 #if defined(mingw32_HOST_OS)
1616 if null (takeExtension s)
1617 then s <.> "exe"
1618 else s
1619 #else
1620 s
1621 #endif
1622 | otherwise =
1623 #if defined(mingw32_HOST_OS)
1624 "main.exe"
1625 #else
1626 "a.out"
1627 #endif
1628
1629 maybeCreateManifest
1630 :: DynFlags
1631 -> FilePath -- filename of executable
1632 -> IO [FilePath] -- extra objects to embed, maybe
1633 #ifndef mingw32_TARGET_OS
1634 maybeCreateManifest _ _ = do
1635 return []
1636 #else
1637 maybeCreateManifest dflags exe_filename = do
1638 if not (dopt Opt_GenManifest dflags) then return [] else do
1639
1640 let manifest_filename = exe_filename <.> "manifest"
1641
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"++
1650 " <security>\n"++
1651 " <requestedPrivileges>\n"++
1652 " <requestedExecutionLevel level=\"asInvoker\" uiAccess=\"false\"/>\n"++
1653 " </requestedPrivileges>\n"++
1654 " </security>\n"++
1655 " </trustInfo>\n"++
1656 "</assembly>\n"
1657
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
1662
1663 rc_filename <- newTempName dflags "rc"
1664 rc_obj_filename <- newTempName dflags (objectSuf dflags)
1665
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.
1671
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"]
1677 ++ wr_opts
1678 -- no FileOptions here: windres doesn't like seeing
1679 -- backslashes, apparently
1680
1681 removeFile manifest_filename
1682
1683 return [rc_obj_filename]
1684 #endif
1685
1686
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
1691
1692 pkgs <- getPreloadPackagesAnd dflags dep_packages
1693
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]
1699 #else
1700 get_pkg_lib_path_opts l = ["-L" ++ l]
1701 #endif
1702
1703 let lib_paths = libraryPaths dflags
1704 let lib_path_opts = map ("-L"++) lib_paths
1705
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
1715 #else
1716 let pkgs_no_rts = pkgs
1717 #endif
1718 let pkg_link_opts = collectLinkOpts dflags pkgs_no_rts
1719
1720 -- probably _stub.o files
1721 extra_ld_inputs <- readIORef v_Ld_inputs
1722
1723 let md_c_flags = machdepCCOpts dflags
1724 let extra_ld_opts = getOpts dflags opt_l
1725
1726 rtsEnabledObj <- mkRtsOptionsLevelObj dflags
1727
1728 #if defined(mingw32_HOST_OS)
1729 -----------------------------------------------------------------------------
1730 -- Making a DLL
1731 -----------------------------------------------------------------------------
1732 let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
1733
1734 SysTools.runLink dflags
1735 ([ SysTools.Option verb
1736 , SysTools.Option "-o"
1737 , SysTools.FileOption "" output_fn
1738 , SysTools.Option "-shared"
1739 ] ++
1740 [ SysTools.FileOption "-Wl,--out-implib=" (output_fn ++ ".a")
1741 | dopt Opt_SharedImplib dflags
1742 ]
1743 ++ map (SysTools.FileOption "") o_files
1744 ++ map SysTools.Option (
1745 md_c_flags
1746
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"]
1750
1751 ++ extra_ld_inputs
1752 ++ lib_path_opts
1753 ++ extra_ld_opts
1754 ++ pkg_lib_path_opts
1755 ++ rtsEnabledObj
1756 ++ pkg_link_opts
1757 ))
1758 #elif defined(darwin_TARGET_OS)
1759 -----------------------------------------------------------------------------
1760 -- Making a darwin dylib
1761 -----------------------------------------------------------------------------
1762 -- About the options used for Darwin:
1763 -- -dynamiclib
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.
1773 -- -single_module
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).
1777 -- -install_name
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.
1784 -- Cabal does this.
1785 -----------------------------------------------------------------------------
1786
1787 let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
1788
1789 instName <- case dylibInstallName dflags of
1790 Just n -> return n
1791 Nothing -> do
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
1799 ]
1800 ++ map SysTools.Option (
1801 md_c_flags
1802 ++ o_files
1803 ++ [ "-undefined", "dynamic_lookup", "-single_module",
1804 #if !defined(x86_64_TARGET_ARCH)
1805 "-Wl,-read_only_relocs,suppress",
1806 #endif
1807 "-install_name", instName ]
1808 ++ extra_ld_inputs
1809 ++ lib_path_opts
1810 ++ extra_ld_opts
1811 ++ pkg_lib_path_opts
1812 ++ rtsEnabledObj
1813 ++ pkg_link_opts
1814 ))
1815 #else
1816 -----------------------------------------------------------------------------
1817 -- Making a DSO
1818 -----------------------------------------------------------------------------
1819
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
1824 -- hooks in the RTS
1825 []
1826 else -- we need symbolic linking to resolve
1827 -- non-PIC intra-package-relocations
1828 ["-Wl,-Bsymbolic"]
1829
1830 SysTools.runLink dflags
1831 ([ SysTools.Option verb
1832 , SysTools.Option "-o"
1833 , SysTools.FileOption "" output_fn
1834 ]
1835 ++ map SysTools.Option (
1836 md_c_flags
1837 ++ o_files
1838 ++ [ "-shared" ]
1839 ++ bsymbolicFlag
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 ]
1843 ++ extra_ld_inputs
1844 ++ lib_path_opts
1845 ++ extra_ld_opts
1846 ++ pkg_lib_path_opts
1847 ++ rtsEnabledObj
1848 ++ pkg_link_opts
1849 ))
1850 #endif
1851 -- -----------------------------------------------------------------------------
1852 -- Running CPP
1853
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
1858
1859 pkg_include_dirs <- getPackageIncludePath dflags []
1860 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
1861 (cmdline_include_paths ++ pkg_include_dirs)
1862
1863 let verb = getVerbFlag dflags
1864
1865 let cc_opts
1866 | not include_cc_opts = []
1867 | otherwise = (optc ++ md_c_flags)
1868 where
1869 optc = getOpts dflags opt_c
1870 md_c_flags = machdepCCOpts dflags
1871
1872 let cpp_prog args | raw = SysTools.runCpp dflags args
1873 | otherwise = SysTools.runCc dflags (SysTools.Option "-E" : args)
1874
1875 let target_defs =
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.
1882
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
1902 ])
1903
1904 hsSourceCppOpts :: [String]
1905 -- Default CPP defines in Haskell source
1906 hsSourceCppOpts =
1907 [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
1908
1909 -- ---------------------------------------------------------------------------
1910 -- join object files into a single relocatable object file, using ld -r
1911
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
1922 ++ args)
1923 ld_x_flag | null cLD_X = ""
1924 | otherwise = "-Wl,-x"
1925
1926 md_c_flags = machdepCCOpts dflags
1927
1928 if cLdIsGNULd == "YES"
1929 then do
1930 script <- newTempName dflags "ldscript"
1931 writeFile script $ "INPUT(" ++ unwords o_files ++ ")"
1932 ld_r [SysTools.FileOption "" script]
1933 else do
1934 ld_r (map (SysTools.FileOption "") o_files)
1935
1936 -- -----------------------------------------------------------------------------
1937 -- Misc.
1938
1939 hscNextPhase :: DynFlags -> HscSource -> HscTarget -> Phase
1940 hscNextPhase _ HsBootFile _ = StopLn
1941 hscNextPhase dflags _ hsc_lang =
1942 case hsc_lang of
1943 HscC -> HCc
1944 HscAsm | dopt Opt_SplitObjs dflags -> SplitMangle
1945 | otherwise -> As
1946 HscLlvm -> LlvmOpt
1947 HscNothing -> StopLn
1948 HscInterpreted -> StopLn
1949 _other -> StopLn
1950