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