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