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