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