Detect linker information at runtime. Fixes Trac #6063
[ghc.git] / compiler / main / DynFlags.hs
1 -------------------------------------------------------------------------------
2 --
3 -- | Dynamic flags
4 --
5 -- Most flags are dynamic flags, which means they can change from compilation
6 -- to compilation using @OPTIONS_GHC@ pragmas, and in a multi-session GHC each
7 -- session can be using different dynamic flags. Dynamic flags can also be set
8 -- at the prompt in GHCi.
9 --
10 -- (c) The University of Glasgow 2005
11 --
12 -------------------------------------------------------------------------------
13
14 {-# OPTIONS -fno-cse #-}
15 -- -fno-cse is needed for GLOBAL_VAR's to behave properly
16
17 module DynFlags (
18 -- * Dynamic flags and associated configuration types
19 DumpFlag(..),
20 GeneralFlag(..),
21 WarningFlag(..),
22 ExtensionFlag(..),
23 Language(..),
24 PlatformConstants(..),
25 FatalMessager, LogAction, FlushOut(..), FlushErr(..),
26 ProfAuto(..),
27 glasgowExtsFlags,
28 dopt, dopt_set, dopt_unset,
29 gopt, gopt_set, gopt_unset,
30 wopt, wopt_set, wopt_unset,
31 xopt, xopt_set, xopt_unset,
32 lang_set,
33 whenGeneratingDynamicToo, ifGeneratingDynamicToo,
34 whenCannotGenerateDynamicToo,
35 doDynamicToo,
36 DynFlags(..),
37 HasDynFlags(..), ContainsDynFlags(..),
38 RtsOptsEnabled(..),
39 HscTarget(..), isObjectTarget, defaultObjectTarget,
40 targetRetainsAllBindings,
41 GhcMode(..), isOneShot,
42 GhcLink(..), isNoLink,
43 PackageFlag(..),
44 PkgConfRef(..),
45 Option(..), showOpt,
46 DynLibLoader(..),
47 fFlags, fWarningFlags, fLangFlags, xFlags,
48 dynFlagDependencies,
49 tablesNextToCode, mkTablesNextToCode,
50
51 printOutputForUser, printInfoForUser,
52
53 Way(..), mkBuildTag, wayRTSOnly, addWay', updateWays,
54 wayGeneralFlags, wayUnsetGeneralFlags,
55
56 -- ** Safe Haskell
57 SafeHaskellMode(..),
58 safeHaskellOn, safeImportsOn, safeLanguageOn, safeInferOn,
59 packageTrustOn,
60 safeDirectImpsReq, safeImplicitImpsReq,
61 unsafeFlags,
62
63 -- ** System tool settings and locations
64 Settings(..),
65 targetPlatform,
66 ghcUsagePath, ghciUsagePath, topDir, tmpDir, rawSettings,
67 extraGccViaCFlags, systemPackageConfig,
68 pgm_L, pgm_P, pgm_F, pgm_c, pgm_s, pgm_a, pgm_l, pgm_dll, pgm_T,
69 pgm_sysman, pgm_windres, pgm_lo, pgm_lc,
70 opt_L, opt_P, opt_F, opt_c, opt_a, opt_l,
71 opt_windres, opt_lo, opt_lc,
72
73
74 -- ** Manipulating DynFlags
75 defaultDynFlags, -- Settings -> DynFlags
76 defaultWays,
77 interpWays,
78 initDynFlags, -- DynFlags -> IO DynFlags
79 defaultFatalMessager,
80 defaultLogAction,
81 defaultLogActionHPrintDoc,
82 defaultFlushOut,
83 defaultFlushErr,
84
85 getOpts, -- DynFlags -> (DynFlags -> [a]) -> [a]
86 getVerbFlags,
87 updOptLevel,
88 setTmpDir,
89 setPackageName,
90
91 -- ** Parsing DynFlags
92 parseDynamicFlagsCmdLine,
93 parseDynamicFilePragma,
94 parseDynamicFlagsFull,
95
96 -- ** Available DynFlags
97 allFlags,
98 flagsAll,
99 flagsDynamic,
100 flagsPackage,
101
102 supportedLanguagesAndExtensions,
103
104 -- ** DynFlags C compiler options
105 picCCOpts, picPOpts,
106
107 -- * Configuration of the stg-to-stg passes
108 StgToDo(..),
109 getStgToDo,
110
111 -- * Compiler configuration suitable for display to the user
112 compilerInfo,
113
114 #ifdef GHCI
115 -- Only in stage 2 can we be sure that the RTS
116 -- exposes the appropriate runtime boolean
117 rtsIsProfiled,
118 #endif
119
120 #include "../includes/dist-derivedconstants/header/GHCConstantsHaskellExports.hs"
121 bLOCK_SIZE_W,
122 wORD_SIZE_IN_BITS,
123 tAG_MASK,
124 mAX_PTR_TAG,
125 tARGET_MIN_INT, tARGET_MAX_INT, tARGET_MAX_WORD,
126
127 unsafeGlobalDynFlags, setUnsafeGlobalDynFlags,
128
129 -- * SSE
130 isSse2Enabled,
131 isSse4_2Enabled,
132
133 -- * Linker information
134 LinkerInfo(..),
135 ) where
136
137 #include "HsVersions.h"
138
139 import Platform
140 import PlatformConstants
141 import Module
142 import PackageConfig
143 import {-# SOURCE #-} PrelNames ( mAIN )
144 import {-# SOURCE #-} Packages (PackageState)
145 import DriverPhases ( Phase(..), phaseInputExt )
146 import Config
147 import CmdLineParser
148 import Constants
149 import Panic
150 import Util
151 import Maybes ( orElse )
152 import MonadUtils
153 import qualified Pretty
154 import SrcLoc
155 import FastString
156 import Outputable
157 #ifdef GHCI
158 import Foreign.C ( CInt(..) )
159 #endif
160 import {-# SOURCE #-} ErrUtils ( Severity(..), MsgDoc, mkLocMessage )
161
162 import System.IO.Unsafe ( unsafePerformIO )
163 import Data.IORef
164 import Control.Monad
165
166 import Data.Bits
167 import Data.Char
168 import Data.Int
169 import Data.List
170 import Data.Map (Map)
171 import qualified Data.Map as Map
172 import Data.Maybe
173 import Data.Set (Set)
174 import qualified Data.Set as Set
175 import Data.Word
176 import System.FilePath
177 import System.IO
178 import System.IO.Error
179
180 import Data.IntSet (IntSet)
181 import qualified Data.IntSet as IntSet
182
183 import GHC.Foreign (withCString, peekCString)
184
185 -- -----------------------------------------------------------------------------
186 -- DynFlags
187
188 data DumpFlag
189
190 -- debugging flags
191 = Opt_D_dump_cmm
192 | Opt_D_dump_cmm_raw
193 -- All of the cmm subflags (there are a lot!) Automatically
194 -- enabled if you run -ddump-cmm
195 | Opt_D_dump_cmm_cfg
196 | Opt_D_dump_cmm_cbe
197 | Opt_D_dump_cmm_proc
198 | Opt_D_dump_cmm_rewrite
199 | Opt_D_dump_cmm_sp
200 | Opt_D_dump_cmm_procmap
201 | Opt_D_dump_cmm_split
202 | Opt_D_dump_cmm_info
203 | Opt_D_dump_cmm_cps
204 -- end cmm subflags
205 | Opt_D_dump_asm
206 | Opt_D_dump_asm_native
207 | Opt_D_dump_asm_liveness
208 | Opt_D_dump_asm_regalloc
209 | Opt_D_dump_asm_regalloc_stages
210 | Opt_D_dump_asm_conflicts
211 | Opt_D_dump_asm_stats
212 | Opt_D_dump_asm_expanded
213 | Opt_D_dump_llvm
214 | Opt_D_dump_core_stats
215 | Opt_D_dump_deriv
216 | Opt_D_dump_ds
217 | Opt_D_dump_foreign
218 | Opt_D_dump_inlinings
219 | Opt_D_dump_rule_firings
220 | Opt_D_dump_rule_rewrites
221 | Opt_D_dump_simpl_trace
222 | Opt_D_dump_occur_anal
223 | Opt_D_dump_parsed
224 | Opt_D_dump_rn
225 | Opt_D_dump_core_pipeline -- TODO FIXME: dump after simplifier stats
226 | Opt_D_dump_simpl
227 | Opt_D_dump_simpl_iterations
228 | Opt_D_dump_simpl_phases
229 | Opt_D_dump_spec
230 | Opt_D_dump_prep
231 | Opt_D_dump_stg
232 | Opt_D_dump_stranal
233 | Opt_D_dump_tc
234 | Opt_D_dump_types
235 | Opt_D_dump_rules
236 | Opt_D_dump_cse
237 | Opt_D_dump_worker_wrapper
238 | Opt_D_dump_rn_trace
239 | Opt_D_dump_rn_stats
240 | Opt_D_dump_opt_cmm
241 | Opt_D_dump_simpl_stats
242 | Opt_D_dump_cs_trace -- Constraint solver in type checker
243 | Opt_D_dump_tc_trace
244 | Opt_D_dump_if_trace
245 | Opt_D_dump_vt_trace
246 | Opt_D_dump_splices
247 | Opt_D_dump_BCOs
248 | Opt_D_dump_vect
249 | Opt_D_dump_ticked
250 | Opt_D_dump_rtti
251 | Opt_D_source_stats
252 | Opt_D_verbose_stg2stg
253 | Opt_D_dump_hi
254 | Opt_D_dump_hi_diffs
255 | Opt_D_dump_mod_cycles
256 | Opt_D_dump_view_pattern_commoning
257 | Opt_D_verbose_core2core
258
259 deriving (Eq, Show, Enum)
260
261 -- | Enumerates the simple on-or-off dynamic flags
262 data GeneralFlag
263
264 = Opt_DumpToFile -- ^ Append dump output to files instead of stdout.
265 | Opt_D_faststring_stats
266 | Opt_D_dump_minimal_imports
267 | Opt_DoCoreLinting
268 | Opt_DoStgLinting
269 | Opt_DoCmmLinting
270 | Opt_DoAsmLinting
271 | Opt_NoLlvmMangler -- hidden flag
272
273 | Opt_WarnIsError -- -Werror; makes warnings fatal
274
275 | Opt_PrintExplicitForalls
276
277 -- optimisation opts
278 | Opt_Strictness
279 | Opt_KillAbsence
280 | Opt_KillOneShot
281 | Opt_FullLaziness
282 | Opt_FloatIn
283 | Opt_Specialise
284 | Opt_StaticArgumentTransformation
285 | Opt_CSE
286 | Opt_LiberateCase
287 | Opt_SpecConstr
288 | Opt_DoLambdaEtaExpansion
289 | Opt_IgnoreAsserts
290 | Opt_DoEtaReduction
291 | Opt_CaseMerge
292 | Opt_UnboxStrictFields
293 | Opt_UnboxSmallStrictFields
294 | Opt_DictsCheap
295 | Opt_EnableRewriteRules -- Apply rewrite rules during simplification
296 | Opt_Vectorise
297 | Opt_VectorisationAvoidance
298 | Opt_RegsGraph -- do graph coloring register allocation
299 | Opt_RegsIterative -- do iterative coalescing graph coloring register allocation
300 | Opt_PedanticBottoms -- Be picky about how we treat bottom
301 | Opt_LlvmTBAA -- Use LLVM TBAA infastructure for improving AA (hidden flag)
302 | Opt_IrrefutableTuples
303 | Opt_CmmSink
304 | Opt_CmmElimCommonBlocks
305 | Opt_OmitYields
306 | Opt_SimpleListLiterals
307 | Opt_FunToThunk -- allow WwLib.mkWorkerArgs to remove all value lambdas
308
309 -- Interface files
310 | Opt_IgnoreInterfacePragmas
311 | Opt_OmitInterfacePragmas
312 | Opt_ExposeAllUnfoldings
313
314 -- profiling opts
315 | Opt_AutoSccsOnIndividualCafs
316 | Opt_ProfCountEntries
317
318 -- misc opts
319 | Opt_Pp
320 | Opt_ForceRecomp
321 | Opt_ExcessPrecision
322 | Opt_EagerBlackHoling
323 | Opt_NoHsMain
324 | Opt_SplitObjs
325 | Opt_StgStats
326 | Opt_HideAllPackages
327 | Opt_PrintBindResult
328 | Opt_Haddock
329 | Opt_HaddockOptions
330 | Opt_Hpc_No_Auto
331 | Opt_BreakOnException
332 | Opt_BreakOnError
333 | Opt_PrintEvldWithShow
334 | Opt_PrintBindContents
335 | Opt_GenManifest
336 | Opt_EmbedManifest
337 | Opt_EmitExternalCore
338 | Opt_SharedImplib
339 | Opt_BuildingCabalPackage
340 | Opt_IgnoreDotGhci
341 | Opt_GhciSandbox
342 | Opt_GhciHistory
343 | Opt_HelpfulErrors
344 | Opt_DeferTypeErrors
345 | Opt_Parallel
346 | Opt_GranMacros
347 | Opt_PIC
348 | Opt_SccProfilingOn
349 | Opt_Ticky
350 | Opt_Ticky_Allocd
351 | Opt_Ticky_LNE
352 | Opt_Ticky_Dyn_Thunk
353 | Opt_Static
354 | Opt_RPath
355 | Opt_RelativeDynlibPaths
356 | Opt_Hpc
357 | Opt_FlatCache
358
359 -- PreInlining is on by default. The option is there just to see how
360 -- bad things get if you turn it off!
361 | Opt_SimplPreInlining
362
363 -- output style opts
364 | Opt_ErrorSpans -- Include full span info in error messages,
365 -- instead of just the start position.
366 | Opt_PprCaseAsLet
367
368 -- Suppress all coercions, them replacing with '...'
369 | Opt_SuppressCoercions
370 | Opt_SuppressVarKinds
371 -- Suppress module id prefixes on variables.
372 | Opt_SuppressModulePrefixes
373 -- Suppress type applications.
374 | Opt_SuppressTypeApplications
375 -- Suppress info such as arity and unfoldings on identifiers.
376 | Opt_SuppressIdInfo
377 -- Suppress separate type signatures in core, but leave types on
378 -- lambda bound vars
379 | Opt_SuppressTypeSignatures
380 -- Suppress unique ids on variables.
381 -- Except for uniques, as some simplifier phases introduce new
382 -- variables that have otherwise identical names.
383 | Opt_SuppressUniques
384
385 -- temporary flags
386 | Opt_RunCPS
387 | Opt_RunCPSZ
388 | Opt_AutoLinkPackages
389 | Opt_ImplicitImportQualified
390
391 -- keeping stuff
392 | Opt_KeepHiDiffs
393 | Opt_KeepHcFiles
394 | Opt_KeepSFiles
395 | Opt_KeepTmpFiles
396 | Opt_KeepRawTokenStream
397 | Opt_KeepLlvmFiles
398
399 | Opt_BuildDynamicToo
400
401 -- safe haskell flags
402 | Opt_DistrustAllPackages
403 | Opt_PackageTrust
404
405 deriving (Eq, Show, Enum)
406
407 data WarningFlag =
408 Opt_WarnDuplicateExports
409 | Opt_WarnDuplicateConstraints
410 | Opt_WarnHiShadows
411 | Opt_WarnImplicitPrelude
412 | Opt_WarnIncompletePatterns
413 | Opt_WarnIncompleteUniPatterns
414 | Opt_WarnIncompletePatternsRecUpd
415 | Opt_WarnMissingFields
416 | Opt_WarnMissingImportList
417 | Opt_WarnMissingMethods
418 | Opt_WarnMissingSigs
419 | Opt_WarnMissingLocalSigs
420 | Opt_WarnNameShadowing
421 | Opt_WarnOverlappingPatterns
422 | Opt_WarnTypeDefaults
423 | Opt_WarnMonomorphism
424 | Opt_WarnUnusedBinds
425 | Opt_WarnUnusedImports
426 | Opt_WarnUnusedMatches
427 | Opt_WarnWarningsDeprecations
428 | Opt_WarnDeprecatedFlags
429 | Opt_WarnDodgyExports
430 | Opt_WarnDodgyImports
431 | Opt_WarnOrphans
432 | Opt_WarnAutoOrphans
433 | Opt_WarnIdentities
434 | Opt_WarnTabs
435 | Opt_WarnUnrecognisedPragmas
436 | Opt_WarnDodgyForeignImports
437 | Opt_WarnLazyUnliftedBindings
438 | Opt_WarnUnusedDoBind
439 | Opt_WarnWrongDoBind
440 | Opt_WarnAlternativeLayoutRuleTransitional
441 | Opt_WarnUnsafe
442 | Opt_WarnSafe
443 | Opt_WarnPointlessPragmas
444 | Opt_WarnUnsupportedCallingConventions
445 | Opt_WarnUnsupportedLlvmVersion
446 | Opt_WarnInlineRuleShadowing
447 | Opt_WarnTypeableInstances
448 deriving (Eq, Show, Enum)
449
450 data Language = Haskell98 | Haskell2010
451 deriving Enum
452
453 -- | The various Safe Haskell modes
454 data SafeHaskellMode
455 = Sf_None
456 | Sf_Unsafe
457 | Sf_Trustworthy
458 | Sf_Safe
459 | Sf_SafeInferred
460 deriving (Eq)
461
462 instance Show SafeHaskellMode where
463 show Sf_None = "None"
464 show Sf_Unsafe = "Unsafe"
465 show Sf_Trustworthy = "Trustworthy"
466 show Sf_Safe = "Safe"
467 show Sf_SafeInferred = "Safe-Inferred"
468
469 instance Outputable SafeHaskellMode where
470 ppr = text . show
471
472 data ExtensionFlag
473 = Opt_Cpp
474 | Opt_OverlappingInstances
475 | Opt_UndecidableInstances
476 | Opt_IncoherentInstances
477 | Opt_MonomorphismRestriction
478 | Opt_MonoPatBinds
479 | Opt_MonoLocalBinds
480 | Opt_RelaxedPolyRec -- Deprecated
481 | Opt_ExtendedDefaultRules -- Use GHC's extended rules for defaulting
482 | Opt_ForeignFunctionInterface
483 | Opt_UnliftedFFITypes
484 | Opt_InterruptibleFFI
485 | Opt_CApiFFI
486 | Opt_GHCForeignImportPrim
487 | Opt_ParallelArrays -- Syntactic support for parallel arrays
488 | Opt_Arrows -- Arrow-notation syntax
489 | Opt_TemplateHaskell
490 | Opt_QuasiQuotes
491 | Opt_ImplicitParams
492 | Opt_ImplicitPrelude
493 | Opt_ScopedTypeVariables
494 | Opt_AllowAmbiguousTypes
495 | Opt_UnboxedTuples
496 | Opt_BangPatterns
497 | Opt_TypeFamilies
498 | Opt_OverloadedStrings
499 | Opt_OverloadedLists
500 | Opt_DisambiguateRecordFields
501 | Opt_RecordWildCards
502 | Opt_RecordPuns
503 | Opt_ViewPatterns
504 | Opt_GADTs
505 | Opt_GADTSyntax
506 | Opt_NPlusKPatterns
507 | Opt_DoAndIfThenElse
508 | Opt_RebindableSyntax
509 | Opt_ConstraintKinds
510 | Opt_PolyKinds -- Kind polymorphism
511 | Opt_DataKinds -- Datatype promotion
512 | Opt_InstanceSigs
513
514 | Opt_StandaloneDeriving
515 | Opt_DeriveDataTypeable
516 | Opt_AutoDeriveTypeable -- Automatic derivation of Typeable
517 | Opt_DeriveFunctor
518 | Opt_DeriveTraversable
519 | Opt_DeriveFoldable
520 | Opt_DeriveGeneric -- Allow deriving Generic/1
521 | Opt_DefaultSignatures -- Allow extra signatures for defmeths
522
523 | Opt_TypeSynonymInstances
524 | Opt_FlexibleContexts
525 | Opt_FlexibleInstances
526 | Opt_ConstrainedClassMethods
527 | Opt_MultiParamTypeClasses
528 | Opt_NullaryTypeClasses
529 | Opt_FunctionalDependencies
530 | Opt_UnicodeSyntax
531 | Opt_ExistentialQuantification
532 | Opt_MagicHash
533 | Opt_EmptyDataDecls
534 | Opt_KindSignatures
535 | Opt_ParallelListComp
536 | Opt_TransformListComp
537 | Opt_MonadComprehensions
538 | Opt_GeneralizedNewtypeDeriving
539 | Opt_RecursiveDo
540 | Opt_PostfixOperators
541 | Opt_TupleSections
542 | Opt_PatternGuards
543 | Opt_LiberalTypeSynonyms
544 | Opt_RankNTypes
545 | Opt_ImpredicativeTypes
546 | Opt_TypeOperators
547 | Opt_ExplicitNamespaces
548 | Opt_PackageImports
549 | Opt_ExplicitForAll
550 | Opt_AlternativeLayoutRule
551 | Opt_AlternativeLayoutRuleTransitional
552 | Opt_DatatypeContexts
553 | Opt_NondecreasingIndentation
554 | Opt_RelaxedLayout
555 | Opt_TraditionalRecordSyntax
556 | Opt_LambdaCase
557 | Opt_MultiWayIf
558 | Opt_TypeHoles
559 | Opt_EmptyCase
560 deriving (Eq, Enum, Show)
561
562 -- | Contains not only a collection of 'GeneralFlag's but also a plethora of
563 -- information relating to the compilation of a single file or GHC session
564 data DynFlags = DynFlags {
565 ghcMode :: GhcMode,
566 ghcLink :: GhcLink,
567 hscTarget :: HscTarget,
568 settings :: Settings,
569 verbosity :: Int, -- ^ Verbosity level: see Note [Verbosity levels]
570 optLevel :: Int, -- ^ Optimisation level
571 simplPhases :: Int, -- ^ Number of simplifier phases
572 maxSimplIterations :: Int, -- ^ Max simplifier iterations
573 shouldDumpSimplPhase :: Maybe String,
574 ruleCheck :: Maybe String,
575 strictnessBefore :: [Int], -- ^ Additional demand analysis
576
577 simplTickFactor :: Int, -- ^ Multiplier for simplifier ticks
578 specConstrThreshold :: Maybe Int, -- ^ Threshold for SpecConstr
579 specConstrCount :: Maybe Int, -- ^ Max number of specialisations for any one function
580 specConstrRecursive :: Int, -- ^ Max number of specialisations for recursive types
581 -- Not optional; otherwise ForceSpecConstr can diverge.
582 liberateCaseThreshold :: Maybe Int, -- ^ Threshold for LiberateCase
583 floatLamArgs :: Maybe Int, -- ^ Arg count for lambda floating
584 -- See CoreMonad.FloatOutSwitches
585 historySize :: Int,
586
587 cmdlineHcIncludes :: [String], -- ^ @\-\#includes@
588 importPaths :: [FilePath],
589 mainModIs :: Module,
590 mainFunIs :: Maybe String,
591 ctxtStkDepth :: Int, -- ^ Typechecker context stack depth
592
593 thisPackage :: PackageId, -- ^ name of package currently being compiled
594
595 -- ways
596 ways :: [Way], -- ^ Way flags from the command line
597 buildTag :: String, -- ^ The global \"way\" (e.g. \"p\" for prof)
598 rtsBuildTag :: String, -- ^ The RTS \"way\"
599
600 -- For object splitting
601 splitInfo :: Maybe (String,Int),
602
603 -- paths etc.
604 objectDir :: Maybe String,
605 dylibInstallName :: Maybe String,
606 hiDir :: Maybe String,
607 stubDir :: Maybe String,
608 dumpDir :: Maybe String,
609
610 objectSuf :: String,
611 hcSuf :: String,
612 hiSuf :: String,
613
614 canGenerateDynamicToo :: IORef Bool,
615 dynObjectSuf :: String,
616 dynHiSuf :: String,
617
618 -- Packages.isDllName needs to know whether a call is within a
619 -- single DLL or not. Normally it does this by seeing if the call
620 -- is to the same package, but for the ghc package, we split the
621 -- package between 2 DLLs. The dllSplit tells us which sets of
622 -- modules are in which package.
623 dllSplitFile :: Maybe FilePath,
624 dllSplit :: Maybe [Set String],
625
626 outputFile :: Maybe String,
627 dynOutputFile :: Maybe String,
628 outputHi :: Maybe String,
629 dynLibLoader :: DynLibLoader,
630
631 -- | This is set by 'DriverPipeline.runPipeline' based on where
632 -- its output is going.
633 dumpPrefix :: Maybe FilePath,
634
635 -- | Override the 'dumpPrefix' set by 'DriverPipeline.runPipeline'.
636 -- Set by @-ddump-file-prefix@
637 dumpPrefixForce :: Maybe FilePath,
638
639 ldInputs :: [Option],
640
641 includePaths :: [String],
642 libraryPaths :: [String],
643 frameworkPaths :: [String], -- used on darwin only
644 cmdlineFrameworks :: [String], -- ditto
645
646 rtsOpts :: Maybe String,
647 rtsOptsEnabled :: RtsOptsEnabled,
648
649 hpcDir :: String, -- ^ Path to store the .mix files
650
651 -- Plugins
652 pluginModNames :: [ModuleName],
653 pluginModNameOpts :: [(ModuleName,String)],
654
655 -- For ghc -M
656 depMakefile :: FilePath,
657 depIncludePkgDeps :: Bool,
658 depExcludeMods :: [ModuleName],
659 depSuffixes :: [String],
660
661 -- Package flags
662 extraPkgConfs :: [PkgConfRef] -> [PkgConfRef],
663 -- ^ The @-package-db@ flags given on the command line, in the order
664 -- they appeared.
665
666 packageFlags :: [PackageFlag],
667 -- ^ The @-package@ and @-hide-package@ flags from the command-line
668
669 -- Package state
670 -- NB. do not modify this field, it is calculated by
671 -- Packages.initPackages and Packages.updatePackages.
672 pkgDatabase :: Maybe [PackageConfig],
673 pkgState :: PackageState,
674
675 -- Temporary files
676 -- These have to be IORefs, because the defaultCleanupHandler needs to
677 -- know what to clean when an exception happens
678 filesToClean :: IORef [FilePath],
679 dirsToClean :: IORef (Map FilePath FilePath),
680 filesToNotIntermediateClean :: IORef [FilePath],
681
682
683 -- Names of files which were generated from -ddump-to-file; used to
684 -- track which ones we need to truncate because it's our first run
685 -- through
686 generatedDumps :: IORef (Set FilePath),
687
688 -- hsc dynamic flags
689 dumpFlags :: IntSet,
690 generalFlags :: IntSet,
691 warningFlags :: IntSet,
692 -- Don't change this without updating extensionFlags:
693 language :: Maybe Language,
694 -- | Safe Haskell mode
695 safeHaskell :: SafeHaskellMode,
696 -- We store the location of where some extension and flags were turned on so
697 -- we can produce accurate error messages when Safe Haskell fails due to
698 -- them.
699 thOnLoc :: SrcSpan,
700 newDerivOnLoc :: SrcSpan,
701 pkgTrustOnLoc :: SrcSpan,
702 warnSafeOnLoc :: SrcSpan,
703 warnUnsafeOnLoc :: SrcSpan,
704 -- Don't change this without updating extensionFlags:
705 extensions :: [OnOff ExtensionFlag],
706 -- extensionFlags should always be equal to
707 -- flattenExtensionFlags language extensions
708 extensionFlags :: IntSet,
709
710 -- Unfolding control
711 -- See Note [Discounts and thresholds] in CoreUnfold
712 ufCreationThreshold :: Int,
713 ufUseThreshold :: Int,
714 ufFunAppDiscount :: Int,
715 ufDictDiscount :: Int,
716 ufKeenessFactor :: Float,
717 ufDearOp :: Int,
718
719 maxWorkerArgs :: Int,
720
721 ghciHistSize :: Int,
722
723 -- | MsgDoc output action: use "ErrUtils" instead of this if you can
724 log_action :: LogAction,
725 flushOut :: FlushOut,
726 flushErr :: FlushErr,
727
728 haddockOptions :: Maybe String,
729 ghciScripts :: [String],
730
731 -- Output style options
732 pprUserLength :: Int,
733 pprCols :: Int,
734 traceLevel :: Int, -- Standard level is 1. Less verbose is 0.
735
736 useUnicodeQuotes :: Bool,
737
738 -- | what kind of {-# SCC #-} to add automatically
739 profAuto :: ProfAuto,
740
741 interactivePrint :: Maybe String,
742
743 llvmVersion :: IORef Int,
744
745 nextWrapperNum :: IORef Int,
746
747 -- | Machine dependant flags (-m<blah> stuff)
748 sseVersion :: Maybe (Int, Int), -- (major, minor)
749
750 -- | Run-time linker information (what options we need, etc.)
751 rtldFlags :: IORef (Maybe LinkerInfo)
752 }
753
754 class HasDynFlags m where
755 getDynFlags :: m DynFlags
756
757 class ContainsDynFlags t where
758 extractDynFlags :: t -> DynFlags
759 replaceDynFlags :: t -> DynFlags -> t
760
761 data ProfAuto
762 = NoProfAuto -- ^ no SCC annotations added
763 | ProfAutoAll -- ^ top-level and nested functions are annotated
764 | ProfAutoTop -- ^ top-level functions annotated only
765 | ProfAutoExports -- ^ exported functions annotated only
766 | ProfAutoCalls -- ^ annotate call-sites
767 deriving (Enum)
768
769 data Settings = Settings {
770 sTargetPlatform :: Platform, -- Filled in by SysTools
771 sGhcUsagePath :: FilePath, -- Filled in by SysTools
772 sGhciUsagePath :: FilePath, -- ditto
773 sTopDir :: FilePath,
774 sTmpDir :: String, -- no trailing '/'
775 -- You shouldn't need to look things up in rawSettings directly.
776 -- They should have their own fields instead.
777 sRawSettings :: [(String, String)],
778 sExtraGccViaCFlags :: [String],
779 sSystemPackageConfig :: FilePath,
780 sLdSupportsCompactUnwind :: Bool,
781 sLdSupportsBuildId :: Bool,
782 sLdSupportsFilelist :: Bool,
783 sLdIsGnuLd :: Bool,
784 -- commands for particular phases
785 sPgm_L :: String,
786 sPgm_P :: (String,[Option]),
787 sPgm_F :: String,
788 sPgm_c :: (String,[Option]),
789 sPgm_s :: (String,[Option]),
790 sPgm_a :: (String,[Option]),
791 sPgm_l :: (String,[Option]),
792 sPgm_dll :: (String,[Option]),
793 sPgm_T :: String,
794 sPgm_sysman :: String,
795 sPgm_windres :: String,
796 sPgm_lo :: (String,[Option]), -- LLVM: opt llvm optimiser
797 sPgm_lc :: (String,[Option]), -- LLVM: llc static compiler
798 -- options for particular phases
799 sOpt_L :: [String],
800 sOpt_P :: [String],
801 sOpt_F :: [String],
802 sOpt_c :: [String],
803 sOpt_a :: [String],
804 sOpt_l :: [String],
805 sOpt_windres :: [String],
806 sOpt_lo :: [String], -- LLVM: llvm optimiser
807 sOpt_lc :: [String], -- LLVM: llc static compiler
808
809 sPlatformConstants :: PlatformConstants
810 }
811
812 targetPlatform :: DynFlags -> Platform
813 targetPlatform dflags = sTargetPlatform (settings dflags)
814
815 ghcUsagePath :: DynFlags -> FilePath
816 ghcUsagePath dflags = sGhcUsagePath (settings dflags)
817 ghciUsagePath :: DynFlags -> FilePath
818 ghciUsagePath dflags = sGhciUsagePath (settings dflags)
819 topDir :: DynFlags -> FilePath
820 topDir dflags = sTopDir (settings dflags)
821 tmpDir :: DynFlags -> String
822 tmpDir dflags = sTmpDir (settings dflags)
823 rawSettings :: DynFlags -> [(String, String)]
824 rawSettings dflags = sRawSettings (settings dflags)
825 extraGccViaCFlags :: DynFlags -> [String]
826 extraGccViaCFlags dflags = sExtraGccViaCFlags (settings dflags)
827 systemPackageConfig :: DynFlags -> FilePath
828 systemPackageConfig dflags = sSystemPackageConfig (settings dflags)
829 pgm_L :: DynFlags -> String
830 pgm_L dflags = sPgm_L (settings dflags)
831 pgm_P :: DynFlags -> (String,[Option])
832 pgm_P dflags = sPgm_P (settings dflags)
833 pgm_F :: DynFlags -> String
834 pgm_F dflags = sPgm_F (settings dflags)
835 pgm_c :: DynFlags -> (String,[Option])
836 pgm_c dflags = sPgm_c (settings dflags)
837 pgm_s :: DynFlags -> (String,[Option])
838 pgm_s dflags = sPgm_s (settings dflags)
839 pgm_a :: DynFlags -> (String,[Option])
840 pgm_a dflags = sPgm_a (settings dflags)
841 pgm_l :: DynFlags -> (String,[Option])
842 pgm_l dflags = sPgm_l (settings dflags)
843 pgm_dll :: DynFlags -> (String,[Option])
844 pgm_dll dflags = sPgm_dll (settings dflags)
845 pgm_T :: DynFlags -> String
846 pgm_T dflags = sPgm_T (settings dflags)
847 pgm_sysman :: DynFlags -> String
848 pgm_sysman dflags = sPgm_sysman (settings dflags)
849 pgm_windres :: DynFlags -> String
850 pgm_windres dflags = sPgm_windres (settings dflags)
851 pgm_lo :: DynFlags -> (String,[Option])
852 pgm_lo dflags = sPgm_lo (settings dflags)
853 pgm_lc :: DynFlags -> (String,[Option])
854 pgm_lc dflags = sPgm_lc (settings dflags)
855 opt_L :: DynFlags -> [String]
856 opt_L dflags = sOpt_L (settings dflags)
857 opt_P :: DynFlags -> [String]
858 opt_P dflags = concatMap (wayOptP (targetPlatform dflags)) (ways dflags)
859 ++ sOpt_P (settings dflags)
860 opt_F :: DynFlags -> [String]
861 opt_F dflags = sOpt_F (settings dflags)
862 opt_c :: DynFlags -> [String]
863 opt_c dflags = concatMap (wayOptc (targetPlatform dflags)) (ways dflags)
864 ++ sOpt_c (settings dflags)
865 opt_a :: DynFlags -> [String]
866 opt_a dflags = sOpt_a (settings dflags)
867 opt_l :: DynFlags -> [String]
868 opt_l dflags = concatMap (wayOptl (targetPlatform dflags)) (ways dflags)
869 ++ sOpt_l (settings dflags)
870 opt_windres :: DynFlags -> [String]
871 opt_windres dflags = sOpt_windres (settings dflags)
872 opt_lo :: DynFlags -> [String]
873 opt_lo dflags = sOpt_lo (settings dflags)
874 opt_lc :: DynFlags -> [String]
875 opt_lc dflags = sOpt_lc (settings dflags)
876
877 -- | The target code type of the compilation (if any).
878 --
879 -- Whenever you change the target, also make sure to set 'ghcLink' to
880 -- something sensible.
881 --
882 -- 'HscNothing' can be used to avoid generating any output, however, note
883 -- that:
884 --
885 -- * This will not run the desugaring step, thus no warnings generated in
886 -- this step will be output. In particular, this includes warnings related
887 -- to pattern matching. You can run the desugarer manually using
888 -- 'GHC.desugarModule'.
889 --
890 -- * If a program uses Template Haskell the typechecker may try to run code
891 -- from an imported module. This will fail if no code has been generated
892 -- for this module. You can use 'GHC.needsTemplateHaskell' to detect
893 -- whether this might be the case and choose to either switch to a
894 -- different target or avoid typechecking such modules. (The latter may be
895 -- preferable for security reasons.)
896 --
897 data HscTarget
898 = HscC -- ^ Generate C code.
899 | HscAsm -- ^ Generate assembly using the native code generator.
900 | HscLlvm -- ^ Generate assembly using the llvm code generator.
901 | HscInterpreted -- ^ Generate bytecode. (Requires 'LinkInMemory')
902 | HscNothing -- ^ Don't generate any code. See notes above.
903 deriving (Eq, Show)
904
905 -- | Will this target result in an object file on the disk?
906 isObjectTarget :: HscTarget -> Bool
907 isObjectTarget HscC = True
908 isObjectTarget HscAsm = True
909 isObjectTarget HscLlvm = True
910 isObjectTarget _ = False
911
912 -- | Does this target retain *all* top-level bindings for a module,
913 -- rather than just the exported bindings, in the TypeEnv and compiled
914 -- code (if any)? In interpreted mode we do this, so that GHCi can
915 -- call functions inside a module. In HscNothing mode we also do it,
916 -- so that Haddock can get access to the GlobalRdrEnv for a module
917 -- after typechecking it.
918 targetRetainsAllBindings :: HscTarget -> Bool
919 targetRetainsAllBindings HscInterpreted = True
920 targetRetainsAllBindings HscNothing = True
921 targetRetainsAllBindings _ = False
922
923 -- | The 'GhcMode' tells us whether we're doing multi-module
924 -- compilation (controlled via the "GHC" API) or one-shot
925 -- (single-module) compilation. This makes a difference primarily to
926 -- the "Finder": in one-shot mode we look for interface files for
927 -- imported modules, but in multi-module mode we look for source files
928 -- in order to check whether they need to be recompiled.
929 data GhcMode
930 = CompManager -- ^ @\-\-make@, GHCi, etc.
931 | OneShot -- ^ @ghc -c Foo.hs@
932 | MkDepend -- ^ @ghc -M@, see "Finder" for why we need this
933 deriving Eq
934
935 instance Outputable GhcMode where
936 ppr CompManager = ptext (sLit "CompManager")
937 ppr OneShot = ptext (sLit "OneShot")
938 ppr MkDepend = ptext (sLit "MkDepend")
939
940 isOneShot :: GhcMode -> Bool
941 isOneShot OneShot = True
942 isOneShot _other = False
943
944 -- | What to do in the link step, if there is one.
945 data GhcLink
946 = NoLink -- ^ Don't link at all
947 | LinkBinary -- ^ Link object code into a binary
948 | LinkInMemory -- ^ Use the in-memory dynamic linker (works for both
949 -- bytecode and object code).
950 | LinkDynLib -- ^ Link objects into a dynamic lib (DLL on Windows, DSO on ELF platforms)
951 deriving (Eq, Show)
952
953 isNoLink :: GhcLink -> Bool
954 isNoLink NoLink = True
955 isNoLink _ = False
956
957 data PackageFlag
958 = ExposePackage String
959 | ExposePackageId String
960 | HidePackage String
961 | IgnorePackage String
962 | TrustPackage String
963 | DistrustPackage String
964 deriving (Eq, Show)
965
966 defaultHscTarget :: Platform -> HscTarget
967 defaultHscTarget = defaultObjectTarget
968
969 -- | The 'HscTarget' value corresponding to the default way to create
970 -- object files on the current platform.
971 defaultObjectTarget :: Platform -> HscTarget
972 defaultObjectTarget platform
973 | platformUnregisterised platform = HscC
974 | cGhcWithNativeCodeGen == "YES" = HscAsm
975 | otherwise = HscLlvm
976
977 tablesNextToCode :: DynFlags -> Bool
978 tablesNextToCode dflags
979 = mkTablesNextToCode (platformUnregisterised (targetPlatform dflags))
980
981 -- Determines whether we will be compiling
982 -- info tables that reside just before the entry code, or with an
983 -- indirection to the entry code. See TABLES_NEXT_TO_CODE in
984 -- includes/rts/storage/InfoTables.h.
985 mkTablesNextToCode :: Bool -> Bool
986 mkTablesNextToCode unregisterised
987 = not unregisterised && cGhcEnableTablesNextToCode == "YES"
988
989 data DynLibLoader
990 = Deployable
991 | SystemDependent
992 deriving Eq
993
994 data RtsOptsEnabled = RtsOptsNone | RtsOptsSafeOnly | RtsOptsAll
995 deriving (Show)
996
997 -----------------------------------------------------------------------------
998 -- Ways
999
1000 -- The central concept of a "way" is that all objects in a given
1001 -- program must be compiled in the same "way". Certain options change
1002 -- parameters of the virtual machine, eg. profiling adds an extra word
1003 -- to the object header, so profiling objects cannot be linked with
1004 -- non-profiling objects.
1005
1006 -- After parsing the command-line options, we determine which "way" we
1007 -- are building - this might be a combination way, eg. profiling+threaded.
1008
1009 -- We then find the "build-tag" associated with this way, and this
1010 -- becomes the suffix used to find .hi files and libraries used in
1011 -- this compilation.
1012
1013 data Way
1014 = WayThreaded
1015 | WayDebug
1016 | WayProf
1017 | WayEventLog
1018 | WayPar
1019 | WayGran
1020 | WayNDP
1021 | WayDyn
1022 deriving (Eq, Ord, Show)
1023
1024 allowed_combination :: [Way] -> Bool
1025 allowed_combination way = and [ x `allowedWith` y
1026 | x <- way, y <- way, x < y ]
1027 where
1028 -- Note ordering in these tests: the left argument is
1029 -- <= the right argument, according to the Ord instance
1030 -- on Way above.
1031
1032 -- dyn is allowed with everything
1033 _ `allowedWith` WayDyn = True
1034 WayDyn `allowedWith` _ = True
1035
1036 -- debug is allowed with everything
1037 _ `allowedWith` WayDebug = True
1038 WayDebug `allowedWith` _ = True
1039
1040 WayProf `allowedWith` WayNDP = True
1041 WayThreaded `allowedWith` WayProf = True
1042 WayThreaded `allowedWith` WayEventLog = True
1043 _ `allowedWith` _ = False
1044
1045 mkBuildTag :: [Way] -> String
1046 mkBuildTag ways = concat (intersperse "_" (map wayTag ways))
1047
1048 wayTag :: Way -> String
1049 wayTag WayThreaded = "thr"
1050 wayTag WayDebug = "debug"
1051 wayTag WayDyn = "dyn"
1052 wayTag WayProf = "p"
1053 wayTag WayEventLog = "l"
1054 wayTag WayPar = "mp"
1055 wayTag WayGran = "mg"
1056 wayTag WayNDP = "ndp"
1057
1058 wayRTSOnly :: Way -> Bool
1059 wayRTSOnly WayThreaded = True
1060 wayRTSOnly WayDebug = True
1061 wayRTSOnly WayDyn = False
1062 wayRTSOnly WayProf = False
1063 wayRTSOnly WayEventLog = True
1064 wayRTSOnly WayPar = False
1065 wayRTSOnly WayGran = False
1066 wayRTSOnly WayNDP = False
1067
1068 wayDesc :: Way -> String
1069 wayDesc WayThreaded = "Threaded"
1070 wayDesc WayDebug = "Debug"
1071 wayDesc WayDyn = "Dynamic"
1072 wayDesc WayProf = "Profiling"
1073 wayDesc WayEventLog = "RTS Event Logging"
1074 wayDesc WayPar = "Parallel"
1075 wayDesc WayGran = "GranSim"
1076 wayDesc WayNDP = "Nested data parallelism"
1077
1078 -- Turn these flags on when enabling this way
1079 wayGeneralFlags :: Platform -> Way -> [GeneralFlag]
1080 wayGeneralFlags _ WayThreaded = []
1081 wayGeneralFlags _ WayDebug = []
1082 wayGeneralFlags _ WayDyn = [Opt_PIC]
1083 wayGeneralFlags _ WayProf = [Opt_SccProfilingOn]
1084 wayGeneralFlags _ WayEventLog = []
1085 wayGeneralFlags _ WayPar = [Opt_Parallel]
1086 wayGeneralFlags _ WayGran = [Opt_GranMacros]
1087 wayGeneralFlags _ WayNDP = []
1088
1089 -- Turn these flags off when enabling this way
1090 wayUnsetGeneralFlags :: Platform -> Way -> [GeneralFlag]
1091 wayUnsetGeneralFlags _ WayThreaded = []
1092 wayUnsetGeneralFlags _ WayDebug = []
1093 wayUnsetGeneralFlags _ WayDyn = [-- There's no point splitting objects
1094 -- when we're going to be dynamically
1095 -- linking. Plus it breaks compilation
1096 -- on OSX x86.
1097 Opt_SplitObjs]
1098 wayUnsetGeneralFlags _ WayProf = []
1099 wayUnsetGeneralFlags _ WayEventLog = []
1100 wayUnsetGeneralFlags _ WayPar = []
1101 wayUnsetGeneralFlags _ WayGran = []
1102 wayUnsetGeneralFlags _ WayNDP = []
1103
1104 wayExtras :: Platform -> Way -> DynFlags -> DynFlags
1105 wayExtras _ WayThreaded dflags = dflags
1106 wayExtras _ WayDebug dflags = dflags
1107 wayExtras _ WayDyn dflags = dflags
1108 wayExtras _ WayProf dflags = dflags
1109 wayExtras _ WayEventLog dflags = dflags
1110 wayExtras _ WayPar dflags = exposePackage' "concurrent" dflags
1111 wayExtras _ WayGran dflags = exposePackage' "concurrent" dflags
1112 wayExtras _ WayNDP dflags = setExtensionFlag' Opt_ParallelArrays
1113 $ setGeneralFlag' Opt_Vectorise dflags
1114
1115 wayOptc :: Platform -> Way -> [String]
1116 wayOptc platform WayThreaded = case platformOS platform of
1117 OSOpenBSD -> ["-pthread"]
1118 OSNetBSD -> ["-pthread"]
1119 _ -> []
1120 wayOptc _ WayDebug = []
1121 wayOptc _ WayDyn = []
1122 wayOptc _ WayProf = ["-DPROFILING"]
1123 wayOptc _ WayEventLog = ["-DTRACING"]
1124 wayOptc _ WayPar = ["-DPAR", "-w"]
1125 wayOptc _ WayGran = ["-DGRAN"]
1126 wayOptc _ WayNDP = []
1127
1128 wayOptl :: Platform -> Way -> [String]
1129 wayOptl platform WayThreaded =
1130 case platformOS platform of
1131 -- FreeBSD's default threading library is the KSE-based M:N libpthread,
1132 -- which GHC has some problems with. It's currently not clear whether
1133 -- the problems are our fault or theirs, but it seems that using the
1134 -- alternative 1:1 threading library libthr works around it:
1135 OSFreeBSD -> ["-lthr"]
1136 OSSolaris2 -> ["-lrt"]
1137 OSOpenBSD -> ["-pthread"]
1138 OSNetBSD -> ["-pthread"]
1139 _ -> []
1140 wayOptl _ WayDebug = []
1141 wayOptl _ WayDyn = []
1142 wayOptl _ WayProf = []
1143 wayOptl _ WayEventLog = []
1144 wayOptl _ WayPar = ["-L${PVM_ROOT}/lib/${PVM_ARCH}",
1145 "-lpvm3",
1146 "-lgpvm3"]
1147 wayOptl _ WayGran = []
1148 wayOptl _ WayNDP = []
1149
1150 wayOptP :: Platform -> Way -> [String]
1151 wayOptP _ WayThreaded = []
1152 wayOptP _ WayDebug = []
1153 wayOptP _ WayDyn = []
1154 wayOptP _ WayProf = ["-DPROFILING"]
1155 wayOptP _ WayEventLog = ["-DTRACING"]
1156 wayOptP _ WayPar = ["-D__PARALLEL_HASKELL__"]
1157 wayOptP _ WayGran = ["-D__GRANSIM__"]
1158 wayOptP _ WayNDP = []
1159
1160 whenGeneratingDynamicToo :: MonadIO m => DynFlags -> m () -> m ()
1161 whenGeneratingDynamicToo dflags f = ifGeneratingDynamicToo dflags f (return ())
1162
1163 ifGeneratingDynamicToo :: MonadIO m => DynFlags -> m a -> m a -> m a
1164 ifGeneratingDynamicToo dflags f g = generateDynamicTooConditional dflags f g g
1165
1166 whenCannotGenerateDynamicToo :: MonadIO m => DynFlags -> m () -> m ()
1167 whenCannotGenerateDynamicToo dflags f
1168 = ifCannotGenerateDynamicToo dflags f (return ())
1169
1170 ifCannotGenerateDynamicToo :: MonadIO m => DynFlags -> m a -> m a -> m a
1171 ifCannotGenerateDynamicToo dflags f g
1172 = generateDynamicTooConditional dflags g f g
1173
1174 generateDynamicTooConditional :: MonadIO m
1175 => DynFlags -> m a -> m a -> m a -> m a
1176 generateDynamicTooConditional dflags canGen cannotGen notTryingToGen
1177 = if gopt Opt_BuildDynamicToo dflags
1178 then do let ref = canGenerateDynamicToo dflags
1179 b <- liftIO $ readIORef ref
1180 if b then canGen else cannotGen
1181 else notTryingToGen
1182
1183 doDynamicToo :: DynFlags -> DynFlags
1184 doDynamicToo dflags0 = let dflags1 = addWay' WayDyn dflags0
1185 dflags2 = dflags1 {
1186 outputFile = dynOutputFile dflags1,
1187 hiSuf = dynHiSuf dflags1,
1188 objectSuf = dynObjectSuf dflags1
1189 }
1190 dflags3 = updateWays dflags2
1191 dflags4 = gopt_unset dflags3 Opt_BuildDynamicToo
1192 in dflags4
1193
1194 -----------------------------------------------------------------------------
1195
1196 -- | Used by 'GHC.newSession' to partially initialize a new 'DynFlags' value
1197 initDynFlags :: DynFlags -> IO DynFlags
1198 initDynFlags dflags = do
1199 let -- We can't build with dynamic-too on Windows, as labels before
1200 -- the fork point are different depending on whether we are
1201 -- building dynamically or not.
1202 platformCanGenerateDynamicToo
1203 = platformOS (targetPlatform dflags) /= OSMinGW32
1204 refCanGenerateDynamicToo <- newIORef platformCanGenerateDynamicToo
1205 refFilesToClean <- newIORef []
1206 refDirsToClean <- newIORef Map.empty
1207 refFilesToNotIntermediateClean <- newIORef []
1208 refGeneratedDumps <- newIORef Set.empty
1209 refLlvmVersion <- newIORef 28
1210 refRtldFlags <- newIORef Nothing
1211 wrapperNum <- newIORef 0
1212 canUseUnicodeQuotes <- do let enc = localeEncoding
1213 str = "‛’"
1214 (withCString enc str $ \cstr ->
1215 do str' <- peekCString enc cstr
1216 return (str == str'))
1217 `catchIOError` \_ -> return False
1218 return dflags{
1219 canGenerateDynamicToo = refCanGenerateDynamicToo,
1220 filesToClean = refFilesToClean,
1221 dirsToClean = refDirsToClean,
1222 filesToNotIntermediateClean = refFilesToNotIntermediateClean,
1223 generatedDumps = refGeneratedDumps,
1224 llvmVersion = refLlvmVersion,
1225 nextWrapperNum = wrapperNum,
1226 useUnicodeQuotes = canUseUnicodeQuotes,
1227 rtldFlags = refRtldFlags
1228 }
1229
1230 -- | The normal 'DynFlags'. Note that they is not suitable for use in this form
1231 -- and must be fully initialized by 'GHC.newSession' first.
1232 defaultDynFlags :: Settings -> DynFlags
1233 defaultDynFlags mySettings =
1234 DynFlags {
1235 ghcMode = CompManager,
1236 ghcLink = LinkBinary,
1237 hscTarget = defaultHscTarget (sTargetPlatform mySettings),
1238 verbosity = 0,
1239 optLevel = 0,
1240 simplPhases = 2,
1241 maxSimplIterations = 4,
1242 shouldDumpSimplPhase = Nothing,
1243 ruleCheck = Nothing,
1244 simplTickFactor = 100,
1245 specConstrThreshold = Just 2000,
1246 specConstrCount = Just 3,
1247 specConstrRecursive = 3,
1248 liberateCaseThreshold = Just 2000,
1249 floatLamArgs = Just 0, -- Default: float only if no fvs
1250 historySize = 20,
1251 strictnessBefore = [],
1252
1253 cmdlineHcIncludes = [],
1254 importPaths = ["."],
1255 mainModIs = mAIN,
1256 mainFunIs = Nothing,
1257 ctxtStkDepth = mAX_CONTEXT_REDUCTION_DEPTH,
1258
1259 thisPackage = mainPackageId,
1260
1261 objectDir = Nothing,
1262 dylibInstallName = Nothing,
1263 hiDir = Nothing,
1264 stubDir = Nothing,
1265 dumpDir = Nothing,
1266
1267 objectSuf = phaseInputExt StopLn,
1268 hcSuf = phaseInputExt HCc,
1269 hiSuf = "hi",
1270
1271 canGenerateDynamicToo = panic "defaultDynFlags: No canGenerateDynamicToo",
1272 dynObjectSuf = "dyn_" ++ phaseInputExt StopLn,
1273 dynHiSuf = "dyn_hi",
1274
1275 dllSplitFile = Nothing,
1276 dllSplit = Nothing,
1277
1278 pluginModNames = [],
1279 pluginModNameOpts = [],
1280
1281 outputFile = Nothing,
1282 dynOutputFile = Nothing,
1283 outputHi = Nothing,
1284 dynLibLoader = SystemDependent,
1285 dumpPrefix = Nothing,
1286 dumpPrefixForce = Nothing,
1287 ldInputs = [],
1288 includePaths = [],
1289 libraryPaths = [],
1290 frameworkPaths = [],
1291 cmdlineFrameworks = [],
1292 rtsOpts = Nothing,
1293 rtsOptsEnabled = RtsOptsSafeOnly,
1294
1295 hpcDir = ".hpc",
1296
1297 extraPkgConfs = id,
1298 packageFlags = [],
1299 pkgDatabase = Nothing,
1300 pkgState = panic "no package state yet: call GHC.setSessionDynFlags",
1301 ways = defaultWays mySettings,
1302 buildTag = mkBuildTag (defaultWays mySettings),
1303 rtsBuildTag = mkBuildTag (defaultWays mySettings),
1304 splitInfo = Nothing,
1305 settings = mySettings,
1306 -- ghc -M values
1307 depMakefile = "Makefile",
1308 depIncludePkgDeps = False,
1309 depExcludeMods = [],
1310 depSuffixes = [],
1311 -- end of ghc -M values
1312 filesToClean = panic "defaultDynFlags: No filesToClean",
1313 dirsToClean = panic "defaultDynFlags: No dirsToClean",
1314 filesToNotIntermediateClean = panic "defaultDynFlags: No filesToNotIntermediateClean",
1315 generatedDumps = panic "defaultDynFlags: No generatedDumps",
1316 haddockOptions = Nothing,
1317 dumpFlags = IntSet.empty,
1318 generalFlags = IntSet.fromList (map fromEnum (defaultFlags mySettings)),
1319 warningFlags = IntSet.fromList (map fromEnum standardWarnings),
1320 ghciScripts = [],
1321 language = Nothing,
1322 safeHaskell = Sf_SafeInferred,
1323 thOnLoc = noSrcSpan,
1324 newDerivOnLoc = noSrcSpan,
1325 pkgTrustOnLoc = noSrcSpan,
1326 warnSafeOnLoc = noSrcSpan,
1327 warnUnsafeOnLoc = noSrcSpan,
1328 extensions = [],
1329 extensionFlags = flattenExtensionFlags Nothing [],
1330
1331 -- The ufCreationThreshold threshold must be reasonably high to
1332 -- take account of possible discounts.
1333 -- E.g. 450 is not enough in 'fulsom' for Interval.sqr to inline
1334 -- into Csg.calc (The unfolding for sqr never makes it into the
1335 -- interface file.)
1336 ufCreationThreshold = 750,
1337 ufUseThreshold = 60,
1338 ufFunAppDiscount = 60,
1339 -- Be fairly keen to inline a fuction if that means
1340 -- we'll be able to pick the right method from a dictionary
1341 ufDictDiscount = 30,
1342 ufKeenessFactor = 1.5,
1343 ufDearOp = 40,
1344
1345 maxWorkerArgs = 10,
1346
1347 ghciHistSize = 50, -- keep a log of length 50 by default
1348
1349 log_action = defaultLogAction,
1350 flushOut = defaultFlushOut,
1351 flushErr = defaultFlushErr,
1352 pprUserLength = 5,
1353 pprCols = 100,
1354 useUnicodeQuotes = False,
1355 traceLevel = 1,
1356 profAuto = NoProfAuto,
1357 llvmVersion = panic "defaultDynFlags: No llvmVersion",
1358 interactivePrint = Nothing,
1359 nextWrapperNum = panic "defaultDynFlags: No nextWrapperNum",
1360 sseVersion = Nothing,
1361 rtldFlags = panic "defaultDynFlags: no rtldFlags"
1362 }
1363
1364 defaultWays :: Settings -> [Way]
1365 defaultWays settings = if pc_DYNAMIC_BY_DEFAULT (sPlatformConstants settings)
1366 then [WayDyn]
1367 else []
1368
1369 interpWays :: [Way]
1370 interpWays = if cDYNAMIC_GHC_PROGRAMS
1371 then [WayDyn]
1372 else []
1373
1374 --------------------------------------------------------------------------
1375
1376 type FatalMessager = String -> IO ()
1377 type LogAction = DynFlags -> Severity -> SrcSpan -> PprStyle -> MsgDoc -> IO ()
1378
1379 defaultFatalMessager :: FatalMessager
1380 defaultFatalMessager = hPutStrLn stderr
1381
1382 defaultLogAction :: LogAction
1383 defaultLogAction dflags severity srcSpan style msg
1384 = case severity of
1385 SevOutput -> printSDoc msg style
1386 SevDump -> printSDoc (msg $$ blankLine) style
1387 SevInfo -> printErrs msg style
1388 SevFatal -> printErrs msg style
1389 _ -> do hPutChar stderr '\n'
1390 printErrs (mkLocMessage severity srcSpan msg) style
1391 -- careful (#2302): printErrs prints in UTF-8, whereas
1392 -- converting to string first and using hPutStr would
1393 -- just emit the low 8 bits of each unicode char.
1394 where printSDoc = defaultLogActionHPrintDoc dflags stdout
1395 printErrs = defaultLogActionHPrintDoc dflags stderr
1396
1397 defaultLogActionHPrintDoc :: DynFlags -> Handle -> SDoc -> PprStyle -> IO ()
1398 defaultLogActionHPrintDoc dflags h d sty
1399 = do let doc = runSDoc d (initSDocContext dflags sty)
1400 Pretty.printDoc Pretty.PageMode (pprCols dflags) h doc
1401 hFlush h
1402
1403 newtype FlushOut = FlushOut (IO ())
1404
1405 defaultFlushOut :: FlushOut
1406 defaultFlushOut = FlushOut $ hFlush stdout
1407
1408 newtype FlushErr = FlushErr (IO ())
1409
1410 defaultFlushErr :: FlushErr
1411 defaultFlushErr = FlushErr $ hFlush stderr
1412
1413 printOutputForUser :: DynFlags -> PrintUnqualified -> SDoc -> IO ()
1414 printOutputForUser = printSevForUser SevOutput
1415
1416 printInfoForUser :: DynFlags -> PrintUnqualified -> SDoc -> IO ()
1417 printInfoForUser = printSevForUser SevInfo
1418
1419 printSevForUser :: Severity -> DynFlags -> PrintUnqualified -> SDoc -> IO ()
1420 printSevForUser sev dflags unqual doc
1421 = log_action dflags dflags sev noSrcSpan (mkUserStyle unqual AllTheWay) doc
1422
1423 {-
1424 Note [Verbosity levels]
1425 ~~~~~~~~~~~~~~~~~~~~~~~
1426 0 | print errors & warnings only
1427 1 | minimal verbosity: print "compiling M ... done." for each module.
1428 2 | equivalent to -dshow-passes
1429 3 | equivalent to existing "ghc -v"
1430 4 | "ghc -v -ddump-most"
1431 5 | "ghc -v -ddump-all"
1432 -}
1433
1434 data OnOff a = On a
1435 | Off a
1436
1437 -- OnOffs accumulate in reverse order, so we use foldr in order to
1438 -- process them in the right order
1439 flattenExtensionFlags :: Maybe Language -> [OnOff ExtensionFlag] -> IntSet
1440 flattenExtensionFlags ml = foldr f defaultExtensionFlags
1441 where f (On f) flags = IntSet.insert (fromEnum f) flags
1442 f (Off f) flags = IntSet.delete (fromEnum f) flags
1443 defaultExtensionFlags = IntSet.fromList (map fromEnum (languageExtensions ml))
1444
1445 languageExtensions :: Maybe Language -> [ExtensionFlag]
1446
1447 languageExtensions Nothing
1448 -- Nothing => the default case
1449 = Opt_NondecreasingIndentation -- This has been on by default for some time
1450 : delete Opt_DatatypeContexts -- The Haskell' committee decided to
1451 -- remove datatype contexts from the
1452 -- language:
1453 -- http://www.haskell.org/pipermail/haskell-prime/2011-January/003335.html
1454 (languageExtensions (Just Haskell2010))
1455
1456 -- NB: MonoPatBinds is no longer the default
1457
1458 languageExtensions (Just Haskell98)
1459 = [Opt_ImplicitPrelude,
1460 Opt_MonomorphismRestriction,
1461 Opt_NPlusKPatterns,
1462 Opt_DatatypeContexts,
1463 Opt_TraditionalRecordSyntax,
1464 Opt_NondecreasingIndentation
1465 -- strictly speaking non-standard, but we always had this
1466 -- on implicitly before the option was added in 7.1, and
1467 -- turning it off breaks code, so we're keeping it on for
1468 -- backwards compatibility. Cabal uses -XHaskell98 by
1469 -- default unless you specify another language.
1470 ]
1471
1472 languageExtensions (Just Haskell2010)
1473 = [Opt_ImplicitPrelude,
1474 Opt_MonomorphismRestriction,
1475 Opt_DatatypeContexts,
1476 Opt_TraditionalRecordSyntax,
1477 Opt_EmptyDataDecls,
1478 Opt_ForeignFunctionInterface,
1479 Opt_PatternGuards,
1480 Opt_DoAndIfThenElse,
1481 Opt_RelaxedPolyRec]
1482
1483 -- | Test whether a 'DumpFlag' is set
1484 dopt :: DumpFlag -> DynFlags -> Bool
1485 dopt f dflags = (fromEnum f `IntSet.member` dumpFlags dflags)
1486 || (verbosity dflags >= 4 && enableIfVerbose f)
1487 where enableIfVerbose Opt_D_dump_tc_trace = False
1488 enableIfVerbose Opt_D_dump_rn_trace = False
1489 enableIfVerbose Opt_D_dump_cs_trace = False
1490 enableIfVerbose Opt_D_dump_if_trace = False
1491 enableIfVerbose Opt_D_dump_vt_trace = False
1492 enableIfVerbose Opt_D_dump_tc = False
1493 enableIfVerbose Opt_D_dump_rn = False
1494 enableIfVerbose Opt_D_dump_rn_stats = False
1495 enableIfVerbose Opt_D_dump_hi_diffs = False
1496 enableIfVerbose Opt_D_verbose_core2core = False
1497 enableIfVerbose Opt_D_verbose_stg2stg = False
1498 enableIfVerbose Opt_D_dump_splices = False
1499 enableIfVerbose Opt_D_dump_rule_firings = False
1500 enableIfVerbose Opt_D_dump_rule_rewrites = False
1501 enableIfVerbose Opt_D_dump_simpl_trace = False
1502 enableIfVerbose Opt_D_dump_rtti = False
1503 enableIfVerbose Opt_D_dump_inlinings = False
1504 enableIfVerbose Opt_D_dump_core_stats = False
1505 enableIfVerbose Opt_D_dump_asm_stats = False
1506 enableIfVerbose Opt_D_dump_types = False
1507 enableIfVerbose Opt_D_dump_simpl_iterations = False
1508 enableIfVerbose Opt_D_dump_ticked = False
1509 enableIfVerbose Opt_D_dump_view_pattern_commoning = False
1510 enableIfVerbose Opt_D_dump_mod_cycles = False
1511 enableIfVerbose _ = True
1512
1513 -- | Set a 'DumpFlag'
1514 dopt_set :: DynFlags -> DumpFlag -> DynFlags
1515 dopt_set dfs f = dfs{ dumpFlags = IntSet.insert (fromEnum f) (dumpFlags dfs) }
1516
1517 -- | Unset a 'DumpFlag'
1518 dopt_unset :: DynFlags -> DumpFlag -> DynFlags
1519 dopt_unset dfs f = dfs{ dumpFlags = IntSet.delete (fromEnum f) (dumpFlags dfs) }
1520
1521 -- | Test whether a 'GeneralFlag' is set
1522 gopt :: GeneralFlag -> DynFlags -> Bool
1523 gopt f dflags = fromEnum f `IntSet.member` generalFlags dflags
1524
1525 -- | Set a 'GeneralFlag'
1526 gopt_set :: DynFlags -> GeneralFlag -> DynFlags
1527 gopt_set dfs f = dfs{ generalFlags = IntSet.insert (fromEnum f) (generalFlags dfs) }
1528
1529 -- | Unset a 'GeneralFlag'
1530 gopt_unset :: DynFlags -> GeneralFlag -> DynFlags
1531 gopt_unset dfs f = dfs{ generalFlags = IntSet.delete (fromEnum f) (generalFlags dfs) }
1532
1533 -- | Test whether a 'WarningFlag' is set
1534 wopt :: WarningFlag -> DynFlags -> Bool
1535 wopt f dflags = fromEnum f `IntSet.member` warningFlags dflags
1536
1537 -- | Set a 'WarningFlag'
1538 wopt_set :: DynFlags -> WarningFlag -> DynFlags
1539 wopt_set dfs f = dfs{ warningFlags = IntSet.insert (fromEnum f) (warningFlags dfs) }
1540
1541 -- | Unset a 'WarningFlag'
1542 wopt_unset :: DynFlags -> WarningFlag -> DynFlags
1543 wopt_unset dfs f = dfs{ warningFlags = IntSet.delete (fromEnum f) (warningFlags dfs) }
1544
1545 -- | Test whether a 'ExtensionFlag' is set
1546 xopt :: ExtensionFlag -> DynFlags -> Bool
1547 xopt f dflags = fromEnum f `IntSet.member` extensionFlags dflags
1548
1549 -- | Set a 'ExtensionFlag'
1550 xopt_set :: DynFlags -> ExtensionFlag -> DynFlags
1551 xopt_set dfs f
1552 = let onoffs = On f : extensions dfs
1553 in dfs { extensions = onoffs,
1554 extensionFlags = flattenExtensionFlags (language dfs) onoffs }
1555
1556 -- | Unset a 'ExtensionFlag'
1557 xopt_unset :: DynFlags -> ExtensionFlag -> DynFlags
1558 xopt_unset dfs f
1559 = let onoffs = Off f : extensions dfs
1560 in dfs { extensions = onoffs,
1561 extensionFlags = flattenExtensionFlags (language dfs) onoffs }
1562
1563 lang_set :: DynFlags -> Maybe Language -> DynFlags
1564 lang_set dflags lang =
1565 dflags {
1566 language = lang,
1567 extensionFlags = flattenExtensionFlags lang (extensions dflags)
1568 }
1569
1570 -- | Set the Haskell language standard to use
1571 setLanguage :: Language -> DynP ()
1572 setLanguage l = upd (`lang_set` Just l)
1573
1574 -- | Some modules have dependencies on others through the DynFlags rather than textual imports
1575 dynFlagDependencies :: DynFlags -> [ModuleName]
1576 dynFlagDependencies = pluginModNames
1577
1578 -- | Is the -fpackage-trust mode on
1579 packageTrustOn :: DynFlags -> Bool
1580 packageTrustOn = gopt Opt_PackageTrust
1581
1582 -- | Is Safe Haskell on in some way (including inference mode)
1583 safeHaskellOn :: DynFlags -> Bool
1584 safeHaskellOn dflags = safeHaskell dflags /= Sf_None
1585
1586 -- | Is the Safe Haskell safe language in use
1587 safeLanguageOn :: DynFlags -> Bool
1588 safeLanguageOn dflags = safeHaskell dflags == Sf_Safe
1589
1590 -- | Is the Safe Haskell safe inference mode active
1591 safeInferOn :: DynFlags -> Bool
1592 safeInferOn dflags = safeHaskell dflags == Sf_SafeInferred
1593
1594 -- | Test if Safe Imports are on in some form
1595 safeImportsOn :: DynFlags -> Bool
1596 safeImportsOn dflags = safeHaskell dflags == Sf_Unsafe ||
1597 safeHaskell dflags == Sf_Trustworthy ||
1598 safeHaskell dflags == Sf_Safe
1599
1600 -- | Set a 'Safe Haskell' flag
1601 setSafeHaskell :: SafeHaskellMode -> DynP ()
1602 setSafeHaskell s = updM f
1603 where f dfs = do
1604 let sf = safeHaskell dfs
1605 safeM <- combineSafeFlags sf s
1606 return $ dfs { safeHaskell = safeM }
1607
1608 -- | Are all direct imports required to be safe for this Safe Haskell mode?
1609 -- Direct imports are when the code explicitly imports a module
1610 safeDirectImpsReq :: DynFlags -> Bool
1611 safeDirectImpsReq d = safeLanguageOn d
1612
1613 -- | Are all implicit imports required to be safe for this Safe Haskell mode?
1614 -- Implicit imports are things in the prelude. e.g System.IO when print is used.
1615 safeImplicitImpsReq :: DynFlags -> Bool
1616 safeImplicitImpsReq d = safeLanguageOn d
1617
1618 -- | Combine two Safe Haskell modes correctly. Used for dealing with multiple flags.
1619 -- This makes Safe Haskell very much a monoid but for now I prefer this as I don't
1620 -- want to export this functionality from the module but do want to export the
1621 -- type constructors.
1622 combineSafeFlags :: SafeHaskellMode -> SafeHaskellMode -> DynP SafeHaskellMode
1623 combineSafeFlags a b | a == Sf_SafeInferred = return b
1624 | b == Sf_SafeInferred = return a
1625 | a == Sf_None = return b
1626 | b == Sf_None = return a
1627 | a == b = return a
1628 | otherwise = addErr errm >> return (panic errm)
1629 where errm = "Incompatible Safe Haskell flags! ("
1630 ++ show a ++ ", " ++ show b ++ ")"
1631
1632 -- | A list of unsafe flags under Safe Haskell. Tuple elements are:
1633 -- * name of the flag
1634 -- * function to get srcspan that enabled the flag
1635 -- * function to test if the flag is on
1636 -- * function to turn the flag off
1637 unsafeFlags :: [(String, DynFlags -> SrcSpan, DynFlags -> Bool, DynFlags -> DynFlags)]
1638 unsafeFlags = [("-XGeneralizedNewtypeDeriving", newDerivOnLoc,
1639 xopt Opt_GeneralizedNewtypeDeriving,
1640 flip xopt_unset Opt_GeneralizedNewtypeDeriving),
1641 ("-XTemplateHaskell", thOnLoc,
1642 xopt Opt_TemplateHaskell,
1643 flip xopt_unset Opt_TemplateHaskell)]
1644
1645 -- | Retrieve the options corresponding to a particular @opt_*@ field in the correct order
1646 getOpts :: DynFlags -- ^ 'DynFlags' to retrieve the options from
1647 -> (DynFlags -> [a]) -- ^ Relevant record accessor: one of the @opt_*@ accessors
1648 -> [a] -- ^ Correctly ordered extracted options
1649 getOpts dflags opts = reverse (opts dflags)
1650 -- We add to the options from the front, so we need to reverse the list
1651
1652 -- | Gets the verbosity flag for the current verbosity level. This is fed to
1653 -- other tools, so GHC-specific verbosity flags like @-ddump-most@ are not included
1654 getVerbFlags :: DynFlags -> [String]
1655 getVerbFlags dflags
1656 | verbosity dflags >= 4 = ["-v"]
1657 | otherwise = []
1658
1659 setObjectDir, setHiDir, setStubDir, setDumpDir, setOutputDir,
1660 setDynObjectSuf, setDynHiSuf,
1661 setDylibInstallName,
1662 setObjectSuf, setHiSuf, setHcSuf, parseDynLibLoaderMode,
1663 setPgmP, addOptl, addOptc, addOptP,
1664 addCmdlineFramework, addHaddockOpts, addGhciScript,
1665 setInteractivePrint
1666 :: String -> DynFlags -> DynFlags
1667 setOutputFile, setDynOutputFile, setOutputHi, setDumpPrefixForce
1668 :: Maybe String -> DynFlags -> DynFlags
1669
1670 setObjectDir f d = d{ objectDir = Just f}
1671 setHiDir f d = d{ hiDir = Just f}
1672 setStubDir f d = d{ stubDir = Just f, includePaths = f : includePaths d }
1673 -- -stubdir D adds an implicit -I D, so that gcc can find the _stub.h file
1674 -- \#included from the .hc file when compiling via C (i.e. unregisterised
1675 -- builds).
1676 setDumpDir f d = d{ dumpDir = Just f}
1677 setOutputDir f = setObjectDir f . setHiDir f . setStubDir f . setDumpDir f
1678 setDylibInstallName f d = d{ dylibInstallName = Just f}
1679
1680 setObjectSuf f d = d{ objectSuf = f}
1681 setDynObjectSuf f d = d{ dynObjectSuf = f}
1682 setHiSuf f d = d{ hiSuf = f}
1683 setDynHiSuf f d = d{ dynHiSuf = f}
1684 setHcSuf f d = d{ hcSuf = f}
1685
1686 setOutputFile f d = d{ outputFile = f}
1687 setDynOutputFile f d = d{ dynOutputFile = f}
1688 setOutputHi f d = d{ outputHi = f}
1689
1690 addPluginModuleName :: String -> DynFlags -> DynFlags
1691 addPluginModuleName name d = d { pluginModNames = (mkModuleName name) : (pluginModNames d) }
1692
1693 addPluginModuleNameOption :: String -> DynFlags -> DynFlags
1694 addPluginModuleNameOption optflag d = d { pluginModNameOpts = (mkModuleName m, option) : (pluginModNameOpts d) }
1695 where (m, rest) = break (== ':') optflag
1696 option = case rest of
1697 [] -> "" -- should probably signal an error
1698 (_:plug_opt) -> plug_opt -- ignore the ':' from break
1699
1700 parseDynLibLoaderMode f d =
1701 case splitAt 8 f of
1702 ("deploy", "") -> d{ dynLibLoader = Deployable }
1703 ("sysdep", "") -> d{ dynLibLoader = SystemDependent }
1704 _ -> throwGhcException (CmdLineError ("Unknown dynlib loader: " ++ f))
1705
1706 setDumpPrefixForce f d = d { dumpPrefixForce = f}
1707
1708 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
1709 -- Config.hs should really use Option.
1710 setPgmP f = let (pgm:args) = words f in alterSettings (\s -> s { sPgm_P = (pgm, map Option args)})
1711 addOptl f = alterSettings (\s -> s { sOpt_l = f : sOpt_l s})
1712 addOptc f = alterSettings (\s -> s { sOpt_c = f : sOpt_c s})
1713 addOptP f = alterSettings (\s -> s { sOpt_P = f : sOpt_P s})
1714
1715
1716 setDepMakefile :: FilePath -> DynFlags -> DynFlags
1717 setDepMakefile f d = d { depMakefile = deOptDep f }
1718
1719 setDepIncludePkgDeps :: Bool -> DynFlags -> DynFlags
1720 setDepIncludePkgDeps b d = d { depIncludePkgDeps = b }
1721
1722 addDepExcludeMod :: String -> DynFlags -> DynFlags
1723 addDepExcludeMod m d
1724 = d { depExcludeMods = mkModuleName (deOptDep m) : depExcludeMods d }
1725
1726 addDepSuffix :: FilePath -> DynFlags -> DynFlags
1727 addDepSuffix s d = d { depSuffixes = deOptDep s : depSuffixes d }
1728
1729 -- XXX Legacy code:
1730 -- We used to use "-optdep-flag -optdeparg", so for legacy applications
1731 -- we need to strip the "-optdep" off of the arg
1732 deOptDep :: String -> String
1733 deOptDep x = case stripPrefix "-optdep" x of
1734 Just rest -> rest
1735 Nothing -> x
1736
1737 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
1738
1739 addHaddockOpts f d = d{ haddockOptions = Just f}
1740
1741 addGhciScript f d = d{ ghciScripts = f : ghciScripts d}
1742
1743 setInteractivePrint f d = d{ interactivePrint = Just f}
1744
1745 -- -----------------------------------------------------------------------------
1746 -- Command-line options
1747
1748 -- | When invoking external tools as part of the compilation pipeline, we
1749 -- pass these a sequence of options on the command-line. Rather than
1750 -- just using a list of Strings, we use a type that allows us to distinguish
1751 -- between filepaths and 'other stuff'. The reason for this is that
1752 -- this type gives us a handle on transforming filenames, and filenames only,
1753 -- to whatever format they're expected to be on a particular platform.
1754 data Option
1755 = FileOption -- an entry that _contains_ filename(s) / filepaths.
1756 String -- a non-filepath prefix that shouldn't be
1757 -- transformed (e.g., "/out=")
1758 String -- the filepath/filename portion
1759 | Option String
1760 deriving ( Eq )
1761
1762 showOpt :: Option -> String
1763 showOpt (FileOption pre f) = pre ++ f
1764 showOpt (Option s) = s
1765
1766 -----------------------------------------------------------------------------
1767 -- Setting the optimisation level
1768
1769 updOptLevel :: Int -> DynFlags -> DynFlags
1770 -- ^ Sets the 'DynFlags' to be appropriate to the optimisation level
1771 updOptLevel n dfs
1772 = dfs2{ optLevel = final_n }
1773 where
1774 final_n = max 0 (min 2 n) -- Clamp to 0 <= n <= 2
1775 dfs1 = foldr (flip gopt_unset) dfs remove_gopts
1776 dfs2 = foldr (flip gopt_set) dfs1 extra_gopts
1777
1778 extra_gopts = [ f | (ns,f) <- optLevelFlags, final_n `elem` ns ]
1779 remove_gopts = [ f | (ns,f) <- optLevelFlags, final_n `notElem` ns ]
1780
1781 -- -----------------------------------------------------------------------------
1782 -- StgToDo: abstraction of stg-to-stg passes to run.
1783
1784 data StgToDo
1785 = StgDoMassageForProfiling -- should be (next to) last
1786 -- There's also setStgVarInfo, but its absolute "lastness"
1787 -- is so critical that it is hardwired in (no flag).
1788 | D_stg_stats
1789
1790 getStgToDo :: DynFlags -> [StgToDo]
1791 getStgToDo dflags
1792 = todo2
1793 where
1794 stg_stats = gopt Opt_StgStats dflags
1795
1796 todo1 = if stg_stats then [D_stg_stats] else []
1797
1798 todo2 | WayProf `elem` ways dflags
1799 = StgDoMassageForProfiling : todo1
1800 | otherwise
1801 = todo1
1802
1803 {- **********************************************************************
1804 %* *
1805 DynFlags parser
1806 %* *
1807 %********************************************************************* -}
1808
1809 -- -----------------------------------------------------------------------------
1810 -- Parsing the dynamic flags.
1811
1812
1813 -- | Parse dynamic flags from a list of command line arguments. Returns the
1814 -- the parsed 'DynFlags', the left-over arguments, and a list of warnings.
1815 -- Throws a 'UsageError' if errors occurred during parsing (such as unknown
1816 -- flags or missing arguments).
1817 parseDynamicFlagsCmdLine :: MonadIO m => DynFlags -> [Located String]
1818 -> m (DynFlags, [Located String], [Located String])
1819 -- ^ Updated 'DynFlags', left-over arguments, and
1820 -- list of warnings.
1821 parseDynamicFlagsCmdLine = parseDynamicFlagsFull flagsAll True
1822
1823
1824 -- | Like 'parseDynamicFlagsCmdLine' but does not allow the package flags
1825 -- (-package, -hide-package, -ignore-package, -hide-all-packages, -package-db).
1826 -- Used to parse flags set in a modules pragma.
1827 parseDynamicFilePragma :: MonadIO m => DynFlags -> [Located String]
1828 -> m (DynFlags, [Located String], [Located String])
1829 -- ^ Updated 'DynFlags', left-over arguments, and
1830 -- list of warnings.
1831 parseDynamicFilePragma = parseDynamicFlagsFull flagsDynamic False
1832
1833
1834 -- | Parses the dynamically set flags for GHC. This is the most general form of
1835 -- the dynamic flag parser that the other methods simply wrap. It allows
1836 -- saying which flags are valid flags and indicating if we are parsing
1837 -- arguments from the command line or from a file pragma.
1838 parseDynamicFlagsFull :: MonadIO m
1839 => [Flag (CmdLineP DynFlags)] -- ^ valid flags to match against
1840 -> Bool -- ^ are the arguments from the command line?
1841 -> DynFlags -- ^ current dynamic flags
1842 -> [Located String] -- ^ arguments to parse
1843 -> m (DynFlags, [Located String], [Located String])
1844 parseDynamicFlagsFull activeFlags cmdline dflags0 args = do
1845 -- XXX Legacy support code
1846 -- We used to accept things like
1847 -- optdep-f -optdepdepend
1848 -- optdep-f -optdep depend
1849 -- optdep -f -optdepdepend
1850 -- optdep -f -optdep depend
1851 -- but the spaces trip up proper argument handling. So get rid of them.
1852 let f (L p "-optdep" : L _ x : xs) = (L p ("-optdep" ++ x)) : f xs
1853 f (x : xs) = x : f xs
1854 f xs = xs
1855 args' = f args
1856
1857 let ((leftover, errs, warns), dflags1)
1858 = runCmdLine (processArgs activeFlags args') dflags0
1859 when (not (null errs)) $ liftIO $
1860 throwGhcExceptionIO $ errorsToGhcException errs
1861
1862 -- check for disabled flags in safe haskell
1863 let (dflags2, sh_warns) = safeFlagCheck cmdline dflags1
1864 dflags3 = updateWays dflags2
1865 theWays = ways dflags3
1866
1867 unless (allowed_combination theWays) $ liftIO $
1868 throwGhcExceptionIO (CmdLineError ("combination not supported: " ++
1869 intercalate "/" (map wayDesc theWays)))
1870
1871 whenGeneratingDynamicToo dflags3 $
1872 unless (isJust (outputFile dflags3) == isJust (dynOutputFile dflags3)) $
1873 liftIO $ throwGhcExceptionIO $ CmdLineError
1874 "With -dynamic-too, must give -dyno iff giving -o"
1875
1876 let (dflags4, consistency_warnings) = makeDynFlagsConsistent dflags3
1877
1878 dflags5 <- case dllSplitFile dflags4 of
1879 Nothing -> return (dflags4 { dllSplit = Nothing })
1880 Just f ->
1881 case dllSplit dflags4 of
1882 Just _ ->
1883 -- If dllSplit is out of date then it would have
1884 -- been set to Nothing. As it's a Just, it must be
1885 -- up-to-date.
1886 return dflags4
1887 Nothing ->
1888 do xs <- liftIO $ readFile f
1889 let ss = map (Set.fromList . words) (lines xs)
1890 return $ dflags4 { dllSplit = Just ss }
1891
1892 liftIO $ setUnsafeGlobalDynFlags dflags5
1893
1894 return (dflags5, leftover, consistency_warnings ++ sh_warns ++ warns)
1895
1896 updateWays :: DynFlags -> DynFlags
1897 updateWays dflags
1898 = let theWays = sort $ nub $ ways dflags
1899 f = if WayDyn `elem` theWays then unSetGeneralFlag'
1900 else setGeneralFlag'
1901 in f Opt_Static
1902 $ dflags {
1903 ways = theWays,
1904 buildTag = mkBuildTag (filter (not . wayRTSOnly) theWays),
1905 rtsBuildTag = mkBuildTag theWays
1906 }
1907
1908 -- | Check (and potentially disable) any extensions that aren't allowed
1909 -- in safe mode.
1910 --
1911 -- The bool is to indicate if we are parsing command line flags (false means
1912 -- file pragma). This allows us to generate better warnings.
1913 safeFlagCheck :: Bool -> DynFlags -> (DynFlags, [Located String])
1914 safeFlagCheck _ dflags | not (safeLanguageOn dflags || safeInferOn dflags)
1915 = (dflags, [])
1916
1917 -- safe or safe-infer ON
1918 safeFlagCheck cmdl dflags =
1919 case safeLanguageOn dflags of
1920 True -> (dflags', warns)
1921
1922 -- throw error if -fpackage-trust by itself with no safe haskell flag
1923 False | not cmdl && packageTrustOn dflags
1924 -> (gopt_unset dflags' Opt_PackageTrust,
1925 [L (pkgTrustOnLoc dflags') $
1926 "-fpackage-trust ignored;" ++
1927 " must be specified with a Safe Haskell flag"]
1928 )
1929
1930 False | null warns && safeInfOk
1931 -> (dflags', [])
1932
1933 | otherwise
1934 -> (dflags' { safeHaskell = Sf_None }, [])
1935 -- Have we inferred Unsafe?
1936 -- See Note [HscMain . Safe Haskell Inference]
1937 where
1938 -- TODO: Can we do better than this for inference?
1939 safeInfOk = not $ xopt Opt_OverlappingInstances dflags
1940
1941 (dflags', warns) = foldl check_method (dflags, []) unsafeFlags
1942
1943 check_method (df, warns) (str,loc,test,fix)
1944 | test df = (apFix fix df, warns ++ safeFailure (loc dflags) str)
1945 | otherwise = (df, warns)
1946
1947 apFix f = if safeInferOn dflags then id else f
1948
1949 safeFailure loc str
1950 = [L loc $ str ++ " is not allowed in Safe Haskell; ignoring " ++ str]
1951
1952 {- **********************************************************************
1953 %* *
1954 DynFlags specifications
1955 %* *
1956 %********************************************************************* -}
1957
1958 -- | All dynamic flags option strings. These are the user facing strings for
1959 -- enabling and disabling options.
1960 allFlags :: [String]
1961 allFlags = map ('-':) $
1962 [ flagName flag | flag <- dynamic_flags ++ package_flags, ok (flagOptKind flag) ] ++
1963 map ("fno-"++) fflags ++
1964 map ("f"++) fflags ++
1965 map ("X"++) supportedExtensions
1966 where ok (PrefixPred _ _) = False
1967 ok _ = True
1968 fflags = fflags0 ++ fflags1 ++ fflags2
1969 fflags0 = [ name | (name, _, _) <- fFlags ]
1970 fflags1 = [ name | (name, _, _) <- fWarningFlags ]
1971 fflags2 = [ name | (name, _, _) <- fLangFlags ]
1972
1973 {-
1974 - Below we export user facing symbols for GHC dynamic flags for use with the
1975 - GHC API.
1976 -}
1977
1978 -- All dynamic flags present in GHC.
1979 flagsAll :: [Flag (CmdLineP DynFlags)]
1980 flagsAll = package_flags ++ dynamic_flags
1981
1982 -- All dynamic flags, minus package flags, present in GHC.
1983 flagsDynamic :: [Flag (CmdLineP DynFlags)]
1984 flagsDynamic = dynamic_flags
1985
1986 -- ALl package flags present in GHC.
1987 flagsPackage :: [Flag (CmdLineP DynFlags)]
1988 flagsPackage = package_flags
1989
1990 --------------- The main flags themselves ------------------
1991 dynamic_flags :: [Flag (CmdLineP DynFlags)]
1992 dynamic_flags = [
1993 Flag "n" (NoArg (addWarn "The -n flag is deprecated and no longer has any effect"))
1994 , Flag "cpp" (NoArg (setExtensionFlag Opt_Cpp))
1995 , Flag "F" (NoArg (setGeneralFlag Opt_Pp))
1996 , Flag "#include"
1997 (HasArg (\s -> do addCmdlineHCInclude s
1998 addWarn "-#include and INCLUDE pragmas are deprecated: They no longer have any effect"))
1999 , Flag "v" (OptIntSuffix setVerbosity)
2000
2001 ------- ways --------------------------------------------------------
2002 , Flag "prof" (NoArg (addWay WayProf))
2003 , Flag "eventlog" (NoArg (addWay WayEventLog))
2004 , Flag "parallel" (NoArg (addWay WayPar))
2005 , Flag "gransim" (NoArg (addWay WayGran))
2006 , Flag "smp" (NoArg (addWay WayThreaded >> deprecate "Use -threaded instead"))
2007 , Flag "debug" (NoArg (addWay WayDebug))
2008 , Flag "ndp" (NoArg (addWay WayNDP))
2009 , Flag "threaded" (NoArg (addWay WayThreaded))
2010
2011 , Flag "ticky" (NoArg (setGeneralFlag Opt_Ticky >> addWay WayDebug))
2012
2013 -- -ticky enables ticky-ticky code generation, and also implies -debug which
2014 -- is required to get the RTS ticky support.
2015
2016 ----- Linker --------------------------------------------------------
2017 , Flag "static" (NoArg removeWayDyn)
2018 , Flag "dynamic" (NoArg (addWay WayDyn))
2019 -- ignored for compat w/ gcc:
2020 , Flag "rdynamic" (NoArg (return ()))
2021 , Flag "relative-dynlib-paths" (NoArg (setGeneralFlag Opt_RelativeDynlibPaths))
2022
2023 ------- Specific phases --------------------------------------------
2024 -- need to appear before -pgmL to be parsed as LLVM flags.
2025 , Flag "pgmlo" (hasArg (\f -> alterSettings (\s -> s { sPgm_lo = (f,[])})))
2026 , Flag "pgmlc" (hasArg (\f -> alterSettings (\s -> s { sPgm_lc = (f,[])})))
2027 , Flag "pgmL" (hasArg (\f -> alterSettings (\s -> s { sPgm_L = f})))
2028 , Flag "pgmP" (hasArg setPgmP)
2029 , Flag "pgmF" (hasArg (\f -> alterSettings (\s -> s { sPgm_F = f})))
2030 , Flag "pgmc" (hasArg (\f -> alterSettings (\s -> s { sPgm_c = (f,[])})))
2031 , Flag "pgmm" (HasArg (\_ -> addWarn "The -pgmm flag does nothing; it will be removed in a future GHC release"))
2032 , Flag "pgms" (hasArg (\f -> alterSettings (\s -> s { sPgm_s = (f,[])})))
2033 , Flag "pgma" (hasArg (\f -> alterSettings (\s -> s { sPgm_a = (f,[])})))
2034 , Flag "pgml" (hasArg (\f -> alterSettings (\s -> s { sPgm_l = (f,[])})))
2035 , Flag "pgmdll" (hasArg (\f -> alterSettings (\s -> s { sPgm_dll = (f,[])})))
2036 , Flag "pgmwindres" (hasArg (\f -> alterSettings (\s -> s { sPgm_windres = f})))
2037
2038 -- need to appear before -optl/-opta to be parsed as LLVM flags.
2039 , Flag "optlo" (hasArg (\f -> alterSettings (\s -> s { sOpt_lo = f : sOpt_lo s})))
2040 , Flag "optlc" (hasArg (\f -> alterSettings (\s -> s { sOpt_lc = f : sOpt_lc s})))
2041 , Flag "optL" (hasArg (\f -> alterSettings (\s -> s { sOpt_L = f : sOpt_L s})))
2042 , Flag "optP" (hasArg addOptP)
2043 , Flag "optF" (hasArg (\f -> alterSettings (\s -> s { sOpt_F = f : sOpt_F s})))
2044 , Flag "optc" (hasArg addOptc)
2045 , Flag "optm" (HasArg (\_ -> addWarn "The -optm flag does nothing; it will be removed in a future GHC release"))
2046 , Flag "opta" (hasArg (\f -> alterSettings (\s -> s { sOpt_a = f : sOpt_a s})))
2047 , Flag "optl" (hasArg addOptl)
2048 , Flag "optwindres" (hasArg (\f -> alterSettings (\s -> s { sOpt_windres = f : sOpt_windres s})))
2049
2050 , Flag "split-objs"
2051 (NoArg (if can_split
2052 then setGeneralFlag Opt_SplitObjs
2053 else addWarn "ignoring -fsplit-objs"))
2054
2055 -------- ghc -M -----------------------------------------------------
2056 , Flag "dep-suffix" (hasArg addDepSuffix)
2057 , Flag "optdep-s" (hasArgDF addDepSuffix "Use -dep-suffix instead")
2058 , Flag "dep-makefile" (hasArg setDepMakefile)
2059 , Flag "optdep-f" (hasArgDF setDepMakefile "Use -dep-makefile instead")
2060 , Flag "optdep-w" (NoArg (deprecate "doesn't do anything"))
2061 , Flag "include-pkg-deps" (noArg (setDepIncludePkgDeps True))
2062 , Flag "optdep--include-prelude" (noArgDF (setDepIncludePkgDeps True) "Use -include-pkg-deps instead")
2063 , Flag "optdep--include-pkg-deps" (noArgDF (setDepIncludePkgDeps True) "Use -include-pkg-deps instead")
2064 , Flag "exclude-module" (hasArg addDepExcludeMod)
2065 , Flag "optdep--exclude-module" (hasArgDF addDepExcludeMod "Use -exclude-module instead")
2066 , Flag "optdep-x" (hasArgDF addDepExcludeMod "Use -exclude-module instead")
2067
2068 -------- Linking ----------------------------------------------------
2069 , Flag "no-link" (noArg (\d -> d{ ghcLink=NoLink }))
2070 , Flag "shared" (noArg (\d -> d{ ghcLink=LinkDynLib }))
2071 , Flag "dynload" (hasArg parseDynLibLoaderMode)
2072 , Flag "dylib-install-name" (hasArg setDylibInstallName)
2073 -- -dll-split is an internal flag, used only during the GHC build
2074 , Flag "dll-split" (hasArg (\f d -> d{ dllSplitFile = Just f, dllSplit = Nothing }))
2075
2076 ------- Libraries ---------------------------------------------------
2077 , Flag "L" (Prefix addLibraryPath)
2078 , Flag "l" (hasArg (addLdInputs . Option . ("-l" ++)))
2079
2080 ------- Frameworks --------------------------------------------------
2081 -- -framework-path should really be -F ...
2082 , Flag "framework-path" (HasArg addFrameworkPath)
2083 , Flag "framework" (hasArg addCmdlineFramework)
2084
2085 ------- Output Redirection ------------------------------------------
2086 , Flag "odir" (hasArg setObjectDir)
2087 , Flag "o" (sepArg (setOutputFile . Just))
2088 , Flag "dyno" (sepArg (setDynOutputFile . Just))
2089 , Flag "ohi" (hasArg (setOutputHi . Just ))
2090 , Flag "osuf" (hasArg setObjectSuf)
2091 , Flag "dynosuf" (hasArg setDynObjectSuf)
2092 , Flag "hcsuf" (hasArg setHcSuf)
2093 , Flag "hisuf" (hasArg setHiSuf)
2094 , Flag "dynhisuf" (hasArg setDynHiSuf)
2095 , Flag "hidir" (hasArg setHiDir)
2096 , Flag "tmpdir" (hasArg setTmpDir)
2097 , Flag "stubdir" (hasArg setStubDir)
2098 , Flag "dumpdir" (hasArg setDumpDir)
2099 , Flag "outputdir" (hasArg setOutputDir)
2100 , Flag "ddump-file-prefix" (hasArg (setDumpPrefixForce . Just))
2101
2102 , Flag "dynamic-too" (NoArg (setGeneralFlag Opt_BuildDynamicToo))
2103
2104 ------- Keeping temporary files -------------------------------------
2105 -- These can be singular (think ghc -c) or plural (think ghc --make)
2106 , Flag "keep-hc-file" (NoArg (setGeneralFlag Opt_KeepHcFiles))
2107 , Flag "keep-hc-files" (NoArg (setGeneralFlag Opt_KeepHcFiles))
2108 , Flag "keep-s-file" (NoArg (setGeneralFlag Opt_KeepSFiles))
2109 , Flag "keep-s-files" (NoArg (setGeneralFlag Opt_KeepSFiles))
2110 , Flag "keep-raw-s-file" (NoArg (addWarn "The -keep-raw-s-file flag does nothing; it will be removed in a future GHC release"))
2111 , Flag "keep-raw-s-files" (NoArg (addWarn "The -keep-raw-s-files flag does nothing; it will be removed in a future GHC release"))
2112 , Flag "keep-llvm-file" (NoArg (do setObjTarget HscLlvm
2113 setGeneralFlag Opt_KeepLlvmFiles))
2114 , Flag "keep-llvm-files" (NoArg (do setObjTarget HscLlvm
2115 setGeneralFlag Opt_KeepLlvmFiles))
2116 -- This only makes sense as plural
2117 , Flag "keep-tmp-files" (NoArg (setGeneralFlag Opt_KeepTmpFiles))
2118
2119 ------- Miscellaneous ----------------------------------------------
2120 , Flag "no-auto-link-packages" (NoArg (unSetGeneralFlag Opt_AutoLinkPackages))
2121 , Flag "no-hs-main" (NoArg (setGeneralFlag Opt_NoHsMain))
2122 , Flag "with-rtsopts" (HasArg setRtsOpts)
2123 , Flag "rtsopts" (NoArg (setRtsOptsEnabled RtsOptsAll))
2124 , Flag "rtsopts=all" (NoArg (setRtsOptsEnabled RtsOptsAll))
2125 , Flag "rtsopts=some" (NoArg (setRtsOptsEnabled RtsOptsSafeOnly))
2126 , Flag "rtsopts=none" (NoArg (setRtsOptsEnabled RtsOptsNone))
2127 , Flag "no-rtsopts" (NoArg (setRtsOptsEnabled RtsOptsNone))
2128 , Flag "main-is" (SepArg setMainIs)
2129 , Flag "haddock" (NoArg (setGeneralFlag Opt_Haddock))
2130 , Flag "haddock-opts" (hasArg addHaddockOpts)
2131 , Flag "hpcdir" (SepArg setOptHpcDir)
2132 , Flag "ghci-script" (hasArg addGhciScript)
2133 , Flag "interactive-print" (hasArg setInteractivePrint)
2134 , Flag "ticky-allocd" (NoArg (setGeneralFlag Opt_Ticky_Allocd))
2135 , Flag "ticky-LNE" (NoArg (setGeneralFlag Opt_Ticky_LNE))
2136 , Flag "ticky-dyn-thunk" (NoArg (setGeneralFlag Opt_Ticky_Dyn_Thunk))
2137 ------- recompilation checker --------------------------------------
2138 , Flag "recomp" (NoArg (do unSetGeneralFlag Opt_ForceRecomp
2139 deprecate "Use -fno-force-recomp instead"))
2140 , Flag "no-recomp" (NoArg (do setGeneralFlag Opt_ForceRecomp
2141 deprecate "Use -fforce-recomp instead"))
2142
2143 ------ HsCpp opts ---------------------------------------------------
2144 , Flag "D" (AnySuffix (upd . addOptP))
2145 , Flag "U" (AnySuffix (upd . addOptP))
2146
2147 ------- Include/Import Paths ----------------------------------------
2148 , Flag "I" (Prefix addIncludePath)
2149 , Flag "i" (OptPrefix addImportPath)
2150
2151 ------ Output style options -----------------------------------------
2152 , Flag "dppr-user-length" (intSuffix (\n d -> d{ pprUserLength = n }))
2153 , Flag "dppr-cols" (intSuffix (\n d -> d{ pprCols = n }))
2154 , Flag "dtrace-level" (intSuffix (\n d -> d{ traceLevel = n }))
2155 -- Suppress all that is suppressable in core dumps.
2156 -- Except for uniques, as some simplifier phases introduce new varibles that
2157 -- have otherwise identical names.
2158 , Flag "dsuppress-all" (NoArg $ do setGeneralFlag Opt_SuppressCoercions
2159 setGeneralFlag Opt_SuppressVarKinds
2160 setGeneralFlag Opt_SuppressModulePrefixes
2161 setGeneralFlag Opt_SuppressTypeApplications
2162 setGeneralFlag Opt_SuppressIdInfo
2163 setGeneralFlag Opt_SuppressTypeSignatures)
2164
2165 ------ Debugging ----------------------------------------------------
2166 , Flag "dstg-stats" (NoArg (setGeneralFlag Opt_StgStats))
2167
2168 , Flag "ddump-cmm" (setDumpFlag Opt_D_dump_cmm)
2169 , Flag "ddump-cmm-raw" (setDumpFlag Opt_D_dump_cmm_raw)
2170 , Flag "ddump-cmm-cfg" (setDumpFlag Opt_D_dump_cmm_cfg)
2171 , Flag "ddump-cmm-cbe" (setDumpFlag Opt_D_dump_cmm_cbe)
2172 , Flag "ddump-cmm-proc" (setDumpFlag Opt_D_dump_cmm_proc)
2173 , Flag "ddump-cmm-rewrite" (setDumpFlag Opt_D_dump_cmm_rewrite)
2174 , Flag "ddump-cmm-sp" (setDumpFlag Opt_D_dump_cmm_sp)
2175 , Flag "ddump-cmm-procmap" (setDumpFlag Opt_D_dump_cmm_procmap)
2176 , Flag "ddump-cmm-split" (setDumpFlag Opt_D_dump_cmm_split)
2177 , Flag "ddump-cmm-info" (setDumpFlag Opt_D_dump_cmm_info)
2178 , Flag "ddump-cmm-cps" (setDumpFlag Opt_D_dump_cmm_cps)
2179 , Flag "ddump-core-stats" (setDumpFlag Opt_D_dump_core_stats)
2180 , Flag "ddump-asm" (setDumpFlag Opt_D_dump_asm)
2181 , Flag "ddump-asm-native" (setDumpFlag Opt_D_dump_asm_native)
2182 , Flag "ddump-asm-liveness" (setDumpFlag Opt_D_dump_asm_liveness)
2183 , Flag "ddump-asm-regalloc" (setDumpFlag Opt_D_dump_asm_regalloc)
2184 , Flag "ddump-asm-conflicts" (setDumpFlag Opt_D_dump_asm_conflicts)
2185 , Flag "ddump-asm-regalloc-stages" (setDumpFlag Opt_D_dump_asm_regalloc_stages)
2186 , Flag "ddump-asm-stats" (setDumpFlag Opt_D_dump_asm_stats)
2187 , Flag "ddump-asm-expanded" (setDumpFlag Opt_D_dump_asm_expanded)
2188 , Flag "ddump-llvm" (NoArg (do setObjTarget HscLlvm
2189 setDumpFlag' Opt_D_dump_llvm))
2190 , Flag "ddump-deriv" (setDumpFlag Opt_D_dump_deriv)
2191 , Flag "ddump-ds" (setDumpFlag Opt_D_dump_ds)
2192 , Flag "ddump-foreign" (setDumpFlag Opt_D_dump_foreign)
2193 , Flag "ddump-inlinings" (setDumpFlag Opt_D_dump_inlinings)
2194 , Flag "ddump-rule-firings" (setDumpFlag Opt_D_dump_rule_firings)
2195 , Flag "ddump-rule-rewrites" (setDumpFlag Opt_D_dump_rule_rewrites)
2196 , Flag "ddump-simpl-trace" (setDumpFlag Opt_D_dump_simpl_trace)
2197 , Flag "ddump-occur-anal" (setDumpFlag Opt_D_dump_occur_anal)
2198 , Flag "ddump-parsed" (setDumpFlag Opt_D_dump_parsed)
2199 , Flag "ddump-rn" (setDumpFlag Opt_D_dump_rn)
2200 , Flag "ddump-core-pipeline" (setDumpFlag Opt_D_dump_core_pipeline)
2201 , Flag "ddump-simpl" (setDumpFlag Opt_D_dump_simpl)
2202 , Flag "ddump-simpl-iterations" (setDumpFlag Opt_D_dump_simpl_iterations)
2203 , Flag "ddump-simpl-phases" (OptPrefix setDumpSimplPhases)
2204 , Flag "ddump-spec" (setDumpFlag Opt_D_dump_spec)
2205 , Flag "ddump-prep" (setDumpFlag Opt_D_dump_prep)
2206 , Flag "ddump-stg" (setDumpFlag Opt_D_dump_stg)
2207 , Flag "ddump-stranal" (setDumpFlag Opt_D_dump_stranal)
2208 , Flag "ddump-tc" (setDumpFlag Opt_D_dump_tc)
2209 , Flag "ddump-types" (setDumpFlag Opt_D_dump_types)
2210 , Flag "ddump-rules" (setDumpFlag Opt_D_dump_rules)
2211 , Flag "ddump-cse" (setDumpFlag Opt_D_dump_cse)
2212 , Flag "ddump-worker-wrapper" (setDumpFlag Opt_D_dump_worker_wrapper)
2213 , Flag "ddump-rn-trace" (setDumpFlag Opt_D_dump_rn_trace)
2214 , Flag "ddump-if-trace" (setDumpFlag Opt_D_dump_if_trace)
2215 , Flag "ddump-cs-trace" (setDumpFlag Opt_D_dump_cs_trace)
2216 , Flag "ddump-tc-trace" (setDumpFlag Opt_D_dump_tc_trace)
2217 , Flag "ddump-vt-trace" (setDumpFlag Opt_D_dump_vt_trace)
2218 , Flag "ddump-splices" (setDumpFlag Opt_D_dump_splices)
2219 , Flag "ddump-rn-stats" (setDumpFlag Opt_D_dump_rn_stats)
2220 , Flag "ddump-opt-cmm" (setDumpFlag Opt_D_dump_opt_cmm)
2221 , Flag "ddump-simpl-stats" (setDumpFlag Opt_D_dump_simpl_stats)
2222 , Flag "ddump-bcos" (setDumpFlag Opt_D_dump_BCOs)
2223 , Flag "dsource-stats" (setDumpFlag Opt_D_source_stats)
2224 , Flag "dverbose-core2core" (NoArg (do setVerbosity (Just 2)
2225 setVerboseCore2Core))
2226 , Flag "dverbose-stg2stg" (setDumpFlag Opt_D_verbose_stg2stg)
2227 , Flag "ddump-hi" (setDumpFlag Opt_D_dump_hi)
2228 , Flag "ddump-minimal-imports" (NoArg (setGeneralFlag Opt_D_dump_minimal_imports))
2229 , Flag "ddump-vect" (setDumpFlag Opt_D_dump_vect)
2230 , Flag "ddump-hpc" (setDumpFlag Opt_D_dump_ticked) -- back compat
2231 , Flag "ddump-ticked" (setDumpFlag Opt_D_dump_ticked)
2232 , Flag "ddump-mod-cycles" (setDumpFlag Opt_D_dump_mod_cycles)
2233 , Flag "ddump-view-pattern-commoning" (setDumpFlag Opt_D_dump_view_pattern_commoning)
2234 , Flag "ddump-to-file" (NoArg (setGeneralFlag Opt_DumpToFile))
2235 , Flag "ddump-hi-diffs" (setDumpFlag Opt_D_dump_hi_diffs)
2236 , Flag "ddump-rtti" (setDumpFlag Opt_D_dump_rtti)
2237 , Flag "dcore-lint" (NoArg (setGeneralFlag Opt_DoCoreLinting))
2238 , Flag "dstg-lint" (NoArg (setGeneralFlag Opt_DoStgLinting))
2239 , Flag "dcmm-lint" (NoArg (setGeneralFlag Opt_DoCmmLinting))
2240 , Flag "dasm-lint" (NoArg (setGeneralFlag Opt_DoAsmLinting))
2241 , Flag "dshow-passes" (NoArg (do forceRecompile
2242 setVerbosity $ Just 2))
2243 , Flag "dfaststring-stats" (NoArg (setGeneralFlag Opt_D_faststring_stats))
2244 , Flag "dno-llvm-mangler" (NoArg (setGeneralFlag Opt_NoLlvmMangler)) -- hidden flag
2245
2246 ------ Machine dependant (-m<blah>) stuff ---------------------------
2247
2248 , Flag "monly-2-regs" (NoArg (addWarn "The -monly-2-regs flag does nothing; it will be removed in a future GHC release"))
2249 , Flag "monly-3-regs" (NoArg (addWarn "The -monly-3-regs flag does nothing; it will be removed in a future GHC release"))
2250 , Flag "monly-4-regs" (NoArg (addWarn "The -monly-4-regs flag does nothing; it will be removed in a future GHC release"))
2251 , Flag "msse" (versionSuffix (\maj min d -> d{ sseVersion = Just (maj, min) }))
2252
2253 ------ Warning opts -------------------------------------------------
2254 , Flag "W" (NoArg (mapM_ setWarningFlag minusWOpts))
2255 , Flag "Werror" (NoArg (setGeneralFlag Opt_WarnIsError))
2256 , Flag "Wwarn" (NoArg (unSetGeneralFlag Opt_WarnIsError))
2257 , Flag "Wall" (NoArg (mapM_ setWarningFlag minusWallOpts))
2258 , Flag "Wnot" (NoArg (do upd (\dfs -> dfs {warningFlags = IntSet.empty})
2259 deprecate "Use -w instead"))
2260 , Flag "w" (NoArg (upd (\dfs -> dfs {warningFlags = IntSet.empty})))
2261
2262 ------ Plugin flags ------------------------------------------------
2263 , Flag "fplugin-opt" (hasArg addPluginModuleNameOption)
2264 , Flag "fplugin" (hasArg addPluginModuleName)
2265
2266 ------ Optimisation flags ------------------------------------------
2267 , Flag "O" (noArgM (setOptLevel 1))
2268 , Flag "Onot" (noArgM (\dflags -> do deprecate "Use -O0 instead"
2269 setOptLevel 0 dflags))
2270 , Flag "Odph" (noArgM setDPHOpt)
2271 , Flag "O" (optIntSuffixM (\mb_n -> setOptLevel (mb_n `orElse` 1)))
2272 -- If the number is missing, use 1
2273
2274 , Flag "fsimplifier-phases" (intSuffix (\n d -> d{ simplPhases = n }))
2275 , Flag "fmax-simplifier-iterations" (intSuffix (\n d -> d{ maxSimplIterations = n }))
2276 , Flag "fsimpl-tick-factor" (intSuffix (\n d -> d{ simplTickFactor = n }))
2277 , Flag "fspec-constr-threshold" (intSuffix (\n d -> d{ specConstrThreshold = Just n }))
2278 , Flag "fno-spec-constr-threshold" (noArg (\d -> d{ specConstrThreshold = Nothing }))
2279 , Flag "fspec-constr-count" (intSuffix (\n d -> d{ specConstrCount = Just n }))
2280 , Flag "fno-spec-constr-count" (noArg (\d -> d{ specConstrCount = Nothing }))
2281 , Flag "fspec-constr-recursive" (intSuffix (\n d -> d{ specConstrRecursive = n }))
2282 , Flag "fliberate-case-threshold" (intSuffix (\n d -> d{ liberateCaseThreshold = Just n }))
2283 , Flag "fno-liberate-case-threshold" (noArg (\d -> d{ liberateCaseThreshold = Nothing }))
2284 , Flag "frule-check" (sepArg (\s d -> d{ ruleCheck = Just s }))
2285 , Flag "fcontext-stack" (intSuffix (\n d -> d{ ctxtStkDepth = n }))
2286 , Flag "fstrictness-before" (intSuffix (\n d -> d{ strictnessBefore = n : strictnessBefore d }))
2287 , Flag "ffloat-lam-args" (intSuffix (\n d -> d{ floatLamArgs = Just n }))
2288 , Flag "ffloat-all-lams" (noArg (\d -> d{ floatLamArgs = Nothing }))
2289 , Flag "fhistory-size" (intSuffix (\n d -> d{ historySize = n }))
2290
2291 , Flag "funfolding-creation-threshold" (intSuffix (\n d -> d {ufCreationThreshold = n}))
2292 , Flag "funfolding-use-threshold" (intSuffix (\n d -> d {ufUseThreshold = n}))
2293 , Flag "funfolding-fun-discount" (intSuffix (\n d -> d {ufFunAppDiscount = n}))
2294 , Flag "funfolding-dict-discount" (intSuffix (\n d -> d {ufDictDiscount = n}))
2295 , Flag "funfolding-keeness-factor" (floatSuffix (\n d -> d {ufKeenessFactor = n}))
2296
2297 , Flag "fmax-worker-args" (intSuffix (\n d -> d {maxWorkerArgs = n}))
2298
2299 , Flag "fghci-hist-size" (intSuffix (\n d -> d {ghciHistSize = n}))
2300
2301 ------ Profiling ----------------------------------------------------
2302
2303 -- OLD profiling flags
2304 , Flag "auto-all" (noArg (\d -> d { profAuto = ProfAutoAll } ))
2305 , Flag "no-auto-all" (noArg (\d -> d { profAuto = NoProfAuto } ))
2306 , Flag "auto" (noArg (\d -> d { profAuto = ProfAutoExports } ))
2307 , Flag "no-auto" (noArg (\d -> d { profAuto = NoProfAuto } ))
2308 , Flag "caf-all" (NoArg (setGeneralFlag Opt_AutoSccsOnIndividualCafs))
2309 , Flag "no-caf-all" (NoArg (unSetGeneralFlag Opt_AutoSccsOnIndividualCafs))
2310
2311 -- NEW profiling flags
2312 , Flag "fprof-auto" (noArg (\d -> d { profAuto = ProfAutoAll } ))
2313 , Flag "fprof-auto-top" (noArg (\d -> d { profAuto = ProfAutoTop } ))
2314 , Flag "fprof-auto-exported" (noArg (\d -> d { profAuto = ProfAutoExports } ))
2315 , Flag "fprof-auto-calls" (noArg (\d -> d { profAuto = ProfAutoCalls } ))
2316 , Flag "fno-prof-auto" (noArg (\d -> d { profAuto = NoProfAuto } ))
2317
2318 ------ Compiler flags -----------------------------------------------
2319
2320 , Flag "fasm" (NoArg (setObjTarget HscAsm))
2321 , Flag "fvia-c" (NoArg
2322 (addWarn "The -fvia-c flag does nothing; it will be removed in a future GHC release"))
2323 , Flag "fvia-C" (NoArg
2324 (addWarn "The -fvia-C flag does nothing; it will be removed in a future GHC release"))
2325 , Flag "fllvm" (NoArg (setObjTarget HscLlvm))
2326
2327 , Flag "fno-code" (NoArg (do upd $ \d -> d{ ghcLink=NoLink }
2328 setTarget HscNothing))
2329 , Flag "fbyte-code" (NoArg (setTarget HscInterpreted))
2330 , Flag "fobject-code" (NoArg (setTargetWithPlatform defaultHscTarget))
2331 , Flag "fglasgow-exts" (NoArg (enableGlasgowExts >> deprecate "Use individual extensions instead"))
2332 , Flag "fno-glasgow-exts" (NoArg (disableGlasgowExts >> deprecate "Use individual extensions instead"))
2333
2334 ------ Safe Haskell flags -------------------------------------------
2335 , Flag "fpackage-trust" (NoArg setPackageTrust)
2336 , Flag "fno-safe-infer" (NoArg (setSafeHaskell Sf_None))
2337 , Flag "fPIC" (NoArg (setGeneralFlag Opt_PIC))
2338 , Flag "fno-PIC" (NoArg (unSetGeneralFlag Opt_PIC))
2339 ]
2340 ++ map (mkFlag turnOn "" setGeneralFlag ) negatableFlags
2341 ++ map (mkFlag turnOff "no-" unSetGeneralFlag) negatableFlags
2342 ++ map (mkFlag turnOn "d" setGeneralFlag ) dFlags
2343 ++ map (mkFlag turnOff "dno-" unSetGeneralFlag) dFlags
2344 ++ map (mkFlag turnOn "f" setGeneralFlag ) fFlags
2345 ++ map (mkFlag turnOff "fno-" unSetGeneralFlag) fFlags
2346 ++ map (mkFlag turnOn "f" setWarningFlag ) fWarningFlags
2347 ++ map (mkFlag turnOff "fno-" unSetWarningFlag) fWarningFlags
2348 ++ map (mkFlag turnOn "f" setExtensionFlag ) fLangFlags
2349 ++ map (mkFlag turnOff "fno-" unSetExtensionFlag) fLangFlags
2350 ++ map (mkFlag turnOn "X" setExtensionFlag ) xFlags
2351 ++ map (mkFlag turnOff "XNo" unSetExtensionFlag) xFlags
2352 ++ map (mkFlag turnOn "X" setLanguage) languageFlags
2353 ++ map (mkFlag turnOn "X" setSafeHaskell) safeHaskellFlags
2354 ++ [ Flag "XGenerics" (NoArg (deprecate "it does nothing; look into -XDefaultSignatures and -XDeriveGeneric for generic programming support."))
2355 , Flag "XNoGenerics" (NoArg (deprecate "it does nothing; look into -XDefaultSignatures and -XDeriveGeneric for generic programming support.")) ]
2356
2357 package_flags :: [Flag (CmdLineP DynFlags)]
2358 package_flags = [
2359 ------- Packages ----------------------------------------------------
2360 Flag "package-db" (HasArg (addPkgConfRef . PkgConfFile))
2361 , Flag "clear-package-db" (NoArg clearPkgConf)
2362 , Flag "no-global-package-db" (NoArg removeGlobalPkgConf)
2363 , Flag "no-user-package-db" (NoArg removeUserPkgConf)
2364 , Flag "global-package-db" (NoArg (addPkgConfRef GlobalPkgConf))
2365 , Flag "user-package-db" (NoArg (addPkgConfRef UserPkgConf))
2366
2367 -- backwards compat with GHC<=7.4 :
2368 , Flag "package-conf" (HasArg $ \path -> do
2369 addPkgConfRef (PkgConfFile path)
2370 deprecate "Use -package-db instead")
2371 , Flag "no-user-package-conf" (NoArg $ do
2372 removeUserPkgConf
2373 deprecate "Use -no-user-package-db instead")
2374
2375 , Flag "package-name" (hasArg setPackageName)
2376 , Flag "package-id" (HasArg exposePackageId)
2377 , Flag "package" (HasArg exposePackage)
2378 , Flag "hide-package" (HasArg hidePackage)
2379 , Flag "hide-all-packages" (NoArg (setGeneralFlag Opt_HideAllPackages))
2380 , Flag "ignore-package" (HasArg ignorePackage)
2381 , Flag "syslib" (HasArg (\s -> do exposePackage s
2382 deprecate "Use -package instead"))
2383 , Flag "distrust-all-packages" (NoArg (setGeneralFlag Opt_DistrustAllPackages))
2384 , Flag "trust" (HasArg trustPackage)
2385 , Flag "distrust" (HasArg distrustPackage)
2386 ]
2387
2388 type TurnOnFlag = Bool -- True <=> we are turning the flag on
2389 -- False <=> we are turning the flag off
2390 turnOn :: TurnOnFlag; turnOn = True
2391 turnOff :: TurnOnFlag; turnOff = False
2392
2393 type FlagSpec flag
2394 = ( String -- Flag in string form
2395 , flag -- Flag in internal form
2396 , TurnOnFlag -> DynP ()) -- Extra action to run when the flag is found
2397 -- Typically, emit a warning or error
2398
2399 mkFlag :: TurnOnFlag -- ^ True <=> it should be turned on
2400 -> String -- ^ The flag prefix
2401 -> (flag -> DynP ()) -- ^ What to do when the flag is found
2402 -> FlagSpec flag -- ^ Specification of this particular flag
2403 -> Flag (CmdLineP DynFlags)
2404 mkFlag turn_on flagPrefix f (name, flag, extra_action)
2405 = Flag (flagPrefix ++ name) (NoArg (f flag >> extra_action turn_on))
2406
2407 deprecatedForExtension :: String -> TurnOnFlag -> DynP ()
2408 deprecatedForExtension lang turn_on
2409 = deprecate ("use -X" ++ flag ++ " or pragma {-# LANGUAGE " ++ flag ++ " #-} instead")
2410 where
2411 flag | turn_on = lang
2412 | otherwise = "No"++lang
2413
2414 useInstead :: String -> TurnOnFlag -> DynP ()
2415 useInstead flag turn_on
2416 = deprecate ("Use -f" ++ no ++ flag ++ " instead")
2417 where
2418 no = if turn_on then "" else "no-"
2419
2420 nop :: TurnOnFlag -> DynP ()
2421 nop _ = return ()
2422
2423 -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
2424 fWarningFlags :: [FlagSpec WarningFlag]
2425 fWarningFlags = [
2426 ( "warn-dodgy-foreign-imports", Opt_WarnDodgyForeignImports, nop ),
2427 ( "warn-dodgy-exports", Opt_WarnDodgyExports, nop ),
2428 ( "warn-dodgy-imports", Opt_WarnDodgyImports, nop ),
2429 ( "warn-duplicate-exports", Opt_WarnDuplicateExports, nop ),
2430 ( "warn-duplicate-constraints", Opt_WarnDuplicateConstraints, nop ),
2431 ( "warn-hi-shadowing", Opt_WarnHiShadows, nop ),
2432 ( "warn-implicit-prelude", Opt_WarnImplicitPrelude, nop ),
2433 ( "warn-incomplete-patterns", Opt_WarnIncompletePatterns, nop ),
2434 ( "warn-incomplete-uni-patterns", Opt_WarnIncompleteUniPatterns, nop ),
2435 ( "warn-incomplete-record-updates", Opt_WarnIncompletePatternsRecUpd, nop ),
2436 ( "warn-missing-fields", Opt_WarnMissingFields, nop ),
2437 ( "warn-missing-import-lists", Opt_WarnMissingImportList, nop ),
2438 ( "warn-missing-methods", Opt_WarnMissingMethods, nop ),
2439 ( "warn-missing-signatures", Opt_WarnMissingSigs, nop ),
2440 ( "warn-missing-local-sigs", Opt_WarnMissingLocalSigs, nop ),
2441 ( "warn-name-shadowing", Opt_WarnNameShadowing, nop ),
2442 ( "warn-overlapping-patterns", Opt_WarnOverlappingPatterns, nop ),
2443 ( "warn-type-defaults", Opt_WarnTypeDefaults, nop ),
2444 ( "warn-monomorphism-restriction", Opt_WarnMonomorphism, nop ),
2445 ( "warn-unused-binds", Opt_WarnUnusedBinds, nop ),
2446 ( "warn-unused-imports", Opt_WarnUnusedImports, nop ),
2447 ( "warn-unused-matches", Opt_WarnUnusedMatches, nop ),
2448 ( "warn-warnings-deprecations", Opt_WarnWarningsDeprecations, nop ),
2449 ( "warn-deprecations", Opt_WarnWarningsDeprecations, nop ),
2450 ( "warn-deprecated-flags", Opt_WarnDeprecatedFlags, nop ),
2451 ( "warn-orphans", Opt_WarnOrphans, nop ),
2452 ( "warn-identities", Opt_WarnIdentities, nop ),
2453 ( "warn-auto-orphans", Opt_WarnAutoOrphans, nop ),
2454 ( "warn-tabs", Opt_WarnTabs, nop ),
2455 ( "warn-unrecognised-pragmas", Opt_WarnUnrecognisedPragmas, nop ),
2456 ( "warn-lazy-unlifted-bindings", Opt_WarnLazyUnliftedBindings, nop ),
2457 ( "warn-unused-do-bind", Opt_WarnUnusedDoBind, nop ),
2458 ( "warn-wrong-do-bind", Opt_WarnWrongDoBind, nop ),
2459 ( "warn-alternative-layout-rule-transitional", Opt_WarnAlternativeLayoutRuleTransitional, nop ),
2460 ( "warn-unsafe", Opt_WarnUnsafe, setWarnUnsafe ),
2461 ( "warn-safe", Opt_WarnSafe, setWarnSafe ),
2462 ( "warn-pointless-pragmas", Opt_WarnPointlessPragmas, nop ),
2463 ( "warn-unsupported-calling-conventions", Opt_WarnUnsupportedCallingConventions, nop ),
2464 ( "warn-inline-rule-shadowing", Opt_WarnInlineRuleShadowing, nop ),
2465 ( "warn-unsupported-llvm-version", Opt_WarnUnsupportedLlvmVersion, nop ),
2466 ( "warn-typeable-instances", Opt_WarnTypeableInstances, nop ) ]
2467
2468 -- | These @-\<blah\>@ flags can all be reversed with @-no-\<blah\>@
2469 negatableFlags :: [FlagSpec GeneralFlag]
2470 negatableFlags = [
2471 ( "ignore-dot-ghci", Opt_IgnoreDotGhci, nop ) ]
2472
2473 -- | These @-d\<blah\>@ flags can all be reversed with @-dno-\<blah\>@
2474 dFlags :: [FlagSpec GeneralFlag]
2475 dFlags = [
2476 ( "suppress-coercions", Opt_SuppressCoercions, nop),
2477 ( "suppress-var-kinds", Opt_SuppressVarKinds, nop),
2478 ( "suppress-module-prefixes", Opt_SuppressModulePrefixes, nop),
2479 ( "suppress-type-applications", Opt_SuppressTypeApplications, nop),
2480 ( "suppress-idinfo", Opt_SuppressIdInfo, nop),
2481 ( "suppress-type-signatures", Opt_SuppressTypeSignatures, nop),
2482 ( "suppress-uniques", Opt_SuppressUniques, nop),
2483 ( "ppr-case-as-let", Opt_PprCaseAsLet, nop)]
2484
2485 -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
2486 fFlags :: [FlagSpec GeneralFlag]
2487 fFlags = [
2488 ( "error-spans", Opt_ErrorSpans, nop ),
2489 ( "print-explicit-foralls", Opt_PrintExplicitForalls, nop ),
2490 ( "strictness", Opt_Strictness, nop ),
2491 ( "specialise", Opt_Specialise, nop ),
2492 ( "float-in", Opt_FloatIn, nop ),
2493 ( "static-argument-transformation", Opt_StaticArgumentTransformation, nop ),
2494 ( "full-laziness", Opt_FullLaziness, nop ),
2495 ( "liberate-case", Opt_LiberateCase, nop ),
2496 ( "spec-constr", Opt_SpecConstr, nop ),
2497 ( "cse", Opt_CSE, nop ),
2498 ( "pedantic-bottoms", Opt_PedanticBottoms, nop ),
2499 ( "ignore-interface-pragmas", Opt_IgnoreInterfacePragmas, nop ),
2500 ( "omit-interface-pragmas", Opt_OmitInterfacePragmas, nop ),
2501 ( "expose-all-unfoldings", Opt_ExposeAllUnfoldings, nop ),
2502 ( "do-lambda-eta-expansion", Opt_DoLambdaEtaExpansion, nop ),
2503 ( "ignore-asserts", Opt_IgnoreAsserts, nop ),
2504 ( "do-eta-reduction", Opt_DoEtaReduction, nop ),
2505 ( "case-merge", Opt_CaseMerge, nop ),
2506 ( "unbox-strict-fields", Opt_UnboxStrictFields, nop ),
2507 ( "unbox-small-strict-fields", Opt_UnboxSmallStrictFields, nop ),
2508 ( "dicts-cheap", Opt_DictsCheap, nop ),
2509 ( "excess-precision", Opt_ExcessPrecision, nop ),
2510 ( "eager-blackholing", Opt_EagerBlackHoling, nop ),
2511 ( "print-bind-result", Opt_PrintBindResult, nop ),
2512 ( "force-recomp", Opt_ForceRecomp, nop ),
2513 ( "hpc-no-auto", Opt_Hpc_No_Auto, nop ),
2514 ( "rewrite-rules", Opt_EnableRewriteRules, useInstead "enable-rewrite-rules" ),
2515 ( "enable-rewrite-rules", Opt_EnableRewriteRules, nop ),
2516 ( "break-on-exception", Opt_BreakOnException, nop ),
2517 ( "break-on-error", Opt_BreakOnError, nop ),
2518 ( "print-evld-with-show", Opt_PrintEvldWithShow, nop ),
2519 ( "print-bind-contents", Opt_PrintBindContents, nop ),
2520 ( "run-cps", Opt_RunCPS, nop ),
2521 ( "run-cpsz", Opt_RunCPSZ, nop ),
2522 ( "vectorise", Opt_Vectorise, nop ),
2523 ( "vectorisation-avoidance", Opt_VectorisationAvoidance, nop ),
2524 ( "regs-graph", Opt_RegsGraph, nop ),
2525 ( "regs-iterative", Opt_RegsIterative, nop ),
2526 ( "llvm-tbaa", Opt_LlvmTBAA, nop), -- hidden flag
2527 ( "irrefutable-tuples", Opt_IrrefutableTuples, nop ),
2528 ( "cmm-sink", Opt_CmmSink, nop ),
2529 ( "cmm-elim-common-blocks", Opt_CmmElimCommonBlocks, nop ),
2530 ( "omit-yields", Opt_OmitYields, nop ),
2531 ( "simple-list-literals", Opt_SimpleListLiterals, nop ),
2532 ( "fun-to-thunk", Opt_FunToThunk, nop ),
2533 ( "gen-manifest", Opt_GenManifest, nop ),
2534 ( "embed-manifest", Opt_EmbedManifest, nop ),
2535 ( "ext-core", Opt_EmitExternalCore, nop ),
2536 ( "shared-implib", Opt_SharedImplib, nop ),
2537 ( "ghci-sandbox", Opt_GhciSandbox, nop ),
2538 ( "ghci-history", Opt_GhciHistory, nop ),
2539 ( "helpful-errors", Opt_HelpfulErrors, nop ),
2540 ( "defer-type-errors", Opt_DeferTypeErrors, nop ),
2541 ( "building-cabal-package", Opt_BuildingCabalPackage, nop ),
2542 ( "implicit-import-qualified", Opt_ImplicitImportQualified, nop ),
2543 ( "prof-count-entries", Opt_ProfCountEntries, nop ),
2544 ( "prof-cafs", Opt_AutoSccsOnIndividualCafs, nop ),
2545 ( "hpc", Opt_Hpc, nop ),
2546 ( "pre-inlining", Opt_SimplPreInlining, nop ),
2547 ( "flat-cache", Opt_FlatCache, nop ),
2548 ( "use-rpaths", Opt_RPath, nop ),
2549 ( "kill-absence", Opt_KillAbsence, nop),
2550 ( "kill-one-shot", Opt_KillOneShot, nop)
2551 ]
2552
2553 -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
2554 fLangFlags :: [FlagSpec ExtensionFlag]
2555 fLangFlags = [
2556 ( "th", Opt_TemplateHaskell,
2557 \on -> deprecatedForExtension "TemplateHaskell" on
2558 >> checkTemplateHaskellOk on ),
2559 ( "fi", Opt_ForeignFunctionInterface,
2560 deprecatedForExtension "ForeignFunctionInterface" ),
2561 ( "ffi", Opt_ForeignFunctionInterface,
2562 deprecatedForExtension "ForeignFunctionInterface" ),
2563 ( "arrows", Opt_Arrows,
2564 deprecatedForExtension "Arrows" ),
2565 ( "implicit-prelude", Opt_ImplicitPrelude,
2566 deprecatedForExtension "ImplicitPrelude" ),
2567 ( "bang-patterns", Opt_BangPatterns,
2568 deprecatedForExtension "BangPatterns" ),
2569 ( "monomorphism-restriction", Opt_MonomorphismRestriction,
2570 deprecatedForExtension "MonomorphismRestriction" ),
2571 ( "mono-pat-binds", Opt_MonoPatBinds,
2572 deprecatedForExtension "MonoPatBinds" ),
2573 ( "extended-default-rules", Opt_ExtendedDefaultRules,
2574 deprecatedForExtension "ExtendedDefaultRules" ),
2575 ( "implicit-params", Opt_ImplicitParams,
2576 deprecatedForExtension "ImplicitParams" ),
2577 ( "scoped-type-variables", Opt_ScopedTypeVariables,
2578 deprecatedForExtension "ScopedTypeVariables" ),
2579 ( "parr", Opt_ParallelArrays,
2580 deprecatedForExtension "ParallelArrays" ),
2581 ( "PArr", Opt_ParallelArrays,
2582 deprecatedForExtension "ParallelArrays" ),
2583 ( "allow-overlapping-instances", Opt_OverlappingInstances,
2584 deprecatedForExtension "OverlappingInstances" ),
2585 ( "allow-undecidable-instances", Opt_UndecidableInstances,
2586 deprecatedForExtension "UndecidableInstances" ),
2587 ( "allow-incoherent-instances", Opt_IncoherentInstances,
2588 deprecatedForExtension "IncoherentInstances" )
2589 ]
2590
2591 supportedLanguages :: [String]
2592 supportedLanguages = [ name | (name, _, _) <- languageFlags ]
2593
2594 supportedLanguageOverlays :: [String]
2595 supportedLanguageOverlays = [ name | (name, _, _) <- safeHaskellFlags ]
2596
2597 supportedExtensions :: [String]
2598 supportedExtensions = [ name' | (name, _, _) <- xFlags, name' <- [name, "No" ++ name] ]
2599
2600 supportedLanguagesAndExtensions :: [String]
2601 supportedLanguagesAndExtensions =
2602 supportedLanguages ++ supportedLanguageOverlays ++ supportedExtensions
2603
2604 -- | These -X<blah> flags cannot be reversed with -XNo<blah>
2605 languageFlags :: [FlagSpec Language]
2606 languageFlags = [
2607 ( "Haskell98", Haskell98, nop ),
2608 ( "Haskell2010", Haskell2010, nop )
2609 ]
2610
2611 -- | These -X<blah> flags cannot be reversed with -XNo<blah>
2612 -- They are used to place hard requirements on what GHC Haskell language
2613 -- features can be used.
2614 safeHaskellFlags :: [FlagSpec SafeHaskellMode]
2615 safeHaskellFlags = [mkF Sf_Unsafe, mkF Sf_Trustworthy, mkF Sf_Safe]
2616 where mkF flag = (show flag, flag, nop)
2617
2618 -- | These -X<blah> flags can all be reversed with -XNo<blah>
2619 xFlags :: [FlagSpec ExtensionFlag]
2620 xFlags = [
2621 ( "CPP", Opt_Cpp, nop ),
2622 ( "PostfixOperators", Opt_PostfixOperators, nop ),
2623 ( "TupleSections", Opt_TupleSections, nop ),
2624 ( "PatternGuards", Opt_PatternGuards, nop ),
2625 ( "UnicodeSyntax", Opt_UnicodeSyntax, nop ),
2626 ( "MagicHash", Opt_MagicHash, nop ),
2627 ( "ExistentialQuantification", Opt_ExistentialQuantification, nop ),
2628 ( "KindSignatures", Opt_KindSignatures, nop ),
2629 ( "EmptyDataDecls", Opt_EmptyDataDecls, nop ),
2630 ( "ParallelListComp", Opt_ParallelListComp, nop ),
2631 ( "TransformListComp", Opt_TransformListComp, nop ),
2632 ( "MonadComprehensions", Opt_MonadComprehensions, nop),
2633 ( "ForeignFunctionInterface", Opt_ForeignFunctionInterface, nop ),
2634 ( "UnliftedFFITypes", Opt_UnliftedFFITypes, nop ),
2635 ( "InterruptibleFFI", Opt_InterruptibleFFI, nop ),
2636 ( "CApiFFI", Opt_CApiFFI, nop ),
2637 ( "GHCForeignImportPrim", Opt_GHCForeignImportPrim, nop ),
2638 ( "LiberalTypeSynonyms", Opt_LiberalTypeSynonyms, nop ),
2639
2640 ( "PolymorphicComponents", Opt_RankNTypes, nop),
2641 ( "Rank2Types", Opt_RankNTypes, nop),
2642 ( "RankNTypes", Opt_RankNTypes, nop ),
2643
2644 ( "ImpredicativeTypes", Opt_ImpredicativeTypes, nop),
2645 ( "TypeOperators", Opt_TypeOperators, nop ),
2646 ( "ExplicitNamespaces", Opt_ExplicitNamespaces, nop ),
2647 ( "RecursiveDo", Opt_RecursiveDo, nop ), -- Enables 'mdo' and 'rec'
2648 ( "DoRec", Opt_RecursiveDo,
2649 deprecatedForExtension "RecursiveDo" ),
2650 ( "Arrows", Opt_Arrows, nop ),
2651 ( "ParallelArrays", Opt_ParallelArrays, nop ),
2652 ( "TemplateHaskell", Opt_TemplateHaskell, checkTemplateHaskellOk ),
2653 ( "QuasiQuotes", Opt_QuasiQuotes, nop ),
2654 ( "ImplicitPrelude", Opt_ImplicitPrelude, nop ),
2655 ( "RecordWildCards", Opt_RecordWildCards, nop ),
2656 ( "NamedFieldPuns", Opt_RecordPuns, nop ),
2657 ( "RecordPuns", Opt_RecordPuns,
2658 deprecatedForExtension "NamedFieldPuns" ),
2659 ( "DisambiguateRecordFields", Opt_DisambiguateRecordFields, nop ),
2660 ( "OverloadedStrings", Opt_OverloadedStrings, nop ),
2661 ( "OverloadedLists", Opt_OverloadedLists, nop),
2662 ( "GADTs", Opt_GADTs, nop ),
2663 ( "GADTSyntax", Opt_GADTSyntax, nop ),
2664 ( "ViewPatterns", Opt_ViewPatterns, nop ),
2665 ( "TypeFamilies", Opt_TypeFamilies, nop ),
2666 ( "BangPatterns", Opt_BangPatterns, nop ),
2667 ( "MonomorphismRestriction", Opt_MonomorphismRestriction, nop ),
2668 ( "NPlusKPatterns", Opt_NPlusKPatterns, nop ),
2669 ( "DoAndIfThenElse", Opt_DoAndIfThenElse, nop ),
2670 ( "RebindableSyntax", Opt_RebindableSyntax, nop ),
2671 ( "ConstraintKinds", Opt_ConstraintKinds, nop ),
2672 ( "PolyKinds", Opt_PolyKinds, nop ),
2673 ( "DataKinds", Opt_DataKinds, nop ),
2674 ( "InstanceSigs", Opt_InstanceSigs, nop ),
2675 ( "MonoPatBinds", Opt_MonoPatBinds,
2676 \ turn_on -> when turn_on $ deprecate "Experimental feature now removed; has no effect" ),
2677 ( "ExplicitForAll", Opt_ExplicitForAll, nop ),
2678 ( "AlternativeLayoutRule", Opt_AlternativeLayoutRule, nop ),
2679 ( "AlternativeLayoutRuleTransitional",Opt_AlternativeLayoutRuleTransitional, nop ),
2680 ( "DatatypeContexts", Opt_DatatypeContexts,
2681 \ turn_on -> when turn_on $ deprecate "It was widely considered a misfeature, and has been removed from the Haskell language." ),
2682 ( "NondecreasingIndentation", Opt_NondecreasingIndentation, nop ),
2683 ( "RelaxedLayout", Opt_RelaxedLayout, nop ),
2684 ( "TraditionalRecordSyntax", Opt_TraditionalRecordSyntax, nop ),
2685 ( "LambdaCase", Opt_LambdaCase, nop ),
2686 ( "MultiWayIf", Opt_MultiWayIf, nop ),
2687 ( "MonoLocalBinds", Opt_MonoLocalBinds, nop ),
2688 ( "RelaxedPolyRec", Opt_RelaxedPolyRec,
2689 \ turn_on -> unless turn_on
2690 $ deprecate "You can't turn off RelaxedPolyRec any more" ),
2691 ( "ExtendedDefaultRules", Opt_ExtendedDefaultRules, nop ),
2692 ( "ImplicitParams", Opt_ImplicitParams, nop ),
2693 ( "ScopedTypeVariables", Opt_ScopedTypeVariables, nop ),
2694 ( "AllowAmbiguousTypes", Opt_AllowAmbiguousTypes, nop),
2695
2696 ( "PatternSignatures", Opt_ScopedTypeVariables,
2697 deprecatedForExtension "ScopedTypeVariables" ),
2698
2699 ( "UnboxedTuples", Opt_UnboxedTuples, nop ),
2700 ( "StandaloneDeriving", Opt_StandaloneDeriving, nop ),
2701 ( "DeriveDataTypeable", Opt_DeriveDataTypeable, nop ),
2702 ( "AutoDeriveTypeable", Opt_AutoDeriveTypeable, nop ),
2703 ( "DeriveFunctor", Opt_DeriveFunctor, nop ),
2704 ( "DeriveTraversable", Opt_DeriveTraversable, nop ),
2705 ( "DeriveFoldable", Opt_DeriveFoldable, nop ),
2706 ( "DeriveGeneric", Opt_DeriveGeneric, nop ),
2707 ( "DefaultSignatures", Opt_DefaultSignatures, nop ),
2708 ( "TypeSynonymInstances", Opt_TypeSynonymInstances, nop ),
2709 ( "FlexibleContexts", Opt_FlexibleContexts, nop ),
2710 ( "FlexibleInstances", Opt_FlexibleInstances, nop ),
2711 ( "ConstrainedClassMethods", Opt_ConstrainedClassMethods, nop ),
2712 ( "MultiParamTypeClasses", Opt_MultiParamTypeClasses, nop ),
2713 ( "NullaryTypeClasses", Opt_NullaryTypeClasses, nop ),
2714 ( "FunctionalDependencies", Opt_FunctionalDependencies, nop ),
2715 ( "GeneralizedNewtypeDeriving", Opt_GeneralizedNewtypeDeriving, setGenDeriving ),
2716 ( "OverlappingInstances", Opt_OverlappingInstances, nop ),
2717 ( "UndecidableInstances", Opt_UndecidableInstances, nop ),
2718 ( "IncoherentInstances", Opt_IncoherentInstances, nop ),
2719 ( "PackageImports", Opt_PackageImports, nop ),
2720 ( "TypeHoles", Opt_TypeHoles, nop ),
2721 ( "EmptyCase", Opt_EmptyCase, nop )
2722 ]
2723
2724 defaultFlags :: Settings -> [GeneralFlag]
2725 defaultFlags settings
2726 = [ Opt_AutoLinkPackages,
2727
2728 Opt_SharedImplib,
2729
2730 Opt_OmitYields,
2731
2732 Opt_GenManifest,
2733 Opt_EmbedManifest,
2734 Opt_PrintBindContents,
2735 Opt_GhciSandbox,
2736 Opt_GhciHistory,
2737 Opt_HelpfulErrors,
2738 Opt_ProfCountEntries,
2739 Opt_SimplPreInlining,
2740 Opt_FlatCache,
2741 Opt_RPath
2742 ]
2743
2744 ++ [f | (ns,f) <- optLevelFlags, 0 `elem` ns]
2745 -- The default -O0 options
2746
2747 ++ default_PIC platform
2748
2749 ++ (if pc_DYNAMIC_BY_DEFAULT (sPlatformConstants settings)
2750 then wayGeneralFlags platform WayDyn
2751 else [])
2752
2753 where platform = sTargetPlatform settings
2754
2755 default_PIC :: Platform -> [GeneralFlag]
2756 default_PIC platform =
2757 case (platformOS platform, platformArch platform) of
2758 (OSDarwin, ArchX86_64) -> [Opt_PIC]
2759 _ -> []
2760
2761 impliedFlags :: [(ExtensionFlag, TurnOnFlag, ExtensionFlag)]
2762 impliedFlags
2763 = [ (Opt_RankNTypes, turnOn, Opt_ExplicitForAll)
2764 , (Opt_ScopedTypeVariables, turnOn, Opt_ExplicitForAll)
2765 , (Opt_LiberalTypeSynonyms, turnOn, Opt_ExplicitForAll)
2766 , (Opt_ExistentialQuantification, turnOn, Opt_ExplicitForAll)
2767 , (Opt_FlexibleInstances, turnOn, Opt_TypeSynonymInstances)
2768 , (Opt_FunctionalDependencies, turnOn, Opt_MultiParamTypeClasses)
2769
2770 , (Opt_RebindableSyntax, turnOff, Opt_ImplicitPrelude) -- NB: turn off!
2771
2772 , (Opt_GADTs, turnOn, Opt_GADTSyntax)
2773 , (Opt_GADTs, turnOn, Opt_MonoLocalBinds)
2774 , (Opt_TypeFamilies, turnOn, Opt_MonoLocalBinds)
2775
2776 , (Opt_TypeFamilies, turnOn, Opt_KindSignatures) -- Type families use kind signatures
2777 , (Opt_PolyKinds, turnOn, Opt_KindSignatures) -- Ditto polymorphic kinds
2778
2779 -- AutoDeriveTypeable is not very useful without DeriveDataTypeable
2780 , (Opt_AutoDeriveTypeable, turnOn, Opt_DeriveDataTypeable)
2781
2782 -- We turn this on so that we can export associated type
2783 -- type synonyms in subordinates (e.g. MyClass(type AssocType))
2784 , (Opt_TypeFamilies, turnOn, Opt_ExplicitNamespaces)
2785 , (Opt_TypeOperators, turnOn, Opt_ExplicitNamespaces)
2786
2787 , (Opt_ImpredicativeTypes, turnOn, Opt_RankNTypes)
2788
2789 -- Record wild-cards implies field disambiguation
2790 -- Otherwise if you write (C {..}) you may well get
2791 -- stuff like " 'a' not in scope ", which is a bit silly
2792 -- if the compiler has just filled in field 'a' of constructor 'C'
2793 , (Opt_RecordWildCards, turnOn, Opt_DisambiguateRecordFields)
2794
2795 , (Opt_ParallelArrays, turnOn, Opt_ParallelListComp)
2796
2797 -- An implicit parameter constraint, `?x::Int`, is desugared into
2798 -- `IP "x" Int`, which requires a flexible context/instance.
2799 , (Opt_ImplicitParams, turnOn, Opt_FlexibleContexts)
2800 , (Opt_ImplicitParams, turnOn, Opt_FlexibleInstances)
2801 ]
2802
2803 optLevelFlags :: [([Int], GeneralFlag)]
2804 optLevelFlags
2805 = [ ([0], Opt_IgnoreInterfacePragmas)
2806 , ([0], Opt_OmitInterfacePragmas)
2807
2808 , ([1,2], Opt_IgnoreAsserts)
2809 , ([1,2], Opt_EnableRewriteRules) -- Off for -O0; see Note [Scoping for Builtin rules]
2810 -- in PrelRules
2811 , ([1,2], Opt_DoEtaReduction)
2812 , ([1,2], Opt_CaseMerge)
2813 , ([1,2], Opt_Strictness)
2814 , ([1,2], Opt_CSE)
2815 , ([1,2], Opt_FullLaziness)
2816 , ([1,2], Opt_Specialise)
2817 , ([1,2], Opt_FloatIn)
2818 , ([1,2], Opt_UnboxSmallStrictFields)
2819
2820 , ([2], Opt_LiberateCase)
2821 , ([2], Opt_SpecConstr)
2822 -- XXX disabled, see #7192
2823 -- , ([2], Opt_RegsGraph)
2824 , ([0,1,2], Opt_LlvmTBAA)
2825 , ([1,2], Opt_CmmSink)
2826 , ([1,2], Opt_CmmElimCommonBlocks)
2827
2828 -- , ([2], Opt_StaticArgumentTransformation)
2829 -- Max writes: I think it's probably best not to enable SAT with -O2 for the
2830 -- 6.10 release. The version of SAT in HEAD at the moment doesn't incorporate
2831 -- several improvements to the heuristics, and I'm concerned that without
2832 -- those changes SAT will interfere with some attempts to write "high
2833 -- performance Haskell", as we saw in some posts on Haskell-Cafe earlier
2834 -- this year. In particular, the version in HEAD lacks the tail call
2835 -- criterion, so many things that look like reasonable loops will be
2836 -- turned into functions with extra (unneccesary) thunk creation.
2837
2838 , ([0,1,2], Opt_DoLambdaEtaExpansion)
2839 -- This one is important for a tiresome reason:
2840 -- we want to make sure that the bindings for data
2841 -- constructors are eta-expanded. This is probably
2842 -- a good thing anyway, but it seems fragile.
2843 , ([0,1,2], Opt_VectorisationAvoidance)
2844 ]
2845
2846 -- -----------------------------------------------------------------------------
2847 -- Standard sets of warning options
2848
2849 standardWarnings :: [WarningFlag]
2850 standardWarnings
2851 = [ Opt_WarnWarningsDeprecations,
2852 Opt_WarnDeprecatedFlags,
2853 Opt_WarnUnrecognisedPragmas,
2854 Opt_WarnOverlappingPatterns,
2855 Opt_WarnMissingFields,
2856 Opt_WarnMissingMethods,
2857 Opt_WarnDuplicateExports,
2858 Opt_WarnLazyUnliftedBindings,
2859 Opt_WarnDodgyForeignImports,
2860 Opt_WarnWrongDoBind,
2861 Opt_WarnAlternativeLayoutRuleTransitional,
2862 Opt_WarnPointlessPragmas,
2863 Opt_WarnUnsupportedCallingConventions,
2864 Opt_WarnUnsupportedLlvmVersion,
2865 Opt_WarnInlineRuleShadowing,
2866 Opt_WarnDuplicateConstraints,
2867 Opt_WarnInlineRuleShadowing,
2868 Opt_WarnTypeableInstances
2869 ]
2870
2871 minusWOpts :: [WarningFlag]
2872 -- Things you get with -W
2873 minusWOpts
2874 = standardWarnings ++
2875 [ Opt_WarnUnusedBinds,
2876 Opt_WarnUnusedMatches,
2877 Opt_WarnUnusedImports,
2878 Opt_WarnIncompletePatterns,
2879 Opt_WarnDodgyExports,
2880 Opt_WarnDodgyImports
2881 ]
2882
2883 minusWallOpts :: [WarningFlag]
2884 -- Things you get with -Wall
2885 minusWallOpts
2886 = minusWOpts ++
2887 [ Opt_WarnTypeDefaults,
2888 Opt_WarnNameShadowing,
2889 Opt_WarnMissingSigs,
2890 Opt_WarnHiShadows,
2891 Opt_WarnOrphans,
2892 Opt_WarnUnusedDoBind
2893 ]
2894
2895 enableGlasgowExts :: DynP ()
2896 enableGlasgowExts = do setGeneralFlag Opt_PrintExplicitForalls
2897 mapM_ setExtensionFlag glasgowExtsFlags
2898
2899 disableGlasgowExts :: DynP ()
2900 disableGlasgowExts = do unSetGeneralFlag Opt_PrintExplicitForalls
2901 mapM_ unSetExtensionFlag glasgowExtsFlags
2902
2903 glasgowExtsFlags :: [ExtensionFlag]
2904 glasgowExtsFlags = [
2905 Opt_ForeignFunctionInterface
2906 , Opt_UnliftedFFITypes
2907 , Opt_ImplicitParams
2908 , Opt_ScopedTypeVariables
2909 , Opt_UnboxedTuples
2910 , Opt_TypeSynonymInstances
2911 , Opt_StandaloneDeriving
2912 , Opt_DeriveDataTypeable
2913 , Opt_DeriveFunctor
2914 , Opt_DeriveFoldable
2915 , Opt_DeriveTraversable
2916 , Opt_DeriveGeneric
2917 , Opt_FlexibleContexts
2918 , Opt_FlexibleInstances
2919 , Opt_ConstrainedClassMethods
2920 , Opt_MultiParamTypeClasses
2921 , Opt_FunctionalDependencies
2922 , Opt_MagicHash
2923 , Opt_ExistentialQuantification
2924 , Opt_UnicodeSyntax
2925 , Opt_PostfixOperators
2926 , Opt_PatternGuards
2927 , Opt_LiberalTypeSynonyms
2928 , Opt_RankNTypes
2929 , Opt_TypeOperators
2930 , Opt_ExplicitNamespaces
2931 , Opt_RecursiveDo
2932 , Opt_ParallelListComp
2933 , Opt_EmptyDataDecls
2934 , Opt_KindSignatures
2935 , Opt_GeneralizedNewtypeDeriving ]
2936
2937 #ifdef GHCI
2938 -- Consult the RTS to find whether GHC itself has been built profiled
2939 -- If so, you can't use Template Haskell
2940 foreign import ccall unsafe "rts_isProfiled" rtsIsProfiledIO :: IO CInt
2941
2942 rtsIsProfiled :: Bool
2943 rtsIsProfiled = unsafePerformIO rtsIsProfiledIO /= 0
2944 #endif
2945
2946 setWarnSafe :: Bool -> DynP ()
2947 setWarnSafe True = getCurLoc >>= \l -> upd (\d -> d { warnSafeOnLoc = l })
2948 setWarnSafe False = return ()
2949
2950 setWarnUnsafe :: Bool -> DynP ()
2951 setWarnUnsafe True = getCurLoc >>= \l -> upd (\d -> d { warnUnsafeOnLoc = l })
2952 setWarnUnsafe False = return ()
2953
2954 setPackageTrust :: DynP ()
2955 setPackageTrust = do
2956 setGeneralFlag Opt_PackageTrust
2957 l <- getCurLoc
2958 upd $ \d -> d { pkgTrustOnLoc = l }
2959
2960 setGenDeriving :: TurnOnFlag -> DynP ()
2961 setGenDeriving True = getCurLoc >>= \l -> upd (\d -> d { newDerivOnLoc = l })
2962 setGenDeriving False = return ()
2963
2964 checkTemplateHaskellOk :: TurnOnFlag -> DynP ()
2965 #ifdef GHCI
2966 checkTemplateHaskellOk turn_on
2967 | turn_on && rtsIsProfiled
2968 = addErr "You can't use Template Haskell with a profiled compiler"
2969 | otherwise
2970 = getCurLoc >>= \l -> upd (\d -> d { thOnLoc = l })
2971 #else
2972 -- In stage 1 we don't know that the RTS has rts_isProfiled,
2973 -- so we simply say "ok". It doesn't matter because TH isn't
2974 -- available in stage 1 anyway.
2975 checkTemplateHaskellOk _ = return ()
2976 #endif
2977
2978 {- **********************************************************************
2979 %* *
2980 DynFlags constructors
2981 %* *
2982 %********************************************************************* -}
2983
2984 type DynP = EwM (CmdLineP DynFlags)
2985
2986 upd :: (DynFlags -> DynFlags) -> DynP ()
2987 upd f = liftEwM (do dflags <- getCmdLineState
2988 putCmdLineState $! f dflags)
2989
2990 updM :: (DynFlags -> DynP DynFlags) -> DynP ()
2991 updM f = do dflags <- liftEwM getCmdLineState
2992 dflags' <- f dflags
2993 liftEwM $ putCmdLineState $! dflags'
2994
2995 --------------- Constructor functions for OptKind -----------------
2996 noArg :: (DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
2997 noArg fn = NoArg (upd fn)
2998
2999 noArgM :: (DynFlags -> DynP DynFlags) -> OptKind (CmdLineP DynFlags)
3000 noArgM fn = NoArg (updM fn)
3001
3002 noArgDF :: (DynFlags -> DynFlags) -> String -> OptKind (CmdLineP DynFlags)
3003 noArgDF fn deprec = NoArg (upd fn >> deprecate deprec)
3004
3005 hasArg :: (String -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
3006 hasArg fn = HasArg (upd . fn)
3007
3008 hasArgDF :: (String -> DynFlags -> DynFlags) -> String -> OptKind (CmdLineP DynFlags)
3009 hasArgDF fn deprec = HasArg (\s -> do upd (fn s)
3010 deprecate deprec)
3011
3012 sepArg :: (String -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
3013 sepArg fn = SepArg (upd . fn)
3014
3015 intSuffix :: (Int -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
3016 intSuffix fn = IntSuffix (\n -> upd (fn n))
3017
3018 floatSuffix :: (Float -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
3019 floatSuffix fn = FloatSuffix (\n -> upd (fn n))
3020
3021 optIntSuffixM :: (Maybe Int -> DynFlags -> DynP DynFlags)
3022 -> OptKind (CmdLineP DynFlags)
3023 optIntSuffixM fn = OptIntSuffix (\mi -> updM (fn mi))
3024
3025 versionSuffix :: (Int -> Int -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
3026 versionSuffix fn = VersionSuffix (\maj min -> upd (fn maj min))
3027
3028 setDumpFlag :: DumpFlag -> OptKind (CmdLineP DynFlags)
3029 setDumpFlag dump_flag = NoArg (setDumpFlag' dump_flag)
3030
3031 --------------------------
3032 addWay :: Way -> DynP ()
3033 addWay w = upd (addWay' w)
3034
3035 addWay' :: Way -> DynFlags -> DynFlags
3036 addWay' w dflags0 = let platform = targetPlatform dflags0
3037 dflags1 = dflags0 { ways = w : ways dflags0 }
3038 dflags2 = wayExtras platform w dflags1
3039 dflags3 = foldr setGeneralFlag' dflags2
3040 (wayGeneralFlags platform w)
3041 dflags4 = foldr unSetGeneralFlag' dflags3
3042 (wayUnsetGeneralFlags platform w)
3043 in dflags4
3044
3045 removeWayDyn :: DynP ()
3046 removeWayDyn = upd (\dfs -> dfs { ways = filter (WayDyn /=) (ways dfs) })
3047
3048 --------------------------
3049 setGeneralFlag, unSetGeneralFlag :: GeneralFlag -> DynP ()
3050 setGeneralFlag f = upd (setGeneralFlag' f)
3051 unSetGeneralFlag f = upd (unSetGeneralFlag' f)
3052
3053 setGeneralFlag' :: GeneralFlag -> DynFlags -> DynFlags
3054 setGeneralFlag' f dflags = gopt_set dflags f
3055 unSetGeneralFlag' :: GeneralFlag -> DynFlags -> DynFlags
3056 unSetGeneralFlag' f dflags = gopt_unset dflags f
3057
3058 --------------------------
3059 setWarningFlag, unSetWarningFlag :: WarningFlag -> DynP ()
3060 setWarningFlag f = upd (\dfs -> wopt_set dfs f)
3061 unSetWarningFlag f = upd (\dfs -> wopt_unset dfs f)
3062
3063 --------------------------
3064 setExtensionFlag, unSetExtensionFlag :: ExtensionFlag -> DynP ()
3065 setExtensionFlag f = upd (setExtensionFlag' f)
3066 unSetExtensionFlag f = upd (unSetExtensionFlag' f)
3067
3068 setExtensionFlag', unSetExtensionFlag' :: ExtensionFlag -> DynFlags -> DynFlags
3069 setExtensionFlag' f dflags = foldr ($) (xopt_set dflags f) deps
3070 where
3071 deps = [ if turn_on then setExtensionFlag' d
3072 else unSetExtensionFlag' d
3073 | (f', turn_on, d) <- impliedFlags, f' == f ]
3074 -- When you set f, set the ones it implies
3075 -- NB: use setExtensionFlag recursively, in case the implied flags
3076 -- implies further flags
3077
3078 unSetExtensionFlag' f dflags = xopt_unset dflags f
3079 -- When you un-set f, however, we don't un-set the things it implies
3080 -- (except for -fno-glasgow-exts, which is treated specially)
3081
3082 --------------------------
3083 alterSettings :: (Settings -> Settings) -> DynFlags -> DynFlags
3084 alterSettings f dflags = dflags { settings = f (settings dflags) }
3085
3086 --------------------------
3087 setDumpFlag' :: DumpFlag -> DynP ()
3088 setDumpFlag' dump_flag
3089 = do upd (\dfs -> dopt_set dfs dump_flag)
3090 when want_recomp forceRecompile
3091 where -- Certain dumpy-things are really interested in what's going
3092 -- on during recompilation checking, so in those cases we
3093 -- don't want to turn it off.
3094 want_recomp = dump_flag `notElem` [Opt_D_dump_if_trace,
3095 Opt_D_dump_hi_diffs]
3096
3097 forceRecompile :: DynP ()
3098 -- Whenver we -ddump, force recompilation (by switching off the
3099 -- recompilation checker), else you don't see the dump! However,
3100 -- don't switch it off in --make mode, else *everything* gets
3101 -- recompiled which probably isn't what you want
3102 forceRecompile = do dfs <- liftEwM getCmdLineState
3103 when (force_recomp dfs) (setGeneralFlag Opt_ForceRecomp)
3104 where
3105 force_recomp dfs = isOneShot (ghcMode dfs)
3106
3107 setVerboseCore2Core :: DynP ()
3108 setVerboseCore2Core = do setDumpFlag' Opt_D_verbose_core2core
3109 upd (\dfs -> dfs { shouldDumpSimplPhase = Nothing })
3110
3111 setDumpSimplPhases :: String -> DynP ()
3112 setDumpSimplPhases s = do forceRecompile
3113 upd (\dfs -> dfs { shouldDumpSimplPhase = Just spec })
3114 where
3115 spec = case s of { ('=' : s') -> s'; _ -> s }
3116
3117 setVerbosity :: Maybe Int -> DynP ()
3118 setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 })
3119
3120 addCmdlineHCInclude :: String -> DynP ()
3121 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes = a : cmdlineHcIncludes s})
3122
3123 data PkgConfRef
3124 = GlobalPkgConf
3125 | UserPkgConf
3126 | PkgConfFile FilePath
3127
3128 addPkgConfRef :: PkgConfRef -> DynP ()
3129 addPkgConfRef p = upd $ \s -> s { extraPkgConfs = (p:) . extraPkgConfs s }
3130
3131 removeUserPkgConf :: DynP ()
3132 removeUserPkgConf = upd $ \s -> s { extraPkgConfs = filter isNotUser . extraPkgConfs s }
3133 where
3134 isNotUser UserPkgConf = False
3135 isNotUser _ = True
3136
3137 removeGlobalPkgConf :: DynP ()
3138 removeGlobalPkgConf = upd $ \s -> s { extraPkgConfs = filter isNotGlobal . extraPkgConfs s }
3139 where
3140 isNotGlobal GlobalPkgConf = False
3141 isNotGlobal _ = True
3142
3143 clearPkgConf :: DynP ()
3144 clearPkgConf = upd $ \s -> s { extraPkgConfs = const [] }
3145
3146 exposePackage, exposePackageId, hidePackage, ignorePackage,
3147 trustPackage, distrustPackage :: String -> DynP ()
3148 exposePackage p = upd (exposePackage' p)
3149 exposePackageId p =
3150 upd (\s -> s{ packageFlags = ExposePackageId p : packageFlags s })
3151 hidePackage p =
3152 upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
3153 ignorePackage p =
3154 upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
3155 trustPackage p = exposePackage p >> -- both trust and distrust also expose a package
3156 upd (\s -> s{ packageFlags = TrustPackage p : packageFlags s })
3157 distrustPackage p = exposePackage p >>
3158 upd (\s -> s{ packageFlags = DistrustPackage p : packageFlags s })
3159
3160 exposePackage' :: String -> DynFlags -> DynFlags
3161 exposePackage' p dflags
3162 = dflags { packageFlags = ExposePackage p : packageFlags dflags }
3163
3164 setPackageName :: String -> DynFlags -> DynFlags
3165 setPackageName p s = s{ thisPackage = stringToPackageId p }
3166
3167 -- If we're linking a binary, then only targets that produce object
3168 -- code are allowed (requests for other target types are ignored).
3169 setTarget :: HscTarget -> DynP ()
3170 setTarget l = setTargetWithPlatform (const l)
3171
3172 setTargetWithPlatform :: (Platform -> HscTarget) -> DynP ()
3173 setTargetWithPlatform f = upd set
3174 where
3175 set dfs = let l = f (targetPlatform dfs)
3176 in if ghcLink dfs /= LinkBinary || isObjectTarget l
3177 then dfs{ hscTarget = l }
3178 else dfs
3179
3180 -- Changes the target only if we're compiling object code. This is
3181 -- used by -fasm and -fllvm, which switch from one to the other, but
3182 -- not from bytecode to object-code. The idea is that -fasm/-fllvm
3183 -- can be safely used in an OPTIONS_GHC pragma.
3184 setObjTarget :: HscTarget -> DynP ()
3185 setObjTarget l = updM set
3186 where
3187 set dflags
3188 | isObjectTarget (hscTarget dflags)
3189 = return $ dflags { hscTarget = l }
3190 | otherwise = return dflags
3191
3192 setOptLevel :: Int -> DynFlags -> DynP DynFlags
3193 setOptLevel n dflags
3194 | hscTarget dflags == HscInterpreted && n > 0
3195 = do addWarn "-O conflicts with --interactive; -O ignored."
3196 return dflags
3197 | otherwise
3198 = return (updOptLevel n dflags)
3199
3200
3201 -- -Odph is equivalent to
3202 --
3203 -- -O2 optimise as much as possible
3204 -- -fmax-simplifier-iterations20 this is necessary sometimes
3205 -- -fsimplifier-phases=3 we use an additional simplifier phase for fusion
3206 --
3207 setDPHOpt :: DynFlags -> DynP DynFlags
3208 setDPHOpt dflags = setOptLevel 2 (dflags { maxSimplIterations = 20
3209 , simplPhases = 3
3210 })
3211
3212 setMainIs :: String -> DynP ()
3213 setMainIs arg
3214 | not (null main_fn) && isLower (head main_fn)
3215 -- The arg looked like "Foo.Bar.baz"
3216 = upd $ \d -> d{ mainFunIs = Just main_fn,
3217 mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
3218
3219 | isUpper (head arg) -- The arg looked like "Foo" or "Foo.Bar"
3220 = upd $ \d -> d{ mainModIs = mkModule mainPackageId (mkModuleName arg) }
3221
3222 | otherwise -- The arg looked like "baz"
3223 = upd $ \d -> d{ mainFunIs = Just arg }
3224 where
3225 (main_mod, main_fn) = splitLongestPrefix arg (== '.')
3226
3227 addLdInputs :: Option -> DynFlags -> DynFlags
3228 addLdInputs p dflags = dflags{ldInputs = ldInputs dflags ++ [p]}
3229
3230 -----------------------------------------------------------------------------
3231 -- Paths & Libraries
3232
3233 addImportPath, addLibraryPath, addIncludePath, addFrameworkPath :: FilePath -> DynP ()
3234
3235 -- -i on its own deletes the import paths
3236 addImportPath "" = upd (\s -> s{importPaths = []})
3237 addImportPath p = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
3238
3239 addLibraryPath p =
3240 upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
3241
3242 addIncludePath p =
3243 upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
3244
3245 addFrameworkPath p =
3246 upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
3247
3248 #ifndef mingw32_TARGET_OS
3249 split_marker :: Char
3250 split_marker = ':' -- not configurable (ToDo)
3251 #endif
3252
3253 splitPathList :: String -> [String]
3254 splitPathList s = filter notNull (splitUp s)
3255 -- empty paths are ignored: there might be a trailing
3256 -- ':' in the initial list, for example. Empty paths can
3257 -- cause confusion when they are translated into -I options
3258 -- for passing to gcc.
3259 where
3260 #ifndef mingw32_TARGET_OS
3261 splitUp xs = split split_marker xs
3262 #else
3263 -- Windows: 'hybrid' support for DOS-style paths in directory lists.
3264 --
3265 -- That is, if "foo:bar:baz" is used, this interpreted as
3266 -- consisting of three entries, 'foo', 'bar', 'baz'.
3267 -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
3268 -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
3269 --
3270 -- Notice that no attempt is made to fully replace the 'standard'
3271 -- split marker ':' with the Windows / DOS one, ';'. The reason being
3272 -- that this will cause too much breakage for users & ':' will
3273 -- work fine even with DOS paths, if you're not insisting on being silly.
3274 -- So, use either.
3275 splitUp [] = []
3276 splitUp (x:':':div:xs) | div `elem` dir_markers
3277 = ((x:':':div:p): splitUp rs)
3278 where
3279 (p,rs) = findNextPath xs
3280 -- we used to check for existence of the path here, but that
3281 -- required the IO monad to be threaded through the command-line
3282 -- parser which is quite inconvenient. The
3283 splitUp xs = cons p (splitUp rs)
3284 where
3285 (p,rs) = findNextPath xs
3286
3287 cons "" xs = xs
3288 cons x xs = x:xs
3289
3290 -- will be called either when we've consumed nought or the
3291 -- "<Drive>:/" part of a DOS path, so splitting is just a Q of
3292 -- finding the next split marker.
3293 findNextPath xs =
3294 case break (`elem` split_markers) xs of
3295 (p, _:ds) -> (p, ds)
3296 (p, xs) -> (p, xs)
3297
3298 split_markers :: [Char]
3299 split_markers = [':', ';']
3300
3301 dir_markers :: [Char]
3302 dir_markers = ['/', '\\']
3303 #endif
3304
3305 -- -----------------------------------------------------------------------------
3306 -- tmpDir, where we store temporary files.
3307
3308 setTmpDir :: FilePath -> DynFlags -> DynFlags
3309 setTmpDir dir = alterSettings (\s -> s { sTmpDir = normalise dir })
3310 -- we used to fix /cygdrive/c/.. on Windows, but this doesn't
3311 -- seem necessary now --SDM 7/2/2008
3312
3313 -----------------------------------------------------------------------------
3314 -- RTS opts
3315
3316 setRtsOpts :: String -> DynP ()
3317 setRtsOpts arg = upd $ \ d -> d {rtsOpts = Just arg}
3318
3319 setRtsOptsEnabled :: RtsOptsEnabled -> DynP ()
3320 setRtsOptsEnabled arg = upd $ \ d -> d {rtsOptsEnabled = arg}
3321
3322 -----------------------------------------------------------------------------
3323 -- Hpc stuff
3324
3325 setOptHpcDir :: String -> DynP ()
3326 setOptHpcDir arg = upd $ \ d -> d{hpcDir = arg}
3327
3328 -----------------------------------------------------------------------------
3329 -- Via-C compilation stuff
3330
3331 -- There are some options that we need to pass to gcc when compiling
3332 -- Haskell code via C, but are only supported by recent versions of
3333 -- gcc. The configure script decides which of these options we need,
3334 -- and puts them in the "settings" file in $topdir. The advantage of
3335 -- having these in a separate file is that the file can be created at
3336 -- install-time depending on the available gcc version, and even
3337 -- re-generated later if gcc is upgraded.
3338 --
3339 -- The options below are not dependent on the version of gcc, only the
3340 -- platform.
3341
3342 picCCOpts :: DynFlags -> [String]
3343 picCCOpts dflags
3344 = case platformOS (targetPlatform dflags) of
3345 OSDarwin
3346 -- Apple prefers to do things the other way round.
3347 -- PIC is on by default.
3348 -- -mdynamic-no-pic:
3349 -- Turn off PIC code generation.
3350 -- -fno-common:
3351 -- Don't generate "common" symbols - these are unwanted
3352 -- in dynamic libraries.
3353
3354 | gopt Opt_PIC dflags -> ["-fno-common", "-U __PIC__", "-D__PIC__"]
3355 | otherwise -> ["-mdynamic-no-pic"]
3356 OSMinGW32 -- no -fPIC for Windows
3357 | gopt Opt_PIC dflags -> ["-U __PIC__", "-D__PIC__"]
3358 | otherwise -> []
3359 _
3360 -- we need -fPIC for C files when we are compiling with -dynamic,
3361 -- otherwise things like stub.c files don't get compiled
3362 -- correctly. They need to reference data in the Haskell
3363 -- objects, but can't without -fPIC. See
3364 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/PositionIndependentCode
3365 | gopt Opt_PIC dflags || not (gopt Opt_Static dflags) ->
3366 ["-fPIC", "-U __PIC__", "-D__PIC__"]
3367 | otherwise -> []
3368
3369 picPOpts :: DynFlags -> [String]
3370 picPOpts dflags
3371 | gopt Opt_PIC dflags = ["-U __PIC__", "-D__PIC__"]
3372 | otherwise = []
3373
3374 -- -----------------------------------------------------------------------------
3375 -- Splitting
3376
3377 can_split :: Bool
3378 can_split = cSupportsSplitObjs == "YES"
3379
3380 -- -----------------------------------------------------------------------------
3381 -- Compiler Info
3382
3383 compilerInfo :: DynFlags -> [(String, String)]
3384 compilerInfo dflags
3385 = -- We always make "Project name" be first to keep parsing in
3386 -- other languages simple, i.e. when looking for other fields,
3387 -- you don't have to worry whether there is a leading '[' or not
3388 ("Project name", cProjectName)
3389 -- Next come the settings, so anything else can be overridden
3390 -- in the settings file (as "lookup" uses the first match for the
3391 -- key)
3392 : rawSettings dflags
3393 ++ [("Project version", cProjectVersion),
3394 ("Booter version", cBooterVersion),
3395 ("Stage", cStage),
3396 ("Build platform", cBuildPlatformString),
3397 ("Host platform", cHostPlatformString),
3398 ("Target platform", cTargetPlatformString),
3399 ("Have interpreter", cGhcWithInterpreter),
3400 ("Object splitting supported", cSupportsSplitObjs),
3401 ("Have native code generator", cGhcWithNativeCodeGen),
3402 ("Support SMP", cGhcWithSMP),
3403 ("Tables next to code", cGhcEnableTablesNextToCode),
3404 ("RTS ways", cGhcRTSWays),
3405 ("Support dynamic-too", "YES"),
3406 ("Dynamic by default", if dYNAMIC_BY_DEFAULT dflags
3407 then "YES" else "NO"),
3408 ("GHC Dynamic", if cDYNAMIC_GHC_PROGRAMS
3409 then "YES" else "NO"),
3410 ("Leading underscore", cLeadingUnderscore),
3411 ("Debug on", show debugIsOn),
3412 ("LibDir", topDir dflags),
3413 ("Global Package DB", systemPackageConfig dflags)
3414 ]
3415
3416 #include "../includes/dist-derivedconstants/header/GHCConstantsHaskellWrappers.hs"
3417
3418 bLOCK_SIZE_W :: DynFlags -> Int
3419 bLOCK_SIZE_W dflags = bLOCK_SIZE dflags `quot` wORD_SIZE dflags
3420
3421 wORD_SIZE_IN_BITS :: DynFlags -> Int
3422 wORD_SIZE_IN_BITS dflags = wORD_SIZE dflags * 8
3423
3424 tAG_MASK :: DynFlags -> Int
3425 tAG_MASK dflags = (1 `shiftL` tAG_BITS dflags) - 1
3426
3427 mAX_PTR_TAG :: DynFlags -> Int
3428 mAX_PTR_TAG = tAG_MASK
3429
3430 -- Might be worth caching these in targetPlatform?
3431 tARGET_MIN_INT, tARGET_MAX_INT, tARGET_MAX_WORD :: DynFlags -> Integer
3432 tARGET_MIN_INT dflags
3433 = case platformWordSize (targetPlatform dflags) of
3434 4 -> toInteger (minBound :: Int32)
3435 8 -> toInteger (minBound :: Int64)
3436 w -> panic ("tARGET_MIN_INT: Unknown platformWordSize: " ++ show w)
3437 tARGET_MAX_INT dflags
3438 = case platformWordSize (targetPlatform dflags) of
3439 4 -> toInteger (maxBound :: Int32)
3440 8 -> toInteger (maxBound :: Int64)
3441 w -> panic ("tARGET_MAX_INT: Unknown platformWordSize: " ++ show w)
3442 tARGET_MAX_WORD dflags
3443 = case platformWordSize (targetPlatform dflags) of
3444 4 -> toInteger (maxBound :: Word32)
3445 8 -> toInteger (maxBound :: Word64)
3446 w -> panic ("tARGET_MAX_WORD: Unknown platformWordSize: " ++ show w)
3447
3448 -- Whenever makeDynFlagsConsistent does anything, it starts over, to
3449 -- ensure that a later change doesn't invalidate an earlier check.
3450 -- Be careful not to introduce potential loops!
3451 makeDynFlagsConsistent :: DynFlags -> (DynFlags, [Located String])
3452 makeDynFlagsConsistent dflags
3453 | hscTarget dflags == HscC &&
3454 not (platformUnregisterised (targetPlatform dflags))
3455 = if cGhcWithNativeCodeGen == "YES"
3456 then let dflags' = dflags { hscTarget = HscAsm }
3457 warn = "Compiler not unregisterised, so using native code generator rather than compiling via C"
3458 in loop dflags' warn
3459 else let dflags' = dflags { hscTarget = HscLlvm }
3460 warn = "Compiler not unregisterised, so using LLVM rather than compiling via C"
3461 in loop dflags' warn
3462 | hscTarget dflags == HscAsm &&
3463 platformUnregisterised (targetPlatform dflags)
3464 = loop (dflags { hscTarget = HscC })
3465 "Compiler unregisterised, so compiling via C"
3466 | hscTarget dflags == HscAsm &&
3467 cGhcWithNativeCodeGen /= "YES"
3468 = let dflags' = dflags { hscTarget = HscLlvm }
3469 warn = "No native code generator, so using LLVM"
3470 in loop dflags' warn
3471 | hscTarget dflags == HscLlvm &&
3472 not ((arch == ArchX86_64) && (os == OSLinux || os == OSDarwin)) &&
3473 not ((isARM arch) && (os == OSLinux)) &&
3474 (not (gopt Opt_Static dflags) || gopt Opt_PIC dflags)
3475 = if cGhcWithNativeCodeGen == "YES"
3476 then let dflags' = dflags { hscTarget = HscAsm }
3477 warn = "Using native code generator rather than LLVM, as LLVM is incompatible with -fPIC and -dynamic on this platform"
3478 in loop dflags' warn
3479 else throwGhcException $ CmdLineError "Can't use -fPIC or -dynamic on this platform"
3480 | os == OSDarwin &&
3481 arch == ArchX86_64 &&
3482 not (gopt Opt_PIC dflags)
3483 = loop (gopt_set dflags Opt_PIC)
3484 "Enabling -fPIC as it is always on for this platform"
3485 | otherwise = (dflags, [])
3486 where loc = mkGeneralSrcSpan (fsLit "when making flags consistent")
3487 loop updated_dflags warning
3488 = case makeDynFlagsConsistent updated_dflags of
3489 (dflags', ws) -> (dflags', L loc warning : ws)
3490 platform = targetPlatform dflags
3491 arch = platformArch platform
3492 os = platformOS platform
3493
3494 --------------------------------------------------------------------------
3495 -- Do not use unsafeGlobalDynFlags!
3496 --
3497 -- unsafeGlobalDynFlags is a hack, necessary because we need to be able
3498 -- to show SDocs when tracing, but we don't always have DynFlags
3499 -- available.
3500 --
3501 -- Do not use it if you can help it. You may get the wrong value!
3502
3503 GLOBAL_VAR(v_unsafeGlobalDynFlags, panic "v_unsafeGlobalDynFlags: not initialised", DynFlags)
3504
3505 unsafeGlobalDynFlags :: DynFlags
3506 unsafeGlobalDynFlags = unsafePerformIO $ readIORef v_unsafeGlobalDynFlags
3507
3508 setUnsafeGlobalDynFlags :: DynFlags -> IO ()
3509 setUnsafeGlobalDynFlags = writeIORef v_unsafeGlobalDynFlags
3510
3511 -- -----------------------------------------------------------------------------
3512 -- SSE
3513
3514 -- TODO: Instead of using a separate predicate (i.e. isSse2Enabled) to
3515 -- check if SSE is enabled, we might have x86-64 imply the -msse2
3516 -- flag.
3517
3518 isSse2Enabled :: DynFlags -> Bool
3519 isSse2Enabled dflags = case platformArch (targetPlatform dflags) of
3520 ArchX86_64 -> -- SSE2 is fixed on for x86_64. It would be
3521 -- possible to make it optional, but we'd need to
3522 -- fix at least the foreign call code where the
3523 -- calling convention specifies the use of xmm regs,
3524 -- and possibly other places.
3525 True
3526 ArchX86 -> sseVersion dflags >= Just (2,0)
3527 _ -> False
3528
3529 isSse4_2Enabled :: DynFlags -> Bool
3530 isSse4_2Enabled dflags = sseVersion dflags >= Just (4,2)
3531
3532 -- -----------------------------------------------------------------------------
3533 -- Linker information
3534
3535 -- LinkerInfo contains any extra options needed by the system linker.
3536 data LinkerInfo
3537 = GnuLD [Option]
3538 | GnuGold [Option]
3539 | DarwinLD [Option]
3540 | UnknownLD
3541 deriving Eq