66c6e97d0c13aacb86edf185f83ea43a59b939eb
[ghc.git] / compiler / main / DriverPipeline.hs
1 {-# LANGUAGE CPP, NamedFieldPuns, NondecreasingIndentation #-}
2 {-# OPTIONS_GHC -fno-cse #-}
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 compileOne, compileOne',
24 link,
25
26 -- Exports for hooks to override runPhase and link
27 PhasePlus(..), CompPipeline(..), PipeEnv(..), PipeState(..),
28 phaseOutputFilename, getPipeState, getPipeEnv,
29 hscPostBackendPhase, getLocation, setModLocation, setDynFlags,
30 runPhase, exeFileName,
31 mkExtraObjToLinkIntoBinary, mkNoteObjsToLinkIntoBinary,
32 maybeCreateManifest, runPhase_MoveBinary,
33 linkingNeeded, checkLinkInfo
34 ) where
35
36 #include "HsVersions.h"
37
38 import PipelineMonad
39 import Packages
40 import HeaderInfo
41 import DriverPhases
42 import SysTools
43 import HscMain
44 import Finder
45 import HscTypes hiding ( Hsc )
46 import Outputable
47 import Module
48 import UniqFM ( eltsUFM )
49 import ErrUtils
50 import DynFlags
51 import Config
52 import Panic
53 import Util
54 import StringBuffer ( hGetStringBuffer )
55 import BasicTypes ( SuccessFlag(..) )
56 import Maybes ( expectJust )
57 import SrcLoc
58 import FastString
59 import LlvmCodeGen ( llvmFixupAsm )
60 import MonadUtils
61 import Platform
62 import TcRnTypes
63 import Hooks
64
65 import Exception
66 import Data.IORef ( readIORef )
67 import System.Directory
68 import System.FilePath
69 import System.IO
70 import Control.Monad
71 import Data.List ( isSuffixOf )
72 import Data.Maybe
73 import System.Environment
74 import Data.Char
75
76 -- ---------------------------------------------------------------------------
77 -- Pre-process
78
79 -- | Just preprocess a file, put the result in a temp. file (used by the
80 -- compilation manager during the summary phase).
81 --
82 -- We return the augmented DynFlags, because they contain the result
83 -- of slurping in the OPTIONS pragmas
84
85 preprocess :: HscEnv
86 -> (FilePath, Maybe Phase) -- ^ filename and starting phase
87 -> IO (DynFlags, FilePath)
88 preprocess hsc_env (filename, mb_phase) =
89 ASSERT2(isJust mb_phase || isHaskellSrcFilename filename, text filename)
90 runPipeline anyHsc hsc_env (filename, fmap RealPhase mb_phase)
91 Nothing Temporary Nothing{-no ModLocation-} Nothing{-no stub-}
92
93 -- ---------------------------------------------------------------------------
94
95 -- | Compile
96 --
97 -- Compile a single module, under the control of the compilation manager.
98 --
99 -- This is the interface between the compilation manager and the
100 -- compiler proper (hsc), where we deal with tedious details like
101 -- reading the OPTIONS pragma from the source file, converting the
102 -- C or assembly that GHC produces into an object file, and compiling
103 -- FFI stub files.
104 --
105 -- NB. No old interface can also mean that the source has changed.
106
107 compileOne :: HscEnv
108 -> ModSummary -- ^ summary for module being compiled
109 -> Int -- ^ module N ...
110 -> Int -- ^ ... of M
111 -> Maybe ModIface -- ^ old interface, if we have one
112 -> Maybe Linkable -- ^ old linkable, if we have one
113 -> SourceModified
114 -> IO HomeModInfo -- ^ the complete HomeModInfo, if successful
115
116 compileOne = compileOne' Nothing (Just batchMsg)
117
118 compileOne' :: Maybe TcGblEnv
119 -> Maybe Messager
120 -> HscEnv
121 -> ModSummary -- ^ summary for module being compiled
122 -> Int -- ^ module N ...
123 -> Int -- ^ ... of M
124 -> Maybe ModIface -- ^ old interface, if we have one
125 -> Maybe Linkable -- ^ old linkable, if we have one
126 -> SourceModified
127 -> IO HomeModInfo -- ^ the complete HomeModInfo, if successful
128
129 compileOne' m_tc_result mHscMessage
130 hsc_env0 summary mod_index nmods mb_old_iface maybe_old_linkable
131 source_modified0
132 = do
133 let dflags0 = ms_hspp_opts summary
134 this_mod = ms_mod summary
135 src_flavour = ms_hsc_src summary
136 location = ms_location summary
137 input_fn = expectJust "compile:hs" (ml_hs_file location)
138 input_fnpp = ms_hspp_file summary
139 mod_graph = hsc_mod_graph hsc_env0
140 needsTH = any (xopt Opt_TemplateHaskell . ms_hspp_opts) mod_graph
141 needsQQ = any (xopt Opt_QuasiQuotes . ms_hspp_opts) mod_graph
142 needsLinker = needsTH || needsQQ
143 isDynWay = any (== WayDyn) (ways dflags0)
144 isProfWay = any (== WayProf) (ways dflags0)
145 -- #8180 - when using TemplateHaskell, switch on -dynamic-too so
146 -- the linker can correctly load the object files.
147 let dflags1 = if needsLinker && dynamicGhc && not isDynWay && not isProfWay
148 then gopt_set dflags0 Opt_BuildDynamicToo
149 else dflags0
150
151 debugTraceMsg dflags1 2 (text "compile: input file" <+> text input_fnpp)
152
153 let basename = dropExtension input_fn
154
155 -- We add the directory in which the .hs files resides) to the import path.
156 -- This is needed when we try to compile the .hc file later, if it
157 -- imports a _stub.h file that we created here.
158 let current_dir = takeDirectory basename
159 old_paths = includePaths dflags1
160 dflags = dflags1 { includePaths = current_dir : old_paths }
161 hsc_env = hsc_env0 {hsc_dflags = dflags}
162
163 -- Figure out what lang we're generating
164 let hsc_lang = hscTarget dflags
165 -- ... and what the next phase should be
166 let next_phase = hscPostBackendPhase dflags src_flavour hsc_lang
167 -- ... and what file to generate the output into
168 output_fn <- getOutputFilename next_phase
169 Temporary basename dflags next_phase (Just location)
170
171 -- -fforce-recomp should also work with --make
172 let force_recomp = gopt Opt_ForceRecomp dflags
173 source_modified
174 | force_recomp || isNothing maybe_old_linkable = SourceModified
175 | otherwise = source_modified0
176 object_filename = ml_obj_file location
177
178 let always_do_basic_recompilation_check = case hsc_lang of
179 HscInterpreted -> True
180 _ -> False
181
182 e <- genericHscCompileGetFrontendResult
183 always_do_basic_recompilation_check
184 m_tc_result mHscMessage
185 hsc_env summary source_modified mb_old_iface (mod_index, nmods)
186
187 case e of
188 Left iface ->
189 do details <- genModDetails hsc_env iface
190 MASSERT(isJust maybe_old_linkable)
191 return (HomeModInfo{ hm_details = details,
192 hm_iface = iface,
193 hm_linkable = maybe_old_linkable })
194
195 Right (tc_result, mb_old_hash) ->
196 -- run the compiler
197 case hsc_lang of
198 HscInterpreted ->
199 case ms_hsc_src summary of
200 t | isHsBootOrSig t ->
201 do (iface, _changed, details) <- hscSimpleIface hsc_env tc_result mb_old_hash
202 return (HomeModInfo{ hm_details = details,
203 hm_iface = iface,
204 hm_linkable = maybe_old_linkable })
205 _ -> do guts0 <- hscDesugar hsc_env summary tc_result
206 guts <- hscSimplify hsc_env guts0
207 (iface, _changed, details, cgguts) <- hscNormalIface hsc_env guts mb_old_hash
208 (hasStub, comp_bc, modBreaks) <- hscInteractive hsc_env cgguts summary
209
210 stub_o <- case hasStub of
211 Nothing -> return []
212 Just stub_c -> do
213 stub_o <- compileStub hsc_env stub_c
214 return [DotO stub_o]
215
216 let hs_unlinked = [BCOs comp_bc modBreaks]
217 unlinked_time = ms_hs_date summary
218 -- Why do we use the timestamp of the source file here,
219 -- rather than the current time? This works better in
220 -- the case where the local clock is out of sync
221 -- with the filesystem's clock. It's just as accurate:
222 -- if the source is modified, then the linkable will
223 -- be out of date.
224 let linkable = LM unlinked_time this_mod
225 (hs_unlinked ++ stub_o)
226
227 return (HomeModInfo{ hm_details = details,
228 hm_iface = iface,
229 hm_linkable = Just linkable })
230 HscNothing ->
231 do (iface, changed, details) <- hscSimpleIface hsc_env tc_result mb_old_hash
232 when (gopt Opt_WriteInterface dflags) $
233 hscWriteIface dflags iface changed summary
234 let linkable = if isHsBootOrSig src_flavour
235 then maybe_old_linkable
236 else Just (LM (ms_hs_date summary) this_mod [])
237 return (HomeModInfo{ hm_details = details,
238 hm_iface = iface,
239 hm_linkable = linkable })
240
241 _ ->
242 case ms_hsc_src summary of
243 t | isHsBootOrSig t ->
244 do (iface, changed, details) <- hscSimpleIface hsc_env tc_result mb_old_hash
245 hscWriteIface dflags iface changed summary
246 touchObjectFile dflags object_filename
247 return (HomeModInfo{ hm_details = details,
248 hm_iface = iface,
249 hm_linkable = maybe_old_linkable })
250
251 _ -> do guts0 <- hscDesugar hsc_env summary tc_result
252 guts <- hscSimplify hsc_env guts0
253 (iface, changed, details, cgguts) <- hscNormalIface hsc_env guts mb_old_hash
254 hscWriteIface dflags iface changed summary
255
256 -- We're in --make mode: finish the compilation pipeline.
257 let mod_name = ms_mod_name summary
258 _ <- runPipeline StopLn hsc_env
259 (output_fn,
260 Just (HscOut src_flavour mod_name (HscRecomp cgguts summary)))
261 (Just basename)
262 Persistent
263 (Just location)
264 Nothing
265 -- The object filename comes from the ModLocation
266 o_time <- getModificationUTCTime object_filename
267 let linkable = LM o_time this_mod [DotO object_filename]
268
269 return (HomeModInfo{ hm_details = details,
270 hm_iface = iface,
271 hm_linkable = Just linkable })
272
273 -----------------------------------------------------------------------------
274 -- stub .h and .c files (for foreign export support)
275
276 -- The _stub.c file is derived from the haskell source file, possibly taking
277 -- into account the -stubdir option.
278 --
279 -- The object file created by compiling the _stub.c file is put into a
280 -- temporary file, which will be later combined with the main .o file
281 -- (see the MergeStubs phase).
282
283 compileStub :: HscEnv -> FilePath -> IO FilePath
284 compileStub hsc_env stub_c = do
285 (_, stub_o) <- runPipeline StopLn hsc_env (stub_c,Nothing) Nothing
286 Temporary Nothing{-no ModLocation-} Nothing
287
288 return stub_o
289
290 -- ---------------------------------------------------------------------------
291 -- Link
292
293 link :: GhcLink -- interactive or batch
294 -> DynFlags -- dynamic flags
295 -> Bool -- attempt linking in batch mode?
296 -> HomePackageTable -- what to link
297 -> IO SuccessFlag
298
299 -- For the moment, in the batch linker, we don't bother to tell doLink
300 -- which packages to link -- it just tries all that are available.
301 -- batch_attempt_linking should only be *looked at* in batch mode. It
302 -- should only be True if the upsweep was successful and someone
303 -- exports main, i.e., we have good reason to believe that linking
304 -- will succeed.
305
306 link ghcLink dflags
307 = lookupHook linkHook l dflags ghcLink dflags
308 where
309 l LinkInMemory _ _ _
310 = if cGhcWithInterpreter == "YES"
311 then -- Not Linking...(demand linker will do the job)
312 return Succeeded
313 else panicBadLink LinkInMemory
314
315 l NoLink _ _ _
316 = return Succeeded
317
318 l LinkBinary dflags batch_attempt_linking hpt
319 = link' dflags batch_attempt_linking hpt
320
321 l LinkStaticLib dflags batch_attempt_linking hpt
322 = link' dflags batch_attempt_linking hpt
323
324 l LinkDynLib dflags batch_attempt_linking hpt
325 = link' dflags batch_attempt_linking hpt
326
327 panicBadLink :: GhcLink -> a
328 panicBadLink other = panic ("link: GHC not built to link this way: " ++
329 show other)
330
331 link' :: DynFlags -- dynamic flags
332 -> Bool -- attempt linking in batch mode?
333 -> HomePackageTable -- what to link
334 -> IO SuccessFlag
335
336 link' dflags batch_attempt_linking hpt
337 | batch_attempt_linking
338 = do
339 let
340 staticLink = case ghcLink dflags of
341 LinkStaticLib -> True
342 _ -> platformBinariesAreStaticLibs (targetPlatform dflags)
343
344 -- Don't attempt to link hsigs; they don't actually produce objects.
345 -- This is in contrast to hs-boot files, which will /eventually/
346 -- get objects.
347 home_mod_infos =
348 filter ((==Nothing).mi_sig_of.hm_iface) (eltsUFM hpt)
349
350 -- the packages we depend on
351 pkg_deps = concatMap (map fst . dep_pkgs . mi_deps . hm_iface) home_mod_infos
352
353 -- the linkables to link
354 linkables = map (expectJust "link".hm_linkable) home_mod_infos
355
356 debugTraceMsg dflags 3 (text "link: linkables are ..." $$ vcat (map ppr linkables))
357
358 -- check for the -no-link flag
359 if isNoLink (ghcLink dflags)
360 then do debugTraceMsg dflags 3 (text "link(batch): linking omitted (-c flag given).")
361 return Succeeded
362 else do
363
364 let getOfiles (LM _ _ us) = map nameOfObject (filter isObject us)
365 obj_files = concatMap getOfiles linkables
366
367 exe_file = exeFileName staticLink dflags
368
369 linking_needed <- linkingNeeded dflags staticLink linkables pkg_deps
370
371 if not (gopt Opt_ForceRecomp dflags) && not linking_needed
372 then do debugTraceMsg dflags 2 (text exe_file <+> ptext (sLit "is up to date, linking not required."))
373 return Succeeded
374 else do
375
376 compilationProgressMsg dflags ("Linking " ++ exe_file ++ " ...")
377
378 -- Don't showPass in Batch mode; doLink will do that for us.
379 let link = case ghcLink dflags of
380 LinkBinary -> linkBinary
381 LinkStaticLib -> linkStaticLibCheck
382 LinkDynLib -> linkDynLibCheck
383 other -> panicBadLink other
384 link dflags obj_files pkg_deps
385
386 debugTraceMsg dflags 3 (text "link: done")
387
388 -- linkBinary only returns if it succeeds
389 return Succeeded
390
391 | otherwise
392 = do debugTraceMsg dflags 3 (text "link(batch): upsweep (partially) failed OR" $$
393 text " Main.main not exported; not linking.")
394 return Succeeded
395
396
397 linkingNeeded :: DynFlags -> Bool -> [Linkable] -> [PackageKey] -> IO Bool
398 linkingNeeded dflags staticLink linkables pkg_deps = do
399 -- if the modification time on the executable is later than the
400 -- modification times on all of the objects and libraries, then omit
401 -- linking (unless the -fforce-recomp flag was given).
402 let exe_file = exeFileName staticLink dflags
403 e_exe_time <- tryIO $ getModificationUTCTime exe_file
404 case e_exe_time of
405 Left _ -> return True
406 Right t -> do
407 -- first check object files and extra_ld_inputs
408 let extra_ld_inputs = [ f | FileOption _ f <- ldInputs dflags ]
409 e_extra_times <- mapM (tryIO . getModificationUTCTime) extra_ld_inputs
410 let (errs,extra_times) = splitEithers e_extra_times
411 let obj_times = map linkableTime linkables ++ extra_times
412 if not (null errs) || any (t <) obj_times
413 then return True
414 else do
415
416 -- next, check libraries. XXX this only checks Haskell libraries,
417 -- not extra_libraries or -l things from the command line.
418 let pkg_hslibs = [ (libraryDirs c, lib)
419 | Just c <- map (lookupPackage dflags) pkg_deps,
420 lib <- packageHsLibs dflags c ]
421
422 pkg_libfiles <- mapM (uncurry (findHSLib dflags)) pkg_hslibs
423 if any isNothing pkg_libfiles then return True else do
424 e_lib_times <- mapM (tryIO . getModificationUTCTime)
425 (catMaybes pkg_libfiles)
426 let (lib_errs,lib_times) = splitEithers e_lib_times
427 if not (null lib_errs) || any (t <) lib_times
428 then return True
429 else checkLinkInfo dflags pkg_deps exe_file
430
431 -- Returns 'False' if it was, and we can avoid linking, because the
432 -- previous binary was linked with "the same options".
433 checkLinkInfo :: DynFlags -> [PackageKey] -> FilePath -> IO Bool
434 checkLinkInfo dflags pkg_deps exe_file
435 | not (platformSupportsSavingLinkOpts (platformOS (targetPlatform dflags)))
436 -- ToDo: Windows and OS X do not use the ELF binary format, so
437 -- readelf does not work there. We need to find another way to do
438 -- this.
439 = return False -- conservatively we should return True, but not
440 -- linking in this case was the behaviour for a long
441 -- time so we leave it as-is.
442 | otherwise
443 = do
444 link_info <- getLinkInfo dflags pkg_deps
445 debugTraceMsg dflags 3 $ text ("Link info: " ++ link_info)
446 m_exe_link_info <- readElfSection dflags ghcLinkInfoSectionName exe_file
447 debugTraceMsg dflags 3 $ text ("Exe link info: " ++ show m_exe_link_info)
448 return (Just link_info /= m_exe_link_info)
449
450 platformSupportsSavingLinkOpts :: OS -> Bool
451 platformSupportsSavingLinkOpts os
452 | os == OSSolaris2 = False -- see #5382
453 | otherwise = osElfTarget os
454
455 ghcLinkInfoSectionName :: String
456 ghcLinkInfoSectionName = ".debug-ghc-link-info"
457 -- if we use the ".debug" prefix, then strip will strip it by default
458
459 findHSLib :: DynFlags -> [String] -> String -> IO (Maybe FilePath)
460 findHSLib dflags dirs lib = do
461 let batch_lib_file = if gopt Opt_Static dflags
462 then "lib" ++ lib <.> "a"
463 else mkSOName (targetPlatform dflags) lib
464 found <- filterM doesFileExist (map (</> batch_lib_file) dirs)
465 case found of
466 [] -> return Nothing
467 (x:_) -> return (Just x)
468
469 -- -----------------------------------------------------------------------------
470 -- Compile files in one-shot mode.
471
472 oneShot :: HscEnv -> Phase -> [(String, Maybe Phase)] -> IO ()
473 oneShot hsc_env stop_phase srcs = do
474 o_files <- mapM (compileFile hsc_env stop_phase) srcs
475 doLink (hsc_dflags hsc_env) stop_phase o_files
476
477 compileFile :: HscEnv -> Phase -> (FilePath, Maybe Phase) -> IO FilePath
478 compileFile hsc_env stop_phase (src, mb_phase) = do
479 exists <- doesFileExist src
480 when (not exists) $
481 throwGhcExceptionIO (CmdLineError ("does not exist: " ++ src))
482
483 let
484 dflags = hsc_dflags hsc_env
485 split = gopt Opt_SplitObjs dflags
486 mb_o_file = outputFile dflags
487 ghc_link = ghcLink dflags -- Set by -c or -no-link
488
489 -- When linking, the -o argument refers to the linker's output.
490 -- otherwise, we use it as the name for the pipeline's output.
491 output
492 -- If we are dong -fno-code, then act as if the output is
493 -- 'Temporary'. This stops GHC trying to copy files to their
494 -- final location.
495 | HscNothing <- hscTarget dflags = Temporary
496 | StopLn <- stop_phase, not (isNoLink ghc_link) = Persistent
497 -- -o foo applies to linker
498 | isJust mb_o_file = SpecificFile
499 -- -o foo applies to the file we are compiling now
500 | otherwise = Persistent
501
502 stop_phase' = case stop_phase of
503 As _ | split -> SplitAs
504 _ -> stop_phase
505
506 ( _, out_file) <- runPipeline stop_phase' hsc_env
507 (src, fmap RealPhase mb_phase) Nothing output
508 Nothing{-no ModLocation-} Nothing
509 return out_file
510
511
512 doLink :: DynFlags -> Phase -> [FilePath] -> IO ()
513 doLink dflags stop_phase o_files
514 | not (isStopLn stop_phase)
515 = return () -- We stopped before the linking phase
516
517 | otherwise
518 = case ghcLink dflags of
519 NoLink -> return ()
520 LinkBinary -> linkBinary dflags o_files []
521 LinkStaticLib -> linkStaticLibCheck dflags o_files []
522 LinkDynLib -> linkDynLibCheck dflags o_files []
523 other -> panicBadLink other
524
525
526 -- ---------------------------------------------------------------------------
527
528 -- | Run a compilation pipeline, consisting of multiple phases.
529 --
530 -- This is the interface to the compilation pipeline, which runs
531 -- a series of compilation steps on a single source file, specifying
532 -- at which stage to stop.
533 --
534 -- The DynFlags can be modified by phases in the pipeline (eg. by
535 -- OPTIONS_GHC pragmas), and the changes affect later phases in the
536 -- pipeline.
537 runPipeline
538 :: Phase -- ^ When to stop
539 -> HscEnv -- ^ Compilation environment
540 -> (FilePath,Maybe PhasePlus) -- ^ Input filename (and maybe -x suffix)
541 -> Maybe FilePath -- ^ original basename (if different from ^^^)
542 -> PipelineOutput -- ^ Output filename
543 -> Maybe ModLocation -- ^ A ModLocation, if this is a Haskell module
544 -> Maybe FilePath -- ^ stub object, if we have one
545 -> IO (DynFlags, FilePath) -- ^ (final flags, output filename)
546 runPipeline stop_phase hsc_env0 (input_fn, mb_phase)
547 mb_basename output maybe_loc maybe_stub_o
548
549 = do let
550 dflags0 = hsc_dflags hsc_env0
551
552 -- Decide where dump files should go based on the pipeline output
553 dflags = dflags0 { dumpPrefix = Just (basename ++ ".") }
554 hsc_env = hsc_env0 {hsc_dflags = dflags}
555
556 (input_basename, suffix) = splitExtension input_fn
557 suffix' = drop 1 suffix -- strip off the .
558 basename | Just b <- mb_basename = b
559 | otherwise = input_basename
560
561 -- If we were given a -x flag, then use that phase to start from
562 start_phase = fromMaybe (RealPhase (startPhase suffix')) mb_phase
563
564 isHaskell (RealPhase (Unlit _)) = True
565 isHaskell (RealPhase (Cpp _)) = True
566 isHaskell (RealPhase (HsPp _)) = True
567 isHaskell (RealPhase (Hsc _)) = True
568 isHaskell (HscOut {}) = True
569 isHaskell _ = False
570
571 isHaskellishFile = isHaskell start_phase
572
573 env = PipeEnv{ pe_isHaskellishFile = isHaskellishFile,
574 stop_phase,
575 src_filename = input_fn,
576 src_basename = basename,
577 src_suffix = suffix',
578 output_spec = output }
579
580 -- We want to catch cases of "you can't get there from here" before
581 -- we start the pipeline, because otherwise it will just run off the
582 -- end.
583 --
584 -- There is a partial ordering on phases, where A < B iff A occurs
585 -- before B in a normal compilation pipeline.
586
587 let happensBefore' = happensBefore dflags
588 case start_phase of
589 RealPhase start_phase' ->
590 when (not (start_phase' `happensBefore'` stop_phase)) $
591 throwGhcExceptionIO (UsageError
592 ("cannot compile this file to desired target: "
593 ++ input_fn))
594 HscOut {} -> return ()
595
596 debugTraceMsg dflags 4 (text "Running the pipeline")
597 r <- runPipeline' start_phase hsc_env env input_fn
598 maybe_loc maybe_stub_o
599
600 -- If we are compiling a Haskell module, and doing
601 -- -dynamic-too, but couldn't do the -dynamic-too fast
602 -- path, then rerun the pipeline for the dyn way
603 let dflags = extractDynFlags hsc_env
604 -- NB: Currently disabled on Windows (ref #7134, #8228, and #5987)
605 when (not $ platformOS (targetPlatform dflags) == OSMinGW32) $ do
606 when isHaskellishFile $ whenCannotGenerateDynamicToo dflags $ do
607 debugTraceMsg dflags 4
608 (text "Running the pipeline again for -dynamic-too")
609 let dflags' = dynamicTooMkDynamicDynFlags dflags
610 hsc_env' <- newHscEnv dflags'
611 _ <- runPipeline' start_phase hsc_env' env input_fn
612 maybe_loc maybe_stub_o
613 return ()
614 return r
615
616 runPipeline'
617 :: PhasePlus -- ^ When to start
618 -> HscEnv -- ^ Compilation environment
619 -> PipeEnv
620 -> FilePath -- ^ Input filename
621 -> Maybe ModLocation -- ^ A ModLocation, if this is a Haskell module
622 -> Maybe FilePath -- ^ stub object, if we have one
623 -> IO (DynFlags, FilePath) -- ^ (final flags, output filename)
624 runPipeline' start_phase hsc_env env input_fn
625 maybe_loc maybe_stub_o
626 = do
627 -- Execute the pipeline...
628 let state = PipeState{ hsc_env, maybe_loc, maybe_stub_o = maybe_stub_o }
629
630 evalP (pipeLoop start_phase input_fn) env state
631
632 -- ---------------------------------------------------------------------------
633 -- outer pipeline loop
634
635 -- | pipeLoop runs phases until we reach the stop phase
636 pipeLoop :: PhasePlus -> FilePath -> CompPipeline (DynFlags, FilePath)
637 pipeLoop phase input_fn = do
638 env <- getPipeEnv
639 dflags <- getDynFlags
640 let happensBefore' = happensBefore dflags
641 stopPhase = stop_phase env
642 case phase of
643 RealPhase realPhase | realPhase `eqPhase` stopPhase -- All done
644 -> -- Sometimes, a compilation phase doesn't actually generate any output
645 -- (eg. the CPP phase when -fcpp is not turned on). If we end on this
646 -- stage, but we wanted to keep the output, then we have to explicitly
647 -- copy the file, remembering to prepend a {-# LINE #-} pragma so that
648 -- further compilation stages can tell what the original filename was.
649 case output_spec env of
650 Temporary ->
651 return (dflags, input_fn)
652 output ->
653 do pst <- getPipeState
654 final_fn <- liftIO $ getOutputFilename
655 stopPhase output (src_basename env)
656 dflags stopPhase (maybe_loc pst)
657 when (final_fn /= input_fn) $ do
658 let msg = ("Copying `" ++ input_fn ++"' to `" ++ final_fn ++ "'")
659 line_prag = Just ("{-# LINE 1 \"" ++ src_filename env ++ "\" #-}\n")
660 liftIO $ copyWithHeader dflags msg line_prag input_fn final_fn
661 return (dflags, final_fn)
662
663
664 | not (realPhase `happensBefore'` stopPhase)
665 -- Something has gone wrong. We'll try to cover all the cases when
666 -- this could happen, so if we reach here it is a panic.
667 -- eg. it might happen if the -C flag is used on a source file that
668 -- has {-# OPTIONS -fasm #-}.
669 -> panic ("pipeLoop: at phase " ++ show realPhase ++
670 " but I wanted to stop at phase " ++ show stopPhase)
671
672 _
673 -> do liftIO $ debugTraceMsg dflags 4
674 (ptext (sLit "Running phase") <+> ppr phase)
675 (next_phase, output_fn) <- runHookedPhase phase input_fn dflags
676 r <- pipeLoop next_phase output_fn
677 case phase of
678 HscOut {} ->
679 whenGeneratingDynamicToo dflags $ do
680 setDynFlags $ dynamicTooMkDynamicDynFlags dflags
681 -- TODO shouldn't ignore result:
682 _ <- pipeLoop phase input_fn
683 return ()
684 _ ->
685 return ()
686 return r
687
688 runHookedPhase :: PhasePlus -> FilePath -> DynFlags
689 -> CompPipeline (PhasePlus, FilePath)
690 runHookedPhase pp input dflags =
691 lookupHook runPhaseHook runPhase dflags pp input dflags
692
693 -- -----------------------------------------------------------------------------
694 -- In each phase, we need to know into what filename to generate the
695 -- output. All the logic about which filenames we generate output
696 -- into is embodied in the following function.
697
698 phaseOutputFilename :: Phase{-next phase-} -> CompPipeline FilePath
699 phaseOutputFilename next_phase = do
700 PipeEnv{stop_phase, src_basename, output_spec} <- getPipeEnv
701 PipeState{maybe_loc, hsc_env} <- getPipeState
702 let dflags = hsc_dflags hsc_env
703 liftIO $ getOutputFilename stop_phase output_spec
704 src_basename dflags next_phase maybe_loc
705
706 getOutputFilename
707 :: Phase -> PipelineOutput -> String
708 -> DynFlags -> Phase{-next phase-} -> Maybe ModLocation -> IO FilePath
709 getOutputFilename stop_phase output basename dflags next_phase maybe_location
710 | is_last_phase, Persistent <- output = persistent_fn
711 | is_last_phase, SpecificFile <- output = case outputFile dflags of
712 Just f -> return f
713 Nothing ->
714 panic "SpecificFile: No filename"
715 | keep_this_output = persistent_fn
716 | otherwise = newTempName dflags suffix
717 where
718 hcsuf = hcSuf dflags
719 odir = objectDir dflags
720 osuf = objectSuf dflags
721 keep_hc = gopt Opt_KeepHcFiles dflags
722 keep_s = gopt Opt_KeepSFiles dflags
723 keep_bc = gopt Opt_KeepLlvmFiles dflags
724
725 myPhaseInputExt HCc = hcsuf
726 myPhaseInputExt MergeStub = osuf
727 myPhaseInputExt StopLn = osuf
728 myPhaseInputExt other = phaseInputExt other
729
730 is_last_phase = next_phase `eqPhase` stop_phase
731
732 -- sometimes, we keep output from intermediate stages
733 keep_this_output =
734 case next_phase of
735 As _ | keep_s -> True
736 LlvmOpt | keep_bc -> True
737 HCc | keep_hc -> True
738 _other -> False
739
740 suffix = myPhaseInputExt next_phase
741
742 -- persistent object files get put in odir
743 persistent_fn
744 | StopLn <- next_phase = return odir_persistent
745 | otherwise = return persistent
746
747 persistent = basename <.> suffix
748
749 odir_persistent
750 | Just loc <- maybe_location = ml_obj_file loc
751 | Just d <- odir = d </> persistent
752 | otherwise = persistent
753
754 -- -----------------------------------------------------------------------------
755 -- | Each phase in the pipeline returns the next phase to execute, and the
756 -- name of the file in which the output was placed.
757 --
758 -- We must do things dynamically this way, because we often don't know
759 -- what the rest of the phases will be until part-way through the
760 -- compilation: for example, an {-# OPTIONS -fasm #-} at the beginning
761 -- of a source file can change the latter stages of the pipeline from
762 -- taking the LLVM route to using the native code generator.
763 --
764 runPhase :: PhasePlus -- ^ Run this phase
765 -> FilePath -- ^ name of the input file
766 -> DynFlags -- ^ for convenience, we pass the current dflags in
767 -> CompPipeline (PhasePlus, -- next phase to run
768 FilePath) -- output filename
769
770 -- Invariant: the output filename always contains the output
771 -- Interesting case: Hsc when there is no recompilation to do
772 -- Then the output filename is still a .o file
773
774
775 -------------------------------------------------------------------------------
776 -- Unlit phase
777
778 runPhase (RealPhase (Unlit sf)) input_fn dflags
779 = do
780 output_fn <- phaseOutputFilename (Cpp sf)
781
782 let flags = [ -- The -h option passes the file name for unlit to
783 -- put in a #line directive
784 SysTools.Option "-h"
785 , SysTools.Option $ escape $ normalise input_fn
786 , SysTools.FileOption "" input_fn
787 , SysTools.FileOption "" output_fn
788 ]
789
790 liftIO $ SysTools.runUnlit dflags flags
791
792 return (RealPhase (Cpp sf), output_fn)
793 where
794 -- escape the characters \, ", and ', but don't try to escape
795 -- Unicode or anything else (so we don't use Util.charToC
796 -- here). If we get this wrong, then in
797 -- Coverage.addTicksToBinds where we check that the filename in
798 -- a SrcLoc is the same as the source filenaame, the two will
799 -- look bogusly different. See test:
800 -- libraries/hpc/tests/function/subdir/tough2.lhs
801 escape ('\\':cs) = '\\':'\\': escape cs
802 escape ('\"':cs) = '\\':'\"': escape cs
803 escape ('\'':cs) = '\\':'\'': escape cs
804 escape (c:cs) = c : escape cs
805 escape [] = []
806
807 -------------------------------------------------------------------------------
808 -- Cpp phase : (a) gets OPTIONS out of file
809 -- (b) runs cpp if necessary
810
811 runPhase (RealPhase (Cpp sf)) input_fn dflags0
812 = do
813 src_opts <- liftIO $ getOptionsFromFile dflags0 input_fn
814 (dflags1, unhandled_flags, warns)
815 <- liftIO $ parseDynamicFilePragma dflags0 src_opts
816 setDynFlags dflags1
817 liftIO $ checkProcessArgsResult dflags1 unhandled_flags
818
819 if not (xopt Opt_Cpp dflags1) then do
820 -- we have to be careful to emit warnings only once.
821 unless (gopt Opt_Pp dflags1) $
822 liftIO $ handleFlagWarnings dflags1 warns
823
824 -- no need to preprocess CPP, just pass input file along
825 -- to the next phase of the pipeline.
826 return (RealPhase (HsPp sf), input_fn)
827 else do
828 output_fn <- phaseOutputFilename (HsPp sf)
829 liftIO $ doCpp dflags1 True{-raw-}
830 input_fn output_fn
831 -- re-read the pragmas now that we've preprocessed the file
832 -- See #2464,#3457
833 src_opts <- liftIO $ getOptionsFromFile dflags0 output_fn
834 (dflags2, unhandled_flags, warns)
835 <- liftIO $ parseDynamicFilePragma dflags0 src_opts
836 liftIO $ checkProcessArgsResult dflags2 unhandled_flags
837 unless (gopt Opt_Pp dflags2) $
838 liftIO $ handleFlagWarnings dflags2 warns
839 -- the HsPp pass below will emit warnings
840
841 setDynFlags dflags2
842
843 return (RealPhase (HsPp sf), output_fn)
844
845 -------------------------------------------------------------------------------
846 -- HsPp phase
847
848 runPhase (RealPhase (HsPp sf)) input_fn dflags
849 = do
850 if not (gopt Opt_Pp dflags) then
851 -- no need to preprocess, just pass input file along
852 -- to the next phase of the pipeline.
853 return (RealPhase (Hsc sf), input_fn)
854 else do
855 PipeEnv{src_basename, src_suffix} <- getPipeEnv
856 let orig_fn = src_basename <.> src_suffix
857 output_fn <- phaseOutputFilename (Hsc sf)
858 liftIO $ SysTools.runPp dflags
859 ( [ SysTools.Option orig_fn
860 , SysTools.Option input_fn
861 , SysTools.FileOption "" output_fn
862 ]
863 )
864
865 -- re-read pragmas now that we've parsed the file (see #3674)
866 src_opts <- liftIO $ getOptionsFromFile dflags output_fn
867 (dflags1, unhandled_flags, warns)
868 <- liftIO $ parseDynamicFilePragma dflags src_opts
869 setDynFlags dflags1
870 liftIO $ checkProcessArgsResult dflags1 unhandled_flags
871 liftIO $ handleFlagWarnings dflags1 warns
872
873 return (RealPhase (Hsc sf), output_fn)
874
875 -----------------------------------------------------------------------------
876 -- Hsc phase
877
878 -- Compilation of a single module, in "legacy" mode (_not_ under
879 -- the direction of the compilation manager).
880 runPhase (RealPhase (Hsc src_flavour)) input_fn dflags0
881 = do -- normal Hsc mode, not mkdependHS
882
883 PipeEnv{ stop_phase=stop,
884 src_basename=basename,
885 src_suffix=suff } <- getPipeEnv
886
887 -- we add the current directory (i.e. the directory in which
888 -- the .hs files resides) to the include path, since this is
889 -- what gcc does, and it's probably what you want.
890 let current_dir = takeDirectory basename
891 paths = includePaths dflags0
892 dflags = dflags0 { includePaths = current_dir : paths }
893
894 setDynFlags dflags
895
896 -- gather the imports and module name
897 (hspp_buf,mod_name,imps,src_imps) <- liftIO $ do
898 do
899 buf <- hGetStringBuffer input_fn
900 (src_imps,imps,L _ mod_name) <- getImports dflags buf input_fn (basename <.> suff)
901 return (Just buf, mod_name, imps, src_imps)
902
903 -- Take -o into account if present
904 -- Very like -ohi, but we must *only* do this if we aren't linking
905 -- (If we're linking then the -o applies to the linked thing, not to
906 -- the object file for one module.)
907 -- Note the nasty duplication with the same computation in compileFile above
908 location <- getLocation src_flavour mod_name
909
910 let o_file = ml_obj_file location -- The real object file
911
912 -- Figure out if the source has changed, for recompilation avoidance.
913 --
914 -- Setting source_unchanged to True means that M.o seems
915 -- to be up to date wrt M.hs; so no need to recompile unless imports have
916 -- changed (which the compiler itself figures out).
917 -- Setting source_unchanged to False tells the compiler that M.o is out of
918 -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
919 src_timestamp <- liftIO $ getModificationUTCTime (basename <.> suff)
920
921 source_unchanged <- liftIO $
922 if not (isStopLn stop)
923 -- SourceModified unconditionally if
924 -- (a) recompilation checker is off, or
925 -- (b) we aren't going all the way to .o file (e.g. ghc -S)
926 then return SourceModified
927 -- Otherwise look at file modification dates
928 else do o_file_exists <- doesFileExist o_file
929 if not o_file_exists
930 then return SourceModified -- Need to recompile
931 else do t2 <- getModificationUTCTime o_file
932 if t2 > src_timestamp
933 then return SourceUnmodified
934 else return SourceModified
935
936 PipeState{hsc_env=hsc_env'} <- getPipeState
937
938 -- Tell the finder cache about this module
939 mod <- liftIO $ addHomeModuleToFinder hsc_env' mod_name location
940
941 -- Make the ModSummary to hand to hscMain
942 let
943 mod_summary = ModSummary { ms_mod = mod,
944 ms_hsc_src = src_flavour,
945 ms_hspp_file = input_fn,
946 ms_hspp_opts = dflags,
947 ms_hspp_buf = hspp_buf,
948 ms_location = location,
949 ms_hs_date = src_timestamp,
950 ms_obj_date = Nothing,
951 ms_textual_imps = imps,
952 ms_srcimps = src_imps }
953
954 -- run the compiler!
955 result <- liftIO $ hscCompileOneShot hsc_env'
956 mod_summary source_unchanged
957
958 return (HscOut src_flavour mod_name result,
959 panic "HscOut doesn't have an input filename")
960
961 runPhase (HscOut src_flavour mod_name result) _ dflags = do
962 location <- getLocation src_flavour mod_name
963 setModLocation location
964
965 let o_file = ml_obj_file location -- The real object file
966 hsc_lang = hscTarget dflags
967 next_phase = hscPostBackendPhase dflags src_flavour hsc_lang
968
969 case result of
970 HscNotGeneratingCode ->
971 return (RealPhase next_phase,
972 panic "No output filename from Hsc when no-code")
973 HscUpToDate ->
974 do liftIO $ touchObjectFile dflags o_file
975 -- The .o file must have a later modification date
976 -- than the source file (else we wouldn't get Nothing)
977 -- but we touch it anyway, to keep 'make' happy (we think).
978 return (RealPhase StopLn, o_file)
979 HscUpdateBoot ->
980 do -- In the case of hs-boot files, generate a dummy .o-boot
981 -- stamp file for the benefit of Make
982 liftIO $ touchObjectFile dflags o_file
983 return (RealPhase next_phase, o_file)
984 HscRecomp cgguts mod_summary
985 -> do output_fn <- phaseOutputFilename next_phase
986
987 PipeState{hsc_env=hsc_env'} <- getPipeState
988
989 (outputFilename, mStub) <- liftIO $ hscGenHardCode hsc_env' cgguts mod_summary output_fn
990 case mStub of
991 Nothing -> return ()
992 Just stub_c ->
993 do stub_o <- liftIO $ compileStub hsc_env' stub_c
994 setStubO stub_o
995
996 return (RealPhase next_phase, outputFilename)
997
998 -----------------------------------------------------------------------------
999 -- Cmm phase
1000
1001 runPhase (RealPhase CmmCpp) input_fn dflags
1002 = do
1003 output_fn <- phaseOutputFilename Cmm
1004 liftIO $ doCpp dflags False{-not raw-}
1005 input_fn output_fn
1006 return (RealPhase Cmm, output_fn)
1007
1008 runPhase (RealPhase Cmm) input_fn dflags
1009 = do
1010 let hsc_lang = hscTarget dflags
1011
1012 let next_phase = hscPostBackendPhase dflags HsSrcFile hsc_lang
1013
1014 output_fn <- phaseOutputFilename next_phase
1015
1016 PipeState{hsc_env} <- getPipeState
1017
1018 liftIO $ hscCompileCmmFile hsc_env input_fn output_fn
1019
1020 return (RealPhase next_phase, output_fn)
1021
1022 -----------------------------------------------------------------------------
1023 -- Cc phase
1024
1025 -- we don't support preprocessing .c files (with -E) now. Doing so introduces
1026 -- way too many hacks, and I can't say I've ever used it anyway.
1027
1028 runPhase (RealPhase cc_phase) input_fn dflags
1029 | any (cc_phase `eqPhase`) [Cc, Ccpp, HCc, Cobjc, Cobjcpp]
1030 = do
1031 let platform = targetPlatform dflags
1032 hcc = cc_phase `eqPhase` HCc
1033
1034 let cmdline_include_paths = includePaths dflags
1035
1036 -- HC files have the dependent packages stamped into them
1037 pkgs <- if hcc then liftIO $ getHCFilePackages input_fn else return []
1038
1039 -- add package include paths even if we're just compiling .c
1040 -- files; this is the Value Add(TM) that using ghc instead of
1041 -- gcc gives you :)
1042 pkg_include_dirs <- liftIO $ getPackageIncludePath dflags pkgs
1043 let include_paths = foldr (\ x xs -> ("-I" ++ x) : xs) []
1044 (cmdline_include_paths ++ pkg_include_dirs)
1045
1046 let gcc_extra_viac_flags = extraGccViaCFlags dflags
1047 let pic_c_flags = picCCOpts dflags
1048
1049 let verbFlags = getVerbFlags dflags
1050
1051 -- cc-options are not passed when compiling .hc files. Our
1052 -- hc code doesn't not #include any header files anyway, so these
1053 -- options aren't necessary.
1054 pkg_extra_cc_opts <- liftIO $
1055 if cc_phase `eqPhase` HCc
1056 then return []
1057 else getPackageExtraCcOpts dflags pkgs
1058
1059 framework_paths <-
1060 if platformUsesFrameworks platform
1061 then do pkgFrameworkPaths <- liftIO $ getPackageFrameworkPath dflags pkgs
1062 let cmdlineFrameworkPaths = frameworkPaths dflags
1063 return $ map ("-F"++)
1064 (cmdlineFrameworkPaths ++ pkgFrameworkPaths)
1065 else return []
1066
1067 let split_objs = gopt Opt_SplitObjs dflags
1068 split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
1069 | otherwise = [ ]
1070
1071 let cc_opt | optLevel dflags >= 2 = [ "-O2" ]
1072 | optLevel dflags >= 1 = [ "-O" ]
1073 | otherwise = []
1074
1075 -- Decide next phase
1076 let next_phase = As False
1077 output_fn <- phaseOutputFilename next_phase
1078
1079 let
1080 more_hcc_opts =
1081 -- on x86 the floating point regs have greater precision
1082 -- than a double, which leads to unpredictable results.
1083 -- By default, we turn this off with -ffloat-store unless
1084 -- the user specified -fexcess-precision.
1085 (if platformArch platform == ArchX86 &&
1086 not (gopt Opt_ExcessPrecision dflags)
1087 then [ "-ffloat-store" ]
1088 else []) ++
1089
1090 -- gcc's -fstrict-aliasing allows two accesses to memory
1091 -- to be considered non-aliasing if they have different types.
1092 -- This interacts badly with the C code we generate, which is
1093 -- very weakly typed, being derived from C--.
1094 ["-fno-strict-aliasing"]
1095
1096 ghcVersionH <- liftIO $ getGhcVersionPathName dflags
1097
1098 let gcc_lang_opt | cc_phase `eqPhase` Ccpp = "c++"
1099 | cc_phase `eqPhase` Cobjc = "objective-c"
1100 | cc_phase `eqPhase` Cobjcpp = "objective-c++"
1101 | otherwise = "c"
1102 liftIO $ SysTools.runCc dflags (
1103 -- force the C compiler to interpret this file as C when
1104 -- compiling .hc files, by adding the -x c option.
1105 -- Also useful for plain .c files, just in case GHC saw a
1106 -- -x c option.
1107 [ SysTools.Option "-x", SysTools.Option gcc_lang_opt
1108 , SysTools.FileOption "" input_fn
1109 , SysTools.Option "-o"
1110 , SysTools.FileOption "" output_fn
1111 ]
1112 ++ map SysTools.Option (
1113 pic_c_flags
1114
1115 -- Stub files generated for foreign exports references the runIO_closure
1116 -- and runNonIO_closure symbols, which are defined in the base package.
1117 -- These symbols are imported into the stub.c file via RtsAPI.h, and the
1118 -- way we do the import depends on whether we're currently compiling
1119 -- the base package or not.
1120 ++ (if platformOS platform == OSMinGW32 &&
1121 thisPackage dflags == basePackageKey
1122 then [ "-DCOMPILING_BASE_PACKAGE" ]
1123 else [])
1124
1125 -- We only support SparcV9 and better because V8 lacks an atomic CAS
1126 -- instruction. Note that the user can still override this
1127 -- (e.g., -mcpu=ultrasparc) as GCC picks the "best" -mcpu flag
1128 -- regardless of the ordering.
1129 --
1130 -- This is a temporary hack. See #2872, commit
1131 -- 5bd3072ac30216a505151601884ac88bf404c9f2
1132 ++ (if platformArch platform == ArchSPARC
1133 then ["-mcpu=v9"]
1134 else [])
1135
1136 -- GCC 4.6+ doesn't like -Wimplicit when compiling C++.
1137 ++ (if (cc_phase /= Ccpp && cc_phase /= Cobjcpp)
1138 then ["-Wimplicit"]
1139 else [])
1140
1141 ++ (if hcc
1142 then gcc_extra_viac_flags ++ more_hcc_opts
1143 else [])
1144 ++ verbFlags
1145 ++ [ "-S" ]
1146 ++ cc_opt
1147 ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt
1148 , "-include", ghcVersionH
1149 ]
1150 ++ framework_paths
1151 ++ split_opt
1152 ++ include_paths
1153 ++ pkg_extra_cc_opts
1154 ))
1155
1156 return (RealPhase next_phase, output_fn)
1157
1158 -----------------------------------------------------------------------------
1159 -- Splitting phase
1160
1161 runPhase (RealPhase Splitter) input_fn dflags
1162 = do -- tmp_pfx is the prefix used for the split .s files
1163
1164 split_s_prefix <- liftIO $ SysTools.newTempName dflags "split"
1165 let n_files_fn = split_s_prefix
1166
1167 liftIO $ SysTools.runSplit dflags
1168 [ SysTools.FileOption "" input_fn
1169 , SysTools.FileOption "" split_s_prefix
1170 , SysTools.FileOption "" n_files_fn
1171 ]
1172
1173 -- Save the number of split files for future references
1174 s <- liftIO $ readFile n_files_fn
1175 let n_files = read s :: Int
1176 dflags' = dflags { splitInfo = Just (split_s_prefix, n_files) }
1177
1178 setDynFlags dflags'
1179
1180 -- Remember to delete all these files
1181 liftIO $ addFilesToClean dflags'
1182 [ split_s_prefix ++ "__" ++ show n ++ ".s"
1183 | n <- [1..n_files]]
1184
1185 return (RealPhase SplitAs,
1186 "**splitter**") -- we don't use the filename in SplitAs
1187
1188 -----------------------------------------------------------------------------
1189 -- As, SpitAs phase : Assembler
1190
1191 -- This is for calling the assembler on a regular assembly file (not split).
1192 runPhase (RealPhase (As with_cpp)) input_fn dflags
1193 = do
1194 -- LLVM from version 3.0 onwards doesn't support the OS X system
1195 -- assembler, so we use clang as the assembler instead. (#5636)
1196 let whichAsProg | hscTarget dflags == HscLlvm &&
1197 platformOS (targetPlatform dflags) == OSDarwin
1198 = do
1199 -- be careful what options we call clang with
1200 -- see #5903 and #7617 for bugs caused by this.
1201 llvmVer <- liftIO $ figureLlvmVersion dflags
1202 return $ case llvmVer of
1203 Just n | n >= 30 -> SysTools.runClang
1204 _ -> SysTools.runAs
1205
1206 | otherwise = return SysTools.runAs
1207
1208 as_prog <- whichAsProg
1209 let cmdline_include_paths = includePaths dflags
1210 let pic_c_flags = picCCOpts dflags
1211
1212 next_phase <- maybeMergeStub
1213 output_fn <- phaseOutputFilename next_phase
1214
1215 -- we create directories for the object file, because it
1216 -- might be a hierarchical module.
1217 liftIO $ createDirectoryIfMissing True (takeDirectory output_fn)
1218
1219 ccInfo <- liftIO $ getCompilerInfo dflags
1220 let runAssembler inputFilename outputFilename
1221 = liftIO $ as_prog dflags
1222 ([ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ]
1223
1224 -- See Note [-fPIC for assembler]
1225 ++ map SysTools.Option pic_c_flags
1226
1227 -- We only support SparcV9 and better because V8 lacks an atomic CAS
1228 -- instruction so we have to make sure that the assembler accepts the
1229 -- instruction set. Note that the user can still override this
1230 -- (e.g., -mcpu=ultrasparc). GCC picks the "best" -mcpu flag
1231 -- regardless of the ordering.
1232 --
1233 -- This is a temporary hack.
1234 ++ (if platformArch (targetPlatform dflags) == ArchSPARC
1235 then [SysTools.Option "-mcpu=v9"]
1236 else [])
1237 ++ (if any (ccInfo ==) [Clang, AppleClang, AppleClang51]
1238 then [SysTools.Option "-Qunused-arguments"]
1239 else [])
1240 ++ [ SysTools.Option "-x"
1241 , if with_cpp
1242 then SysTools.Option "assembler-with-cpp"
1243 else SysTools.Option "assembler"
1244 , SysTools.Option "-c"
1245 , SysTools.FileOption "" inputFilename
1246 , SysTools.Option "-o"
1247 , SysTools.FileOption "" outputFilename
1248 ])
1249
1250 liftIO $ debugTraceMsg dflags 4 (text "Running the assembler")
1251 runAssembler input_fn output_fn
1252 return (RealPhase next_phase, output_fn)
1253
1254
1255 -- This is for calling the assembler on a split assembly file (so a collection
1256 -- of assembly files)
1257 runPhase (RealPhase SplitAs) _input_fn dflags
1258 = do
1259 -- we'll handle the stub_o file in this phase, so don't MergeStub,
1260 -- just jump straight to StopLn afterwards.
1261 let next_phase = StopLn
1262 output_fn <- phaseOutputFilename next_phase
1263
1264 let base_o = dropExtension output_fn
1265 osuf = objectSuf dflags
1266 split_odir = base_o ++ "_" ++ osuf ++ "_split"
1267
1268 let pic_c_flags = picCCOpts dflags
1269
1270 -- this also creates the hierarchy
1271 liftIO $ createDirectoryIfMissing True split_odir
1272
1273 -- remove M_split/ *.o, because we're going to archive M_split/ *.o
1274 -- later and we don't want to pick up any old objects.
1275 fs <- liftIO $ getDirectoryContents split_odir
1276 liftIO $ mapM_ removeFile $
1277 map (split_odir </>) $ filter (osuf `isSuffixOf`) fs
1278
1279 let (split_s_prefix, n) = case splitInfo dflags of
1280 Nothing -> panic "No split info"
1281 Just x -> x
1282
1283 let split_s n = split_s_prefix ++ "__" ++ show n <.> "s"
1284
1285 split_obj :: Int -> FilePath
1286 split_obj n = split_odir </>
1287 takeFileName base_o ++ "__" ++ show n <.> osuf
1288
1289 let assemble_file n
1290 = SysTools.runAs dflags (
1291
1292 -- We only support SparcV9 and better because V8 lacks an atomic CAS
1293 -- instruction so we have to make sure that the assembler accepts the
1294 -- instruction set. Note that the user can still override this
1295 -- (e.g., -mcpu=ultrasparc). GCC picks the "best" -mcpu flag
1296 -- regardless of the ordering.
1297 --
1298 -- This is a temporary hack.
1299 (if platformArch (targetPlatform dflags) == ArchSPARC
1300 then [SysTools.Option "-mcpu=v9"]
1301 else []) ++
1302
1303 -- See Note [-fPIC for assembler]
1304 map SysTools.Option pic_c_flags ++
1305
1306 [ SysTools.Option "-c"
1307 , SysTools.Option "-o"
1308 , SysTools.FileOption "" (split_obj n)
1309 , SysTools.FileOption "" (split_s n)
1310 ])
1311
1312 liftIO $ mapM_ assemble_file [1..n]
1313
1314 -- Note [pipeline-split-init]
1315 -- If we have a stub file, it may contain constructor
1316 -- functions for initialisation of this module. We can't
1317 -- simply leave the stub as a separate object file, because it
1318 -- will never be linked in: nothing refers to it. We need to
1319 -- ensure that if we ever refer to the data in this module
1320 -- that needs initialisation, then we also pull in the
1321 -- initialisation routine.
1322 --
1323 -- To that end, we make a DANGEROUS ASSUMPTION here: the data
1324 -- that needs to be initialised is all in the FIRST split
1325 -- object. See Note [codegen-split-init].
1326
1327 PipeState{maybe_stub_o} <- getPipeState
1328 case maybe_stub_o of
1329 Nothing -> return ()
1330 Just stub_o -> liftIO $ do
1331 tmp_split_1 <- newTempName dflags osuf
1332 let split_1 = split_obj 1
1333 copyFile split_1 tmp_split_1
1334 removeFile split_1
1335 joinObjectFiles dflags [tmp_split_1, stub_o] split_1
1336
1337 -- join them into a single .o file
1338 liftIO $ joinObjectFiles dflags (map split_obj [1..n]) output_fn
1339
1340 return (RealPhase next_phase, output_fn)
1341
1342 -----------------------------------------------------------------------------
1343 -- LlvmOpt phase
1344
1345 runPhase (RealPhase LlvmOpt) input_fn dflags
1346 = do
1347 ver <- liftIO $ readIORef (llvmVersion dflags)
1348
1349 let opt_lvl = max 0 (min 2 $ optLevel dflags)
1350 -- don't specify anything if user has specified commands. We do this
1351 -- for opt but not llc since opt is very specifically for optimisation
1352 -- passes only, so if the user is passing us extra options we assume
1353 -- they know what they are doing and don't get in the way.
1354 optFlag = if null (getOpts dflags opt_lo)
1355 then map SysTools.Option $ words (llvmOpts ver !! opt_lvl)
1356 else []
1357 tbaa | ver < 29 = "" -- no tbaa in 2.8 and earlier
1358 | gopt Opt_LlvmTBAA dflags = "--enable-tbaa=true"
1359 | otherwise = "--enable-tbaa=false"
1360
1361
1362 output_fn <- phaseOutputFilename LlvmLlc
1363
1364 liftIO $ SysTools.runLlvmOpt dflags
1365 ([ SysTools.FileOption "" input_fn,
1366 SysTools.Option "-o",
1367 SysTools.FileOption "" output_fn]
1368 ++ optFlag
1369 ++ [SysTools.Option tbaa])
1370
1371 return (RealPhase LlvmLlc, output_fn)
1372 where
1373 -- we always (unless -optlo specified) run Opt since we rely on it to
1374 -- fix up some pretty big deficiencies in the code we generate
1375 llvmOpts ver = [ "-mem2reg -globalopt"
1376 , if ver >= 34 then "-O1 -globalopt" else "-O1"
1377 -- LLVM 3.4 -O1 doesn't eliminate aliases reliably (bug #8855)
1378 , "-O2"
1379 ]
1380
1381 -----------------------------------------------------------------------------
1382 -- LlvmLlc phase
1383
1384 runPhase (RealPhase LlvmLlc) input_fn dflags
1385 = do
1386 ver <- liftIO $ readIORef (llvmVersion dflags)
1387
1388 let opt_lvl = max 0 (min 2 $ optLevel dflags)
1389 -- iOS requires external references to be loaded indirectly from the
1390 -- DATA segment or dyld traps at runtime writing into TEXT: see #7722
1391 rmodel | platformOS (targetPlatform dflags) == OSiOS = "dynamic-no-pic"
1392 | gopt Opt_PIC dflags = "pic"
1393 | not (gopt Opt_Static dflags) = "dynamic-no-pic"
1394 | otherwise = "static"
1395 tbaa | ver < 29 = "" -- no tbaa in 2.8 and earlier
1396 | gopt Opt_LlvmTBAA dflags = "--enable-tbaa=true"
1397 | otherwise = "--enable-tbaa=false"
1398
1399 -- hidden debugging flag '-dno-llvm-mangler' to skip mangling
1400 let next_phase = case gopt Opt_NoLlvmMangler dflags of
1401 False -> LlvmMangle
1402 True | gopt Opt_SplitObjs dflags -> Splitter
1403 True -> As False
1404
1405 output_fn <- phaseOutputFilename next_phase
1406
1407 liftIO $ SysTools.runLlvmLlc dflags
1408 ([ SysTools.Option (llvmOpts !! opt_lvl),
1409 SysTools.Option $ "-relocation-model=" ++ rmodel,
1410 SysTools.FileOption "" input_fn,
1411 SysTools.Option "-o", SysTools.FileOption "" output_fn]
1412 ++ [SysTools.Option tbaa]
1413 ++ map SysTools.Option fpOpts
1414 ++ map SysTools.Option abiOpts
1415 ++ map SysTools.Option sseOpts
1416 ++ map SysTools.Option avxOpts
1417 ++ map SysTools.Option avx512Opts
1418 ++ map SysTools.Option stackAlignOpts)
1419
1420 return (RealPhase next_phase, output_fn)
1421 where
1422 -- Bug in LLVM at O3 on OSX.
1423 llvmOpts = if platformOS (targetPlatform dflags) == OSDarwin
1424 then ["-O1", "-O2", "-O2"]
1425 else ["-O1", "-O2", "-O3"]
1426 -- On ARMv7 using LLVM, LLVM fails to allocate floating point registers
1427 -- while compiling GHC source code. It's probably due to fact that it
1428 -- does not enable VFP by default. Let's do this manually here
1429 fpOpts = case platformArch (targetPlatform dflags) of
1430 ArchARM ARMv7 ext _ -> if (elem VFPv3 ext)
1431 then ["-mattr=+v7,+vfp3"]
1432 else if (elem VFPv3D16 ext)
1433 then ["-mattr=+v7,+vfp3,+d16"]
1434 else []
1435 ArchARM ARMv6 ext _ -> if (elem VFPv2 ext)
1436 then ["-mattr=+v6,+vfp2"]
1437 else ["-mattr=+v6"]
1438 _ -> []
1439 -- On Ubuntu/Debian with ARM hard float ABI, LLVM's llc still
1440 -- compiles into soft-float ABI. We need to explicitly set abi
1441 -- to hard
1442 abiOpts = case platformArch (targetPlatform dflags) of
1443 ArchARM _ _ HARD -> ["-float-abi=hard"]
1444 ArchARM _ _ _ -> []
1445 _ -> []
1446
1447 sseOpts | isSse4_2Enabled dflags = ["-mattr=+sse42"]
1448 | isSse2Enabled dflags = ["-mattr=+sse2"]
1449 | isSseEnabled dflags = ["-mattr=+sse"]
1450 | otherwise = []
1451
1452 avxOpts | isAvx512fEnabled dflags = ["-mattr=+avx512f"]
1453 | isAvx2Enabled dflags = ["-mattr=+avx2"]
1454 | isAvxEnabled dflags = ["-mattr=+avx"]
1455 | otherwise = []
1456
1457 avx512Opts =
1458 [ "-mattr=+avx512cd" | isAvx512cdEnabled dflags ] ++
1459 [ "-mattr=+avx512er" | isAvx512erEnabled dflags ] ++
1460 [ "-mattr=+avx512pf" | isAvx512pfEnabled dflags ]
1461
1462 stackAlignOpts =
1463 case platformArch (targetPlatform dflags) of
1464 ArchX86_64 | isAvxEnabled dflags -> ["-stack-alignment=32"]
1465 _ -> []
1466
1467 -----------------------------------------------------------------------------
1468 -- LlvmMangle phase
1469
1470 runPhase (RealPhase LlvmMangle) input_fn dflags
1471 = do
1472 let next_phase = if gopt Opt_SplitObjs dflags then Splitter else As False
1473 output_fn <- phaseOutputFilename next_phase
1474 liftIO $ llvmFixupAsm dflags input_fn output_fn
1475 return (RealPhase next_phase, output_fn)
1476
1477 -----------------------------------------------------------------------------
1478 -- merge in stub objects
1479
1480 runPhase (RealPhase MergeStub) input_fn dflags
1481 = do
1482 PipeState{maybe_stub_o} <- getPipeState
1483 output_fn <- phaseOutputFilename StopLn
1484 liftIO $ createDirectoryIfMissing True (takeDirectory output_fn)
1485 case maybe_stub_o of
1486 Nothing ->
1487 panic "runPhase(MergeStub): no stub"
1488 Just stub_o -> do
1489 liftIO $ joinObjectFiles dflags [input_fn, stub_o] output_fn
1490 return (RealPhase StopLn, output_fn)
1491
1492 -- warning suppression
1493 runPhase (RealPhase other) _input_fn _dflags =
1494 panic ("runPhase: don't know how to run phase " ++ show other)
1495
1496 maybeMergeStub :: CompPipeline Phase
1497 maybeMergeStub
1498 = do
1499 PipeState{maybe_stub_o} <- getPipeState
1500 if isJust maybe_stub_o then return MergeStub else return StopLn
1501
1502 getLocation :: HscSource -> ModuleName -> CompPipeline ModLocation
1503 getLocation src_flavour mod_name = do
1504 dflags <- getDynFlags
1505
1506 PipeEnv{ src_basename=basename,
1507 src_suffix=suff } <- getPipeEnv
1508
1509 -- Build a ModLocation to pass to hscMain.
1510 -- The source filename is rather irrelevant by now, but it's used
1511 -- by hscMain for messages. hscMain also needs
1512 -- the .hi and .o filenames, and this is as good a way
1513 -- as any to generate them, and better than most. (e.g. takes
1514 -- into account the -osuf flags)
1515 location1 <- liftIO $ mkHomeModLocation2 dflags mod_name basename suff
1516
1517 -- Boot-ify it if necessary
1518 let location2 | HsBootFile <- src_flavour = addBootSuffixLocn location1
1519 | otherwise = location1
1520
1521
1522 -- Take -ohi into account if present
1523 -- This can't be done in mkHomeModuleLocation because
1524 -- it only applies to the module being compiles
1525 let ohi = outputHi dflags
1526 location3 | Just fn <- ohi = location2{ ml_hi_file = fn }
1527 | otherwise = location2
1528
1529 -- Take -o into account if present
1530 -- Very like -ohi, but we must *only* do this if we aren't linking
1531 -- (If we're linking then the -o applies to the linked thing, not to
1532 -- the object file for one module.)
1533 -- Note the nasty duplication with the same computation in compileFile above
1534 let expl_o_file = outputFile dflags
1535 location4 | Just ofile <- expl_o_file
1536 , isNoLink (ghcLink dflags)
1537 = location3 { ml_obj_file = ofile }
1538 | otherwise = location3
1539
1540 return location4
1541
1542 -----------------------------------------------------------------------------
1543 -- MoveBinary sort-of-phase
1544 -- After having produced a binary, move it somewhere else and generate a
1545 -- wrapper script calling the binary. Currently, we need this only in
1546 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
1547 -- central directory.
1548 -- This is called from linkBinary below, after linking. I haven't made it
1549 -- a separate phase to minimise interfering with other modules, and
1550 -- we don't need the generality of a phase (MoveBinary is always
1551 -- done after linking and makes only sense in a parallel setup) -- HWL
1552
1553 runPhase_MoveBinary :: DynFlags -> FilePath -> IO Bool
1554 runPhase_MoveBinary dflags input_fn
1555 | WayPar `elem` ways dflags && not (gopt Opt_Static dflags) =
1556 panic ("Don't know how to combine PVM wrapper and dynamic wrapper")
1557 | WayPar `elem` ways dflags = do
1558 let sysMan = pgm_sysman dflags
1559 pvm_root <- getEnv "PVM_ROOT"
1560 pvm_arch <- getEnv "PVM_ARCH"
1561 let
1562 pvm_executable_base = "=" ++ input_fn
1563 pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
1564 -- nuke old binary; maybe use configur'ed names for cp and rm?
1565 _ <- tryIO (removeFile pvm_executable)
1566 -- move the newly created binary into PVM land
1567 copy dflags "copying PVM executable" input_fn pvm_executable
1568 -- generate a wrapper script for running a parallel prg under PVM
1569 writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
1570 return True
1571 | otherwise = return True
1572
1573 mkExtraObj :: DynFlags -> Suffix -> String -> IO FilePath
1574 mkExtraObj dflags extn xs
1575 = do cFile <- newTempName dflags extn
1576 oFile <- newTempName dflags "o"
1577 writeFile cFile xs
1578 let rtsDetails = getPackageDetails dflags rtsPackageKey
1579 SysTools.runCc dflags
1580 ([Option "-c",
1581 FileOption "" cFile,
1582 Option "-o",
1583 FileOption "" oFile]
1584 ++ map (FileOption "-I") (includeDirs rtsDetails))
1585 return oFile
1586
1587 -- When linking a binary, we need to create a C main() function that
1588 -- starts everything off. This used to be compiled statically as part
1589 -- of the RTS, but that made it hard to change the -rtsopts setting,
1590 -- so now we generate and compile a main() stub as part of every
1591 -- binary and pass the -rtsopts setting directly to the RTS (#5373)
1592 --
1593 mkExtraObjToLinkIntoBinary :: DynFlags -> IO FilePath
1594 mkExtraObjToLinkIntoBinary dflags = do
1595 when (gopt Opt_NoHsMain dflags && haveRtsOptsFlags dflags) $ do
1596 log_action dflags dflags SevInfo noSrcSpan defaultUserStyle
1597 (text "Warning: -rtsopts and -with-rtsopts have no effect with -no-hs-main." $$
1598 text " Call hs_init_ghc() from your main() function to set these options.")
1599
1600 mkExtraObj dflags "c" (showSDoc dflags main)
1601
1602 where
1603 main
1604 | gopt Opt_NoHsMain dflags = Outputable.empty
1605 | otherwise = vcat [
1606 text "#include \"Rts.h\"",
1607 text "extern StgClosure ZCMain_main_closure;",
1608 text "int main(int argc, char *argv[])",
1609 char '{',
1610 text " RtsConfig __conf = defaultRtsConfig;",
1611 text " __conf.rts_opts_enabled = "
1612 <> text (show (rtsOptsEnabled dflags)) <> semi,
1613 case rtsOpts dflags of
1614 Nothing -> Outputable.empty
1615 Just opts -> ptext (sLit " __conf.rts_opts= ") <>
1616 text (show opts) <> semi,
1617 text " __conf.rts_hs_main = rtsTrue;",
1618 text " return hs_main(argc,argv,&ZCMain_main_closure,__conf);",
1619 char '}',
1620 char '\n' -- final newline, to keep gcc happy
1621 ]
1622
1623 -- Write out the link info section into a new assembly file. Previously
1624 -- this was included as inline assembly in the main.c file but this
1625 -- is pretty fragile. gas gets upset trying to calculate relative offsets
1626 -- that span the .note section (notably .text) when debug info is present
1627 mkNoteObjsToLinkIntoBinary :: DynFlags -> [PackageKey] -> IO [FilePath]
1628 mkNoteObjsToLinkIntoBinary dflags dep_packages = do
1629 link_info <- getLinkInfo dflags dep_packages
1630
1631 if (platformSupportsSavingLinkOpts (platformOS (targetPlatform dflags)))
1632 then fmap (:[]) $ mkExtraObj dflags "s" (showSDoc dflags (link_opts link_info))
1633 else return []
1634
1635 where
1636 link_opts info = hcat [
1637 text "\t.section ", text ghcLinkInfoSectionName,
1638 text ",\"\",",
1639 text elfSectionNote,
1640 text "\n",
1641
1642 text "\t.ascii \"", info', text "\"\n",
1643
1644 -- ALL generated assembly must have this section to disable
1645 -- executable stacks. See also
1646 -- compiler/nativeGen/AsmCodeGen.lhs for another instance
1647 -- where we need to do this.
1648 (if platformHasGnuNonexecStack (targetPlatform dflags)
1649 then text ".section .note.GNU-stack,\"\",@progbits\n"
1650 else Outputable.empty)
1651
1652 ]
1653 where
1654 info' = text $ escape info
1655
1656 escape :: String -> String
1657 escape = concatMap (charToC.fromIntegral.ord)
1658
1659 elfSectionNote :: String
1660 elfSectionNote = case platformArch (targetPlatform dflags) of
1661 ArchARM _ _ _ -> "%note"
1662 _ -> "@note"
1663
1664 -- The "link info" is a string representing the parameters of the
1665 -- link. We save this information in the binary, and the next time we
1666 -- link, if nothing else has changed, we use the link info stored in
1667 -- the existing binary to decide whether to re-link or not.
1668 getLinkInfo :: DynFlags -> [PackageKey] -> IO String
1669 getLinkInfo dflags dep_packages = do
1670 package_link_opts <- getPackageLinkOpts dflags dep_packages
1671 pkg_frameworks <- if platformUsesFrameworks (targetPlatform dflags)
1672 then getPackageFrameworks dflags dep_packages
1673 else return []
1674 let extra_ld_inputs = ldInputs dflags
1675 let
1676 link_info = (package_link_opts,
1677 pkg_frameworks,
1678 rtsOpts dflags,
1679 rtsOptsEnabled dflags,
1680 gopt Opt_NoHsMain dflags,
1681 map showOpt extra_ld_inputs,
1682 getOpts dflags opt_l)
1683 --
1684 return (show link_info)
1685
1686 -- generates a Perl skript starting a parallel prg under PVM
1687 mk_pvm_wrapper_script :: String -> String -> String -> String
1688 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
1689 [
1690 "eval 'exec perl -S $0 ${1+\"$@\"}'",
1691 " if $running_under_some_shell;",
1692 "# =!=!=!=!=!=!=!=!=!=!=!",
1693 "# This script is automatically generated: DO NOT EDIT!!!",
1694 "# Generated by Glasgow Haskell Compiler",
1695 "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
1696 "#",
1697 "$pvm_executable = '" ++ pvm_executable ++ "';",
1698 "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
1699 "$SysMan = '" ++ sysMan ++ "';",
1700 "",
1701 {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
1702 "# first, some magical shortcuts to run "commands" on the binary",
1703 "# (which is hidden)",
1704 "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
1705 " local($cmd) = $1;",
1706 " system("$cmd $pvm_executable");",
1707 " exit(0); # all done",
1708 "}", -}
1709 "",
1710 "# Now, run the real binary; process the args first",
1711 "$ENV{'PE'} = $pvm_executable_base;", -- ++ pvm_executable_base,
1712 "$debug = '';",
1713 "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
1714 "@nonPVM_args = ();",
1715 "$in_RTS_args = 0;",
1716 "",
1717 "args: while ($a = shift(@ARGV)) {",
1718 " if ( $a eq '+RTS' ) {",
1719 " $in_RTS_args = 1;",
1720 " } elsif ( $a eq '-RTS' ) {",
1721 " $in_RTS_args = 0;",
1722 " }",
1723 " if ( $a eq '-d' && $in_RTS_args ) {",
1724 " $debug = '-';",
1725 " } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
1726 " $nprocessors = $1;",
1727 " } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
1728 " $nprocessors = $1;",
1729 " } else {",
1730 " push(@nonPVM_args, $a);",
1731 " }",
1732 "}",
1733 "",
1734 "local($return_val) = 0;",
1735 "# Start the parallel execution by calling SysMan",
1736 "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
1737 "$return_val = $?;",
1738 "# ToDo: fix race condition moving files and flushing them!!",
1739 "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
1740 "exit($return_val);"
1741 ]
1742
1743 -----------------------------------------------------------------------------
1744 -- Look for the /* GHC_PACKAGES ... */ comment at the top of a .hc file
1745
1746 getHCFilePackages :: FilePath -> IO [PackageKey]
1747 getHCFilePackages filename =
1748 Exception.bracket (openFile filename ReadMode) hClose $ \h -> do
1749 l <- hGetLine h
1750 case l of
1751 '/':'*':' ':'G':'H':'C':'_':'P':'A':'C':'K':'A':'G':'E':'S':rest ->
1752 return (map stringToPackageKey (words rest))
1753 _other ->
1754 return []
1755
1756 -----------------------------------------------------------------------------
1757 -- Static linking, of .o files
1758
1759 -- The list of packages passed to link is the list of packages on
1760 -- which this program depends, as discovered by the compilation
1761 -- manager. It is combined with the list of packages that the user
1762 -- specifies on the command line with -package flags.
1763 --
1764 -- In one-shot linking mode, we can't discover the package
1765 -- dependencies (because we haven't actually done any compilation or
1766 -- read any interface files), so the user must explicitly specify all
1767 -- the packages.
1768
1769 linkBinary :: DynFlags -> [FilePath] -> [PackageKey] -> IO ()
1770 linkBinary = linkBinary' False
1771
1772 linkBinary' :: Bool -> DynFlags -> [FilePath] -> [PackageKey] -> IO ()
1773 linkBinary' staticLink dflags o_files dep_packages = do
1774 let platform = targetPlatform dflags
1775 mySettings = settings dflags
1776 verbFlags = getVerbFlags dflags
1777 output_fn = exeFileName staticLink dflags
1778
1779 -- get the full list of packages to link with, by combining the
1780 -- explicit packages with the auto packages and all of their
1781 -- dependencies, and eliminating duplicates.
1782
1783 full_output_fn <- if isAbsolute output_fn
1784 then return output_fn
1785 else do d <- getCurrentDirectory
1786 return $ normalise (d </> output_fn)
1787 pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1788 let pkg_lib_path_opts = concatMap get_pkg_lib_path_opts pkg_lib_paths
1789 get_pkg_lib_path_opts l
1790 | osElfTarget (platformOS platform) &&
1791 dynLibLoader dflags == SystemDependent &&
1792 not (gopt Opt_Static dflags)
1793 = let libpath = if gopt Opt_RelativeDynlibPaths dflags
1794 then "$ORIGIN" </>
1795 (l `makeRelativeTo` full_output_fn)
1796 else l
1797 rpath = if gopt Opt_RPath dflags
1798 then ["-Wl,-rpath", "-Wl," ++ libpath]
1799 else []
1800 -- Solaris 11's linker does not support -rpath-link option. It silently
1801 -- ignores it and then complains about next option which is -l<some
1802 -- dir> as being a directory and not expected object file, E.g
1803 -- ld: elf error: file
1804 -- /tmp/ghc-src/libraries/base/dist-install/build:
1805 -- elf_begin: I/O error: region read: Is a directory
1806 rpathlink = if (platformOS platform) == OSSolaris2
1807 then []
1808 else ["-Wl,-rpath-link", "-Wl," ++ l]
1809 in ["-L" ++ l] ++ rpathlink ++ rpath
1810 | osMachOTarget (platformOS platform) &&
1811 dynLibLoader dflags == SystemDependent &&
1812 not (gopt Opt_Static dflags) &&
1813 gopt Opt_RPath dflags
1814 = let libpath = if gopt Opt_RelativeDynlibPaths dflags
1815 then "@loader_path" </>
1816 (l `makeRelativeTo` full_output_fn)
1817 else l
1818 in ["-L" ++ l] ++ ["-Wl,-rpath", "-Wl," ++ libpath]
1819 | otherwise = ["-L" ++ l]
1820
1821 let lib_paths = libraryPaths dflags
1822 let lib_path_opts = map ("-L"++) lib_paths
1823
1824 extraLinkObj <- mkExtraObjToLinkIntoBinary dflags
1825 noteLinkObjs <- mkNoteObjsToLinkIntoBinary dflags dep_packages
1826
1827 pkg_link_opts <- do
1828 (package_hs_libs, extra_libs, other_flags) <- getPackageLinkOpts dflags dep_packages
1829 return $ if staticLink
1830 then package_hs_libs -- If building an executable really means making a static
1831 -- library (e.g. iOS), then we only keep the -l options for
1832 -- HS packages, because libtool doesn't accept other options.
1833 -- In the case of iOS these need to be added by hand to the
1834 -- final link in Xcode.
1835 else other_flags ++ package_hs_libs ++ extra_libs -- -Wl,-u,<sym> contained in other_flags
1836 -- needs to be put before -l<package>,
1837 -- otherwise Solaris linker fails linking
1838 -- a binary with unresolved symbols in RTS
1839 -- which are defined in base package
1840 -- the reason for this is a note in ld(1) about
1841 -- '-u' option: "The placement of this option
1842 -- on the command line is significant.
1843 -- This option must be placed before the library
1844 -- that defines the symbol."
1845
1846 pkg_framework_path_opts <-
1847 if platformUsesFrameworks platform
1848 then do pkg_framework_paths <- getPackageFrameworkPath dflags dep_packages
1849 return $ map ("-F" ++) pkg_framework_paths
1850 else return []
1851
1852 framework_path_opts <-
1853 if platformUsesFrameworks platform
1854 then do let framework_paths = frameworkPaths dflags
1855 return $ map ("-F" ++) framework_paths
1856 else return []
1857
1858 pkg_framework_opts <-
1859 if platformUsesFrameworks platform
1860 then do pkg_frameworks <- getPackageFrameworks dflags dep_packages
1861 return $ concat [ ["-framework", fw] | fw <- pkg_frameworks ]
1862 else return []
1863
1864 framework_opts <-
1865 if platformUsesFrameworks platform
1866 then do let frameworks = cmdlineFrameworks dflags
1867 -- reverse because they're added in reverse order from
1868 -- the cmd line:
1869 return $ concat [ ["-framework", fw]
1870 | fw <- reverse frameworks ]
1871 else return []
1872
1873 -- probably _stub.o files
1874 let extra_ld_inputs = ldInputs dflags
1875
1876 -- Here are some libs that need to be linked at the *end* of
1877 -- the command line, because they contain symbols that are referred to
1878 -- by the RTS. We can't therefore use the ordinary way opts for these.
1879 let
1880 debug_opts | WayDebug `elem` ways dflags = [
1881 #if defined(HAVE_LIBBFD)
1882 "-lbfd", "-liberty"
1883 #endif
1884 ]
1885 | otherwise = []
1886
1887 let thread_opts
1888 | WayThreaded `elem` ways dflags =
1889 let os = platformOS (targetPlatform dflags)
1890 in if os == OSOsf3 then ["-lpthread", "-lexc"]
1891 else if os `elem` [OSMinGW32, OSFreeBSD, OSOpenBSD,
1892 OSNetBSD, OSHaiku, OSQNXNTO, OSiOS, OSDarwin]
1893 then []
1894 else ["-lpthread"]
1895 | otherwise = []
1896
1897 rc_objs <- maybeCreateManifest dflags output_fn
1898
1899 let link = if staticLink
1900 then SysTools.runLibtool
1901 else SysTools.runLink
1902 link dflags (
1903 map SysTools.Option verbFlags
1904 ++ [ SysTools.Option "-o"
1905 , SysTools.FileOption "" output_fn
1906 ]
1907 ++ map SysTools.Option (
1908 []
1909
1910 -- Permit the linker to auto link _symbol to _imp_symbol.
1911 -- This lets us link against DLLs without needing an "import library".
1912 ++ (if platformOS platform == OSMinGW32
1913 then ["-Wl,--enable-auto-import"]
1914 else [])
1915
1916 -- '-no_compact_unwind'
1917 -- C++/Objective-C exceptions cannot use optimised
1918 -- stack unwinding code. The optimised form is the
1919 -- default in Xcode 4 on at least x86_64, and
1920 -- without this flag we're also seeing warnings
1921 -- like
1922 -- ld: warning: could not create compact unwind for .LFB3: non-standard register 5 being saved in prolog
1923 -- on x86.
1924 ++ (if sLdSupportsCompactUnwind mySettings &&
1925 not staticLink &&
1926 (platformOS platform == OSDarwin || platformOS platform == OSiOS) &&
1927 case platformArch platform of
1928 ArchX86 -> True
1929 ArchX86_64 -> True
1930 ArchARM {} -> True
1931 _ -> False
1932 then ["-Wl,-no_compact_unwind"]
1933 else [])
1934
1935 -- '-no_pie'
1936 -- iOS uses 'dynamic-no-pic', so we must pass this to ld to suppress a warning; see #7722
1937 ++ (if platformOS platform == OSiOS &&
1938 not staticLink
1939 then ["-Wl,-no_pie"]
1940 else [])
1941
1942 -- '-Wl,-read_only_relocs,suppress'
1943 -- ld gives loads of warnings like:
1944 -- ld: warning: text reloc in _base_GHCziArr_unsafeArray_info to _base_GHCziArr_unsafeArray_closure
1945 -- when linking any program. We're not sure
1946 -- whether this is something we ought to fix, but
1947 -- for now this flags silences them.
1948 ++ (if platformOS platform == OSDarwin &&
1949 platformArch platform == ArchX86 &&
1950 not staticLink
1951 then ["-Wl,-read_only_relocs,suppress"]
1952 else [])
1953
1954 ++ o_files
1955 ++ lib_path_opts)
1956 ++ extra_ld_inputs
1957 ++ map SysTools.Option (
1958 rc_objs
1959 ++ framework_path_opts
1960 ++ framework_opts
1961 ++ pkg_lib_path_opts
1962 ++ extraLinkObj:noteLinkObjs
1963 ++ pkg_link_opts
1964 ++ pkg_framework_path_opts
1965 ++ pkg_framework_opts
1966 ++ debug_opts
1967 ++ thread_opts
1968 ))
1969
1970 -- parallel only: move binary to another dir -- HWL
1971 success <- runPhase_MoveBinary dflags output_fn
1972 unless success $
1973 throwGhcExceptionIO (InstallationError ("cannot move binary"))
1974
1975
1976 exeFileName :: Bool -> DynFlags -> FilePath
1977 exeFileName staticLink dflags
1978 | Just s <- outputFile dflags =
1979 case platformOS (targetPlatform dflags) of
1980 OSMinGW32 -> s <?.> "exe"
1981 _ -> if staticLink
1982 then s <?.> "a"
1983 else s
1984 | otherwise =
1985 if platformOS (targetPlatform dflags) == OSMinGW32
1986 then "main.exe"
1987 else if staticLink
1988 then "liba.a"
1989 else "a.out"
1990 where s <?.> ext | null (takeExtension s) = s <.> ext
1991 | otherwise = s
1992
1993 maybeCreateManifest
1994 :: DynFlags
1995 -> FilePath -- filename of executable
1996 -> IO [FilePath] -- extra objects to embed, maybe
1997 maybeCreateManifest dflags exe_filename
1998 | platformOS (targetPlatform dflags) == OSMinGW32 &&
1999 gopt Opt_GenManifest dflags
2000 = do let manifest_filename = exe_filename <.> "manifest"
2001
2002 writeFile manifest_filename $
2003 "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"++
2004 " <assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">\n"++
2005 " <assemblyIdentity version=\"1.0.0.0\"\n"++
2006 " processorArchitecture=\"X86\"\n"++
2007 " name=\"" ++ dropExtension exe_filename ++ "\"\n"++
2008 " type=\"win32\"/>\n\n"++
2009 " <trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v3\">\n"++
2010 " <security>\n"++
2011 " <requestedPrivileges>\n"++
2012 " <requestedExecutionLevel level=\"asInvoker\" uiAccess=\"false\"/>\n"++
2013 " </requestedPrivileges>\n"++
2014 " </security>\n"++
2015 " </trustInfo>\n"++
2016 "</assembly>\n"
2017
2018 -- Windows will find the manifest file if it is named
2019 -- foo.exe.manifest. However, for extra robustness, and so that
2020 -- we can move the binary around, we can embed the manifest in
2021 -- the binary itself using windres:
2022 if not (gopt Opt_EmbedManifest dflags) then return [] else do
2023
2024 rc_filename <- newTempName dflags "rc"
2025 rc_obj_filename <- newTempName dflags (objectSuf dflags)
2026
2027 writeFile rc_filename $
2028 "1 24 MOVEABLE PURE " ++ show manifest_filename ++ "\n"
2029 -- magic numbers :-)
2030 -- show is a bit hackish above, but we need to escape the
2031 -- backslashes in the path.
2032
2033 runWindres dflags $ map SysTools.Option $
2034 ["--input="++rc_filename,
2035 "--output="++rc_obj_filename,
2036 "--output-format=coff"]
2037 -- no FileOptions here: windres doesn't like seeing
2038 -- backslashes, apparently
2039
2040 removeFile manifest_filename
2041
2042 return [rc_obj_filename]
2043 | otherwise = return []
2044
2045
2046 linkDynLibCheck :: DynFlags -> [String] -> [PackageKey] -> IO ()
2047 linkDynLibCheck dflags o_files dep_packages
2048 = do
2049 when (haveRtsOptsFlags dflags) $ do
2050 log_action dflags dflags SevInfo noSrcSpan defaultUserStyle
2051 (text "Warning: -rtsopts and -with-rtsopts have no effect with -shared." $$
2052 text " Call hs_init_ghc() from your main() function to set these options.")
2053
2054 linkDynLib dflags o_files dep_packages
2055
2056 linkStaticLibCheck :: DynFlags -> [String] -> [PackageKey] -> IO ()
2057 linkStaticLibCheck dflags o_files dep_packages
2058 = do
2059 when (platformOS (targetPlatform dflags) `notElem` [OSiOS, OSDarwin]) $
2060 throwGhcExceptionIO (ProgramError "Static archive creation only supported on Darwin/OS X/iOS")
2061 linkBinary' True dflags o_files dep_packages
2062
2063 -- -----------------------------------------------------------------------------
2064 -- Running CPP
2065
2066 doCpp :: DynFlags -> Bool -> FilePath -> FilePath -> IO ()
2067 doCpp dflags raw input_fn output_fn = do
2068 let hscpp_opts = picPOpts dflags
2069 let cmdline_include_paths = includePaths dflags
2070
2071 pkg_include_dirs <- getPackageIncludePath dflags []
2072 let include_paths = foldr (\ x xs -> "-I" : x : xs) []
2073 (cmdline_include_paths ++ pkg_include_dirs)
2074
2075 let verbFlags = getVerbFlags dflags
2076
2077 let cpp_prog args | raw = SysTools.runCpp dflags args
2078 | otherwise = SysTools.runCc dflags (SysTools.Option "-E" : args)
2079
2080 let target_defs =
2081 [ "-D" ++ HOST_OS ++ "_BUILD_OS=1",
2082 "-D" ++ HOST_ARCH ++ "_BUILD_ARCH=1",
2083 "-D" ++ TARGET_OS ++ "_HOST_OS=1",
2084 "-D" ++ TARGET_ARCH ++ "_HOST_ARCH=1" ]
2085 -- remember, in code we *compile*, the HOST is the same our TARGET,
2086 -- and BUILD is the same as our HOST.
2087
2088 let sse_defs =
2089 [ "-D__SSE__=1" | isSseEnabled dflags ] ++
2090 [ "-D__SSE2__=1" | isSse2Enabled dflags ] ++
2091 [ "-D__SSE4_2__=1" | isSse4_2Enabled dflags ]
2092
2093 let avx_defs =
2094 [ "-D__AVX__=1" | isAvxEnabled dflags ] ++
2095 [ "-D__AVX2__=1" | isAvx2Enabled dflags ] ++
2096 [ "-D__AVX512CD__=1" | isAvx512cdEnabled dflags ] ++
2097 [ "-D__AVX512ER__=1" | isAvx512erEnabled dflags ] ++
2098 [ "-D__AVX512F__=1" | isAvx512fEnabled dflags ] ++
2099 [ "-D__AVX512PF__=1" | isAvx512pfEnabled dflags ]
2100
2101 backend_defs <- getBackendDefs dflags
2102
2103 #ifdef GHCI
2104 let th_defs = [ "-D__GLASGOW_HASKELL_TH__=YES" ]
2105 #else
2106 let th_defs = [ "-D__GLASGOW_HASKELL_TH__=NO" ]
2107 #endif
2108 -- Default CPP defines in Haskell source
2109 ghcVersionH <- getGhcVersionPathName dflags
2110 let hsSourceCppOpts =
2111 [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt
2112 , "-include", ghcVersionH
2113 ]
2114
2115 cpp_prog ( map SysTools.Option verbFlags
2116 ++ map SysTools.Option include_paths
2117 ++ map SysTools.Option hsSourceCppOpts
2118 ++ map SysTools.Option target_defs
2119 ++ map SysTools.Option backend_defs
2120 ++ map SysTools.Option th_defs
2121 ++ map SysTools.Option hscpp_opts
2122 ++ map SysTools.Option sse_defs
2123 ++ map SysTools.Option avx_defs
2124 -- Set the language mode to assembler-with-cpp when preprocessing. This
2125 -- alleviates some of the C99 macro rules relating to whitespace and the hash
2126 -- operator, which we tend to abuse. Clang in particular is not very happy
2127 -- about this.
2128 ++ [ SysTools.Option "-x"
2129 , SysTools.Option "assembler-with-cpp"
2130 , SysTools.Option input_fn
2131 -- We hackily use Option instead of FileOption here, so that the file
2132 -- name is not back-slashed on Windows. cpp is capable of
2133 -- dealing with / in filenames, so it works fine. Furthermore
2134 -- if we put in backslashes, cpp outputs #line directives
2135 -- with *double* backslashes. And that in turn means that
2136 -- our error messages get double backslashes in them.
2137 -- In due course we should arrange that the lexer deals
2138 -- with these \\ escapes properly.
2139 , SysTools.Option "-o"
2140 , SysTools.FileOption "" output_fn
2141 ])
2142
2143 getBackendDefs :: DynFlags -> IO [String]
2144 getBackendDefs dflags | hscTarget dflags == HscLlvm = do
2145 llvmVer <- figureLlvmVersion dflags
2146 return $ case llvmVer of
2147 Just n -> [ "-D__GLASGOW_HASKELL_LLVM__="++show n ]
2148 _ -> []
2149
2150 getBackendDefs _ =
2151 return []
2152
2153 -- ---------------------------------------------------------------------------
2154 -- join object files into a single relocatable object file, using ld -r
2155
2156 joinObjectFiles :: DynFlags -> [FilePath] -> FilePath -> IO ()
2157 joinObjectFiles dflags o_files output_fn = do
2158 let mySettings = settings dflags
2159 ldIsGnuLd = sLdIsGnuLd mySettings
2160 osInfo = platformOS (targetPlatform dflags)
2161 ld_r args cc = SysTools.runLink dflags ([
2162 SysTools.Option "-nostdlib",
2163 SysTools.Option "-Wl,-r"
2164 ]
2165 ++ (if any (cc ==) [Clang, AppleClang, AppleClang51]
2166 then []
2167 else [SysTools.Option "-nodefaultlibs"])
2168 ++ (if osInfo == OSFreeBSD
2169 then [SysTools.Option "-L/usr/lib"]
2170 else [])
2171 -- gcc on sparc sets -Wl,--relax implicitly, but
2172 -- -r and --relax are incompatible for ld, so
2173 -- disable --relax explicitly.
2174 ++ (if platformArch (targetPlatform dflags) == ArchSPARC
2175 && ldIsGnuLd
2176 then [SysTools.Option "-Wl,-no-relax"]
2177 else [])
2178 ++ map SysTools.Option ld_build_id
2179 ++ [ SysTools.Option "-o",
2180 SysTools.FileOption "" output_fn ]
2181 ++ args)
2182
2183 -- suppress the generation of the .note.gnu.build-id section,
2184 -- which we don't need and sometimes causes ld to emit a
2185 -- warning:
2186 ld_build_id | sLdSupportsBuildId mySettings = ["-Wl,--build-id=none"]
2187 | otherwise = []
2188
2189 ccInfo <- getCompilerInfo dflags
2190 if ldIsGnuLd
2191 then do
2192 script <- newTempName dflags "ldscript"
2193 cwd <- getCurrentDirectory
2194 let o_files_abs = map (cwd </>) o_files
2195 writeFile script $ "INPUT(" ++ unwords o_files_abs ++ ")"
2196 ld_r [SysTools.FileOption "" script] ccInfo
2197 else if sLdSupportsFilelist mySettings
2198 then do
2199 filelist <- newTempName dflags "filelist"
2200 writeFile filelist $ unlines o_files
2201 ld_r [SysTools.Option "-Wl,-filelist",
2202 SysTools.FileOption "-Wl," filelist] ccInfo
2203 else do
2204 ld_r (map (SysTools.FileOption "") o_files) ccInfo
2205
2206 -- -----------------------------------------------------------------------------
2207 -- Misc.
2208
2209 -- | What phase to run after one of the backend code generators has run
2210 hscPostBackendPhase :: DynFlags -> HscSource -> HscTarget -> Phase
2211 hscPostBackendPhase _ HsBootFile _ = StopLn
2212 hscPostBackendPhase _ HsigFile _ = StopLn
2213 hscPostBackendPhase dflags _ hsc_lang =
2214 case hsc_lang of
2215 HscC -> HCc
2216 HscAsm | gopt Opt_SplitObjs dflags -> Splitter
2217 | otherwise -> As False
2218 HscLlvm -> LlvmOpt
2219 HscNothing -> StopLn
2220 HscInterpreted -> StopLn
2221
2222 touchObjectFile :: DynFlags -> FilePath -> IO ()
2223 touchObjectFile dflags path = do
2224 createDirectoryIfMissing True $ takeDirectory path
2225 SysTools.touch dflags "Touching object file" path
2226
2227 haveRtsOptsFlags :: DynFlags -> Bool
2228 haveRtsOptsFlags dflags =
2229 isJust (rtsOpts dflags) || case rtsOptsEnabled dflags of
2230 RtsOptsSafeOnly -> False
2231 _ -> True
2232
2233 -- | Find out path to @ghcversion.h@ file
2234 getGhcVersionPathName :: DynFlags -> IO FilePath
2235 getGhcVersionPathName dflags = do
2236 dirs <- getPackageIncludePath dflags [rtsPackageKey]
2237
2238 found <- filterM doesFileExist (map (</> "ghcversion.h") dirs)
2239 case found of
2240 [] -> throwGhcExceptionIO (InstallationError ("ghcversion.h missing"))
2241 (x:_) -> return x
2242
2243 -- Note [-fPIC for assembler]
2244 -- When compiling .c source file GHC's driver pipeline basically
2245 -- does the following two things:
2246 -- 1. ${CC} -S 'PIC_CFLAGS' source.c
2247 -- 2. ${CC} -x assembler -c 'PIC_CFLAGS' source.S
2248 --
2249 -- Why do we need to pass 'PIC_CFLAGS' both to C compiler and assembler?
2250 -- Because on some architectures (at least sparc32) assembler also chooses
2251 -- the relocation type!
2252 -- Consider the following C module:
2253 --
2254 -- /* pic-sample.c */
2255 -- int v;
2256 -- void set_v (int n) { v = n; }
2257 -- int get_v (void) { return v; }
2258 --
2259 -- $ gcc -S -fPIC pic-sample.c
2260 -- $ gcc -c pic-sample.s -o pic-sample.no-pic.o # incorrect binary
2261 -- $ gcc -c -fPIC pic-sample.s -o pic-sample.pic.o # correct binary
2262 --
2263 -- $ objdump -r -d pic-sample.pic.o > pic-sample.pic.o.od
2264 -- $ objdump -r -d pic-sample.no-pic.o > pic-sample.no-pic.o.od
2265 -- $ diff -u pic-sample.pic.o.od pic-sample.no-pic.o.od
2266 --
2267 -- Most of architectures won't show any difference in this test, but on sparc32
2268 -- the following assembly snippet:
2269 --
2270 -- sethi %hi(_GLOBAL_OFFSET_TABLE_-8), %l7
2271 --
2272 -- generates two kinds or relocations, only 'R_SPARC_PC22' is correct:
2273 --
2274 -- 3c: 2f 00 00 00 sethi %hi(0), %l7
2275 -- - 3c: R_SPARC_PC22 _GLOBAL_OFFSET_TABLE_-0x8
2276 -- + 3c: R_SPARC_HI22 _GLOBAL_OFFSET_TABLE_-0x8