default to using @note for saving the linker opts (someone mentioned
[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 import Platform
55
56 import Exception
57 import Data.IORef ( readIORef )
58 import System.Directory
59 import System.FilePath
60 import System.IO
61 import Control.Monad
62 import Data.List ( isSuffixOf )
63 import Data.Maybe
64 import System.Environment
65 import Data.Char
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 -> SourceModified
105 -> IO HomeModInfo -- ^ the complete HomeModInfo, if successful
106
107 compile = compile' (hscCompileNothing, hscCompileInteractive, hscCompileBatch)
108
109 compile' ::
110 (Compiler (HscStatus, ModIface, ModDetails),
111 Compiler (InteractiveStatus, ModIface, ModDetails),
112 Compiler (HscStatus, ModIface, ModDetails))
113 -> HscEnv
114 -> ModSummary -- ^ summary for module being compiled
115 -> Int -- ^ module N ...
116 -> Int -- ^ ... of M
117 -> Maybe ModIface -- ^ old interface, if we have one
118 -> Maybe Linkable -- ^ old linkable, if we have one
119 -> SourceModified
120 -> IO HomeModInfo -- ^ the complete HomeModInfo, if successful
121
122 compile' (nothingCompiler, interactiveCompiler, batchCompiler)
123 hsc_env0 summary mod_index nmods mb_old_iface maybe_old_linkable
124 source_modified0
125 = do
126 let dflags0 = ms_hspp_opts summary
127 this_mod = ms_mod summary
128 src_flavour = ms_hsc_src summary
129 location = ms_location summary
130 input_fn = expectJust "compile:hs" (ml_hs_file location)
131 input_fnpp = ms_hspp_file summary
132
133 debugTraceMsg dflags0 2 (text "compile: input file" <+> text input_fnpp)
134
135 let basename = dropExtension input_fn
136
137 -- We add the directory in which the .hs files resides) to the import path.
138 -- This is needed when we try to compile the .hc file later, if it
139 -- imports a _stub.h file that we created here.
140 let current_dir = case takeDirectory basename of
141 "" -> "." -- XXX Hack
142 d -> d
143 old_paths = includePaths dflags0
144 dflags = dflags0 { includePaths = current_dir : old_paths }
145 hsc_env = hsc_env0 {hsc_dflags = dflags}
146
147 -- Figure out what lang we're generating
148 let hsc_lang = hscTarget dflags
149 -- ... and what the next phase should be
150 let next_phase = hscNextPhase dflags src_flavour hsc_lang
151 -- ... and what file to generate the output into
152 output_fn <- getOutputFilename next_phase
153 Temporary basename dflags next_phase (Just location)
154
155 let dflags' = dflags { hscTarget = hsc_lang,
156 hscOutName = output_fn,
157 extCoreName = basename ++ ".hcr" }
158 let hsc_env' = hsc_env { hsc_dflags = dflags' }
159
160 -- -fforce-recomp should also work with --make
161 let force_recomp = dopt Opt_ForceRecomp dflags
162 source_modified
163 | force_recomp || isNothing maybe_old_linkable = SourceModified
164 | otherwise = source_modified0
165 object_filename = ml_obj_file location
166
167 let handleBatch HscNoRecomp
168 = ASSERT (isJust maybe_old_linkable)
169 return maybe_old_linkable
170
171 handleBatch (HscRecomp hasStub _)
172 | isHsBoot src_flavour
173 = do when (isObjectTarget hsc_lang) $ -- interpreted reaches here too
174 liftIO $ SysTools.touch dflags' "Touching object file"
175 object_filename
176 return maybe_old_linkable
177
178 | otherwise
179 = do (hs_unlinked, unlinked_time) <-
180 case hsc_lang of
181 HscNothing ->
182 return ([], ms_hs_date summary)
183 -- We're in --make mode: finish the compilation pipeline.
184 _other -> do
185 maybe_stub_o <- case hasStub of
186 Nothing -> return Nothing
187 Just stub_c -> do
188 stub_o <- compileStub hsc_env' stub_c
189 return (Just stub_o)
190 _ <- runPipeline StopLn hsc_env' (output_fn,Nothing)
191 (Just basename)
192 Persistent
193 (Just location)
194 maybe_stub_o
195 -- The object filename comes from the ModLocation
196 o_time <- getModificationTime object_filename
197 return ([DotO object_filename], o_time)
198
199 let linkable = LM unlinked_time this_mod hs_unlinked
200 return (Just linkable)
201
202 handleInterpreted HscNoRecomp
203 = ASSERT (isJust maybe_old_linkable)
204 return maybe_old_linkable
205 handleInterpreted (HscRecomp _hasStub Nothing)
206 = ASSERT (isHsBoot src_flavour)
207 return maybe_old_linkable
208 handleInterpreted (HscRecomp hasStub (Just (comp_bc, modBreaks)))
209 = do stub_o <- case hasStub of
210 Nothing -> return []
211 Just stub_c -> do
212 stub_o <- compileStub hsc_env' stub_c
213 return [DotO stub_o]
214
215 let hs_unlinked = [BCOs comp_bc modBreaks]
216 unlinked_time = ms_hs_date summary
217 -- Why do we use the timestamp of the source file here,
218 -- rather than the current time? This works better in
219 -- the case where the local clock is out of sync
220 -- with the filesystem's clock. It's just as accurate:
221 -- if the source is modified, then the linkable will
222 -- be out of date.
223 let linkable = LM unlinked_time this_mod
224 (hs_unlinked ++ stub_o)
225 return (Just linkable)
226
227 let -- runCompiler :: Compiler result -> (result -> Maybe Linkable)
228 -- -> m HomeModInfo
229 runCompiler compiler handle
230 = do (result, iface, details)
231 <- compiler hsc_env' summary source_modified mb_old_iface
232 (Just (mod_index, nmods))
233 linkable <- handle result
234 return (HomeModInfo{ hm_details = details,
235 hm_iface = iface,
236 hm_linkable = linkable })
237 -- run the compiler
238 case hsc_lang of
239 HscInterpreted -> runCompiler interactiveCompiler handleInterpreted
240 HscNothing -> runCompiler nothingCompiler handleBatch
241 _other -> runCompiler batchCompiler handleBatch
242
243 -----------------------------------------------------------------------------
244 -- stub .h and .c files (for foreign export support)
245
246 -- The _stub.c file is derived from the haskell source file, possibly taking
247 -- into account the -stubdir option.
248 --
249 -- The object file created by compiling the _stub.c file is put into a
250 -- temporary file, which will be later combined with the main .o file
251 -- (see the MergeStubs phase).
252
253 compileStub :: HscEnv -> FilePath -> IO FilePath
254 compileStub hsc_env stub_c = do
255 (_, stub_o) <- runPipeline StopLn hsc_env (stub_c,Nothing) Nothing
256 Temporary Nothing{-no ModLocation-} Nothing
257
258 return stub_o
259
260 -- ---------------------------------------------------------------------------
261 -- Link
262
263 link :: GhcLink -- interactive or batch
264 -> DynFlags -- dynamic flags
265 -> Bool -- attempt linking in batch mode?
266 -> HomePackageTable -- what to link
267 -> IO SuccessFlag
268
269 -- For the moment, in the batch linker, we don't bother to tell doLink
270 -- which packages to link -- it just tries all that are available.
271 -- batch_attempt_linking should only be *looked at* in batch mode. It
272 -- should only be True if the upsweep was successful and someone
273 -- exports main, i.e., we have good reason to believe that linking
274 -- will succeed.
275
276 link LinkInMemory _ _ _
277 = if cGhcWithInterpreter == "YES"
278 then -- Not Linking...(demand linker will do the job)
279 return Succeeded
280 else panicBadLink LinkInMemory
281
282 link NoLink _ _ _
283 = return Succeeded
284
285 link LinkBinary dflags batch_attempt_linking hpt
286 = link' dflags batch_attempt_linking hpt
287
288 link LinkDynLib dflags batch_attempt_linking hpt
289 = link' dflags batch_attempt_linking hpt
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 (map fst . 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 checkLinkInfo dflags pkg_deps exe_file
387
388 -- Returns 'False' if it was, and we can avoid linking, because the
389 -- previous binary was linked with "the same options".
390 checkLinkInfo :: DynFlags -> [PackageId] -> FilePath -> IO Bool
391 checkLinkInfo dflags pkg_deps exe_file
392 | not (platformSupportsSavingLinkOpts (platformOS (targetPlatform dflags)))
393 -- ToDo: Windows and OS X do not use the ELF binary format, so
394 -- readelf does not work there. We need to find another way to do
395 -- this.
396 = return False -- conservatively we should return True, but not
397 -- linking in this case was the behaviour for a long
398 -- time so we leave it as-is.
399 | otherwise
400 = do
401 link_info <- getLinkInfo dflags pkg_deps
402 debugTraceMsg dflags 3 $ text ("Link info: " ++ link_info)
403 m_exe_link_info <- readElfSection dflags ghcLinkInfoSectionName exe_file
404 debugTraceMsg dflags 3 $ text ("Exe link info: " ++ show m_exe_link_info)
405 return (Just link_info /= m_exe_link_info)
406
407 platformSupportsSavingLinkOpts :: OS -> Bool
408 platformSupportsSavingLinkOpts os
409 | os == OSSolaris2 = False -- see #5382
410 | otherwise = osElfTarget os
411
412 ghcLinkInfoSectionName :: String
413 ghcLinkInfoSectionName = ".debug-ghc-link-info"
414 -- if we use the ".debug" prefix, then strip will strip it by default
415
416 findHSLib :: [String] -> String -> IO (Maybe FilePath)
417 findHSLib dirs lib = do
418 let batch_lib_file = "lib" ++ lib <.> "a"
419 found <- filterM doesFileExist (map (</> batch_lib_file) dirs)
420 case found of
421 [] -> return Nothing
422 (x:_) -> return (Just x)
423
424 -- -----------------------------------------------------------------------------
425 -- Compile files in one-shot mode.
426
427 oneShot :: HscEnv -> Phase -> [(String, Maybe Phase)] -> IO ()
428 oneShot hsc_env stop_phase srcs = do
429 o_files <- mapM (compileFile hsc_env stop_phase) srcs
430 doLink (hsc_dflags hsc_env) stop_phase o_files
431
432 compileFile :: HscEnv -> Phase -> (FilePath, Maybe Phase) -> IO FilePath
433 compileFile hsc_env stop_phase (src, mb_phase) = do
434 exists <- doesFileExist src
435 when (not exists) $
436 ghcError (CmdLineError ("does not exist: " ++ src))
437
438 let
439 dflags = hsc_dflags hsc_env
440 split = dopt Opt_SplitObjs dflags
441 mb_o_file = outputFile dflags
442 ghc_link = ghcLink dflags -- Set by -c or -no-link
443
444 -- When linking, the -o argument refers to the linker's output.
445 -- otherwise, we use it as the name for the pipeline's output.
446 output
447 | StopLn <- stop_phase, not (isNoLink ghc_link) = Persistent
448 -- -o foo applies to linker
449 | Just o_file <- mb_o_file = SpecificFile o_file
450 -- -o foo applies to the file we are compiling now
451 | otherwise = Persistent
452
453 stop_phase' = case stop_phase of
454 As | split -> SplitAs
455 _ -> stop_phase
456
457 ( _, out_file) <- runPipeline stop_phase' hsc_env
458 (src, mb_phase) Nothing output
459 Nothing{-no ModLocation-} Nothing
460 return out_file
461
462
463 doLink :: DynFlags -> Phase -> [FilePath] -> IO ()
464 doLink dflags stop_phase o_files
465 | not (isStopLn stop_phase)
466 = return () -- We stopped before the linking phase
467
468 | otherwise
469 = case ghcLink dflags of
470 NoLink -> return ()
471 LinkBinary -> linkBinary dflags o_files []
472 LinkDynLib -> linkDynLib dflags o_files []
473 other -> panicBadLink other
474
475
476 -- ---------------------------------------------------------------------------
477
478 data PipelineOutput
479 = Temporary
480 -- ^ Output should be to a temporary file: we're going to
481 -- run more compilation steps on this output later.
482 | Persistent
483 -- ^ We want a persistent file, i.e. a file in the current directory
484 -- derived from the input filename, but with the appropriate extension.
485 -- eg. in "ghc -c Foo.hs" the output goes into ./Foo.o.
486 | SpecificFile FilePath
487 -- ^ The output must go into the specified file.
488
489 -- | Run a compilation pipeline, consisting of multiple phases.
490 --
491 -- This is the interface to the compilation pipeline, which runs
492 -- a series of compilation steps on a single source file, specifying
493 -- at which stage to stop.
494 --
495 -- The DynFlags can be modified by phases in the pipeline (eg. by
496 -- OPTIONS_GHC pragmas), and the changes affect later phases in the
497 -- pipeline.
498 runPipeline
499 :: Phase -- ^ When to stop
500 -> HscEnv -- ^ Compilation environment
501 -> (FilePath,Maybe Phase) -- ^ Input filename (and maybe -x suffix)
502 -> Maybe FilePath -- ^ original basename (if different from ^^^)
503 -> PipelineOutput -- ^ Output filename
504 -> Maybe ModLocation -- ^ A ModLocation, if this is a Haskell module
505 -> Maybe FilePath -- ^ stub object, if we have one
506 -> IO (DynFlags, FilePath) -- ^ (final flags, output filename)
507
508 runPipeline stop_phase hsc_env0 (input_fn, mb_phase)
509 mb_basename output maybe_loc maybe_stub_o
510 = do
511 let dflags0 = hsc_dflags hsc_env0
512 (input_basename, suffix) = splitExtension input_fn
513 suffix' = drop 1 suffix -- strip off the .
514 basename | Just b <- mb_basename = b
515 | otherwise = input_basename
516
517 -- Decide where dump files should go based on the pipeline output
518 dflags = dflags0 { dumpPrefix = Just (basename ++ ".") }
519 hsc_env = hsc_env0 {hsc_dflags = dflags}
520
521 -- If we were given a -x flag, then use that phase to start from
522 start_phase = fromMaybe (startPhase suffix') mb_phase
523
524 -- We want to catch cases of "you can't get there from here" before
525 -- we start the pipeline, because otherwise it will just run off the
526 -- end.
527 --
528 -- There is a partial ordering on phases, where A < B iff A occurs
529 -- before B in a normal compilation pipeline.
530
531 when (not (start_phase `happensBefore` stop_phase)) $
532 ghcError (UsageError
533 ("cannot compile this file to desired target: "
534 ++ input_fn))
535
536 -- this is a function which will be used to calculate output file names
537 -- as we go along (we partially apply it to some of its inputs here)
538 let get_output_fn = getOutputFilename stop_phase output basename
539
540 -- Execute the pipeline...
541 let env = PipeEnv{ stop_phase,
542 src_basename = basename,
543 src_suffix = suffix',
544 output_spec = output }
545
546 state = PipeState{ hsc_env, maybe_loc, maybe_stub_o = maybe_stub_o }
547
548 (state', output_fn) <- unP (pipeLoop start_phase input_fn) env state
549
550 let PipeState{ hsc_env=hsc_env', maybe_loc } = state'
551 dflags' = hsc_dflags hsc_env'
552
553 -- Sometimes, a compilation phase doesn't actually generate any output
554 -- (eg. the CPP phase when -fcpp is not turned on). If we end on this
555 -- stage, but we wanted to keep the output, then we have to explicitly
556 -- copy the file, remembering to prepend a {-# LINE #-} pragma so that
557 -- further compilation stages can tell what the original filename was.
558 case output of
559 Temporary ->
560 return (dflags', output_fn)
561 _other ->
562 do final_fn <- get_output_fn dflags' stop_phase maybe_loc
563 when (final_fn /= output_fn) $ do
564 let msg = ("Copying `" ++ output_fn ++"' to `" ++ final_fn ++ "'")
565 line_prag = Just ("{-# LINE 1 \"" ++ input_fn ++ "\" #-}\n")
566 copyWithHeader dflags msg line_prag output_fn final_fn
567 return (dflags', final_fn)
568
569 -- -----------------------------------------------------------------------------
570 -- The pipeline uses a monad to carry around various bits of information
571
572 -- PipeEnv: invariant information passed down
573 data PipeEnv = PipeEnv {
574 stop_phase :: Phase, -- ^ Stop just before this phase
575 src_basename :: String, -- ^ basename of original input source
576 src_suffix :: String, -- ^ its extension
577 output_spec :: PipelineOutput -- ^ says where to put the pipeline output
578 }
579
580 -- PipeState: information that might change during a pipeline run
581 data PipeState = PipeState {
582 hsc_env :: HscEnv,
583 -- ^ only the DynFlags change in the HscEnv. The DynFlags change
584 -- at various points, for example when we read the OPTIONS_GHC
585 -- pragmas in the Cpp phase.
586 maybe_loc :: Maybe ModLocation,
587 -- ^ the ModLocation. This is discovered during compilation,
588 -- in the Hsc phase where we read the module header.
589 maybe_stub_o :: Maybe FilePath
590 -- ^ the stub object. This is set by the Hsc phase if a stub
591 -- object was created. The stub object will be joined with
592 -- the main compilation object using "ld -r" at the end.
593 }
594
595 getPipeEnv :: CompPipeline PipeEnv
596 getPipeEnv = P $ \env state -> return (state, env)
597
598 getPipeState :: CompPipeline PipeState
599 getPipeState = P $ \_env state -> return (state, state)
600
601 getDynFlags :: CompPipeline DynFlags
602 getDynFlags = P $ \_env state -> return (state, hsc_dflags (hsc_env state))
603
604 setDynFlags :: DynFlags -> CompPipeline ()
605 setDynFlags dflags = P $ \_env state ->
606 return (state{hsc_env= (hsc_env state){ hsc_dflags = dflags }}, ())
607
608 setModLocation :: ModLocation -> CompPipeline ()
609 setModLocation loc = P $ \_env state ->
610 return (state{ maybe_loc = Just loc }, ())
611
612 setStubO :: FilePath -> CompPipeline ()
613 setStubO stub_o = P $ \_env state ->
614 return (state{ maybe_stub_o = Just stub_o }, ())
615
616 newtype CompPipeline a = P { unP :: PipeEnv -> PipeState -> IO (PipeState, a) }
617
618 instance Monad CompPipeline where
619 return a = P $ \_env state -> return (state, a)
620 P m >>= k = P $ \env state -> do (state',a) <- m env state
621 unP (k a) env state'
622
623 io :: IO a -> CompPipeline a
624 io m = P $ \_env state -> do a <- m; return (state, a)
625
626 phaseOutputFilename :: Phase{-next phase-} -> CompPipeline FilePath
627 phaseOutputFilename next_phase = do
628 PipeEnv{stop_phase, src_basename, output_spec} <- getPipeEnv
629 PipeState{maybe_loc, hsc_env} <- getPipeState
630 let dflags = hsc_dflags hsc_env
631 io $ getOutputFilename stop_phase output_spec
632 src_basename dflags next_phase maybe_loc
633
634 -- ---------------------------------------------------------------------------
635 -- outer pipeline loop
636
637 -- | pipeLoop runs phases until we reach the stop phase
638 pipeLoop :: Phase -> FilePath -> CompPipeline FilePath
639 pipeLoop phase input_fn = do
640 PipeEnv{stop_phase} <- getPipeEnv
641 PipeState{hsc_env} <- getPipeState
642 case () of
643 _ | phase `eqPhase` stop_phase -- All done
644 -> return input_fn
645
646 | not (phase `happensBefore` stop_phase)
647 -- Something has gone wrong. We'll try to cover all the cases when
648 -- this could happen, so if we reach here it is a panic.
649 -- eg. it might happen if the -C flag is used on a source file that
650 -- has {-# OPTIONS -fasm #-}.
651 -> panic ("pipeLoop: at phase " ++ show phase ++
652 " but I wanted to stop at phase " ++ show stop_phase)
653
654 | otherwise
655 -> do io $ debugTraceMsg (hsc_dflags hsc_env) 4
656 (ptext (sLit "Running phase") <+> ppr phase)
657 dflags <- getDynFlags
658 (next_phase, output_fn) <- runPhase phase input_fn dflags
659 pipeLoop next_phase output_fn
660
661 -- -----------------------------------------------------------------------------
662 -- In each phase, we need to know into what filename to generate the
663 -- output. All the logic about which filenames we generate output
664 -- into is embodied in the following function.
665
666 getOutputFilename
667 :: Phase -> PipelineOutput -> String
668 -> DynFlags -> Phase{-next phase-} -> Maybe ModLocation -> IO FilePath
669 getOutputFilename stop_phase output basename
670 = func
671 where
672 func dflags next_phase maybe_location
673 | is_last_phase, Persistent <- output = persistent_fn
674 | is_last_phase, SpecificFile f <- output = return f
675 | keep_this_output = persistent_fn
676 | otherwise = newTempName dflags suffix
677 where
678 hcsuf = hcSuf dflags
679 odir = objectDir dflags
680 osuf = objectSuf dflags
681 keep_hc = dopt Opt_KeepHcFiles dflags
682 keep_s = dopt Opt_KeepSFiles dflags
683 keep_bc = dopt Opt_KeepLlvmFiles dflags
684
685 myPhaseInputExt HCc = hcsuf
686 myPhaseInputExt MergeStub = osuf
687 myPhaseInputExt StopLn = osuf
688 myPhaseInputExt other = phaseInputExt other
689
690 is_last_phase = next_phase `eqPhase` stop_phase
691
692 -- sometimes, we keep output from intermediate stages
693 keep_this_output =
694 case next_phase of
695 As | keep_s -> True
696 LlvmOpt | keep_bc -> True
697 HCc | keep_hc -> True
698 _other -> False
699
700 suffix = myPhaseInputExt next_phase
701
702 -- persistent object files get put in odir
703 persistent_fn
704 | StopLn <- next_phase = return odir_persistent
705 | otherwise = return persistent
706
707 persistent = basename <.> suffix
708
709 odir_persistent
710 | Just loc <- maybe_location = ml_obj_file loc
711 | Just d <- odir = d </> persistent
712 | otherwise = persistent
713
714
715 -- -----------------------------------------------------------------------------
716 -- | Each phase in the pipeline returns the next phase to execute, and the
717 -- name of the file in which the output was placed.
718 --
719 -- We must do things dynamically this way, because we often don't know
720 -- what the rest of the phases will be until part-way through the
721 -- compilation: for example, an {-# OPTIONS -fasm #-} at the beginning
722 -- of a source file can change the latter stages of the pipeline from
723 -- taking the via-C route to using the native code generator.
724 --
725 runPhase :: Phase -- ^ Run this phase
726 -> FilePath -- ^ name of the input file
727 -> DynFlags -- ^ for convenience, we pass the current dflags in
728 -> CompPipeline (Phase, -- next phase to run
729 FilePath) -- output filename
730
731 -- Invariant: the output filename always contains the output
732 -- Interesting case: Hsc when there is no recompilation to do
733 -- Then the output filename is still a .o file
734
735
736 -------------------------------------------------------------------------------
737 -- Unlit phase
738
739 runPhase (Unlit sf) input_fn dflags
740 = do
741 output_fn <- phaseOutputFilename (Cpp sf)
742
743 let unlit_flags = getOpts dflags opt_L
744 flags = map SysTools.Option unlit_flags ++
745 [ -- The -h option passes the file name for unlit to
746 -- put in a #line directive
747 SysTools.Option "-h"
748 -- cpp interprets \b etc as escape sequences,
749 -- so we use / for filenames in pragmas
750 , SysTools.Option $ reslash Forwards $ normalise input_fn
751 , SysTools.FileOption "" input_fn
752 , SysTools.FileOption "" output_fn
753 ]
754
755 io $ SysTools.runUnlit dflags flags
756
757 return (Cpp sf, output_fn)
758
759 -------------------------------------------------------------------------------
760 -- Cpp phase : (a) gets OPTIONS out of file
761 -- (b) runs cpp if necessary
762
763 runPhase (Cpp sf) input_fn dflags0
764 = do
765 src_opts <- io $ getOptionsFromFile dflags0 input_fn
766 (dflags1, unhandled_flags, warns)
767 <- io $ parseDynamicFilePragma dflags0 src_opts
768 setDynFlags dflags1
769 io $ checkProcessArgsResult unhandled_flags
770
771 if not (xopt Opt_Cpp dflags1) then do
772 -- we have to be careful to emit warnings only once.
773 unless (dopt Opt_Pp dflags1) $ io $ handleFlagWarnings dflags1 warns
774
775 -- no need to preprocess CPP, just pass input file along
776 -- to the next phase of the pipeline.
777 return (HsPp sf, input_fn)
778 else do
779 output_fn <- phaseOutputFilename (HsPp sf)
780 io $ doCpp dflags1 True{-raw-} False{-no CC opts-} input_fn output_fn
781 -- re-read the pragmas now that we've preprocessed the file
782 -- See #2464,#3457
783 src_opts <- io $ getOptionsFromFile dflags0 output_fn
784 (dflags2, unhandled_flags, warns)
785 <- io $ parseDynamicFilePragma dflags0 src_opts
786 io $ checkProcessArgsResult unhandled_flags
787 unless (dopt Opt_Pp dflags2) $ io $ handleFlagWarnings dflags2 warns
788 -- the HsPp pass below will emit warnings
789
790 setDynFlags dflags2
791
792 return (HsPp sf, output_fn)
793
794 -------------------------------------------------------------------------------
795 -- HsPp phase
796
797 runPhase (HsPp sf) input_fn dflags
798 = do
799 if not (dopt Opt_Pp dflags) then
800 -- no need to preprocess, just pass input file along
801 -- to the next phase of the pipeline.
802 return (Hsc sf, input_fn)
803 else do
804 let hspp_opts = getOpts dflags opt_F
805 PipeEnv{src_basename, src_suffix} <- getPipeEnv
806 let orig_fn = src_basename <.> src_suffix
807 output_fn <- phaseOutputFilename (Hsc sf)
808 io $ SysTools.runPp dflags
809 ( [ SysTools.Option orig_fn
810 , SysTools.Option input_fn
811 , SysTools.FileOption "" output_fn
812 ] ++
813 map SysTools.Option hspp_opts
814 )
815
816 -- re-read pragmas now that we've parsed the file (see #3674)
817 src_opts <- io $ getOptionsFromFile dflags output_fn
818 (dflags1, unhandled_flags, warns)
819 <- io $ parseDynamicFilePragma dflags src_opts
820 setDynFlags dflags1
821 io $ checkProcessArgsResult unhandled_flags
822 io $ handleFlagWarnings dflags1 warns
823
824 return (Hsc sf, output_fn)
825
826 -----------------------------------------------------------------------------
827 -- Hsc phase
828
829 -- Compilation of a single module, in "legacy" mode (_not_ under
830 -- the direction of the compilation manager).
831 runPhase (Hsc src_flavour) input_fn dflags0
832 = do -- normal Hsc mode, not mkdependHS
833
834 PipeEnv{ stop_phase=stop,
835 src_basename=basename,
836 src_suffix=suff } <- getPipeEnv
837
838 -- we add the current directory (i.e. the directory in which
839 -- the .hs files resides) to the include path, since this is
840 -- what gcc does, and it's probably what you want.
841 let current_dir = case takeDirectory basename of
842 "" -> "." -- XXX Hack
843 d -> d
844
845 paths = includePaths dflags0
846 dflags = dflags0 { includePaths = current_dir : paths }
847
848 setDynFlags dflags
849
850 -- gather the imports and module name
851 (hspp_buf,mod_name,imps,src_imps) <- io $
852 case src_flavour of
853 ExtCoreFile -> do -- no explicit imports in ExtCore input.
854 m <- getCoreModuleName input_fn
855 return (Nothing, mkModuleName m, [], [])
856
857 _ -> do
858 buf <- hGetStringBuffer input_fn
859 (src_imps,imps,L _ mod_name) <- getImports dflags buf input_fn (basename <.> suff)
860 return (Just buf, mod_name, imps, src_imps)
861
862 -- Build a ModLocation to pass to hscMain.
863 -- The source filename is rather irrelevant by now, but it's used
864 -- by hscMain for messages. hscMain also needs
865 -- the .hi and .o filenames, and this is as good a way
866 -- as any to generate them, and better than most. (e.g. takes
867 -- into accout the -osuf flags)
868 location1 <- io $ mkHomeModLocation2 dflags mod_name basename suff
869
870 -- Boot-ify it if necessary
871 let location2 | isHsBoot src_flavour = addBootSuffixLocn location1
872 | otherwise = location1
873
874
875 -- Take -ohi into account if present
876 -- This can't be done in mkHomeModuleLocation because
877 -- it only applies to the module being compiles
878 let ohi = outputHi dflags
879 location3 | Just fn <- ohi = location2{ ml_hi_file = fn }
880 | otherwise = location2
881
882 -- Take -o into account if present
883 -- Very like -ohi, but we must *only* do this if we aren't linking
884 -- (If we're linking then the -o applies to the linked thing, not to
885 -- the object file for one module.)
886 -- Note the nasty duplication with the same computation in compileFile above
887 let expl_o_file = outputFile dflags
888 location4 | Just ofile <- expl_o_file
889 , isNoLink (ghcLink dflags)
890 = location3 { ml_obj_file = ofile }
891 | otherwise = location3
892
893 o_file = ml_obj_file location4 -- The real object file
894
895 setModLocation location4
896
897 -- Figure out if the source has changed, for recompilation avoidance.
898 --
899 -- Setting source_unchanged to True means that M.o seems
900 -- to be up to date wrt M.hs; so no need to recompile unless imports have
901 -- changed (which the compiler itself figures out).
902 -- Setting source_unchanged to False tells the compiler that M.o is out of
903 -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
904 src_timestamp <- io $ getModificationTime (basename <.> suff)
905
906 let hsc_lang = hscTarget dflags
907 source_unchanged <- io $
908 if not (isStopLn stop)
909 -- SourceModified unconditionally if
910 -- (a) recompilation checker is off, or
911 -- (b) we aren't going all the way to .o file (e.g. ghc -S)
912 then return SourceModified
913 -- Otherwise look at file modification dates
914 else do o_file_exists <- doesFileExist o_file
915 if not o_file_exists
916 then return SourceModified -- Need to recompile
917 else do t2 <- getModificationTime o_file
918 if t2 > src_timestamp
919 then return SourceUnmodified
920 else return SourceModified
921
922 -- get the DynFlags
923 let next_phase = hscNextPhase dflags src_flavour hsc_lang
924 output_fn <- phaseOutputFilename next_phase
925
926 let dflags' = dflags { hscTarget = hsc_lang,
927 hscOutName = output_fn,
928 extCoreName = basename ++ ".hcr" }
929
930 setDynFlags dflags'
931 PipeState{hsc_env=hsc_env'} <- getPipeState
932
933 -- Tell the finder cache about this module
934 mod <- io $ addHomeModuleToFinder hsc_env' mod_name location4
935
936 -- Make the ModSummary to hand to hscMain
937 let
938 mod_summary = ModSummary { ms_mod = mod,
939 ms_hsc_src = src_flavour,
940 ms_hspp_file = input_fn,
941 ms_hspp_opts = dflags,
942 ms_hspp_buf = hspp_buf,
943 ms_location = location4,
944 ms_hs_date = src_timestamp,
945 ms_obj_date = Nothing,
946 ms_textual_imps = imps,
947 ms_srcimps = src_imps }
948
949 -- run the compiler!
950 result <- io $ hscCompileOneShot hsc_env'
951 mod_summary source_unchanged
952 Nothing -- No iface
953 Nothing -- No "module i of n" progress info
954
955 case result of
956 HscNoRecomp
957 -> do io $ SysTools.touch dflags' "Touching object file" o_file
958 -- The .o file must have a later modification date
959 -- than the source file (else we wouldn't be in HscNoRecomp)
960 -- but we touch it anyway, to keep 'make' happy (we think).
961 return (StopLn, o_file)
962 (HscRecomp hasStub _)
963 -> do case hasStub of
964 Nothing -> return ()
965 Just stub_c ->
966 do stub_o <- io $ compileStub hsc_env' stub_c
967 setStubO stub_o
968 -- In the case of hs-boot files, generate a dummy .o-boot
969 -- stamp file for the benefit of Make
970 when (isHsBoot src_flavour) $
971 io $ SysTools.touch dflags' "Touching object file" o_file
972 return (next_phase, output_fn)
973
974 -----------------------------------------------------------------------------
975 -- Cmm phase
976
977 runPhase CmmCpp input_fn dflags
978 = do
979 output_fn <- phaseOutputFilename Cmm
980 io $ doCpp dflags False{-not raw-} True{-include CC opts-}
981 input_fn output_fn
982 return (Cmm, output_fn)
983
984 runPhase Cmm input_fn dflags
985 = do
986 PipeEnv{src_basename} <- getPipeEnv
987 let hsc_lang = hscTarget dflags
988
989 let next_phase = hscNextPhase dflags HsSrcFile hsc_lang
990
991 output_fn <- phaseOutputFilename next_phase
992
993 let dflags' = dflags { hscTarget = hsc_lang,
994 hscOutName = output_fn,
995 extCoreName = src_basename ++ ".hcr" }
996
997 setDynFlags dflags'
998 PipeState{hsc_env} <- getPipeState
999
1000 io $ hscCompileCmmFile hsc_env input_fn
1001
1002 -- XXX: catch errors above and convert them into ghcError? Original
1003 -- code was:
1004 --
1005 --when (not ok) $ ghcError (PhaseFailed "cmm" (ExitFailure 1))
1006
1007 return (next_phase, output_fn)
1008
1009 -----------------------------------------------------------------------------
1010 -- Cc phase
1011
1012 -- we don't support preprocessing .c files (with -E) now. Doing so introduces
1013 -- way too many hacks, and I can't say I've ever used it anyway.
1014
1015 runPhase cc_phase input_fn dflags
1016 | any (cc_phase `eqPhase`) [Cc, Ccpp, HCc, Cobjc, Cobjcpp]
1017 = do
1018 let cc_opts = getOpts dflags opt_c
1019 hcc = cc_phase `eqPhase` HCc
1020
1021 let cmdline_include_paths = includePaths dflags
1022
1023 -- HC files have the dependent packages stamped into them
1024 pkgs <- if hcc then io $ getHCFilePackages input_fn else return []
1025
1026 -- add package include paths even if we're just compiling .c
1027 -- files; this is the Value Add(TM) that using ghc instead of
1028 -- gcc gives you :)
1029 pkg_include_dirs <- io $ getPackageIncludePath dflags pkgs
1030 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
1031 (cmdline_include_paths ++ pkg_include_dirs)
1032
1033 let gcc_extra_viac_flags = extraGccViaCFlags dflags
1034 let pic_c_flags = picCCOpts dflags
1035
1036 let verbFlags = getVerbFlags dflags
1037
1038 -- cc-options are not passed when compiling .hc files. Our
1039 -- hc code doesn't not #include any header files anyway, so these
1040 -- options aren't necessary.
1041 pkg_extra_cc_opts <- io $
1042 if cc_phase `eqPhase` HCc
1043 then return []
1044 else getPackageExtraCcOpts dflags pkgs
1045
1046 #ifdef darwin_TARGET_OS
1047 pkg_framework_paths <- io $ getPackageFrameworkPath dflags pkgs
1048 let cmdline_framework_paths = frameworkPaths dflags
1049 let framework_paths = map ("-F"++)
1050 (cmdline_framework_paths ++ pkg_framework_paths)
1051 #endif
1052
1053 let split_objs = dopt Opt_SplitObjs dflags
1054 split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
1055 | otherwise = [ ]
1056
1057 let cc_opt | optLevel dflags >= 2 = "-O2"
1058 | otherwise = "-O"
1059
1060 -- Decide next phase
1061
1062 let next_phase = As
1063 output_fn <- phaseOutputFilename next_phase
1064
1065 let
1066 more_hcc_opts =
1067 -- on x86 the floating point regs have greater precision
1068 -- than a double, which leads to unpredictable results.
1069 -- By default, we turn this off with -ffloat-store unless
1070 -- the user specified -fexcess-precision.
1071 (if platformArch (targetPlatform dflags) == ArchX86 &&
1072 not (dopt Opt_ExcessPrecision dflags)
1073 then [ "-ffloat-store" ]
1074 else []) ++
1075
1076 -- gcc's -fstrict-aliasing allows two accesses to memory
1077 -- to be considered non-aliasing if they have different types.
1078 -- This interacts badly with the C code we generate, which is
1079 -- very weakly typed, being derived from C--.
1080 ["-fno-strict-aliasing"]
1081
1082 let gcc_lang_opt | cc_phase `eqPhase` Ccpp = "c++"
1083 | cc_phase `eqPhase` Cobjc = "objective-c"
1084 | cc_phase `eqPhase` Cobjcpp = "objective-c++"
1085 | otherwise = "c"
1086 io $ SysTools.runCc dflags (
1087 -- force the C compiler to interpret this file as C when
1088 -- compiling .hc files, by adding the -x c option.
1089 -- Also useful for plain .c files, just in case GHC saw a
1090 -- -x c option.
1091 [ SysTools.Option "-x", SysTools.Option gcc_lang_opt
1092 , SysTools.FileOption "" input_fn
1093 , SysTools.Option "-o"
1094 , SysTools.FileOption "" output_fn
1095 ]
1096 ++ map SysTools.Option (
1097 pic_c_flags
1098
1099 -- Stub files generated for foreign exports references the runIO_closure
1100 -- and runNonIO_closure symbols, which are defined in the base package.
1101 -- These symbols are imported into the stub.c file via RtsAPI.h, and the
1102 -- way we do the import depends on whether we're currently compiling
1103 -- the base package or not.
1104 ++ (if platformOS (targetPlatform dflags) == OSMinGW32 &&
1105 thisPackage dflags == basePackageId
1106 then [ "-DCOMPILING_BASE_PACKAGE" ]
1107 else [])
1108
1109 -- We only support SparcV9 and better because V8 lacks an atomic CAS
1110 -- instruction. Note that the user can still override this
1111 -- (e.g., -mcpu=ultrasparc) as GCC picks the "best" -mcpu flag
1112 -- regardless of the ordering.
1113 --
1114 -- This is a temporary hack.
1115 ++ (if platformArch (targetPlatform dflags) == ArchSPARC
1116 then ["-mcpu=v9"]
1117 else [])
1118
1119 ++ (if hcc
1120 then gcc_extra_viac_flags ++ more_hcc_opts
1121 else [])
1122 ++ verbFlags
1123 ++ [ "-S", "-Wimplicit", cc_opt ]
1124 ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
1125 #ifdef darwin_TARGET_OS
1126 ++ framework_paths
1127 #endif
1128 ++ cc_opts
1129 ++ split_opt
1130 ++ include_paths
1131 ++ pkg_extra_cc_opts
1132 ))
1133
1134 return (next_phase, output_fn)
1135
1136 -- ToDo: postprocess the output from gcc
1137
1138 -----------------------------------------------------------------------------
1139 -- Splitting phase
1140
1141 runPhase SplitMangle input_fn dflags
1142 = do -- tmp_pfx is the prefix used for the split .s files
1143
1144 split_s_prefix <- io $ SysTools.newTempName dflags "split"
1145 let n_files_fn = split_s_prefix
1146
1147 io $ SysTools.runSplit dflags
1148 [ SysTools.FileOption "" input_fn
1149 , SysTools.FileOption "" split_s_prefix
1150 , SysTools.FileOption "" n_files_fn
1151 ]
1152
1153 -- Save the number of split files for future references
1154 s <- io $ readFile n_files_fn
1155 let n_files = read s :: Int
1156 dflags' = dflags { splitInfo = Just (split_s_prefix, n_files) }
1157
1158 setDynFlags dflags'
1159
1160 -- Remember to delete all these files
1161 io $ addFilesToClean dflags' [ split_s_prefix ++ "__" ++ show n ++ ".s"
1162 | n <- [1..n_files]]
1163
1164 return (SplitAs, "**splitmangle**")
1165 -- we don't use the filename
1166
1167 -----------------------------------------------------------------------------
1168 -- As phase
1169
1170 runPhase As input_fn dflags
1171 = do
1172 let as_opts = getOpts dflags opt_a
1173 let cmdline_include_paths = includePaths dflags
1174
1175 next_phase <- maybeMergeStub
1176 output_fn <- phaseOutputFilename next_phase
1177
1178 -- we create directories for the object file, because it
1179 -- might be a hierarchical module.
1180 io $ createDirectoryHierarchy (takeDirectory output_fn)
1181
1182 io $ SysTools.runAs dflags
1183 (map SysTools.Option as_opts
1184 ++ [ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ]
1185
1186 -- We only support SparcV9 and better because V8 lacks an atomic CAS
1187 -- instruction so we have to make sure that the assembler accepts the
1188 -- instruction set. Note that the user can still override this
1189 -- (e.g., -mcpu=ultrasparc). GCC picks the "best" -mcpu flag
1190 -- regardless of the ordering.
1191 --
1192 -- This is a temporary hack.
1193 ++ (if platformArch (targetPlatform dflags) == ArchSPARC
1194 then [SysTools.Option "-mcpu=v9"]
1195 else [])
1196
1197 ++ [ SysTools.Option "-c"
1198 , SysTools.FileOption "" input_fn
1199 , SysTools.Option "-o"
1200 , SysTools.FileOption "" output_fn
1201 ])
1202
1203 return (next_phase, output_fn)
1204
1205
1206 runPhase SplitAs _input_fn dflags
1207 = do
1208 -- we'll handle the stub_o file in this phase, so don't MergeStub,
1209 -- just jump straight to StopLn afterwards.
1210 let next_phase = StopLn
1211 output_fn <- phaseOutputFilename next_phase
1212
1213 let base_o = dropExtension output_fn
1214 osuf = objectSuf dflags
1215 split_odir = base_o ++ "_" ++ osuf ++ "_split"
1216
1217 io $ createDirectoryHierarchy split_odir
1218
1219 -- remove M_split/ *.o, because we're going to archive M_split/ *.o
1220 -- later and we don't want to pick up any old objects.
1221 fs <- io $ getDirectoryContents split_odir
1222 io $ mapM_ removeFile $
1223 map (split_odir </>) $ filter (osuf `isSuffixOf`) fs
1224
1225 let as_opts = getOpts dflags opt_a
1226
1227 let (split_s_prefix, n) = case splitInfo dflags of
1228 Nothing -> panic "No split info"
1229 Just x -> x
1230
1231 let split_s n = split_s_prefix ++ "__" ++ show n <.> "s"
1232
1233 split_obj :: Int -> FilePath
1234 split_obj n = split_odir </>
1235 takeFileName base_o ++ "__" ++ show n <.> osuf
1236
1237 let assemble_file n
1238 = SysTools.runAs dflags
1239 (map SysTools.Option as_opts ++
1240
1241 -- We only support SparcV9 and better because V8 lacks an atomic CAS
1242 -- instruction so we have to make sure that the assembler accepts the
1243 -- instruction set. Note that the user can still override this
1244 -- (e.g., -mcpu=ultrasparc). GCC picks the "best" -mcpu flag
1245 -- regardless of the ordering.
1246 --
1247 -- This is a temporary hack.
1248 (if platformArch (targetPlatform dflags) == ArchSPARC
1249 then [SysTools.Option "-mcpu=v9"]
1250 else []) ++
1251
1252 [ SysTools.Option "-c"
1253 , SysTools.Option "-o"
1254 , SysTools.FileOption "" (split_obj n)
1255 , SysTools.FileOption "" (split_s n)
1256 ])
1257
1258 io $ mapM_ assemble_file [1..n]
1259
1260 -- Note [pipeline-split-init]
1261 -- If we have a stub file, it may contain constructor
1262 -- functions for initialisation of this module. We can't
1263 -- simply leave the stub as a separate object file, because it
1264 -- will never be linked in: nothing refers to it. We need to
1265 -- ensure that if we ever refer to the data in this module
1266 -- that needs initialisation, then we also pull in the
1267 -- initialisation routine.
1268 --
1269 -- To that end, we make a DANGEROUS ASSUMPTION here: the data
1270 -- that needs to be initialised is all in the FIRST split
1271 -- object. See Note [codegen-split-init].
1272
1273 PipeState{maybe_stub_o} <- getPipeState
1274 case maybe_stub_o of
1275 Nothing -> return ()
1276 Just stub_o -> io $ do
1277 tmp_split_1 <- newTempName dflags osuf
1278 let split_1 = split_obj 1
1279 copyFile split_1 tmp_split_1
1280 removeFile split_1
1281 joinObjectFiles dflags [tmp_split_1, stub_o] split_1
1282
1283 -- join them into a single .o file
1284 io $ joinObjectFiles dflags (map split_obj [1..n]) output_fn
1285
1286 return (next_phase, output_fn)
1287
1288 -----------------------------------------------------------------------------
1289 -- LlvmOpt phase
1290
1291 runPhase LlvmOpt input_fn dflags
1292 = do
1293 let lo_opts = getOpts dflags opt_lo
1294 let opt_lvl = max 0 (min 2 $ optLevel dflags)
1295 -- don't specify anything if user has specified commands. We do this for
1296 -- opt but not llc since opt is very specifically for optimisation passes
1297 -- only, so if the user is passing us extra options we assume they know
1298 -- what they are doing and don't get in the way.
1299 let optFlag = if null lo_opts
1300 then [SysTools.Option (llvmOpts !! opt_lvl)]
1301 else []
1302
1303 output_fn <- phaseOutputFilename LlvmLlc
1304
1305 io $ SysTools.runLlvmOpt dflags
1306 ([ SysTools.FileOption "" input_fn,
1307 SysTools.Option "-o",
1308 SysTools.FileOption "" output_fn]
1309 ++ optFlag
1310 ++ map SysTools.Option lo_opts)
1311
1312 return (LlvmLlc, output_fn)
1313 where
1314 -- we always (unless -optlo specified) run Opt since we rely on it to
1315 -- fix up some pretty big deficiencies in the code we generate
1316 llvmOpts = ["-mem2reg", "-O1", "-O2"]
1317
1318 -----------------------------------------------------------------------------
1319 -- LlvmLlc phase
1320
1321 runPhase LlvmLlc input_fn dflags
1322 = do
1323 let lc_opts = getOpts dflags opt_lc
1324 opt_lvl = max 0 (min 2 $ optLevel dflags)
1325 rmodel | opt_PIC = "pic"
1326 | not opt_Static = "dynamic-no-pic"
1327 | otherwise = "static"
1328
1329 output_fn <- phaseOutputFilename LlvmMangle
1330
1331 io $ SysTools.runLlvmLlc dflags
1332 ([ SysTools.Option (llvmOpts !! opt_lvl),
1333 SysTools.Option $ "-relocation-model=" ++ rmodel,
1334 SysTools.FileOption "" input_fn,
1335 SysTools.Option "-o", SysTools.FileOption "" output_fn]
1336 ++ map SysTools.Option lc_opts)
1337
1338 return (LlvmMangle, output_fn)
1339 where
1340 -- Bug in LLVM at O3 on OSX.
1341 llvmOpts = if platformOS (targetPlatform dflags) == OSDarwin
1342 then ["-O1", "-O2", "-O2"]
1343 else ["-O1", "-O2", "-O3"]
1344
1345 -----------------------------------------------------------------------------
1346 -- LlvmMangle phase
1347
1348 runPhase LlvmMangle input_fn _dflags
1349 = do
1350 output_fn <- phaseOutputFilename As
1351 io $ llvmFixupAsm input_fn output_fn
1352 return (As, output_fn)
1353
1354 -----------------------------------------------------------------------------
1355 -- merge in stub objects
1356
1357 runPhase MergeStub input_fn dflags
1358 = do
1359 PipeState{maybe_stub_o} <- getPipeState
1360 output_fn <- phaseOutputFilename StopLn
1361 case maybe_stub_o of
1362 Nothing ->
1363 panic "runPhase(MergeStub): no stub"
1364 Just stub_o -> do
1365 io $ joinObjectFiles dflags [input_fn, stub_o] output_fn
1366 return (StopLn, output_fn)
1367
1368 -- warning suppression
1369 runPhase other _input_fn _dflags =
1370 panic ("runPhase: don't know how to run phase " ++ show other)
1371
1372 maybeMergeStub :: CompPipeline Phase
1373 maybeMergeStub
1374 = do
1375 PipeState{maybe_stub_o} <- getPipeState
1376 if isJust maybe_stub_o then return MergeStub else return StopLn
1377
1378 -----------------------------------------------------------------------------
1379 -- MoveBinary sort-of-phase
1380 -- After having produced a binary, move it somewhere else and generate a
1381 -- wrapper script calling the binary. Currently, we need this only in
1382 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
1383 -- central directory.
1384 -- This is called from linkBinary below, after linking. I haven't made it
1385 -- a separate phase to minimise interfering with other modules, and
1386 -- we don't need the generality of a phase (MoveBinary is always
1387 -- done after linking and makes only sense in a parallel setup) -- HWL
1388
1389 runPhase_MoveBinary :: DynFlags -> FilePath -> IO Bool
1390 runPhase_MoveBinary dflags input_fn
1391 | WayPar `elem` (wayNames dflags) && not opt_Static =
1392 panic ("Don't know how to combine PVM wrapper and dynamic wrapper")
1393 | WayPar `elem` (wayNames dflags) = do
1394 let sysMan = pgm_sysman dflags
1395 pvm_root <- getEnv "PVM_ROOT"
1396 pvm_arch <- getEnv "PVM_ARCH"
1397 let
1398 pvm_executable_base = "=" ++ input_fn
1399 pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
1400 -- nuke old binary; maybe use configur'ed names for cp and rm?
1401 _ <- tryIO (removeFile pvm_executable)
1402 -- move the newly created binary into PVM land
1403 copy dflags "copying PVM executable" input_fn pvm_executable
1404 -- generate a wrapper script for running a parallel prg under PVM
1405 writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
1406 return True
1407 | otherwise = return True
1408
1409 mkExtraCObj :: DynFlags -> String -> IO FilePath
1410 mkExtraCObj dflags xs
1411 = do cFile <- newTempName dflags "c"
1412 oFile <- newTempName dflags "o"
1413 writeFile cFile xs
1414 let rtsDetails = getPackageDetails (pkgState dflags) rtsPackageId
1415 SysTools.runCc dflags
1416 ([Option "-c",
1417 FileOption "" cFile,
1418 Option "-o",
1419 FileOption "" oFile] ++
1420 map (FileOption "-I") (includeDirs rtsDetails))
1421 return oFile
1422
1423 mkExtraObjToLinkIntoBinary :: DynFlags -> [PackageId] -> IO FilePath
1424 mkExtraObjToLinkIntoBinary dflags dep_packages = do
1425 link_info <- getLinkInfo dflags dep_packages
1426 mkExtraCObj dflags (showSDoc (vcat [rts_opts_enabled,
1427 extra_rts_opts,
1428 link_opts link_info]
1429 <> char '\n')) -- final newline, to
1430 -- keep gcc happy
1431
1432 where
1433 mk_rts_opts_enabled val
1434 = vcat [text "#include \"Rts.h\"",
1435 text "#include \"RtsOpts.h\"",
1436 text "const RtsOptsEnabledEnum rtsOptsEnabled = " <>
1437 text val <> semi ]
1438
1439 rts_opts_enabled = case rtsOptsEnabled dflags of
1440 RtsOptsNone -> mk_rts_opts_enabled "RtsOptsNone"
1441 RtsOptsSafeOnly -> empty -- The default
1442 RtsOptsAll -> mk_rts_opts_enabled "RtsOptsAll"
1443
1444 extra_rts_opts = case rtsOpts dflags of
1445 Nothing -> empty
1446 Just opts -> text "char *ghc_rts_opts = " <> text (show opts) <> semi
1447
1448 link_opts info
1449 | not (platformSupportsSavingLinkOpts (platformOS (targetPlatform dflags)))
1450 = empty
1451 | otherwise = hcat [
1452 text "__asm__(\"\\t.section ", text ghcLinkInfoSectionName,
1453 text ",\\\"\\\",",
1454 text elfSectionNote,
1455 text "\\n",
1456
1457 text "\\t.ascii \\\"", info', text "\\\"\\n\");" ]
1458 where
1459 -- we need to escape twice: once because we're inside a C string,
1460 -- and again because we're inside an asm string.
1461 info' = text $ (escape.escape) info
1462
1463 escape :: String -> String
1464 escape = concatMap (charToC.fromIntegral.ord)
1465
1466 elfSectionNote :: String
1467 elfSectionNote = case platformArch (targetPlatform dflags) of
1468 ArchARM -> "%note"
1469 _ -> "@note"
1470
1471 -- The "link info" is a string representing the parameters of the
1472 -- link. We save this information in the binary, and the next time we
1473 -- link, if nothing else has changed, we use the link info stored in
1474 -- the existing binary to decide whether to re-link or not.
1475 getLinkInfo :: DynFlags -> [PackageId] -> IO String
1476 getLinkInfo dflags dep_packages = do
1477 package_link_opts <- getPackageLinkOpts dflags dep_packages
1478 #ifdef darwin_TARGET_OS
1479 pkg_frameworks <- getPackageFrameworks dflags dep_packages
1480 #endif
1481 extra_ld_inputs <- readIORef v_Ld_inputs
1482 let
1483 link_info = (package_link_opts,
1484 #ifdef darwin_TARGET_OS
1485 pkg_frameworks,
1486 #endif
1487 rtsOpts dflags,
1488 rtsOptsEnabled dflags,
1489 dopt Opt_NoHsMain dflags,
1490 extra_ld_inputs,
1491 getOpts dflags opt_l)
1492 --
1493 return (show link_info)
1494
1495 -- generates a Perl skript starting a parallel prg under PVM
1496 mk_pvm_wrapper_script :: String -> String -> String -> String
1497 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
1498 [
1499 "eval 'exec perl -S $0 ${1+\"$@\"}'",
1500 " if $running_under_some_shell;",
1501 "# =!=!=!=!=!=!=!=!=!=!=!",
1502 "# This script is automatically generated: DO NOT EDIT!!!",
1503 "# Generated by Glasgow Haskell Compiler",
1504 "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
1505 "#",
1506 "$pvm_executable = '" ++ pvm_executable ++ "';",
1507 "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
1508 "$SysMan = '" ++ sysMan ++ "';",
1509 "",
1510 {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
1511 "# first, some magical shortcuts to run "commands" on the binary",
1512 "# (which is hidden)",
1513 "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
1514 " local($cmd) = $1;",
1515 " system("$cmd $pvm_executable");",
1516 " exit(0); # all done",
1517 "}", -}
1518 "",
1519 "# Now, run the real binary; process the args first",
1520 "$ENV{'PE'} = $pvm_executable_base;", -- ++ pvm_executable_base,
1521 "$debug = '';",
1522 "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
1523 "@nonPVM_args = ();",
1524 "$in_RTS_args = 0;",
1525 "",
1526 "args: while ($a = shift(@ARGV)) {",
1527 " if ( $a eq '+RTS' ) {",
1528 " $in_RTS_args = 1;",
1529 " } elsif ( $a eq '-RTS' ) {",
1530 " $in_RTS_args = 0;",
1531 " }",
1532 " if ( $a eq '-d' && $in_RTS_args ) {",
1533 " $debug = '-';",
1534 " } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
1535 " $nprocessors = $1;",
1536 " } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
1537 " $nprocessors = $1;",
1538 " } else {",
1539 " push(@nonPVM_args, $a);",
1540 " }",
1541 "}",
1542 "",
1543 "local($return_val) = 0;",
1544 "# Start the parallel execution by calling SysMan",
1545 "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
1546 "$return_val = $?;",
1547 "# ToDo: fix race condition moving files and flushing them!!",
1548 "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
1549 "exit($return_val);"
1550 ]
1551
1552 -----------------------------------------------------------------------------
1553 -- Look for the /* GHC_PACKAGES ... */ comment at the top of a .hc file
1554
1555 getHCFilePackages :: FilePath -> IO [PackageId]
1556 getHCFilePackages filename =
1557 Exception.bracket (openFile filename ReadMode) hClose $ \h -> do
1558 l <- hGetLine h
1559 case l of
1560 '/':'*':' ':'G':'H':'C':'_':'P':'A':'C':'K':'A':'G':'E':'S':rest ->
1561 return (map stringToPackageId (words rest))
1562 _other ->
1563 return []
1564
1565 -----------------------------------------------------------------------------
1566 -- Static linking, of .o files
1567
1568 -- The list of packages passed to link is the list of packages on
1569 -- which this program depends, as discovered by the compilation
1570 -- manager. It is combined with the list of packages that the user
1571 -- specifies on the command line with -package flags.
1572 --
1573 -- In one-shot linking mode, we can't discover the package
1574 -- dependencies (because we haven't actually done any compilation or
1575 -- read any interface files), so the user must explicitly specify all
1576 -- the packages.
1577
1578 linkBinary :: DynFlags -> [FilePath] -> [PackageId] -> IO ()
1579 linkBinary dflags o_files dep_packages = do
1580 let verbFlags = getVerbFlags dflags
1581 output_fn = exeFileName dflags
1582
1583 -- get the full list of packages to link with, by combining the
1584 -- explicit packages with the auto packages and all of their
1585 -- dependencies, and eliminating duplicates.
1586
1587 pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1588 let pkg_lib_path_opts = concat (map get_pkg_lib_path_opts pkg_lib_paths)
1589 get_pkg_lib_path_opts l
1590 | osElfTarget (platformOS (targetPlatform dflags)) &&
1591 dynLibLoader dflags == SystemDependent &&
1592 not opt_Static
1593 = ["-L" ++ l, "-Wl,-rpath", "-Wl," ++ l]
1594 | otherwise = ["-L" ++ l]
1595
1596 let lib_paths = libraryPaths dflags
1597 let lib_path_opts = map ("-L"++) lib_paths
1598
1599 -- The C "main" function is not in the rts but in a separate static
1600 -- library libHSrtsmain.a that sits next to the rts lib files. Assuming
1601 -- we're using a Haskell main function then we need to link it in.
1602 let no_hs_main = dopt Opt_NoHsMain dflags
1603 let main_lib | no_hs_main = []
1604 | otherwise = [ "-lHSrtsmain" ]
1605
1606 extraLinkObj <- mkExtraObjToLinkIntoBinary dflags dep_packages
1607
1608 pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1609
1610 #ifdef darwin_TARGET_OS
1611 pkg_framework_paths <- getPackageFrameworkPath dflags dep_packages
1612 let pkg_framework_path_opts = map ("-F"++) pkg_framework_paths
1613
1614 let framework_paths = frameworkPaths dflags
1615 framework_path_opts = map ("-F"++) framework_paths
1616
1617 pkg_frameworks <- getPackageFrameworks dflags dep_packages
1618 let pkg_framework_opts = concat [ ["-framework", fw] | fw <- pkg_frameworks ]
1619
1620 let frameworks = cmdlineFrameworks dflags
1621 framework_opts = concat [ ["-framework", fw] | fw <- reverse frameworks ]
1622 -- reverse because they're added in reverse order from the cmd line
1623 #endif
1624 -- probably _stub.o files
1625 extra_ld_inputs <- readIORef v_Ld_inputs
1626
1627 -- opts from -optl-<blah> (including -l<blah> options)
1628 let extra_ld_opts = getOpts dflags opt_l
1629
1630 let ways = wayNames dflags
1631
1632 -- Here are some libs that need to be linked at the *end* of
1633 -- the command line, because they contain symbols that are referred to
1634 -- by the RTS. We can't therefore use the ordinary way opts for these.
1635 let
1636 debug_opts | WayDebug `elem` ways = [
1637 #if defined(HAVE_LIBBFD)
1638 "-lbfd", "-liberty"
1639 #endif
1640 ]
1641 | otherwise = []
1642
1643 let
1644 thread_opts | WayThreaded `elem` ways = [
1645 #if !defined(mingw32_TARGET_OS) && !defined(freebsd_TARGET_OS) && !defined(openbsd_TARGET_OS) && !defined(haiku_TARGET_OS)
1646 "-lpthread"
1647 #endif
1648 #if defined(osf3_TARGET_OS)
1649 , "-lexc"
1650 #endif
1651 ]
1652 | otherwise = []
1653
1654 rc_objs <- maybeCreateManifest dflags output_fn
1655
1656 SysTools.runLink dflags (
1657 map SysTools.Option verbFlags
1658 ++ [ SysTools.Option "-o"
1659 , SysTools.FileOption "" output_fn
1660 ]
1661 ++ map SysTools.Option (
1662 []
1663
1664 -- Permit the linker to auto link _symbol to _imp_symbol.
1665 -- This lets us link against DLLs without needing an "import library".
1666 ++ (if platformOS (targetPlatform dflags) == OSMinGW32
1667 then ["-Wl,--enable-auto-import"]
1668 else [])
1669
1670 -- '-no_compact_unwind'
1671 -- - C++/Objective-C exceptions cannot use optimised stack
1672 -- unwinding code (the optimised form is the default in Xcode 4 on
1673 -- x86_64).
1674 ++ (if platformOS (targetPlatform dflags) == OSDarwin &&
1675 platformArch (targetPlatform dflags) == ArchX86_64
1676 then ["-Wl,-no_compact_unwind"]
1677 else [])
1678
1679 ++ o_files
1680 ++ extra_ld_inputs
1681 ++ lib_path_opts
1682 ++ extra_ld_opts
1683 ++ rc_objs
1684 #ifdef darwin_TARGET_OS
1685 ++ framework_path_opts
1686 ++ framework_opts
1687 #endif
1688 ++ pkg_lib_path_opts
1689 ++ main_lib
1690 ++ [extraLinkObj]
1691 ++ pkg_link_opts
1692 #ifdef darwin_TARGET_OS
1693 ++ pkg_framework_path_opts
1694 ++ pkg_framework_opts
1695 #endif
1696 ++ debug_opts
1697 ++ thread_opts
1698 ))
1699
1700 -- parallel only: move binary to another dir -- HWL
1701 success <- runPhase_MoveBinary dflags output_fn
1702 if success then return ()
1703 else ghcError (InstallationError ("cannot move binary"))
1704
1705
1706 exeFileName :: DynFlags -> FilePath
1707 exeFileName dflags
1708 | Just s <- outputFile dflags =
1709 if platformOS (targetPlatform dflags) == OSMinGW32
1710 then if null (takeExtension s)
1711 then s <.> "exe"
1712 else s
1713 else s
1714 | otherwise =
1715 if platformOS (targetPlatform dflags) == OSMinGW32
1716 then "main.exe"
1717 else "a.out"
1718
1719 maybeCreateManifest
1720 :: DynFlags
1721 -> FilePath -- filename of executable
1722 -> IO [FilePath] -- extra objects to embed, maybe
1723 maybeCreateManifest dflags exe_filename
1724 | platformOS (targetPlatform dflags) == OSMinGW32 &&
1725 dopt Opt_GenManifest dflags
1726 = do let manifest_filename = exe_filename <.> "manifest"
1727
1728 writeFile manifest_filename $
1729 "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"++
1730 " <assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">\n"++
1731 " <assemblyIdentity version=\"1.0.0.0\"\n"++
1732 " processorArchitecture=\"X86\"\n"++
1733 " name=\"" ++ dropExtension exe_filename ++ "\"\n"++
1734 " type=\"win32\"/>\n\n"++
1735 " <trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v3\">\n"++
1736 " <security>\n"++
1737 " <requestedPrivileges>\n"++
1738 " <requestedExecutionLevel level=\"asInvoker\" uiAccess=\"false\"/>\n"++
1739 " </requestedPrivileges>\n"++
1740 " </security>\n"++
1741 " </trustInfo>\n"++
1742 "</assembly>\n"
1743
1744 -- Windows will find the manifest file if it is named
1745 -- foo.exe.manifest. However, for extra robustness, and so that
1746 -- we can move the binary around, we can embed the manifest in
1747 -- the binary itself using windres:
1748 if not (dopt Opt_EmbedManifest dflags) then return [] else do
1749
1750 rc_filename <- newTempName dflags "rc"
1751 rc_obj_filename <- newTempName dflags (objectSuf dflags)
1752
1753 writeFile rc_filename $
1754 "1 24 MOVEABLE PURE " ++ show manifest_filename ++ "\n"
1755 -- magic numbers :-)
1756 -- show is a bit hackish above, but we need to escape the
1757 -- backslashes in the path.
1758
1759 let wr_opts = getOpts dflags opt_windres
1760 runWindres dflags $ map SysTools.Option $
1761 ["--input="++rc_filename,
1762 "--output="++rc_obj_filename,
1763 "--output-format=coff"]
1764 ++ wr_opts
1765 -- no FileOptions here: windres doesn't like seeing
1766 -- backslashes, apparently
1767
1768 removeFile manifest_filename
1769
1770 return [rc_obj_filename]
1771 | otherwise = return []
1772
1773
1774 linkDynLib :: DynFlags -> [String] -> [PackageId] -> IO ()
1775 linkDynLib dflags o_files dep_packages = do
1776 let verbFlags = getVerbFlags dflags
1777 let o_file = outputFile dflags
1778
1779 pkgs <- getPreloadPackagesAnd dflags dep_packages
1780
1781 let pkg_lib_paths = collectLibraryPaths pkgs
1782 let pkg_lib_path_opts = concatMap get_pkg_lib_path_opts pkg_lib_paths
1783 get_pkg_lib_path_opts l
1784 | osElfTarget (platformOS (targetPlatform dflags)) &&
1785 dynLibLoader dflags == SystemDependent &&
1786 not opt_Static
1787 = ["-L" ++ l, "-Wl,-rpath", "-Wl," ++ l]
1788 | otherwise = ["-L" ++ l]
1789
1790 let lib_paths = libraryPaths dflags
1791 let lib_path_opts = map ("-L"++) lib_paths
1792
1793 -- We don't want to link our dynamic libs against the RTS package,
1794 -- because the RTS lib comes in several flavours and we want to be
1795 -- able to pick the flavour when a binary is linked.
1796 -- On Windows we need to link the RTS import lib as Windows does
1797 -- not allow undefined symbols.
1798 -- The RTS library path is still added to the library search path
1799 -- above in case the RTS is being explicitly linked in (see #3807).
1800 let pkgs_no_rts = case platformOS (targetPlatform dflags) of
1801 OSMinGW32 ->
1802 pkgs
1803 _ ->
1804 filter ((/= rtsPackageId) . packageConfigId) pkgs
1805 let pkg_link_opts = collectLinkOpts dflags pkgs_no_rts
1806
1807 -- probably _stub.o files
1808 extra_ld_inputs <- readIORef v_Ld_inputs
1809
1810 let extra_ld_opts = getOpts dflags opt_l
1811
1812 extraLinkObj <- mkExtraObjToLinkIntoBinary dflags dep_packages
1813
1814 #if defined(mingw32_HOST_OS)
1815 -----------------------------------------------------------------------------
1816 -- Making a DLL
1817 -----------------------------------------------------------------------------
1818 let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
1819
1820 SysTools.runLink dflags (
1821 map SysTools.Option verbFlags
1822 ++ [ SysTools.Option "-o"
1823 , SysTools.FileOption "" output_fn
1824 , SysTools.Option "-shared"
1825 ] ++
1826 [ SysTools.FileOption "-Wl,--out-implib=" (output_fn ++ ".a")
1827 | dopt Opt_SharedImplib dflags
1828 ]
1829 ++ map (SysTools.FileOption "") o_files
1830 ++ map SysTools.Option (
1831
1832 -- Permit the linker to auto link _symbol to _imp_symbol
1833 -- This lets us link against DLLs without needing an "import library"
1834 ["-Wl,--enable-auto-import"]
1835
1836 ++ extra_ld_inputs
1837 ++ lib_path_opts
1838 ++ extra_ld_opts
1839 ++ pkg_lib_path_opts
1840 ++ [extraLinkObj]
1841 ++ pkg_link_opts
1842 ))
1843 #elif defined(darwin_TARGET_OS)
1844 -----------------------------------------------------------------------------
1845 -- Making a darwin dylib
1846 -----------------------------------------------------------------------------
1847 -- About the options used for Darwin:
1848 -- -dynamiclib
1849 -- Apple's way of saying -shared
1850 -- -undefined dynamic_lookup:
1851 -- Without these options, we'd have to specify the correct dependencies
1852 -- for each of the dylibs. Note that we could (and should) do without this
1853 -- for all libraries except the RTS; all we need to do is to pass the
1854 -- correct HSfoo_dyn.dylib files to the link command.
1855 -- This feature requires Mac OS X 10.3 or later; there is a similar feature,
1856 -- -flat_namespace -undefined suppress, which works on earlier versions,
1857 -- but it has other disadvantages.
1858 -- -single_module
1859 -- Build the dynamic library as a single "module", i.e. no dynamic binding
1860 -- nonsense when referring to symbols from within the library. The NCG
1861 -- assumes that this option is specified (on i386, at least).
1862 -- -install_name
1863 -- Mac OS/X stores the path where a dynamic library is (to be) installed
1864 -- in the library itself. It's called the "install name" of the library.
1865 -- Then any library or executable that links against it before it's
1866 -- installed will search for it in its ultimate install location. By
1867 -- default we set the install name to the absolute path at build time, but
1868 -- it can be overridden by the -dylib-install-name option passed to ghc.
1869 -- Cabal does this.
1870 -----------------------------------------------------------------------------
1871
1872 let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
1873
1874 instName <- case dylibInstallName dflags of
1875 Just n -> return n
1876 Nothing -> do
1877 pwd <- getCurrentDirectory
1878 return $ pwd `combine` output_fn
1879 SysTools.runLink dflags (
1880 map SysTools.Option verbFlags
1881 ++ [ SysTools.Option "-dynamiclib"
1882 , SysTools.Option "-o"
1883 , SysTools.FileOption "" output_fn
1884 ]
1885 ++ map SysTools.Option (
1886 o_files
1887 ++ [ "-undefined", "dynamic_lookup", "-single_module",
1888 #if !defined(x86_64_TARGET_ARCH)
1889 "-Wl,-read_only_relocs,suppress",
1890 #endif
1891 "-install_name", instName ]
1892 ++ extra_ld_inputs
1893 ++ lib_path_opts
1894 ++ extra_ld_opts
1895 ++ pkg_lib_path_opts
1896 ++ [extraLinkObj]
1897 ++ pkg_link_opts
1898 ))
1899 #else
1900 -----------------------------------------------------------------------------
1901 -- Making a DSO
1902 -----------------------------------------------------------------------------
1903
1904 let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
1905 let buildingRts = thisPackage dflags == rtsPackageId
1906 let bsymbolicFlag = if buildingRts
1907 then -- -Bsymbolic breaks the way we implement
1908 -- hooks in the RTS
1909 []
1910 else -- we need symbolic linking to resolve
1911 -- non-PIC intra-package-relocations
1912 ["-Wl,-Bsymbolic"]
1913
1914 SysTools.runLink dflags (
1915 map SysTools.Option verbFlags
1916 ++ [ SysTools.Option "-o"
1917 , SysTools.FileOption "" output_fn
1918 ]
1919 ++ map SysTools.Option (
1920 o_files
1921 ++ [ "-shared" ]
1922 ++ bsymbolicFlag
1923 -- Set the library soname. We use -h rather than -soname as
1924 -- Solaris 10 doesn't support the latter:
1925 ++ [ "-Wl,-h," ++ takeFileName output_fn ]
1926 ++ extra_ld_inputs
1927 ++ lib_path_opts
1928 ++ extra_ld_opts
1929 ++ pkg_lib_path_opts
1930 ++ [extraLinkObj]
1931 ++ pkg_link_opts
1932 ))
1933 #endif
1934 -- -----------------------------------------------------------------------------
1935 -- Running CPP
1936
1937 doCpp :: DynFlags -> Bool -> Bool -> FilePath -> FilePath -> IO ()
1938 doCpp dflags raw include_cc_opts input_fn output_fn = do
1939 let hscpp_opts = getOpts dflags opt_P
1940 let cmdline_include_paths = includePaths dflags
1941
1942 pkg_include_dirs <- getPackageIncludePath dflags []
1943 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
1944 (cmdline_include_paths ++ pkg_include_dirs)
1945
1946 let verbFlags = getVerbFlags dflags
1947
1948 let cc_opts
1949 | include_cc_opts = getOpts dflags opt_c
1950 | otherwise = []
1951
1952 let cpp_prog args | raw = SysTools.runCpp dflags args
1953 | otherwise = SysTools.runCc dflags (SysTools.Option "-E" : args)
1954
1955 let target_defs =
1956 [ "-D" ++ HOST_OS ++ "_BUILD_OS=1",
1957 "-D" ++ HOST_ARCH ++ "_BUILD_ARCH=1",
1958 "-D" ++ TARGET_OS ++ "_HOST_OS=1",
1959 "-D" ++ TARGET_ARCH ++ "_HOST_ARCH=1" ]
1960 -- remember, in code we *compile*, the HOST is the same our TARGET,
1961 -- and BUILD is the same as our HOST.
1962
1963 cpp_prog ( map SysTools.Option verbFlags
1964 ++ map SysTools.Option include_paths
1965 ++ map SysTools.Option hsSourceCppOpts
1966 ++ map SysTools.Option target_defs
1967 ++ map SysTools.Option hscpp_opts
1968 ++ map SysTools.Option cc_opts
1969 ++ [ SysTools.Option "-x"
1970 , SysTools.Option "c"
1971 , SysTools.Option input_fn
1972 -- We hackily use Option instead of FileOption here, so that the file
1973 -- name is not back-slashed on Windows. cpp is capable of
1974 -- dealing with / in filenames, so it works fine. Furthermore
1975 -- if we put in backslashes, cpp outputs #line directives
1976 -- with *double* backslashes. And that in turn means that
1977 -- our error messages get double backslashes in them.
1978 -- In due course we should arrange that the lexer deals
1979 -- with these \\ escapes properly.
1980 , SysTools.Option "-o"
1981 , SysTools.FileOption "" output_fn
1982 ])
1983
1984 hsSourceCppOpts :: [String]
1985 -- Default CPP defines in Haskell source
1986 hsSourceCppOpts =
1987 [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
1988
1989 -- ---------------------------------------------------------------------------
1990 -- join object files into a single relocatable object file, using ld -r
1991
1992 joinObjectFiles :: DynFlags -> [FilePath] -> FilePath -> IO ()
1993 joinObjectFiles dflags o_files output_fn = do
1994 let ld_r args = SysTools.runLink dflags ([
1995 SysTools.Option "-nostdlib",
1996 SysTools.Option "-nodefaultlibs",
1997 SysTools.Option "-Wl,-r"
1998 ]
1999 -- gcc on sparc sets -Wl,--relax implicitly, but
2000 -- -r and --relax are incompatible for ld, so
2001 -- disable --relax explicitly.
2002 ++ (if platformArch (targetPlatform dflags) == ArchSPARC
2003 then [SysTools.Option "-Wl,-no-relax"]
2004 else [])
2005 ++ [
2006 SysTools.Option ld_build_id,
2007 SysTools.Option ld_x_flag,
2008 SysTools.Option "-o",
2009 SysTools.FileOption "" output_fn ]
2010 ++ args)
2011
2012 ld_x_flag | null cLD_X = ""
2013 | otherwise = "-Wl,-x"
2014
2015 -- suppress the generation of the .note.gnu.build-id section,
2016 -- which we don't need and sometimes causes ld to emit a
2017 -- warning:
2018 ld_build_id | cLdHasBuildId == "YES" = "-Wl,--build-id=none"
2019 | otherwise = ""
2020
2021 if cLdIsGNULd == "YES"
2022 then do
2023 script <- newTempName dflags "ldscript"
2024 writeFile script $ "INPUT(" ++ unwords o_files ++ ")"
2025 ld_r [SysTools.FileOption "" script]
2026 else do
2027 ld_r (map (SysTools.FileOption "") o_files)
2028
2029 -- -----------------------------------------------------------------------------
2030 -- Misc.
2031
2032 hscNextPhase :: DynFlags -> HscSource -> HscTarget -> Phase
2033 hscNextPhase _ HsBootFile _ = StopLn
2034 hscNextPhase dflags _ hsc_lang =
2035 case hsc_lang of
2036 HscC -> HCc
2037 HscAsm | dopt Opt_SplitObjs dflags -> SplitMangle
2038 | otherwise -> As
2039 HscLlvm -> LlvmOpt
2040 HscNothing -> StopLn
2041 HscInterpreted -> StopLn
2042