PageRenderTime 85ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/ghc-7.4.1/compiler/main/DriverPipeline.hs

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