PageRenderTime 34ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/compiler/main/DriverPipeline.hs

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