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