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