Implement late lambda lift
[ghc.git] / compiler / main / DynFlags.hs
1 {-# LANGUAGE CPP #-}
2 {-# LANGUAGE FlexibleInstances #-}
3
4 -------------------------------------------------------------------------------
5 --
6 -- | Dynamic flags
7 --
8 -- Most flags are dynamic flags, which means they can change from compilation
9 -- to compilation using @OPTIONS_GHC@ pragmas, and in a multi-session GHC each
10 -- session can be using different dynamic flags. Dynamic flags can also be set
11 -- at the prompt in GHCi.
12 --
13 -- (c) The University of Glasgow 2005
14 --
15 -------------------------------------------------------------------------------
16
17 {-# OPTIONS_GHC -fno-cse #-}
18 -- -fno-cse is needed for GLOBAL_VAR's to behave properly
19
20 module DynFlags (
21 -- * Dynamic flags and associated configuration types
22 DumpFlag(..),
23 GeneralFlag(..),
24 WarningFlag(..), WarnReason(..),
25 Language(..),
26 PlatformConstants(..),
27 FatalMessager, LogAction, FlushOut(..), FlushErr(..),
28 ProfAuto(..),
29 glasgowExtsFlags,
30 warningGroups, warningHierarchies,
31 hasPprDebug, hasNoDebugOutput, hasNoStateHack, hasNoOptCoercion,
32 dopt, dopt_set, dopt_unset,
33 gopt, gopt_set, gopt_unset, setGeneralFlag', unSetGeneralFlag',
34 wopt, wopt_set, wopt_unset,
35 wopt_fatal, wopt_set_fatal, wopt_unset_fatal,
36 xopt, xopt_set, xopt_unset,
37 lang_set,
38 useUnicodeSyntax,
39 useStarIsType,
40 whenGeneratingDynamicToo, ifGeneratingDynamicToo,
41 whenCannotGenerateDynamicToo,
42 dynamicTooMkDynamicDynFlags,
43 DynFlags(..),
44 FlagSpec(..),
45 HasDynFlags(..), ContainsDynFlags(..),
46 RtsOptsEnabled(..),
47 HscTarget(..), isObjectTarget, defaultObjectTarget,
48 targetRetainsAllBindings,
49 GhcMode(..), isOneShot,
50 GhcLink(..), isNoLink,
51 PackageFlag(..), PackageArg(..), ModRenaming(..),
52 packageFlagsChanged,
53 IgnorePackageFlag(..), TrustFlag(..),
54 PackageDBFlag(..), PkgConfRef(..),
55 Option(..), showOpt,
56 DynLibLoader(..),
57 fFlags, fLangFlags, xFlags,
58 wWarningFlags,
59 dynFlagDependencies,
60 tablesNextToCode, mkTablesNextToCode,
61 makeDynFlagsConsistent,
62 shouldUseColor,
63 shouldUseHexWordLiterals,
64 positionIndependent,
65 optimisationFlags,
66
67 Way(..), mkBuildTag, wayRTSOnly, addWay', updateWays,
68 wayGeneralFlags, wayUnsetGeneralFlags,
69
70 thisPackage, thisComponentId, thisUnitIdInsts,
71
72 -- ** Log output
73 putLogMsg,
74
75 -- ** Safe Haskell
76 SafeHaskellMode(..),
77 safeHaskellOn, safeImportsOn, safeLanguageOn, safeInferOn,
78 packageTrustOn,
79 safeDirectImpsReq, safeImplicitImpsReq,
80 unsafeFlags, unsafeFlagsForInfer,
81
82 -- ** LLVM Targets
83 LlvmTarget(..), LlvmTargets, LlvmPasses, LlvmConfig,
84
85 -- ** System tool settings and locations
86 Settings(..),
87 targetPlatform, programName, projectVersion,
88 ghcUsagePath, ghciUsagePath, topDir, tmpDir, rawSettings,
89 versionedAppDir,
90 extraGccViaCFlags, systemPackageConfig,
91 pgm_L, pgm_P, pgm_F, pgm_c, pgm_s, pgm_a, pgm_l, pgm_dll, pgm_T,
92 pgm_windres, pgm_libtool, pgm_ar, pgm_ranlib, pgm_lo, pgm_lc,
93 pgm_lcc, pgm_i, opt_L, opt_P, opt_F, opt_c, opt_a, opt_l, opt_i,
94 opt_P_signature,
95 opt_windres, opt_lo, opt_lc, opt_lcc,
96
97 -- ** Manipulating DynFlags
98 addPluginModuleName,
99 defaultDynFlags, -- Settings -> DynFlags
100 defaultWays,
101 interpWays,
102 interpreterProfiled, interpreterDynamic,
103 initDynFlags, -- DynFlags -> IO DynFlags
104 defaultFatalMessager,
105 defaultLogAction,
106 defaultLogActionHPrintDoc,
107 defaultLogActionHPutStrDoc,
108 defaultFlushOut,
109 defaultFlushErr,
110
111 getOpts, -- DynFlags -> (DynFlags -> [a]) -> [a]
112 getVerbFlags,
113 updOptLevel,
114 setTmpDir,
115 setUnitId,
116 interpretPackageEnv,
117 canonicalizeHomeModule,
118 canonicalizeModuleIfHome,
119
120 -- ** Parsing DynFlags
121 parseDynamicFlagsCmdLine,
122 parseDynamicFilePragma,
123 parseDynamicFlagsFull,
124
125 -- ** Available DynFlags
126 allNonDeprecatedFlags,
127 flagsAll,
128 flagsDynamic,
129 flagsPackage,
130 flagsForCompletion,
131
132 supportedLanguagesAndExtensions,
133 languageExtensions,
134
135 -- ** DynFlags C compiler options
136 picCCOpts, picPOpts,
137
138 -- * Compiler configuration suitable for display to the user
139 compilerInfo,
140
141 rtsIsProfiled,
142 dynamicGhc,
143
144 #include "GHCConstantsHaskellExports.hs"
145 bLOCK_SIZE_W,
146 wORD_SIZE_IN_BITS,
147 tAG_MASK,
148 mAX_PTR_TAG,
149 tARGET_MIN_INT, tARGET_MAX_INT, tARGET_MAX_WORD,
150
151 unsafeGlobalDynFlags, setUnsafeGlobalDynFlags,
152
153 -- * SSE and AVX
154 isSseEnabled,
155 isSse2Enabled,
156 isSse4_2Enabled,
157 isBmiEnabled,
158 isBmi2Enabled,
159 isAvxEnabled,
160 isAvx2Enabled,
161 isAvx512cdEnabled,
162 isAvx512erEnabled,
163 isAvx512fEnabled,
164 isAvx512pfEnabled,
165
166 -- * Linker/compiler information
167 LinkerInfo(..),
168 CompilerInfo(..),
169
170 -- * File cleanup
171 FilesToClean(..), emptyFilesToClean,
172
173 -- * Include specifications
174 IncludeSpecs(..), addGlobalInclude, addQuoteInclude, flattenIncludes,
175
176
177 -- * Make use of the Cmm CFG
178 CfgWeights(..), backendMaintainsCfg
179 ) where
180
181 #include "HsVersions.h"
182
183 import GhcPrelude
184
185 import Platform
186 import PlatformConstants
187 import Module
188 import PackageConfig
189 import {-# SOURCE #-} Plugins
190 import {-# SOURCE #-} Hooks
191 import {-# SOURCE #-} PrelNames ( mAIN )
192 import {-# SOURCE #-} Packages (PackageState, emptyPackageState)
193 import DriverPhases ( Phase(..), phaseInputExt )
194 import Config
195 import CmdLineParser hiding (WarnReason(..))
196 import qualified CmdLineParser as Cmd
197 import Constants
198 import Panic
199 import qualified PprColour as Col
200 import Util
201 import Maybes
202 import MonadUtils
203 import qualified Pretty
204 import SrcLoc
205 import BasicTypes ( IntWithInf, treatZeroAsInf )
206 import FastString
207 import Fingerprint
208 import Outputable
209 import Foreign.C ( CInt(..) )
210 import System.IO.Unsafe ( unsafeDupablePerformIO )
211 import {-# SOURCE #-} ErrUtils ( Severity(..), MsgDoc, mkLocMessageAnn
212 , getCaretDiagnostic )
213 import Json
214 import SysTools.Terminal ( stderrSupportsAnsiColors )
215 import SysTools.BaseDir ( expandToolDir, expandTopDir )
216
217 import System.IO.Unsafe ( unsafePerformIO )
218 import Data.IORef
219 import Control.Arrow ((&&&))
220 import Control.Monad
221 import Control.Monad.Trans.Class
222 import Control.Monad.Trans.Writer
223 import Control.Monad.Trans.Reader
224 import Control.Monad.Trans.Except
225 import Control.Exception (throwIO)
226
227 import Data.Ord
228 import Data.Bits
229 import Data.Char
230 import Data.Int
231 import Data.List
232 import Data.Map (Map)
233 import qualified Data.Map as Map
234 import Data.Set (Set)
235 import qualified Data.Set as Set
236 import Data.Word
237 import System.FilePath
238 import System.Directory
239 import System.Environment (getEnv, lookupEnv)
240 import System.IO
241 import System.IO.Error
242 import Text.ParserCombinators.ReadP hiding (char)
243 import Text.ParserCombinators.ReadP as R
244
245 import EnumSet (EnumSet)
246 import qualified EnumSet
247
248 import GHC.Foreign (withCString, peekCString)
249 import qualified GHC.LanguageExtensions as LangExt
250
251 #if defined(GHCI)
252 import Foreign (Ptr) -- needed for 2nd stage
253 #endif
254
255 -- Note [Updating flag description in the User's Guide]
256 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
257 --
258 -- If you modify anything in this file please make sure that your changes are
259 -- described in the User's Guide. Please update the flag description in the
260 -- users guide (docs/users_guide) whenever you add or change a flag.
261
262 -- Note [Supporting CLI completion]
263 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
264 --
265 -- The command line interface completion (in for example bash) is an easy way
266 -- for the developer to learn what flags are available from GHC.
267 -- GHC helps by separating which flags are available when compiling with GHC,
268 -- and which flags are available when using GHCi.
269 -- A flag is assumed to either work in both these modes, or only in one of them.
270 -- When adding or changing a flag, please consider for which mode the flag will
271 -- have effect, and annotate it accordingly. For Flags use defFlag, defGhcFlag,
272 -- defGhciFlag, and for FlagSpec use flagSpec or flagGhciSpec.
273
274 -- Note [Adding a language extension]
275 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
276 --
277 -- There are a few steps to adding (or removing) a language extension,
278 --
279 -- * Adding the extension to GHC.LanguageExtensions
280 --
281 -- The Extension type in libraries/ghc-boot-th/GHC/LanguageExtensions/Type.hs
282 -- is the canonical list of language extensions known by GHC.
283 --
284 -- * Adding a flag to DynFlags.xFlags
285 --
286 -- This is fairly self-explanatory. The name should be concise, memorable,
287 -- and consistent with any previous implementations of the similar idea in
288 -- other Haskell compilers.
289 --
290 -- * Adding the flag to the documentation
291 --
292 -- This is the same as any other flag. See
293 -- Note [Updating flag description in the User's Guide]
294 --
295 -- * Adding the flag to Cabal
296 --
297 -- The Cabal library has its own list of all language extensions supported
298 -- by all major compilers. This is the list that user code being uploaded
299 -- to Hackage is checked against to ensure language extension validity.
300 -- Consequently, it is very important that this list remains up-to-date.
301 --
302 -- To this end, there is a testsuite test (testsuite/tests/driver/T4437.hs)
303 -- whose job it is to ensure these GHC's extensions are consistent with
304 -- Cabal.
305 --
306 -- The recommended workflow is,
307 --
308 -- 1. Temporarily add your new language extension to the
309 -- expectedGhcOnlyExtensions list in T4437 to ensure the test doesn't
310 -- break while Cabal is updated.
311 --
312 -- 2. After your GHC change is accepted, submit a Cabal pull request adding
313 -- your new extension to Cabal's list (found in
314 -- Cabal/Language/Haskell/Extension.hs).
315 --
316 -- 3. After your Cabal change is accepted, let the GHC developers know so
317 -- they can update the Cabal submodule and remove the extensions from
318 -- expectedGhcOnlyExtensions.
319 --
320 -- * Adding the flag to the GHC Wiki
321 --
322 -- There is a change log tracking language extension additions and removals
323 -- on the GHC wiki: https://ghc.haskell.org/trac/ghc/wiki/LanguagePragmaHistory
324 --
325 -- See Trac #4437 and #8176.
326
327 -- -----------------------------------------------------------------------------
328 -- DynFlags
329
330 data DumpFlag
331 -- See Note [Updating flag description in the User's Guide]
332
333 -- debugging flags
334 = Opt_D_dump_cmm
335 | Opt_D_dump_cmm_from_stg
336 | Opt_D_dump_cmm_raw
337 | Opt_D_dump_cmm_verbose
338 -- All of the cmm subflags (there are a lot!) automatically
339 -- enabled if you run -ddump-cmm-verbose
340 -- Each flag corresponds to exact stage of Cmm pipeline.
341 | Opt_D_dump_cmm_cfg
342 | Opt_D_dump_cmm_cbe
343 | Opt_D_dump_cmm_switch
344 | Opt_D_dump_cmm_proc
345 | Opt_D_dump_cmm_sp
346 | Opt_D_dump_cmm_sink
347 | Opt_D_dump_cmm_caf
348 | Opt_D_dump_cmm_procmap
349 | Opt_D_dump_cmm_split
350 | Opt_D_dump_cmm_info
351 | Opt_D_dump_cmm_cps
352 -- end cmm subflags
353 | Opt_D_dump_cfg_weights -- ^ Dump the cfg used for block layout.
354 | Opt_D_dump_asm
355 | Opt_D_dump_asm_native
356 | Opt_D_dump_asm_liveness
357 | Opt_D_dump_asm_regalloc
358 | Opt_D_dump_asm_regalloc_stages
359 | Opt_D_dump_asm_conflicts
360 | Opt_D_dump_asm_stats
361 | Opt_D_dump_asm_expanded
362 | Opt_D_dump_llvm
363 | Opt_D_dump_core_stats
364 | Opt_D_dump_deriv
365 | Opt_D_dump_ds
366 | Opt_D_dump_ds_preopt
367 | Opt_D_dump_foreign
368 | Opt_D_dump_inlinings
369 | Opt_D_dump_rule_firings
370 | Opt_D_dump_rule_rewrites
371 | Opt_D_dump_simpl_trace
372 | Opt_D_dump_occur_anal
373 | Opt_D_dump_parsed
374 | Opt_D_dump_parsed_ast
375 | Opt_D_dump_rn
376 | Opt_D_dump_rn_ast
377 | Opt_D_dump_shape
378 | Opt_D_dump_simpl
379 | Opt_D_dump_simpl_iterations
380 | Opt_D_dump_spec
381 | Opt_D_dump_prep
382 | Opt_D_dump_stg
383 | Opt_D_dump_call_arity
384 | Opt_D_dump_exitify
385 | Opt_D_dump_stranal
386 | Opt_D_dump_str_signatures
387 | Opt_D_dump_tc
388 | Opt_D_dump_tc_ast
389 | Opt_D_dump_types
390 | Opt_D_dump_rules
391 | Opt_D_dump_cse
392 | Opt_D_dump_worker_wrapper
393 | Opt_D_dump_rn_trace
394 | Opt_D_dump_rn_stats
395 | Opt_D_dump_opt_cmm
396 | Opt_D_dump_simpl_stats
397 | Opt_D_dump_cs_trace -- Constraint solver in type checker
398 | Opt_D_dump_tc_trace
399 | Opt_D_dump_ec_trace -- Pattern match exhaustiveness checker
400 | Opt_D_dump_if_trace
401 | Opt_D_dump_vt_trace
402 | Opt_D_dump_splices
403 | Opt_D_th_dec_file
404 | Opt_D_dump_BCOs
405 | Opt_D_dump_ticked
406 | Opt_D_dump_rtti
407 | Opt_D_source_stats
408 | Opt_D_verbose_stg2stg
409 | Opt_D_dump_hi
410 | Opt_D_dump_hi_diffs
411 | Opt_D_dump_mod_cycles
412 | Opt_D_dump_mod_map
413 | Opt_D_dump_timings
414 | Opt_D_dump_view_pattern_commoning
415 | Opt_D_verbose_core2core
416 | Opt_D_dump_debug
417 | Opt_D_dump_json
418 | Opt_D_ppr_debug
419 | Opt_D_no_debug_output
420 deriving (Eq, Show, Enum)
421
422
423 -- | Enumerates the simple on-or-off dynamic flags
424 data GeneralFlag
425 -- See Note [Updating flag description in the User's Guide]
426
427 = Opt_DumpToFile -- ^ Append dump output to files instead of stdout.
428 | Opt_D_faststring_stats
429 | Opt_D_dump_minimal_imports
430 | Opt_DoCoreLinting
431 | Opt_DoStgLinting
432 | Opt_DoCmmLinting
433 | Opt_DoAsmLinting
434 | Opt_DoAnnotationLinting
435 | Opt_NoLlvmMangler -- hidden flag
436 | Opt_FastLlvm -- hidden flag
437
438 | Opt_WarnIsError -- -Werror; makes warnings fatal
439 | Opt_ShowWarnGroups -- Show the group a warning belongs to
440 | Opt_HideSourcePaths -- Hide module source/object paths
441
442 | Opt_PrintExplicitForalls
443 | Opt_PrintExplicitKinds
444 | Opt_PrintExplicitCoercions
445 | Opt_PrintExplicitRuntimeReps
446 | Opt_PrintEqualityRelations
447 | Opt_PrintUnicodeSyntax
448 | Opt_PrintExpandedSynonyms
449 | Opt_PrintPotentialInstances
450 | Opt_PrintTypecheckerElaboration
451
452 -- optimisation opts
453 | Opt_CallArity
454 | Opt_Exitification
455 | Opt_Strictness
456 | Opt_LateDmdAnal -- #6087
457 | Opt_KillAbsence
458 | Opt_KillOneShot
459 | Opt_FullLaziness
460 | Opt_FloatIn
461 | Opt_LateSpecialise
462 | Opt_Specialise
463 | Opt_SpecialiseAggressively
464 | Opt_CrossModuleSpecialise
465 | Opt_StaticArgumentTransformation
466 | Opt_CSE
467 | Opt_StgCSE
468 | Opt_StgLiftLams
469 | Opt_LiberateCase
470 | Opt_SpecConstr
471 | Opt_SpecConstrKeen
472 | Opt_DoLambdaEtaExpansion
473 | Opt_IgnoreAsserts
474 | Opt_DoEtaReduction
475 | Opt_CaseMerge
476 | Opt_CaseFolding -- Constant folding through case-expressions
477 | Opt_UnboxStrictFields
478 | Opt_UnboxSmallStrictFields
479 | Opt_DictsCheap
480 | Opt_EnableRewriteRules -- Apply rewrite rules during simplification
481 | Opt_RegsGraph -- do graph coloring register allocation
482 | Opt_RegsIterative -- do iterative coalescing graph coloring register allocation
483 | Opt_PedanticBottoms -- Be picky about how we treat bottom
484 | Opt_LlvmTBAA -- Use LLVM TBAA infastructure for improving AA (hidden flag)
485 | Opt_LlvmFillUndefWithGarbage -- Testing for undef bugs (hidden flag)
486 | Opt_IrrefutableTuples
487 | Opt_CmmSink
488 | Opt_CmmElimCommonBlocks
489 | Opt_AsmShortcutting
490 | Opt_OmitYields
491 | Opt_FunToThunk -- allow WwLib.mkWorkerArgs to remove all value lambdas
492 | Opt_DictsStrict -- be strict in argument dictionaries
493 | Opt_DmdTxDictSel -- use a special demand transformer for dictionary selectors
494 | Opt_Loopification -- See Note [Self-recursive tail calls]
495 | Opt_CfgBlocklayout -- ^ Use the cfg based block layout algorithm.
496 | Opt_WeightlessBlocklayout -- ^ Layout based on last instruction per block.
497 | Opt_CprAnal
498 | Opt_WorkerWrapper
499 | Opt_SolveConstantDicts
500 | Opt_AlignmentSanitisation
501 | Opt_CatchBottoms
502 | Opt_NumConstantFolding
503
504 -- PreInlining is on by default. The option is there just to see how
505 -- bad things get if you turn it off!
506 | Opt_SimplPreInlining
507
508 -- Interface files
509 | Opt_IgnoreInterfacePragmas
510 | Opt_OmitInterfacePragmas
511 | Opt_ExposeAllUnfoldings
512 | Opt_WriteInterface -- forces .hi files to be written even with -fno-code
513
514 -- profiling opts
515 | Opt_AutoSccsOnIndividualCafs
516 | Opt_ProfCountEntries
517
518 -- misc opts
519 | Opt_Pp
520 | Opt_ForceRecomp
521 | Opt_IgnoreOptimChanges
522 | Opt_IgnoreHpcChanges
523 | Opt_ExcessPrecision
524 | Opt_EagerBlackHoling
525 | Opt_NoHsMain
526 | Opt_SplitObjs
527 | Opt_SplitSections
528 | Opt_StgStats
529 | Opt_HideAllPackages
530 | Opt_HideAllPluginPackages
531 | Opt_PrintBindResult
532 | Opt_Haddock
533 | Opt_HaddockOptions
534 | Opt_BreakOnException
535 | Opt_BreakOnError
536 | Opt_PrintEvldWithShow
537 | Opt_PrintBindContents
538 | Opt_GenManifest
539 | Opt_EmbedManifest
540 | Opt_SharedImplib
541 | Opt_BuildingCabalPackage
542 | Opt_IgnoreDotGhci
543 | Opt_GhciSandbox
544 | Opt_GhciHistory
545 | Opt_GhciLeakCheck
546 | Opt_LocalGhciHistory
547 | Opt_NoIt
548 | Opt_HelpfulErrors
549 | Opt_DeferTypeErrors
550 | Opt_DeferTypedHoles
551 | Opt_DeferOutOfScopeVariables
552 | Opt_PIC -- ^ @-fPIC@
553 | Opt_PIE -- ^ @-fPIE@
554 | Opt_PICExecutable -- ^ @-pie@
555 | Opt_ExternalDynamicRefs
556 | Opt_SccProfilingOn
557 | Opt_Ticky
558 | Opt_Ticky_Allocd
559 | Opt_Ticky_LNE
560 | Opt_Ticky_Dyn_Thunk
561 | Opt_RPath
562 | Opt_RelativeDynlibPaths
563 | Opt_Hpc
564 | Opt_FlatCache
565 | Opt_ExternalInterpreter
566 | Opt_OptimalApplicativeDo
567 | Opt_VersionMacros
568 | Opt_WholeArchiveHsLibs
569 -- copy all libs into a single folder prior to linking binaries
570 -- this should elivate the excessive command line limit restrictions
571 -- on windows, by only requiring a single -L argument instead of
572 -- one for each dependency. At the time of this writing, gcc
573 -- forwards all -L flags to the collect2 command without using a
574 -- response file and as such breaking apart.
575 | Opt_SingleLibFolder
576 | Opt_KeepCAFs
577
578 -- output style opts
579 | Opt_ErrorSpans -- Include full span info in error messages,
580 -- instead of just the start position.
581 | Opt_DiagnosticsShowCaret -- Show snippets of offending code
582 | Opt_PprCaseAsLet
583 | Opt_PprShowTicks
584 | Opt_ShowHoleConstraints
585 -- Options relating to the display of valid hole fits
586 -- when generating an error message for a typed hole
587 -- See Note [Valid hole fits include] in TcHoleErrors.hs
588 | Opt_ShowValidHoleFits
589 | Opt_SortValidHoleFits
590 | Opt_SortBySizeHoleFits
591 | Opt_SortBySubsumHoleFits
592 | Opt_AbstractRefHoleFits
593 | Opt_UnclutterValidHoleFits
594 | Opt_ShowTypeAppOfHoleFits
595 | Opt_ShowTypeAppVarsOfHoleFits
596 | Opt_ShowDocsOfHoleFits
597 | Opt_ShowTypeOfHoleFits
598 | Opt_ShowProvOfHoleFits
599 | Opt_ShowMatchesOfHoleFits
600
601 | Opt_ShowLoadedModules
602 | Opt_HexWordLiterals -- See Note [Print Hexadecimal Literals]
603
604 -- Suppress all coercions, them replacing with '...'
605 | Opt_SuppressCoercions
606 | Opt_SuppressVarKinds
607 -- Suppress module id prefixes on variables.
608 | Opt_SuppressModulePrefixes
609 -- Suppress type applications.
610 | Opt_SuppressTypeApplications
611 -- Suppress info such as arity and unfoldings on identifiers.
612 | Opt_SuppressIdInfo
613 -- Suppress separate type signatures in core, but leave types on
614 -- lambda bound vars
615 | Opt_SuppressUnfoldings
616 -- Suppress the details of even stable unfoldings
617 | Opt_SuppressTypeSignatures
618 -- Suppress unique ids on variables.
619 -- Except for uniques, as some simplifier phases introduce new
620 -- variables that have otherwise identical names.
621 | Opt_SuppressUniques
622 | Opt_SuppressStgExts
623 | Opt_SuppressTicks -- Replaces Opt_PprShowTicks
624 | Opt_SuppressTimestamps -- ^ Suppress timestamps in dumps
625
626 -- temporary flags
627 | Opt_AutoLinkPackages
628 | Opt_ImplicitImportQualified
629
630 -- keeping stuff
631 | Opt_KeepHscppFiles
632 | Opt_KeepHiDiffs
633 | Opt_KeepHcFiles
634 | Opt_KeepSFiles
635 | Opt_KeepTmpFiles
636 | Opt_KeepRawTokenStream
637 | Opt_KeepLlvmFiles
638 | Opt_KeepHiFiles
639 | Opt_KeepOFiles
640
641 | Opt_BuildDynamicToo
642
643 -- safe haskell flags
644 | Opt_DistrustAllPackages
645 | Opt_PackageTrust
646
647 | Opt_G_NoStateHack
648 | Opt_G_NoOptCoercion
649 deriving (Eq, Show, Enum)
650
651 -- Check whether a flag should be considered an "optimisation flag"
652 -- for purposes of recompilation avoidance (see
653 -- Note [Ignoring some flag changes] in FlagChecker). Being listed here is
654 -- not a guarantee that the flag has no other effect. We could, and
655 -- perhaps should, separate out the flags that have some minor impact on
656 -- program semantics and/or error behavior (e.g., assertions), but
657 -- then we'd need to go to extra trouble (and an additional flag)
658 -- to allow users to ignore the optimisation level even though that
659 -- means ignoring some change.
660 optimisationFlags :: EnumSet GeneralFlag
661 optimisationFlags = EnumSet.fromList
662 [ Opt_CallArity
663 , Opt_Strictness
664 , Opt_LateDmdAnal
665 , Opt_KillAbsence
666 , Opt_KillOneShot
667 , Opt_FullLaziness
668 , Opt_FloatIn
669 , Opt_LateSpecialise
670 , Opt_Specialise
671 , Opt_SpecialiseAggressively
672 , Opt_CrossModuleSpecialise
673 , Opt_StaticArgumentTransformation
674 , Opt_CSE
675 , Opt_StgCSE
676 , Opt_StgLiftLams
677 , Opt_LiberateCase
678 , Opt_SpecConstr
679 , Opt_SpecConstrKeen
680 , Opt_DoLambdaEtaExpansion
681 , Opt_IgnoreAsserts
682 , Opt_DoEtaReduction
683 , Opt_CaseMerge
684 , Opt_CaseFolding
685 , Opt_UnboxStrictFields
686 , Opt_UnboxSmallStrictFields
687 , Opt_DictsCheap
688 , Opt_EnableRewriteRules
689 , Opt_RegsGraph
690 , Opt_RegsIterative
691 , Opt_PedanticBottoms
692 , Opt_LlvmTBAA
693 , Opt_LlvmFillUndefWithGarbage
694 , Opt_IrrefutableTuples
695 , Opt_CmmSink
696 , Opt_CmmElimCommonBlocks
697 , Opt_AsmShortcutting
698 , Opt_OmitYields
699 , Opt_FunToThunk
700 , Opt_DictsStrict
701 , Opt_DmdTxDictSel
702 , Opt_Loopification
703 , Opt_CfgBlocklayout
704 , Opt_WeightlessBlocklayout
705 , Opt_CprAnal
706 , Opt_WorkerWrapper
707 , Opt_SolveConstantDicts
708 , Opt_CatchBottoms
709 , Opt_IgnoreAsserts
710 ]
711
712 -- | Used when outputting warnings: if a reason is given, it is
713 -- displayed. If a warning isn't controlled by a flag, this is made
714 -- explicit at the point of use.
715 data WarnReason
716 = NoReason
717 -- | Warning was enabled with the flag
718 | Reason !WarningFlag
719 -- | Warning was made an error because of -Werror or -Werror=WarningFlag
720 | ErrReason !(Maybe WarningFlag)
721 deriving Show
722
723 -- | Used to differentiate the scope an include needs to apply to.
724 -- We have to split the include paths to avoid accidentally forcing recursive
725 -- includes since -I overrides the system search paths. See Trac #14312.
726 data IncludeSpecs
727 = IncludeSpecs { includePathsQuote :: [String]
728 , includePathsGlobal :: [String]
729 }
730 deriving Show
731
732 -- | Append to the list of includes a path that shall be included using `-I`
733 -- when the C compiler is called. These paths override system search paths.
734 addGlobalInclude :: IncludeSpecs -> [String] -> IncludeSpecs
735 addGlobalInclude spec paths = let f = includePathsGlobal spec
736 in spec { includePathsGlobal = f ++ paths }
737
738 -- | Append to the list of includes a path that shall be included using
739 -- `-iquote` when the C compiler is called. These paths only apply when quoted
740 -- includes are used. e.g. #include "foo.h"
741 addQuoteInclude :: IncludeSpecs -> [String] -> IncludeSpecs
742 addQuoteInclude spec paths = let f = includePathsQuote spec
743 in spec { includePathsQuote = f ++ paths }
744
745 -- | Concatenate and flatten the list of global and quoted includes returning
746 -- just a flat list of paths.
747 flattenIncludes :: IncludeSpecs -> [String]
748 flattenIncludes specs = includePathsQuote specs ++ includePathsGlobal specs
749
750 instance Outputable WarnReason where
751 ppr = text . show
752
753 instance ToJson WarnReason where
754 json NoReason = JSNull
755 json (Reason wf) = JSString (show wf)
756 json (ErrReason Nothing) = JSString "Opt_WarnIsError"
757 json (ErrReason (Just wf)) = JSString (show wf)
758
759 data WarningFlag =
760 -- See Note [Updating flag description in the User's Guide]
761 Opt_WarnDuplicateExports
762 | Opt_WarnDuplicateConstraints
763 | Opt_WarnRedundantConstraints
764 | Opt_WarnHiShadows
765 | Opt_WarnImplicitPrelude
766 | Opt_WarnIncompletePatterns
767 | Opt_WarnIncompleteUniPatterns
768 | Opt_WarnIncompletePatternsRecUpd
769 | Opt_WarnOverflowedLiterals
770 | Opt_WarnEmptyEnumerations
771 | Opt_WarnMissingFields
772 | Opt_WarnMissingImportList
773 | Opt_WarnMissingMethods
774 | Opt_WarnMissingSignatures
775 | Opt_WarnMissingLocalSignatures
776 | Opt_WarnNameShadowing
777 | Opt_WarnOverlappingPatterns
778 | Opt_WarnTypeDefaults
779 | Opt_WarnMonomorphism
780 | Opt_WarnUnusedTopBinds
781 | Opt_WarnUnusedLocalBinds
782 | Opt_WarnUnusedPatternBinds
783 | Opt_WarnUnusedImports
784 | Opt_WarnUnusedMatches
785 | Opt_WarnUnusedTypePatterns
786 | Opt_WarnUnusedForalls
787 | Opt_WarnWarningsDeprecations
788 | Opt_WarnDeprecatedFlags
789 | Opt_WarnMissingMonadFailInstances -- since 8.0
790 | Opt_WarnSemigroup -- since 8.0
791 | Opt_WarnDodgyExports
792 | Opt_WarnDodgyImports
793 | Opt_WarnOrphans
794 | Opt_WarnAutoOrphans
795 | Opt_WarnIdentities
796 | Opt_WarnTabs
797 | Opt_WarnUnrecognisedPragmas
798 | Opt_WarnDodgyForeignImports
799 | Opt_WarnUnusedDoBind
800 | Opt_WarnWrongDoBind
801 | Opt_WarnAlternativeLayoutRuleTransitional
802 | Opt_WarnUnsafe
803 | Opt_WarnSafe
804 | Opt_WarnTrustworthySafe
805 | Opt_WarnMissedSpecs
806 | Opt_WarnAllMissedSpecs
807 | Opt_WarnUnsupportedCallingConventions
808 | Opt_WarnUnsupportedLlvmVersion
809 | Opt_WarnInlineRuleShadowing
810 | Opt_WarnTypedHoles
811 | Opt_WarnPartialTypeSignatures
812 | Opt_WarnMissingExportedSignatures
813 | Opt_WarnUntickedPromotedConstructors
814 | Opt_WarnDerivingTypeable
815 | Opt_WarnDeferredTypeErrors
816 | Opt_WarnDeferredOutOfScopeVariables
817 | Opt_WarnNonCanonicalMonadInstances -- since 8.0
818 | Opt_WarnNonCanonicalMonadFailInstances -- since 8.0
819 | Opt_WarnNonCanonicalMonoidInstances -- since 8.0
820 | Opt_WarnMissingPatternSynonymSignatures -- since 8.0
821 | Opt_WarnUnrecognisedWarningFlags -- since 8.0
822 | Opt_WarnSimplifiableClassConstraints -- Since 8.2
823 | Opt_WarnCPPUndef -- Since 8.2
824 | Opt_WarnUnbangedStrictPatterns -- Since 8.2
825 | Opt_WarnMissingHomeModules -- Since 8.2
826 | Opt_WarnPartialFields -- Since 8.4
827 | Opt_WarnMissingExportList
828 | Opt_WarnInaccessibleCode
829 | Opt_WarnStarIsType -- Since 8.6
830 | Opt_WarnStarBinder -- Since 8.6
831 | Opt_WarnImplicitKindVars -- Since 8.6
832 | Opt_WarnSpaceAfterBang
833 deriving (Eq, Show, Enum)
834
835 data Language = Haskell98 | Haskell2010
836 deriving (Eq, Enum, Show)
837
838 instance Outputable Language where
839 ppr = text . show
840
841 -- | The various Safe Haskell modes
842 data SafeHaskellMode
843 = Sf_None
844 | Sf_Unsafe
845 | Sf_Trustworthy
846 | Sf_Safe
847 deriving (Eq)
848
849 instance Show SafeHaskellMode where
850 show Sf_None = "None"
851 show Sf_Unsafe = "Unsafe"
852 show Sf_Trustworthy = "Trustworthy"
853 show Sf_Safe = "Safe"
854
855 instance Outputable SafeHaskellMode where
856 ppr = text . show
857
858 -- | Contains not only a collection of 'GeneralFlag's but also a plethora of
859 -- information relating to the compilation of a single file or GHC session
860 data DynFlags = DynFlags {
861 ghcMode :: GhcMode,
862 ghcLink :: GhcLink,
863 hscTarget :: HscTarget,
864 settings :: Settings,
865 integerLibrary :: IntegerLibrary,
866 -- ^ IntegerGMP or IntegerSimple. Set at configure time, but may be overriden
867 -- by GHC-API users. See Note [The integer library] in PrelNames
868 llvmTargets :: LlvmTargets,
869 llvmPasses :: LlvmPasses,
870 verbosity :: Int, -- ^ Verbosity level: see Note [Verbosity levels]
871 optLevel :: Int, -- ^ Optimisation level
872 debugLevel :: Int, -- ^ How much debug information to produce
873 simplPhases :: Int, -- ^ Number of simplifier phases
874 maxSimplIterations :: Int, -- ^ Max simplifier iterations
875 maxPmCheckIterations :: Int, -- ^ Max no iterations for pm checking
876 ruleCheck :: Maybe String,
877 inlineCheck :: Maybe String, -- ^ A prefix to report inlining decisions about
878 strictnessBefore :: [Int], -- ^ Additional demand analysis
879
880 parMakeCount :: Maybe Int, -- ^ The number of modules to compile in parallel
881 -- in --make mode, where Nothing ==> compile as
882 -- many in parallel as there are CPUs.
883
884 enableTimeStats :: Bool, -- ^ Enable RTS timing statistics?
885 ghcHeapSize :: Maybe Int, -- ^ The heap size to set.
886
887 maxRelevantBinds :: Maybe Int, -- ^ Maximum number of bindings from the type envt
888 -- to show in type error messages
889 maxValidHoleFits :: Maybe Int, -- ^ Maximum number of hole fits to show
890 -- in typed hole error messages
891 maxRefHoleFits :: Maybe Int, -- ^ Maximum number of refinement hole
892 -- fits to show in typed hole error
893 -- messages
894 refLevelHoleFits :: Maybe Int, -- ^ Maximum level of refinement for
895 -- refinement hole fits in typed hole
896 -- error messages
897 maxUncoveredPatterns :: Int, -- ^ Maximum number of unmatched patterns to show
898 -- in non-exhaustiveness warnings
899 simplTickFactor :: Int, -- ^ Multiplier for simplifier ticks
900 specConstrThreshold :: Maybe Int, -- ^ Threshold for SpecConstr
901 specConstrCount :: Maybe Int, -- ^ Max number of specialisations for any one function
902 specConstrRecursive :: Int, -- ^ Max number of specialisations for recursive types
903 -- Not optional; otherwise ForceSpecConstr can diverge.
904 liberateCaseThreshold :: Maybe Int, -- ^ Threshold for LiberateCase
905 floatLamArgs :: Maybe Int, -- ^ Arg count for lambda floating
906 -- See CoreMonad.FloatOutSwitches
907
908 liftLamsRecArgs :: Maybe Int, -- ^ Maximum number of arguments after lambda lifting a
909 -- recursive function.
910 liftLamsNonRecArgs :: Maybe Int, -- ^ Maximum number of arguments after lambda lifting a
911 -- non-recursive function.
912 liftLamsKnown :: Bool, -- ^ Lambda lift even when this turns a known call
913 -- into an unknown call.
914
915 cmmProcAlignment :: Maybe Int, -- ^ Align Cmm functions at this boundary or use default.
916
917 historySize :: Int, -- ^ Simplification history size
918
919 importPaths :: [FilePath],
920 mainModIs :: Module,
921 mainFunIs :: Maybe String,
922 reductionDepth :: IntWithInf, -- ^ Typechecker maximum stack depth
923 solverIterations :: IntWithInf, -- ^ Number of iterations in the constraints solver
924 -- Typically only 1 is needed
925
926 thisInstalledUnitId :: InstalledUnitId,
927 thisComponentId_ :: Maybe ComponentId,
928 thisUnitIdInsts_ :: Maybe [(ModuleName, Module)],
929
930 -- ways
931 ways :: [Way], -- ^ Way flags from the command line
932 buildTag :: String, -- ^ The global \"way\" (e.g. \"p\" for prof)
933
934 -- For object splitting
935 splitInfo :: Maybe (String,Int),
936
937 -- paths etc.
938 objectDir :: Maybe String,
939 dylibInstallName :: Maybe String,
940 hiDir :: Maybe String,
941 stubDir :: Maybe String,
942 dumpDir :: Maybe String,
943
944 objectSuf :: String,
945 hcSuf :: String,
946 hiSuf :: String,
947
948 canGenerateDynamicToo :: IORef Bool,
949 dynObjectSuf :: String,
950 dynHiSuf :: String,
951
952 outputFile :: Maybe String,
953 dynOutputFile :: Maybe String,
954 outputHi :: Maybe String,
955 dynLibLoader :: DynLibLoader,
956
957 -- | This is set by 'DriverPipeline.runPipeline' based on where
958 -- its output is going.
959 dumpPrefix :: Maybe FilePath,
960
961 -- | Override the 'dumpPrefix' set by 'DriverPipeline.runPipeline'.
962 -- Set by @-ddump-file-prefix@
963 dumpPrefixForce :: Maybe FilePath,
964
965 ldInputs :: [Option],
966
967 includePaths :: IncludeSpecs,
968 libraryPaths :: [String],
969 frameworkPaths :: [String], -- used on darwin only
970 cmdlineFrameworks :: [String], -- ditto
971
972 rtsOpts :: Maybe String,
973 rtsOptsEnabled :: RtsOptsEnabled,
974 rtsOptsSuggestions :: Bool,
975
976 hpcDir :: String, -- ^ Path to store the .mix files
977
978 -- Plugins
979 pluginModNames :: [ModuleName],
980 pluginModNameOpts :: [(ModuleName,String)],
981 frontendPluginOpts :: [String],
982 -- ^ the @-ffrontend-opt@ flags given on the command line, in *reverse*
983 -- order that they're specified on the command line.
984 plugins :: [LoadedPlugin],
985 -- ^ plugins loaded after processing arguments. What will be loaded here
986 -- is directed by pluginModNames. Arguments are loaded from
987 -- pluginModNameOpts. The purpose of this field is to cache the plugins so
988 -- they don't have to be loaded each time they are needed.
989 -- See 'DynamicLoading.initializePlugins'.
990
991 -- GHC API hooks
992 hooks :: Hooks,
993
994 -- For ghc -M
995 depMakefile :: FilePath,
996 depIncludePkgDeps :: Bool,
997 depExcludeMods :: [ModuleName],
998 depSuffixes :: [String],
999
1000 -- Package flags
1001 packageDBFlags :: [PackageDBFlag],
1002 -- ^ The @-package-db@ flags given on the command line, In
1003 -- *reverse* order that they're specified on the command line.
1004 -- This is intended to be applied with the list of "initial"
1005 -- package databases derived from @GHC_PACKAGE_PATH@; see
1006 -- 'getPackageConfRefs'.
1007
1008 ignorePackageFlags :: [IgnorePackageFlag],
1009 -- ^ The @-ignore-package@ flags from the command line.
1010 -- In *reverse* order that they're specified on the command line.
1011 packageFlags :: [PackageFlag],
1012 -- ^ The @-package@ and @-hide-package@ flags from the command-line.
1013 -- In *reverse* order that they're specified on the command line.
1014 pluginPackageFlags :: [PackageFlag],
1015 -- ^ The @-plugin-package-id@ flags from command line.
1016 -- In *reverse* order that they're specified on the command line.
1017 trustFlags :: [TrustFlag],
1018 -- ^ The @-trust@ and @-distrust@ flags.
1019 -- In *reverse* order that they're specified on the command line.
1020 packageEnv :: Maybe FilePath,
1021 -- ^ Filepath to the package environment file (if overriding default)
1022
1023 -- Package state
1024 -- NB. do not modify this field, it is calculated by
1025 -- Packages.initPackages
1026 pkgDatabase :: Maybe [(FilePath, [PackageConfig])],
1027 pkgState :: PackageState,
1028
1029 -- Temporary files
1030 -- These have to be IORefs, because the defaultCleanupHandler needs to
1031 -- know what to clean when an exception happens
1032 filesToClean :: IORef FilesToClean,
1033 dirsToClean :: IORef (Map FilePath FilePath),
1034 -- The next available suffix to uniquely name a temp file, updated atomically
1035 nextTempSuffix :: IORef Int,
1036
1037 -- Names of files which were generated from -ddump-to-file; used to
1038 -- track which ones we need to truncate because it's our first run
1039 -- through
1040 generatedDumps :: IORef (Set FilePath),
1041
1042 -- hsc dynamic flags
1043 dumpFlags :: EnumSet DumpFlag,
1044 generalFlags :: EnumSet GeneralFlag,
1045 warningFlags :: EnumSet WarningFlag,
1046 fatalWarningFlags :: EnumSet WarningFlag,
1047 -- Don't change this without updating extensionFlags:
1048 language :: Maybe Language,
1049 -- | Safe Haskell mode
1050 safeHaskell :: SafeHaskellMode,
1051 safeInfer :: Bool,
1052 safeInferred :: Bool,
1053 -- We store the location of where some extension and flags were turned on so
1054 -- we can produce accurate error messages when Safe Haskell fails due to
1055 -- them.
1056 thOnLoc :: SrcSpan,
1057 newDerivOnLoc :: SrcSpan,
1058 overlapInstLoc :: SrcSpan,
1059 incoherentOnLoc :: SrcSpan,
1060 pkgTrustOnLoc :: SrcSpan,
1061 warnSafeOnLoc :: SrcSpan,
1062 warnUnsafeOnLoc :: SrcSpan,
1063 trustworthyOnLoc :: SrcSpan,
1064 -- Don't change this without updating extensionFlags:
1065 extensions :: [OnOff LangExt.Extension],
1066 -- extensionFlags should always be equal to
1067 -- flattenExtensionFlags language extensions
1068 -- LangExt.Extension is defined in libraries/ghc-boot so that it can be used
1069 -- by template-haskell
1070 extensionFlags :: EnumSet LangExt.Extension,
1071
1072 -- Unfolding control
1073 -- See Note [Discounts and thresholds] in CoreUnfold
1074 ufCreationThreshold :: Int,
1075 ufUseThreshold :: Int,
1076 ufFunAppDiscount :: Int,
1077 ufDictDiscount :: Int,
1078 ufKeenessFactor :: Float,
1079 ufDearOp :: Int,
1080 ufVeryAggressive :: Bool,
1081
1082 maxWorkerArgs :: Int,
1083
1084 ghciHistSize :: Int,
1085
1086 -- | MsgDoc output action: use "ErrUtils" instead of this if you can
1087 log_action :: LogAction,
1088 flushOut :: FlushOut,
1089 flushErr :: FlushErr,
1090
1091 ghcVersionFile :: Maybe FilePath,
1092 haddockOptions :: Maybe String,
1093
1094 -- | GHCi scripts specified by -ghci-script, in reverse order
1095 ghciScripts :: [String],
1096
1097 -- Output style options
1098 pprUserLength :: Int,
1099 pprCols :: Int,
1100
1101 useUnicode :: Bool,
1102 useColor :: OverridingBool,
1103 canUseColor :: Bool,
1104 colScheme :: Col.Scheme,
1105
1106 -- | what kind of {-# SCC #-} to add automatically
1107 profAuto :: ProfAuto,
1108
1109 interactivePrint :: Maybe String,
1110
1111 nextWrapperNum :: IORef (ModuleEnv Int),
1112
1113 -- | Machine dependent flags (-m<blah> stuff)
1114 sseVersion :: Maybe SseVersion,
1115 bmiVersion :: Maybe BmiVersion,
1116 avx :: Bool,
1117 avx2 :: Bool,
1118 avx512cd :: Bool, -- Enable AVX-512 Conflict Detection Instructions.
1119 avx512er :: Bool, -- Enable AVX-512 Exponential and Reciprocal Instructions.
1120 avx512f :: Bool, -- Enable AVX-512 instructions.
1121 avx512pf :: Bool, -- Enable AVX-512 PreFetch Instructions.
1122
1123 -- | Run-time linker information (what options we need, etc.)
1124 rtldInfo :: IORef (Maybe LinkerInfo),
1125
1126 -- | Run-time compiler information
1127 rtccInfo :: IORef (Maybe CompilerInfo),
1128
1129 -- Constants used to control the amount of optimization done.
1130
1131 -- | Max size, in bytes, of inline array allocations.
1132 maxInlineAllocSize :: Int,
1133
1134 -- | Only inline memcpy if it generates no more than this many
1135 -- pseudo (roughly: Cmm) instructions.
1136 maxInlineMemcpyInsns :: Int,
1137
1138 -- | Only inline memset if it generates no more than this many
1139 -- pseudo (roughly: Cmm) instructions.
1140 maxInlineMemsetInsns :: Int,
1141
1142 -- | Reverse the order of error messages in GHC/GHCi
1143 reverseErrors :: Bool,
1144
1145 -- | Limit the maximum number of errors to show
1146 maxErrors :: Maybe Int,
1147
1148 -- | Unique supply configuration for testing build determinism
1149 initialUnique :: Int,
1150 uniqueIncrement :: Int,
1151
1152 -- | Temporary: CFG Edge weights for fast iterations
1153 cfgWeightInfo :: CfgWeights
1154 }
1155
1156 -- | Edge weights to use when generating a CFG from CMM
1157 data CfgWeights
1158 = CFGWeights
1159 { uncondWeight :: Int
1160 , condBranchWeight :: Int
1161 , switchWeight :: Int
1162 , callWeight :: Int
1163 , likelyCondWeight :: Int
1164 , unlikelyCondWeight :: Int
1165 , infoTablePenalty :: Int
1166 , backEdgeBonus :: Int
1167 }
1168
1169 defaultCfgWeights :: CfgWeights
1170 defaultCfgWeights
1171 = CFGWeights
1172 { uncondWeight = 1000
1173 , condBranchWeight = 800
1174 , switchWeight = 1
1175 , callWeight = -10
1176 , likelyCondWeight = 900
1177 , unlikelyCondWeight = 300
1178 , infoTablePenalty = 300
1179 , backEdgeBonus = 400
1180 }
1181
1182 parseCfgWeights :: String -> CfgWeights -> CfgWeights
1183 parseCfgWeights s oldWeights =
1184 foldl' (\cfg (n,v) -> update n v cfg) oldWeights assignments
1185 where
1186 assignments = map assignment $ settings s
1187 update "uncondWeight" n w =
1188 w {uncondWeight = n}
1189 update "condBranchWeight" n w =
1190 w {condBranchWeight = n}
1191 update "switchWeight" n w =
1192 w {switchWeight = n}
1193 update "callWeight" n w =
1194 w {callWeight = n}
1195 update "likelyCondWeight" n w =
1196 w {likelyCondWeight = n}
1197 update "unlikelyCondWeight" n w =
1198 w {unlikelyCondWeight = n}
1199 update "infoTablePenalty" n w =
1200 w {infoTablePenalty = n}
1201 update "backEdgeBonus" n w =
1202 w {backEdgeBonus = n}
1203 update other _ _
1204 = panic $ other ++
1205 " is not a cfg weight parameter. " ++
1206 exampleString
1207 settings s
1208 | (s1,rest) <- break (== ',') s
1209 , null rest
1210 = [s1]
1211 | (s1,rest) <- break (== ',') s
1212 = [s1] ++ settings (drop 1 rest)
1213 | otherwise = panic $ "Invalid cfg parameters." ++ exampleString
1214 assignment as
1215 | (name, _:val) <- break (== '=') as
1216 = (name,read val)
1217 | otherwise
1218 = panic $ "Invalid cfg parameters." ++ exampleString
1219 exampleString = "Example parameters: uncondWeight=1000," ++
1220 "condBranchWeight=800,switchWeight=0,callWeight=300" ++
1221 ",likelyCondWeight=900,unlikelyCondWeight=300" ++
1222 ",infoTablePenalty=300,backEdgeBonus=400"
1223
1224 backendMaintainsCfg :: DynFlags -> Bool
1225 backendMaintainsCfg dflags = case (platformArch $ targetPlatform dflags) of
1226 -- ArchX86 -- Should work but not tested so disabled currently.
1227 ArchX86_64 -> True
1228 _otherwise -> False
1229
1230 class HasDynFlags m where
1231 getDynFlags :: m DynFlags
1232
1233 {- It would be desirable to have the more generalised
1234
1235 instance (MonadTrans t, Monad m, HasDynFlags m) => HasDynFlags (t m) where
1236 getDynFlags = lift getDynFlags
1237
1238 instance definition. However, that definition would overlap with the
1239 `HasDynFlags (GhcT m)` instance. Instead we define instances for a
1240 couple of common Monad transformers explicitly. -}
1241
1242 instance (Monoid a, Monad m, HasDynFlags m) => HasDynFlags (WriterT a m) where
1243 getDynFlags = lift getDynFlags
1244
1245 instance (Monad m, HasDynFlags m) => HasDynFlags (ReaderT a m) where
1246 getDynFlags = lift getDynFlags
1247
1248 instance (Monad m, HasDynFlags m) => HasDynFlags (MaybeT m) where
1249 getDynFlags = lift getDynFlags
1250
1251 instance (Monad m, HasDynFlags m) => HasDynFlags (ExceptT e m) where
1252 getDynFlags = lift getDynFlags
1253
1254 class ContainsDynFlags t where
1255 extractDynFlags :: t -> DynFlags
1256
1257 data ProfAuto
1258 = NoProfAuto -- ^ no SCC annotations added
1259 | ProfAutoAll -- ^ top-level and nested functions are annotated
1260 | ProfAutoTop -- ^ top-level functions annotated only
1261 | ProfAutoExports -- ^ exported functions annotated only
1262 | ProfAutoCalls -- ^ annotate call-sites
1263 deriving (Eq,Enum)
1264
1265 data LlvmTarget = LlvmTarget
1266 { lDataLayout :: String
1267 , lCPU :: String
1268 , lAttributes :: [String]
1269 }
1270
1271 type LlvmTargets = [(String, LlvmTarget)]
1272 type LlvmPasses = [(Int, String)]
1273 type LlvmConfig = (LlvmTargets, LlvmPasses)
1274
1275 data Settings = Settings {
1276 sTargetPlatform :: Platform, -- Filled in by SysTools
1277 sGhcUsagePath :: FilePath, -- ditto
1278 sGhciUsagePath :: FilePath, -- ditto
1279 sToolDir :: Maybe FilePath, -- ditto
1280 sTopDir :: FilePath, -- ditto
1281 sTmpDir :: String, -- no trailing '/'
1282 sProgramName :: String,
1283 sProjectVersion :: String,
1284 -- You shouldn't need to look things up in rawSettings directly.
1285 -- They should have their own fields instead.
1286 sRawSettings :: [(String, String)],
1287 sExtraGccViaCFlags :: [String],
1288 sSystemPackageConfig :: FilePath,
1289 sLdSupportsCompactUnwind :: Bool,
1290 sLdSupportsBuildId :: Bool,
1291 sLdSupportsFilelist :: Bool,
1292 sLdIsGnuLd :: Bool,
1293 sGccSupportsNoPie :: Bool,
1294 -- commands for particular phases
1295 sPgm_L :: String,
1296 sPgm_P :: (String,[Option]),
1297 sPgm_F :: String,
1298 sPgm_c :: (String,[Option]),
1299 sPgm_s :: (String,[Option]),
1300 sPgm_a :: (String,[Option]),
1301 sPgm_l :: (String,[Option]),
1302 sPgm_dll :: (String,[Option]),
1303 sPgm_T :: String,
1304 sPgm_windres :: String,
1305 sPgm_libtool :: String,
1306 sPgm_ar :: String,
1307 sPgm_ranlib :: String,
1308 sPgm_lo :: (String,[Option]), -- LLVM: opt llvm optimiser
1309 sPgm_lc :: (String,[Option]), -- LLVM: llc static compiler
1310 sPgm_lcc :: (String,[Option]), -- LLVM: c compiler
1311 sPgm_i :: String,
1312 -- options for particular phases
1313 sOpt_L :: [String],
1314 sOpt_P :: [String],
1315 sOpt_P_fingerprint :: Fingerprint, -- cached Fingerprint of sOpt_P
1316 -- See Note [Repeated -optP hashing]
1317 sOpt_F :: [String],
1318 sOpt_c :: [String],
1319 sOpt_a :: [String],
1320 sOpt_l :: [String],
1321 sOpt_windres :: [String],
1322 sOpt_lo :: [String], -- LLVM: llvm optimiser
1323 sOpt_lc :: [String], -- LLVM: llc static compiler
1324 sOpt_lcc :: [String], -- LLVM: c compiler
1325 sOpt_i :: [String], -- iserv options
1326
1327 sPlatformConstants :: PlatformConstants
1328 }
1329
1330 targetPlatform :: DynFlags -> Platform
1331 targetPlatform dflags = sTargetPlatform (settings dflags)
1332 programName :: DynFlags -> String
1333 programName dflags = sProgramName (settings dflags)
1334 projectVersion :: DynFlags -> String
1335 projectVersion dflags = sProjectVersion (settings dflags)
1336 ghcUsagePath :: DynFlags -> FilePath
1337 ghcUsagePath dflags = sGhcUsagePath (settings dflags)
1338 ghciUsagePath :: DynFlags -> FilePath
1339 ghciUsagePath dflags = sGhciUsagePath (settings dflags)
1340 toolDir :: DynFlags -> Maybe FilePath
1341 toolDir dflags = sToolDir (settings dflags)
1342 topDir :: DynFlags -> FilePath
1343 topDir dflags = sTopDir (settings dflags)
1344 tmpDir :: DynFlags -> String
1345 tmpDir dflags = sTmpDir (settings dflags)
1346 rawSettings :: DynFlags -> [(String, String)]
1347 rawSettings dflags = sRawSettings (settings dflags)
1348 extraGccViaCFlags :: DynFlags -> [String]
1349 extraGccViaCFlags dflags = sExtraGccViaCFlags (settings dflags)
1350 systemPackageConfig :: DynFlags -> FilePath
1351 systemPackageConfig dflags = sSystemPackageConfig (settings dflags)
1352 pgm_L :: DynFlags -> String
1353 pgm_L dflags = sPgm_L (settings dflags)
1354 pgm_P :: DynFlags -> (String,[Option])
1355 pgm_P dflags = sPgm_P (settings dflags)
1356 pgm_F :: DynFlags -> String
1357 pgm_F dflags = sPgm_F (settings dflags)
1358 pgm_c :: DynFlags -> (String,[Option])
1359 pgm_c dflags = sPgm_c (settings dflags)
1360 pgm_s :: DynFlags -> (String,[Option])
1361 pgm_s dflags = sPgm_s (settings dflags)
1362 pgm_a :: DynFlags -> (String,[Option])
1363 pgm_a dflags = sPgm_a (settings dflags)
1364 pgm_l :: DynFlags -> (String,[Option])
1365 pgm_l dflags = sPgm_l (settings dflags)
1366 pgm_dll :: DynFlags -> (String,[Option])
1367 pgm_dll dflags = sPgm_dll (settings dflags)
1368 pgm_T :: DynFlags -> String
1369 pgm_T dflags = sPgm_T (settings dflags)
1370 pgm_windres :: DynFlags -> String
1371 pgm_windres dflags = sPgm_windres (settings dflags)
1372 pgm_libtool :: DynFlags -> String
1373 pgm_libtool dflags = sPgm_libtool (settings dflags)
1374 pgm_lcc :: DynFlags -> (String,[Option])
1375 pgm_lcc dflags = sPgm_lcc (settings dflags)
1376 pgm_ar :: DynFlags -> String
1377 pgm_ar dflags = sPgm_ar (settings dflags)
1378 pgm_ranlib :: DynFlags -> String
1379 pgm_ranlib dflags = sPgm_ranlib (settings dflags)
1380 pgm_lo :: DynFlags -> (String,[Option])
1381 pgm_lo dflags = sPgm_lo (settings dflags)
1382 pgm_lc :: DynFlags -> (String,[Option])
1383 pgm_lc dflags = sPgm_lc (settings dflags)
1384 pgm_i :: DynFlags -> String
1385 pgm_i dflags = sPgm_i (settings dflags)
1386 opt_L :: DynFlags -> [String]
1387 opt_L dflags = sOpt_L (settings dflags)
1388 opt_P :: DynFlags -> [String]
1389 opt_P dflags = concatMap (wayOptP (targetPlatform dflags)) (ways dflags)
1390 ++ sOpt_P (settings dflags)
1391
1392 -- This function packages everything that's needed to fingerprint opt_P
1393 -- flags. See Note [Repeated -optP hashing].
1394 opt_P_signature :: DynFlags -> ([String], Fingerprint)
1395 opt_P_signature dflags =
1396 ( concatMap (wayOptP (targetPlatform dflags)) (ways dflags)
1397 , sOpt_P_fingerprint (settings dflags))
1398
1399 opt_F :: DynFlags -> [String]
1400 opt_F dflags = sOpt_F (settings dflags)
1401 opt_c :: DynFlags -> [String]
1402 opt_c dflags = concatMap (wayOptc (targetPlatform dflags)) (ways dflags)
1403 ++ sOpt_c (settings dflags)
1404 opt_a :: DynFlags -> [String]
1405 opt_a dflags = sOpt_a (settings dflags)
1406 opt_l :: DynFlags -> [String]
1407 opt_l dflags = concatMap (wayOptl (targetPlatform dflags)) (ways dflags)
1408 ++ sOpt_l (settings dflags)
1409 opt_windres :: DynFlags -> [String]
1410 opt_windres dflags = sOpt_windres (settings dflags)
1411 opt_lcc :: DynFlags -> [String]
1412 opt_lcc dflags = sOpt_lcc (settings dflags)
1413 opt_lo :: DynFlags -> [String]
1414 opt_lo dflags = sOpt_lo (settings dflags)
1415 opt_lc :: DynFlags -> [String]
1416 opt_lc dflags = sOpt_lc (settings dflags)
1417 opt_i :: DynFlags -> [String]
1418 opt_i dflags = sOpt_i (settings dflags)
1419
1420 -- | The directory for this version of ghc in the user's app directory
1421 -- (typically something like @~/.ghc/x86_64-linux-7.6.3@)
1422 --
1423 versionedAppDir :: DynFlags -> MaybeT IO FilePath
1424 versionedAppDir dflags = do
1425 -- Make sure we handle the case the HOME isn't set (see #11678)
1426 appdir <- tryMaybeT $ getAppUserDataDirectory (programName dflags)
1427 return $ appdir </> versionedFilePath dflags
1428
1429 -- | A filepath like @x86_64-linux-7.6.3@ with the platform string to use when
1430 -- constructing platform-version-dependent files that need to co-exist.
1431 --
1432 versionedFilePath :: DynFlags -> FilePath
1433 versionedFilePath dflags = TARGET_ARCH
1434 ++ '-':TARGET_OS
1435 ++ '-':projectVersion dflags
1436 -- NB: This functionality is reimplemented in Cabal, so if you
1437 -- change it, be sure to update Cabal.
1438
1439 -- | The target code type of the compilation (if any).
1440 --
1441 -- Whenever you change the target, also make sure to set 'ghcLink' to
1442 -- something sensible.
1443 --
1444 -- 'HscNothing' can be used to avoid generating any output, however, note
1445 -- that:
1446 --
1447 -- * If a program uses Template Haskell the typechecker may need to run code
1448 -- from an imported module. To facilitate this, code generation is enabled
1449 -- for modules imported by modules that use template haskell.
1450 -- See Note [-fno-code mode].
1451 --
1452 data HscTarget
1453 = HscC -- ^ Generate C code.
1454 | HscAsm -- ^ Generate assembly using the native code generator.
1455 | HscLlvm -- ^ Generate assembly using the llvm code generator.
1456 | HscInterpreted -- ^ Generate bytecode. (Requires 'LinkInMemory')
1457 | HscNothing -- ^ Don't generate any code. See notes above.
1458 deriving (Eq, Show)
1459
1460 -- | Will this target result in an object file on the disk?
1461 isObjectTarget :: HscTarget -> Bool
1462 isObjectTarget HscC = True
1463 isObjectTarget HscAsm = True
1464 isObjectTarget HscLlvm = True
1465 isObjectTarget _ = False
1466
1467 -- | Does this target retain *all* top-level bindings for a module,
1468 -- rather than just the exported bindings, in the TypeEnv and compiled
1469 -- code (if any)? In interpreted mode we do this, so that GHCi can
1470 -- call functions inside a module. In HscNothing mode we also do it,
1471 -- so that Haddock can get access to the GlobalRdrEnv for a module
1472 -- after typechecking it.
1473 targetRetainsAllBindings :: HscTarget -> Bool
1474 targetRetainsAllBindings HscInterpreted = True
1475 targetRetainsAllBindings HscNothing = True
1476 targetRetainsAllBindings _ = False
1477
1478 -- | The 'GhcMode' tells us whether we're doing multi-module
1479 -- compilation (controlled via the "GHC" API) or one-shot
1480 -- (single-module) compilation. This makes a difference primarily to
1481 -- the "Finder": in one-shot mode we look for interface files for
1482 -- imported modules, but in multi-module mode we look for source files
1483 -- in order to check whether they need to be recompiled.
1484 data GhcMode
1485 = CompManager -- ^ @\-\-make@, GHCi, etc.
1486 | OneShot -- ^ @ghc -c Foo.hs@
1487 | MkDepend -- ^ @ghc -M@, see "Finder" for why we need this
1488 deriving Eq
1489
1490 instance Outputable GhcMode where
1491 ppr CompManager = text "CompManager"
1492 ppr OneShot = text "OneShot"
1493 ppr MkDepend = text "MkDepend"
1494
1495 isOneShot :: GhcMode -> Bool
1496 isOneShot OneShot = True
1497 isOneShot _other = False
1498
1499 -- | What to do in the link step, if there is one.
1500 data GhcLink
1501 = NoLink -- ^ Don't link at all
1502 | LinkBinary -- ^ Link object code into a binary
1503 | LinkInMemory -- ^ Use the in-memory dynamic linker (works for both
1504 -- bytecode and object code).
1505 | LinkDynLib -- ^ Link objects into a dynamic lib (DLL on Windows, DSO on ELF platforms)
1506 | LinkStaticLib -- ^ Link objects into a static lib
1507 deriving (Eq, Show)
1508
1509 isNoLink :: GhcLink -> Bool
1510 isNoLink NoLink = True
1511 isNoLink _ = False
1512
1513 -- | We accept flags which make packages visible, but how they select
1514 -- the package varies; this data type reflects what selection criterion
1515 -- is used.
1516 data PackageArg =
1517 PackageArg String -- ^ @-package@, by 'PackageName'
1518 | UnitIdArg UnitId -- ^ @-package-id@, by 'UnitId'
1519 deriving (Eq, Show)
1520 instance Outputable PackageArg where
1521 ppr (PackageArg pn) = text "package" <+> text pn
1522 ppr (UnitIdArg uid) = text "unit" <+> ppr uid
1523
1524 -- | Represents the renaming that may be associated with an exposed
1525 -- package, e.g. the @rns@ part of @-package "foo (rns)"@.
1526 --
1527 -- Here are some example parsings of the package flags (where
1528 -- a string literal is punned to be a 'ModuleName':
1529 --
1530 -- * @-package foo@ is @ModRenaming True []@
1531 -- * @-package foo ()@ is @ModRenaming False []@
1532 -- * @-package foo (A)@ is @ModRenaming False [("A", "A")]@
1533 -- * @-package foo (A as B)@ is @ModRenaming False [("A", "B")]@
1534 -- * @-package foo with (A as B)@ is @ModRenaming True [("A", "B")]@
1535 data ModRenaming = ModRenaming {
1536 modRenamingWithImplicit :: Bool, -- ^ Bring all exposed modules into scope?
1537 modRenamings :: [(ModuleName, ModuleName)] -- ^ Bring module @m@ into scope
1538 -- under name @n@.
1539 } deriving (Eq)
1540 instance Outputable ModRenaming where
1541 ppr (ModRenaming b rns) = ppr b <+> parens (ppr rns)
1542
1543 -- | Flags for manipulating the set of non-broken packages.
1544 newtype IgnorePackageFlag = IgnorePackage String -- ^ @-ignore-package@
1545 deriving (Eq)
1546
1547 -- | Flags for manipulating package trust.
1548 data TrustFlag
1549 = TrustPackage String -- ^ @-trust@
1550 | DistrustPackage String -- ^ @-distrust@
1551 deriving (Eq)
1552
1553 -- | Flags for manipulating packages visibility.
1554 data PackageFlag
1555 = ExposePackage String PackageArg ModRenaming -- ^ @-package@, @-package-id@
1556 | HidePackage String -- ^ @-hide-package@
1557 deriving (Eq) -- NB: equality instance is used by packageFlagsChanged
1558
1559 data PackageDBFlag
1560 = PackageDB PkgConfRef
1561 | NoUserPackageDB
1562 | NoGlobalPackageDB
1563 | ClearPackageDBs
1564 deriving (Eq)
1565
1566 packageFlagsChanged :: DynFlags -> DynFlags -> Bool
1567 packageFlagsChanged idflags1 idflags0 =
1568 packageFlags idflags1 /= packageFlags idflags0 ||
1569 ignorePackageFlags idflags1 /= ignorePackageFlags idflags0 ||
1570 pluginPackageFlags idflags1 /= pluginPackageFlags idflags0 ||
1571 trustFlags idflags1 /= trustFlags idflags0 ||
1572 packageDBFlags idflags1 /= packageDBFlags idflags0 ||
1573 packageGFlags idflags1 /= packageGFlags idflags0
1574 where
1575 packageGFlags dflags = map (`gopt` dflags)
1576 [ Opt_HideAllPackages
1577 , Opt_HideAllPluginPackages
1578 , Opt_AutoLinkPackages ]
1579
1580 instance Outputable PackageFlag where
1581 ppr (ExposePackage n arg rn) = text n <> braces (ppr arg <+> ppr rn)
1582 ppr (HidePackage str) = text "-hide-package" <+> text str
1583
1584 defaultHscTarget :: Platform -> HscTarget
1585 defaultHscTarget = defaultObjectTarget
1586
1587 -- | The 'HscTarget' value corresponding to the default way to create
1588 -- object files on the current platform.
1589 defaultObjectTarget :: Platform -> HscTarget
1590 defaultObjectTarget platform
1591 | platformUnregisterised platform = HscC
1592 | cGhcWithNativeCodeGen == "YES" = HscAsm
1593 | otherwise = HscLlvm
1594
1595 tablesNextToCode :: DynFlags -> Bool
1596 tablesNextToCode dflags
1597 = mkTablesNextToCode (platformUnregisterised (targetPlatform dflags))
1598
1599 -- Determines whether we will be compiling
1600 -- info tables that reside just before the entry code, or with an
1601 -- indirection to the entry code. See TABLES_NEXT_TO_CODE in
1602 -- includes/rts/storage/InfoTables.h.
1603 mkTablesNextToCode :: Bool -> Bool
1604 mkTablesNextToCode unregisterised
1605 = not unregisterised && cGhcEnableTablesNextToCode == "YES"
1606
1607 data DynLibLoader
1608 = Deployable
1609 | SystemDependent
1610 deriving Eq
1611
1612 data RtsOptsEnabled
1613 = RtsOptsNone | RtsOptsIgnore | RtsOptsIgnoreAll | RtsOptsSafeOnly
1614 | RtsOptsAll
1615 deriving (Show)
1616
1617 shouldUseColor :: DynFlags -> Bool
1618 shouldUseColor dflags = overrideWith (canUseColor dflags) (useColor dflags)
1619
1620 shouldUseHexWordLiterals :: DynFlags -> Bool
1621 shouldUseHexWordLiterals dflags =
1622 Opt_HexWordLiterals `EnumSet.member` generalFlags dflags
1623
1624 -- | Are we building with @-fPIE@ or @-fPIC@ enabled?
1625 positionIndependent :: DynFlags -> Bool
1626 positionIndependent dflags = gopt Opt_PIC dflags || gopt Opt_PIE dflags
1627
1628 -----------------------------------------------------------------------------
1629 -- Ways
1630
1631 -- The central concept of a "way" is that all objects in a given
1632 -- program must be compiled in the same "way". Certain options change
1633 -- parameters of the virtual machine, eg. profiling adds an extra word
1634 -- to the object header, so profiling objects cannot be linked with
1635 -- non-profiling objects.
1636
1637 -- After parsing the command-line options, we determine which "way" we
1638 -- are building - this might be a combination way, eg. profiling+threaded.
1639
1640 -- We then find the "build-tag" associated with this way, and this
1641 -- becomes the suffix used to find .hi files and libraries used in
1642 -- this compilation.
1643
1644 data Way
1645 = WayCustom String -- for GHC API clients building custom variants
1646 | WayThreaded
1647 | WayDebug
1648 | WayProf
1649 | WayEventLog
1650 | WayDyn
1651 deriving (Eq, Ord, Show)
1652
1653 allowed_combination :: [Way] -> Bool
1654 allowed_combination way = and [ x `allowedWith` y
1655 | x <- way, y <- way, x < y ]
1656 where
1657 -- Note ordering in these tests: the left argument is
1658 -- <= the right argument, according to the Ord instance
1659 -- on Way above.
1660
1661 -- dyn is allowed with everything
1662 _ `allowedWith` WayDyn = True
1663 WayDyn `allowedWith` _ = True
1664
1665 -- debug is allowed with everything
1666 _ `allowedWith` WayDebug = True
1667 WayDebug `allowedWith` _ = True
1668
1669 (WayCustom {}) `allowedWith` _ = True
1670 WayThreaded `allowedWith` WayProf = True
1671 WayThreaded `allowedWith` WayEventLog = True
1672 WayProf `allowedWith` WayEventLog = True
1673 _ `allowedWith` _ = False
1674
1675 mkBuildTag :: [Way] -> String
1676 mkBuildTag ways = concat (intersperse "_" (map wayTag ways))
1677
1678 wayTag :: Way -> String
1679 wayTag (WayCustom xs) = xs
1680 wayTag WayThreaded = "thr"
1681 wayTag WayDebug = "debug"
1682 wayTag WayDyn = "dyn"
1683 wayTag WayProf = "p"
1684 wayTag WayEventLog = "l"
1685
1686 wayRTSOnly :: Way -> Bool
1687 wayRTSOnly (WayCustom {}) = False
1688 wayRTSOnly WayThreaded = True
1689 wayRTSOnly WayDebug = True
1690 wayRTSOnly WayDyn = False
1691 wayRTSOnly WayProf = False
1692 wayRTSOnly WayEventLog = True
1693
1694 wayDesc :: Way -> String
1695 wayDesc (WayCustom xs) = xs
1696 wayDesc WayThreaded = "Threaded"
1697 wayDesc WayDebug = "Debug"
1698 wayDesc WayDyn = "Dynamic"
1699 wayDesc WayProf = "Profiling"
1700 wayDesc WayEventLog = "RTS Event Logging"
1701
1702 -- Turn these flags on when enabling this way
1703 wayGeneralFlags :: Platform -> Way -> [GeneralFlag]
1704 wayGeneralFlags _ (WayCustom {}) = []
1705 wayGeneralFlags _ WayThreaded = []
1706 wayGeneralFlags _ WayDebug = []
1707 wayGeneralFlags _ WayDyn = [Opt_PIC, Opt_ExternalDynamicRefs]
1708 -- We could get away without adding -fPIC when compiling the
1709 -- modules of a program that is to be linked with -dynamic; the
1710 -- program itself does not need to be position-independent, only
1711 -- the libraries need to be. HOWEVER, GHCi links objects into a
1712 -- .so before loading the .so using the system linker. Since only
1713 -- PIC objects can be linked into a .so, we have to compile even
1714 -- modules of the main program with -fPIC when using -dynamic.
1715 wayGeneralFlags _ WayProf = [Opt_SccProfilingOn]
1716 wayGeneralFlags _ WayEventLog = []
1717
1718 -- Turn these flags off when enabling this way
1719 wayUnsetGeneralFlags :: Platform -> Way -> [GeneralFlag]
1720 wayUnsetGeneralFlags _ (WayCustom {}) = []
1721 wayUnsetGeneralFlags _ WayThreaded = []
1722 wayUnsetGeneralFlags _ WayDebug = []
1723 wayUnsetGeneralFlags _ WayDyn = [-- There's no point splitting objects
1724 -- when we're going to be dynamically
1725 -- linking. Plus it breaks compilation
1726 -- on OSX x86.
1727 Opt_SplitObjs,
1728 -- If splitobjs wasn't useful for this,
1729 -- assume sections aren't either.
1730 Opt_SplitSections]
1731 wayUnsetGeneralFlags _ WayProf = []
1732 wayUnsetGeneralFlags _ WayEventLog = []
1733
1734 wayOptc :: Platform -> Way -> [String]
1735 wayOptc _ (WayCustom {}) = []
1736 wayOptc platform WayThreaded = case platformOS platform of
1737 OSOpenBSD -> ["-pthread"]
1738 OSNetBSD -> ["-pthread"]
1739 _ -> []
1740 wayOptc _ WayDebug = []
1741 wayOptc _ WayDyn = []
1742 wayOptc _ WayProf = ["-DPROFILING"]
1743 wayOptc _ WayEventLog = ["-DTRACING"]
1744
1745 wayOptl :: Platform -> Way -> [String]
1746 wayOptl _ (WayCustom {}) = []
1747 wayOptl platform WayThreaded =
1748 case platformOS platform of
1749 OSFreeBSD -> ["-pthread"]
1750 OSOpenBSD -> ["-pthread"]
1751 OSNetBSD -> ["-pthread"]
1752 _ -> []
1753 wayOptl _ WayDebug = []
1754 wayOptl _ WayDyn = []
1755 wayOptl _ WayProf = []
1756 wayOptl _ WayEventLog = []
1757
1758 wayOptP :: Platform -> Way -> [String]
1759 wayOptP _ (WayCustom {}) = []
1760 wayOptP _ WayThreaded = []
1761 wayOptP _ WayDebug = []
1762 wayOptP _ WayDyn = []
1763 wayOptP _ WayProf = ["-DPROFILING"]
1764 wayOptP _ WayEventLog = ["-DTRACING"]
1765
1766 whenGeneratingDynamicToo :: MonadIO m => DynFlags -> m () -> m ()
1767 whenGeneratingDynamicToo dflags f = ifGeneratingDynamicToo dflags f (return ())
1768
1769 ifGeneratingDynamicToo :: MonadIO m => DynFlags -> m a -> m a -> m a
1770 ifGeneratingDynamicToo dflags f g = generateDynamicTooConditional dflags f g g
1771
1772 whenCannotGenerateDynamicToo :: MonadIO m => DynFlags -> m () -> m ()
1773 whenCannotGenerateDynamicToo dflags f
1774 = ifCannotGenerateDynamicToo dflags f (return ())
1775
1776 ifCannotGenerateDynamicToo :: MonadIO m => DynFlags -> m a -> m a -> m a
1777 ifCannotGenerateDynamicToo dflags f g
1778 = generateDynamicTooConditional dflags g f g
1779
1780 generateDynamicTooConditional :: MonadIO m
1781 => DynFlags -> m a -> m a -> m a -> m a
1782 generateDynamicTooConditional dflags canGen cannotGen notTryingToGen
1783 = if gopt Opt_BuildDynamicToo dflags
1784 then do let ref = canGenerateDynamicToo dflags
1785 b <- liftIO $ readIORef ref
1786 if b then canGen else cannotGen
1787 else notTryingToGen
1788
1789 dynamicTooMkDynamicDynFlags :: DynFlags -> DynFlags
1790 dynamicTooMkDynamicDynFlags dflags0
1791 = let dflags1 = addWay' WayDyn dflags0
1792 dflags2 = dflags1 {
1793 outputFile = dynOutputFile dflags1,
1794 hiSuf = dynHiSuf dflags1,
1795 objectSuf = dynObjectSuf dflags1
1796 }
1797 dflags3 = updateWays dflags2
1798 dflags4 = gopt_unset dflags3 Opt_BuildDynamicToo
1799 in dflags4
1800
1801 -----------------------------------------------------------------------------
1802
1803 -- | Used by 'GHC.runGhc' to partially initialize a new 'DynFlags' value
1804 initDynFlags :: DynFlags -> IO DynFlags
1805 initDynFlags dflags = do
1806 let -- We can't build with dynamic-too on Windows, as labels before
1807 -- the fork point are different depending on whether we are
1808 -- building dynamically or not.
1809 platformCanGenerateDynamicToo
1810 = platformOS (targetPlatform dflags) /= OSMinGW32
1811 refCanGenerateDynamicToo <- newIORef platformCanGenerateDynamicToo
1812 refNextTempSuffix <- newIORef 0
1813 refFilesToClean <- newIORef emptyFilesToClean
1814 refDirsToClean <- newIORef Map.empty
1815 refGeneratedDumps <- newIORef Set.empty
1816 refRtldInfo <- newIORef Nothing
1817 refRtccInfo <- newIORef Nothing
1818 wrapperNum <- newIORef emptyModuleEnv
1819 canUseUnicode <- do let enc = localeEncoding
1820 str = "‘’"
1821 (withCString enc str $ \cstr ->
1822 do str' <- peekCString enc cstr
1823 return (str == str'))
1824 `catchIOError` \_ -> return False
1825 canUseColor <- stderrSupportsAnsiColors
1826 maybeGhcColorsEnv <- lookupEnv "GHC_COLORS"
1827 maybeGhcColoursEnv <- lookupEnv "GHC_COLOURS"
1828 let adjustCols (Just env) = Col.parseScheme env
1829 adjustCols Nothing = id
1830 let (useColor', colScheme') =
1831 (adjustCols maybeGhcColoursEnv . adjustCols maybeGhcColorsEnv)
1832 (useColor dflags, colScheme dflags)
1833 return dflags{
1834 canGenerateDynamicToo = refCanGenerateDynamicToo,
1835 nextTempSuffix = refNextTempSuffix,
1836 filesToClean = refFilesToClean,
1837 dirsToClean = refDirsToClean,
1838 generatedDumps = refGeneratedDumps,
1839 nextWrapperNum = wrapperNum,
1840 useUnicode = canUseUnicode,
1841 useColor = useColor',
1842 canUseColor = canUseColor,
1843 colScheme = colScheme',
1844 rtldInfo = refRtldInfo,
1845 rtccInfo = refRtccInfo
1846 }
1847
1848 -- | The normal 'DynFlags'. Note that they are not suitable for use in this form
1849 -- and must be fully initialized by 'GHC.runGhc' first.
1850 defaultDynFlags :: Settings -> LlvmConfig -> DynFlags
1851 defaultDynFlags mySettings (myLlvmTargets, myLlvmPasses) =
1852 -- See Note [Updating flag description in the User's Guide]
1853 DynFlags {
1854 ghcMode = CompManager,
1855 ghcLink = LinkBinary,
1856 hscTarget = defaultHscTarget (sTargetPlatform mySettings),
1857 integerLibrary = cIntegerLibraryType,
1858 verbosity = 0,
1859 optLevel = 0,
1860 debugLevel = 0,
1861 simplPhases = 2,
1862 maxSimplIterations = 4,
1863 maxPmCheckIterations = 2000000,
1864 ruleCheck = Nothing,
1865 inlineCheck = Nothing,
1866 maxRelevantBinds = Just 6,
1867 maxValidHoleFits = Just 6,
1868 maxRefHoleFits = Just 6,
1869 refLevelHoleFits = Nothing,
1870 maxUncoveredPatterns = 4,
1871 simplTickFactor = 100,
1872 specConstrThreshold = Just 2000,
1873 specConstrCount = Just 3,
1874 specConstrRecursive = 3,
1875 liberateCaseThreshold = Just 2000,
1876 floatLamArgs = Just 0, -- Default: float only if no fvs
1877 liftLamsRecArgs = Just 5, -- Default: the number of available argument hardware registers on x86_64
1878 liftLamsNonRecArgs = Just 5, -- Default: the number of available argument hardware registers on x86_64
1879 liftLamsKnown = False, -- Default: don't turn known calls into unknown ones
1880 cmmProcAlignment = Nothing,
1881
1882 historySize = 20,
1883 strictnessBefore = [],
1884
1885 parMakeCount = Just 1,
1886
1887 enableTimeStats = False,
1888 ghcHeapSize = Nothing,
1889
1890 importPaths = ["."],
1891 mainModIs = mAIN,
1892 mainFunIs = Nothing,
1893 reductionDepth = treatZeroAsInf mAX_REDUCTION_DEPTH,
1894 solverIterations = treatZeroAsInf mAX_SOLVER_ITERATIONS,
1895
1896 thisInstalledUnitId = toInstalledUnitId mainUnitId,
1897 thisUnitIdInsts_ = Nothing,
1898 thisComponentId_ = Nothing,
1899
1900 objectDir = Nothing,
1901 dylibInstallName = Nothing,
1902 hiDir = Nothing,
1903 stubDir = Nothing,
1904 dumpDir = Nothing,
1905
1906 objectSuf = phaseInputExt StopLn,
1907 hcSuf = phaseInputExt HCc,
1908 hiSuf = "hi",
1909
1910 canGenerateDynamicToo = panic "defaultDynFlags: No canGenerateDynamicToo",
1911 dynObjectSuf = "dyn_" ++ phaseInputExt StopLn,
1912 dynHiSuf = "dyn_hi",
1913
1914 pluginModNames = [],
1915 pluginModNameOpts = [],
1916 frontendPluginOpts = [],
1917 plugins = [],
1918 hooks = emptyHooks,
1919
1920 outputFile = Nothing,
1921 dynOutputFile = Nothing,
1922 outputHi = Nothing,
1923 dynLibLoader = SystemDependent,
1924 dumpPrefix = Nothing,
1925 dumpPrefixForce = Nothing,
1926 ldInputs = [],
1927 includePaths = IncludeSpecs [] [],
1928 libraryPaths = [],
1929 frameworkPaths = [],
1930 cmdlineFrameworks = [],
1931 rtsOpts = Nothing,
1932 rtsOptsEnabled = RtsOptsSafeOnly,
1933 rtsOptsSuggestions = True,
1934
1935 hpcDir = ".hpc",
1936
1937 packageDBFlags = [],
1938 packageFlags = [],
1939 pluginPackageFlags = [],
1940 ignorePackageFlags = [],
1941 trustFlags = [],
1942 packageEnv = Nothing,
1943 pkgDatabase = Nothing,
1944 -- This gets filled in with GHC.setSessionDynFlags
1945 pkgState = emptyPackageState,
1946 ways = defaultWays mySettings,
1947 buildTag = mkBuildTag (defaultWays mySettings),
1948 splitInfo = Nothing,
1949 settings = mySettings,
1950 llvmTargets = myLlvmTargets,
1951 llvmPasses = myLlvmPasses,
1952
1953 -- ghc -M values
1954 depMakefile = "Makefile",
1955 depIncludePkgDeps = False,
1956 depExcludeMods = [],
1957 depSuffixes = [],
1958 -- end of ghc -M values
1959 nextTempSuffix = panic "defaultDynFlags: No nextTempSuffix",
1960 filesToClean = panic "defaultDynFlags: No filesToClean",
1961 dirsToClean = panic "defaultDynFlags: No dirsToClean",
1962 generatedDumps = panic "defaultDynFlags: No generatedDumps",
1963 ghcVersionFile = Nothing,
1964 haddockOptions = Nothing,
1965 dumpFlags = EnumSet.empty,
1966 generalFlags = EnumSet.fromList (defaultFlags mySettings),
1967 warningFlags = EnumSet.fromList standardWarnings,
1968 fatalWarningFlags = EnumSet.empty,
1969 ghciScripts = [],
1970 language = Nothing,
1971 safeHaskell = Sf_None,
1972 safeInfer = True,
1973 safeInferred = True,
1974 thOnLoc = noSrcSpan,
1975 newDerivOnLoc = noSrcSpan,
1976 overlapInstLoc = noSrcSpan,
1977 incoherentOnLoc = noSrcSpan,
1978 pkgTrustOnLoc = noSrcSpan,
1979 warnSafeOnLoc = noSrcSpan,
1980 warnUnsafeOnLoc = noSrcSpan,
1981 trustworthyOnLoc = noSrcSpan,
1982 extensions = [],
1983 extensionFlags = flattenExtensionFlags Nothing [],
1984
1985 -- The ufCreationThreshold threshold must be reasonably high to
1986 -- take account of possible discounts.
1987 -- E.g. 450 is not enough in 'fulsom' for Interval.sqr to inline
1988 -- into Csg.calc (The unfolding for sqr never makes it into the
1989 -- interface file.)
1990 ufCreationThreshold = 750,
1991 ufUseThreshold = 60,
1992 ufFunAppDiscount = 60,
1993 -- Be fairly keen to inline a function if that means
1994 -- we'll be able to pick the right method from a dictionary
1995 ufDictDiscount = 30,
1996 ufKeenessFactor = 1.5,
1997 ufDearOp = 40,
1998 ufVeryAggressive = False,
1999
2000 maxWorkerArgs = 10,
2001
2002 ghciHistSize = 50, -- keep a log of length 50 by default
2003
2004 -- Logging
2005
2006 log_action = defaultLogAction,
2007
2008 flushOut = defaultFlushOut,
2009 flushErr = defaultFlushErr,
2010 pprUserLength = 5,
2011 pprCols = 100,
2012 useUnicode = False,
2013 useColor = Auto,
2014 canUseColor = False,
2015 colScheme = Col.defaultScheme,
2016 profAuto = NoProfAuto,
2017 interactivePrint = Nothing,
2018 nextWrapperNum = panic "defaultDynFlags: No nextWrapperNum",
2019 sseVersion = Nothing,
2020 bmiVersion = Nothing,
2021 avx = False,
2022 avx2 = False,
2023 avx512cd = False,
2024 avx512er = False,
2025 avx512f = False,
2026 avx512pf = False,
2027 rtldInfo = panic "defaultDynFlags: no rtldInfo",
2028 rtccInfo = panic "defaultDynFlags: no rtccInfo",
2029
2030 maxInlineAllocSize = 128,
2031 maxInlineMemcpyInsns = 32,
2032 maxInlineMemsetInsns = 32,
2033
2034 initialUnique = 0,
2035 uniqueIncrement = 1,
2036
2037 reverseErrors = False,
2038 maxErrors = Nothing,
2039 cfgWeightInfo = defaultCfgWeights
2040 }
2041
2042 defaultWays :: Settings -> [Way]
2043 defaultWays settings = if pc_DYNAMIC_BY_DEFAULT (sPlatformConstants settings)
2044 then [WayDyn]
2045 else []
2046
2047 interpWays :: [Way]
2048 interpWays
2049 | dynamicGhc = [WayDyn]
2050 | rtsIsProfiled = [WayProf]
2051 | otherwise = []
2052
2053 interpreterProfiled :: DynFlags -> Bool
2054 interpreterProfiled dflags
2055 | gopt Opt_ExternalInterpreter dflags = gopt Opt_SccProfilingOn dflags
2056 | otherwise = rtsIsProfiled
2057
2058 interpreterDynamic :: DynFlags -> Bool
2059 interpreterDynamic dflags
2060 | gopt Opt_ExternalInterpreter dflags = WayDyn `elem` ways dflags
2061 | otherwise = dynamicGhc
2062
2063 --------------------------------------------------------------------------
2064 --
2065 -- Note [JSON Error Messages]
2066 --
2067 -- When the user requests the compiler output to be dumped as json
2068 -- we used to collect them all in an IORef and then print them at the end.
2069 -- This doesn't work very well with GHCi. (See #14078) So instead we now
2070 -- use the simpler method of just outputting a JSON document inplace to
2071 -- stdout.
2072 --
2073 -- Before the compiler calls log_action, it has already turned the `ErrMsg`
2074 -- into a formatted message. This means that we lose some possible
2075 -- information to provide to the user but refactoring log_action is quite
2076 -- invasive as it is called in many places. So, for now I left it alone
2077 -- and we can refine its behaviour as users request different output.
2078
2079 type FatalMessager = String -> IO ()
2080
2081 type LogAction = DynFlags
2082 -> WarnReason
2083 -> Severity
2084 -> SrcSpan
2085 -> PprStyle
2086 -> MsgDoc
2087 -> IO ()
2088
2089 defaultFatalMessager :: FatalMessager
2090 defaultFatalMessager = hPutStrLn stderr
2091
2092
2093 -- See Note [JSON Error Messages]
2094 --
2095 jsonLogAction :: LogAction
2096 jsonLogAction dflags reason severity srcSpan _style msg
2097 = do
2098 defaultLogActionHPutStrDoc dflags stdout (doc $$ text "")
2099 (mkCodeStyle CStyle)
2100 where
2101 doc = renderJSON $
2102 JSObject [ ( "span", json srcSpan )
2103 , ( "doc" , JSString (showSDoc dflags msg) )
2104 , ( "severity", json severity )
2105 , ( "reason" , json reason )
2106 ]
2107
2108
2109 defaultLogAction :: LogAction
2110 defaultLogAction dflags reason severity srcSpan style msg
2111 = case severity of
2112 SevOutput -> printOut msg style
2113 SevDump -> printOut (msg $$ blankLine) style
2114 SevInteractive -> putStrSDoc msg style
2115 SevInfo -> printErrs msg style
2116 SevFatal -> printErrs msg style
2117 SevWarning -> printWarns
2118 SevError -> printWarns
2119 where
2120 printOut = defaultLogActionHPrintDoc dflags stdout
2121 printErrs = defaultLogActionHPrintDoc dflags stderr
2122 putStrSDoc = defaultLogActionHPutStrDoc dflags stdout
2123 -- Pretty print the warning flag, if any (#10752)
2124 message = mkLocMessageAnn flagMsg severity srcSpan msg
2125
2126 printWarns = do
2127 hPutChar stderr '\n'
2128 caretDiagnostic <-
2129 if gopt Opt_DiagnosticsShowCaret dflags
2130 then getCaretDiagnostic severity srcSpan
2131 else pure empty
2132 printErrs (message $+$ caretDiagnostic)
2133 (setStyleColoured True style)
2134 -- careful (#2302): printErrs prints in UTF-8,
2135 -- whereas converting to string first and using
2136 -- hPutStr would just emit the low 8 bits of
2137 -- each unicode char.
2138
2139 flagMsg =
2140 case reason of
2141 NoReason -> Nothing
2142 Reason wflag -> do
2143 spec <- flagSpecOf wflag
2144 return ("-W" ++ flagSpecName spec ++ warnFlagGrp wflag)
2145 ErrReason Nothing ->
2146 return "-Werror"
2147 ErrReason (Just wflag) -> do
2148 spec <- flagSpecOf wflag
2149 return $
2150 "-W" ++ flagSpecName spec ++ warnFlagGrp wflag ++
2151 ", -Werror=" ++ flagSpecName spec
2152
2153 warnFlagGrp flag
2154 | gopt Opt_ShowWarnGroups dflags =
2155 case smallestGroups flag of
2156 [] -> ""
2157 groups -> " (in " ++ intercalate ", " (map ("-W"++) groups) ++ ")"
2158 | otherwise = ""
2159
2160 -- | Like 'defaultLogActionHPutStrDoc' but appends an extra newline.
2161 defaultLogActionHPrintDoc :: DynFlags -> Handle -> SDoc -> PprStyle -> IO ()
2162 defaultLogActionHPrintDoc dflags h d sty
2163 = defaultLogActionHPutStrDoc dflags h (d $$ text "") sty
2164
2165 defaultLogActionHPutStrDoc :: DynFlags -> Handle -> SDoc -> PprStyle -> IO ()
2166 defaultLogActionHPutStrDoc dflags h d sty
2167 -- Don't add a newline at the end, so that successive
2168 -- calls to this log-action can output all on the same line
2169 = printSDoc Pretty.PageMode dflags h sty d
2170
2171 newtype FlushOut = FlushOut (IO ())
2172
2173 defaultFlushOut :: FlushOut
2174 defaultFlushOut = FlushOut $ hFlush stdout
2175
2176 newtype FlushErr = FlushErr (IO ())
2177
2178 defaultFlushErr :: FlushErr
2179 defaultFlushErr = FlushErr $ hFlush stderr
2180
2181 {-
2182 Note [Verbosity levels]
2183 ~~~~~~~~~~~~~~~~~~~~~~~
2184 0 | print errors & warnings only
2185 1 | minimal verbosity: print "compiling M ... done." for each module.
2186 2 | equivalent to -dshow-passes
2187 3 | equivalent to existing "ghc -v"
2188 4 | "ghc -v -ddump-most"
2189 5 | "ghc -v -ddump-all"
2190 -}
2191
2192 data OnOff a = On a
2193 | Off a
2194 deriving (Eq, Show)
2195
2196 instance Outputable a => Outputable (OnOff a) where
2197 ppr (On x) = text "On" <+> ppr x
2198 ppr (Off x) = text "Off" <+> ppr x
2199
2200 -- OnOffs accumulate in reverse order, so we use foldr in order to
2201 -- process them in the right order
2202 flattenExtensionFlags :: Maybe Language -> [OnOff LangExt.Extension] -> EnumSet LangExt.Extension
2203 flattenExtensionFlags ml = foldr f defaultExtensionFlags
2204 where f (On f) flags = EnumSet.insert f flags
2205 f (Off f) flags = EnumSet.delete f flags
2206 defaultExtensionFlags = EnumSet.fromList (languageExtensions ml)
2207
2208 languageExtensions :: Maybe Language -> [LangExt.Extension]
2209
2210 languageExtensions Nothing
2211 -- Nothing => the default case
2212 = LangExt.NondecreasingIndentation -- This has been on by default for some time
2213 : delete LangExt.DatatypeContexts -- The Haskell' committee decided to
2214 -- remove datatype contexts from the
2215 -- language:
2216 -- http://www.haskell.org/pipermail/haskell-prime/2011-January/003335.html
2217 (languageExtensions (Just Haskell2010))
2218
2219 -- NB: MonoPatBinds is no longer the default
2220
2221 languageExtensions (Just Haskell98)
2222 = [LangExt.ImplicitPrelude,
2223 -- See Note [When is StarIsType enabled]
2224 LangExt.StarIsType,
2225 LangExt.MonadFailDesugaring,
2226 LangExt.MonomorphismRestriction,
2227 LangExt.NPlusKPatterns,
2228 LangExt.DatatypeContexts,
2229 LangExt.TraditionalRecordSyntax,
2230 LangExt.NondecreasingIndentation
2231 -- strictly speaking non-standard, but we always had this
2232 -- on implicitly before the option was added in 7.1, and
2233 -- turning it off breaks code, so we're keeping it on for
2234 -- backwards compatibility. Cabal uses -XHaskell98 by
2235 -- default unless you specify another language.
2236 ]
2237
2238 languageExtensions (Just Haskell2010)
2239 = [LangExt.ImplicitPrelude,
2240 -- See Note [When is StarIsType enabled]
2241 LangExt.StarIsType,
2242 LangExt.MonadFailDesugaring,
2243 LangExt.MonomorphismRestriction,
2244 LangExt.DatatypeContexts,
2245 LangExt.TraditionalRecordSyntax,
2246 LangExt.EmptyDataDecls,
2247 LangExt.ForeignFunctionInterface,
2248 LangExt.PatternGuards,
2249 LangExt.DoAndIfThenElse,
2250 LangExt.RelaxedPolyRec]
2251
2252 hasPprDebug :: DynFlags -> Bool
2253 hasPprDebug = dopt Opt_D_ppr_debug
2254
2255 hasNoDebugOutput :: DynFlags -> Bool
2256 hasNoDebugOutput = dopt Opt_D_no_debug_output
2257
2258 hasNoStateHack :: DynFlags -> Bool
2259 hasNoStateHack = gopt Opt_G_NoStateHack
2260
2261 hasNoOptCoercion :: DynFlags -> Bool
2262 hasNoOptCoercion = gopt Opt_G_NoOptCoercion
2263
2264
2265 -- | Test whether a 'DumpFlag' is set
2266 dopt :: DumpFlag -> DynFlags -> Bool
2267 dopt f dflags = (f `EnumSet.member` dumpFlags dflags)
2268 || (verbosity dflags >= 4 && enableIfVerbose f)
2269 where enableIfVerbose Opt_D_dump_tc_trace = False
2270 enableIfVerbose Opt_D_dump_rn_trace = False
2271 enableIfVerbose Opt_D_dump_cs_trace = False
2272 enableIfVerbose Opt_D_dump_if_trace = False
2273 enableIfVerbose Opt_D_dump_vt_trace = False
2274 enableIfVerbose Opt_D_dump_tc = False
2275 enableIfVerbose Opt_D_dump_rn = False
2276 enableIfVerbose Opt_D_dump_shape = False
2277 enableIfVerbose Opt_D_dump_rn_stats = False
2278 enableIfVerbose Opt_D_dump_hi_diffs = False
2279 enableIfVerbose Opt_D_verbose_core2core = False
2280 enableIfVerbose Opt_D_verbose_stg2stg = False
2281 enableIfVerbose Opt_D_dump_splices = False
2282 enableIfVerbose Opt_D_th_dec_file = False
2283 enableIfVerbose Opt_D_dump_rule_firings = False
2284 enableIfVerbose Opt_D_dump_rule_rewrites = False
2285 enableIfVerbose Opt_D_dump_simpl_trace = False
2286 enableIfVerbose Opt_D_dump_rtti = False
2287 enableIfVerbose Opt_D_dump_inlinings = False
2288 enableIfVerbose Opt_D_dump_core_stats = False
2289 enableIfVerbose Opt_D_dump_asm_stats = False
2290 enableIfVerbose Opt_D_dump_types = False
2291 enableIfVerbose Opt_D_dump_simpl_iterations = False
2292 enableIfVerbose Opt_D_dump_ticked = False
2293 enableIfVerbose Opt_D_dump_view_pattern_commoning = False
2294 enableIfVerbose Opt_D_dump_mod_cycles = False
2295 enableIfVerbose Opt_D_dump_mod_map = False
2296 enableIfVerbose Opt_D_dump_ec_trace = False
2297 enableIfVerbose _ = True
2298
2299 -- | Set a 'DumpFlag'
2300 dopt_set :: DynFlags -> DumpFlag -> DynFlags
2301 dopt_set dfs f = dfs{ dumpFlags = EnumSet.insert f (dumpFlags dfs) }
2302
2303 -- | Unset a 'DumpFlag'
2304 dopt_unset :: DynFlags -> DumpFlag -> DynFlags
2305 dopt_unset dfs f = dfs{ dumpFlags = EnumSet.delete f (dumpFlags dfs) }
2306
2307 -- | Test whether a 'GeneralFlag' is set
2308 gopt :: GeneralFlag -> DynFlags -> Bool
2309 gopt f dflags = f `EnumSet.member` generalFlags dflags
2310
2311 -- | Set a 'GeneralFlag'
2312 gopt_set :: DynFlags -> GeneralFlag -> DynFlags
2313 gopt_set dfs f = dfs{ generalFlags = EnumSet.insert f (generalFlags dfs) }
2314
2315 -- | Unset a 'GeneralFlag'
2316 gopt_unset :: DynFlags -> GeneralFlag -> DynFlags
2317 gopt_unset dfs f = dfs{ generalFlags = EnumSet.delete f (generalFlags dfs) }
2318
2319 -- | Test whether a 'WarningFlag' is set
2320 wopt :: WarningFlag -> DynFlags -> Bool
2321 wopt f dflags = f `EnumSet.member` warningFlags dflags
2322
2323 -- | Set a 'WarningFlag'
2324 wopt_set :: DynFlags -> WarningFlag -> DynFlags
2325 wopt_set dfs f = dfs{ warningFlags = EnumSet.insert f (warningFlags dfs) }
2326
2327 -- | Unset a 'WarningFlag'
2328 wopt_unset :: DynFlags -> WarningFlag -> DynFlags
2329 wopt_unset dfs f = dfs{ warningFlags = EnumSet.delete f (warningFlags dfs) }
2330
2331 -- | Test whether a 'WarningFlag' is set as fatal
2332 wopt_fatal :: WarningFlag -> DynFlags -> Bool
2333 wopt_fatal f dflags = f `EnumSet.member` fatalWarningFlags dflags
2334
2335 -- | Mark a 'WarningFlag' as fatal (do not set the flag)
2336 wopt_set_fatal :: DynFlags -> WarningFlag -> DynFlags
2337 wopt_set_fatal dfs f
2338 = dfs { fatalWarningFlags = EnumSet.insert f (fatalWarningFlags dfs) }
2339
2340 -- | Mark a 'WarningFlag' as not fatal
2341 wopt_unset_fatal :: DynFlags -> WarningFlag -> DynFlags
2342 wopt_unset_fatal dfs f
2343 = dfs { fatalWarningFlags = EnumSet.delete f (fatalWarningFlags dfs) }
2344
2345 -- | Test whether a 'LangExt.Extension' is set
2346 xopt :: LangExt.Extension -> DynFlags -> Bool
2347 xopt f dflags = f `EnumSet.member` extensionFlags dflags
2348
2349 -- | Set a 'LangExt.Extension'
2350 xopt_set :: DynFlags -> LangExt.Extension -> DynFlags
2351 xopt_set dfs f
2352 = let onoffs = On f : extensions dfs
2353 in dfs { extensions = onoffs,
2354 extensionFlags = flattenExtensionFlags (language dfs) onoffs }
2355
2356 -- | Unset a 'LangExt.Extension'
2357 xopt_unset :: DynFlags -> LangExt.Extension -> DynFlags
2358 xopt_unset dfs f
2359 = let onoffs = Off f : extensions dfs
2360 in dfs { extensions = onoffs,
2361 extensionFlags = flattenExtensionFlags (language dfs) onoffs }
2362
2363 lang_set :: DynFlags -> Maybe Language -> DynFlags
2364 lang_set dflags lang =
2365 dflags {
2366 language = lang,
2367 extensionFlags = flattenExtensionFlags lang (extensions dflags)
2368 }
2369
2370 -- | An internal helper to check whether to use unicode syntax for output.
2371 --
2372 -- Note: You should very likely be using 'Outputable.unicodeSyntax' instead
2373 -- of this function.
2374 useUnicodeSyntax :: DynFlags -> Bool
2375 useUnicodeSyntax = gopt Opt_PrintUnicodeSyntax
2376
2377 useStarIsType :: DynFlags -> Bool
2378 useStarIsType = xopt LangExt.StarIsType
2379
2380 -- | Set the Haskell language standard to use
2381 setLanguage :: Language -> DynP ()
2382 setLanguage l = upd (`lang_set` Just l)
2383
2384 -- | Some modules have dependencies on others through the DynFlags rather than textual imports
2385 dynFlagDependencies :: DynFlags -> [ModuleName]
2386 dynFlagDependencies = pluginModNames
2387
2388 -- | Is the -fpackage-trust mode on
2389 packageTrustOn :: DynFlags -> Bool
2390 packageTrustOn = gopt Opt_PackageTrust
2391
2392 -- | Is Safe Haskell on in some way (including inference mode)
2393 safeHaskellOn :: DynFlags -> Bool
2394 safeHaskellOn dflags = safeHaskell dflags /= Sf_None || safeInferOn dflags
2395
2396 -- | Is the Safe Haskell safe language in use
2397 safeLanguageOn :: DynFlags -> Bool
2398 safeLanguageOn dflags = safeHaskell dflags == Sf_Safe
2399
2400 -- | Is the Safe Haskell safe inference mode active
2401 safeInferOn :: DynFlags -> Bool
2402 safeInferOn = safeInfer
2403
2404 -- | Test if Safe Imports are on in some form
2405 safeImportsOn :: DynFlags -> Bool
2406 safeImportsOn dflags = safeHaskell dflags == Sf_Unsafe ||
2407 safeHaskell dflags == Sf_Trustworthy ||
2408 safeHaskell dflags == Sf_Safe
2409
2410 -- | Set a 'Safe Haskell' flag
2411 setSafeHaskell :: SafeHaskellMode -> DynP ()
2412 setSafeHaskell s = updM f
2413 where f dfs = do
2414 let sf = safeHaskell dfs
2415 safeM <- combineSafeFlags sf s
2416 case s of
2417 Sf_Safe -> return $ dfs { safeHaskell = safeM, safeInfer = False }
2418 -- leave safe inferrence on in Trustworthy mode so we can warn
2419 -- if it could have been inferred safe.
2420 Sf_Trustworthy -> do
2421 l <- getCurLoc
2422 return $ dfs { safeHaskell = safeM, trustworthyOnLoc = l }
2423 -- leave safe inference on in Unsafe mode as well.
2424 _ -> return $ dfs { safeHaskell = safeM }
2425
2426 -- | Are all direct imports required to be safe for this Safe Haskell mode?
2427 -- Direct imports are when the code explicitly imports a module
2428 safeDirectImpsReq :: DynFlags -> Bool
2429 safeDirectImpsReq d = safeLanguageOn d
2430
2431 -- | Are all implicit imports required to be safe for this Safe Haskell mode?
2432 -- Implicit imports are things in the prelude. e.g System.IO when print is used.
2433 safeImplicitImpsReq :: DynFlags -> Bool
2434 safeImplicitImpsReq d = safeLanguageOn d
2435
2436 -- | Combine two Safe Haskell modes correctly. Used for dealing with multiple flags.
2437 -- This makes Safe Haskell very much a monoid but for now I prefer this as I don't
2438 -- want to export this functionality from the module but do want to export the
2439 -- type constructors.
2440 combineSafeFlags :: SafeHaskellMode -> SafeHaskellMode -> DynP SafeHaskellMode
2441 combineSafeFlags a b | a == Sf_None = return b
2442 | b == Sf_None = return a
2443 | a == b = return a
2444 | otherwise = addErr errm >> pure a
2445 where errm = "Incompatible Safe Haskell flags! ("
2446 ++ show a ++ ", " ++ show b ++ ")"
2447
2448 -- | A list of unsafe flags under Safe Haskell. Tuple elements are:
2449 -- * name of the flag
2450 -- * function to get srcspan that enabled the flag
2451 -- * function to test if the flag is on
2452 -- * function to turn the flag off
2453 unsafeFlags, unsafeFlagsForInfer
2454 :: [(String, DynFlags -> SrcSpan, DynFlags -> Bool, DynFlags -> DynFlags)]
2455 unsafeFlags = [ ("-XGeneralizedNewtypeDeriving", newDerivOnLoc,
2456 xopt LangExt.GeneralizedNewtypeDeriving,
2457 flip xopt_unset LangExt.GeneralizedNewtypeDeriving)
2458 , ("-XTemplateHaskell", thOnLoc,
2459 xopt LangExt.TemplateHaskell,
2460 flip xopt_unset LangExt.TemplateHaskell)
2461 ]
2462 unsafeFlagsForInfer = unsafeFlags
2463
2464
2465 -- | Retrieve the options corresponding to a particular @opt_*@ field in the correct order
2466 getOpts :: DynFlags -- ^ 'DynFlags' to retrieve the options from
2467 -> (DynFlags -> [a]) -- ^ Relevant record accessor: one of the @opt_*@ accessors
2468 -> [a] -- ^ Correctly ordered extracted options
2469 getOpts dflags opts = reverse (opts dflags)
2470 -- We add to the options from the front, so we need to reverse the list
2471
2472 -- | Gets the verbosity flag for the current verbosity level. This is fed to
2473 -- other tools, so GHC-specific verbosity flags like @-ddump-most@ are not included
2474 getVerbFlags :: DynFlags -> [String]
2475 getVerbFlags dflags
2476 | verbosity dflags >= 4 = ["-v"]
2477 | otherwise = []
2478
2479 setObjectDir, setHiDir, setStubDir, setDumpDir, setOutputDir,
2480 setDynObjectSuf, setDynHiSuf,
2481 setDylibInstallName,
2482 setObjectSuf, setHiSuf, setHcSuf, parseDynLibLoaderMode,
2483 setPgmP, addOptl, addOptc, addOptP,
2484 addCmdlineFramework, addHaddockOpts, addGhciScript,
2485 setInteractivePrint
2486 :: String -> DynFlags -> DynFlags
2487 setOutputFile, setDynOutputFile, setOutputHi, setDumpPrefixForce
2488 :: Maybe String -> DynFlags -> DynFlags
2489
2490 setObjectDir f d = d { objectDir = Just f}
2491 setHiDir f d = d { hiDir = Just f}
2492 setStubDir f d = d { stubDir = Just f
2493 , includePaths = addGlobalInclude (includePaths d) [f] }
2494 -- -stubdir D adds an implicit -I D, so that gcc can find the _stub.h file
2495 -- \#included from the .hc file when compiling via C (i.e. unregisterised
2496 -- builds).
2497 setDumpDir f d = d { dumpDir = Just f}
2498 setOutputDir f = setObjectDir f . setHiDir f . setStubDir f . setDumpDir f
2499 setDylibInstallName f d = d { dylibInstallName = Just f}
2500
2501 setObjectSuf f d = d { objectSuf = f}
2502 setDynObjectSuf f d = d { dynObjectSuf = f}
2503 setHiSuf f d = d { hiSuf = f}
2504 setDynHiSuf f d = d { dynHiSuf = f}
2505 setHcSuf f d = d { hcSuf = f}
2506
2507 setOutputFile f d = d { outputFile = f}
2508 setDynOutputFile f d = d { dynOutputFile = f}
2509 setOutputHi f d = d { outputHi = f}
2510
2511 setJsonLogAction :: DynFlags -> DynFlags
2512 setJsonLogAction d = d { log_action = jsonLogAction }
2513
2514 thisComponentId :: DynFlags -> ComponentId
2515 thisComponentId dflags =
2516 case thisComponentId_ dflags of
2517 Just cid -> cid
2518 Nothing ->
2519 case thisUnitIdInsts_ dflags of
2520 Just _ ->
2521 throwGhcException $ CmdLineError ("Use of -instantiated-with requires -this-component-id")
2522 Nothing -> ComponentId (unitIdFS (thisPackage dflags))
2523
2524 thisUnitIdInsts :: DynFlags -> [(ModuleName, Module)]
2525 thisUnitIdInsts dflags =
2526 case thisUnitIdInsts_ dflags of
2527 Just insts -> insts
2528 Nothing -> []
2529
2530 thisPackage :: DynFlags -> UnitId
2531 thisPackage dflags =
2532 case thisUnitIdInsts_ dflags of
2533 Nothing -> default_uid
2534 Just insts
2535 | all (\(x,y) -> mkHoleModule x == y) insts
2536 -> newUnitId (thisComponentId dflags) insts
2537 | otherwise
2538 -> default_uid
2539 where
2540 default_uid = DefiniteUnitId (DefUnitId (thisInstalledUnitId dflags))
2541
2542 parseUnitIdInsts :: String -> [(ModuleName, Module)]
2543 parseUnitIdInsts str = case filter ((=="").snd) (readP_to_S parse str) of
2544 [(r, "")] -> r
2545 _ -> throwGhcException $ CmdLineError ("Can't parse -instantiated-with: " ++ str)
2546 where parse = sepBy parseEntry (R.char ',')
2547 parseEntry = do
2548 n <- parseModuleName
2549 _ <- R.char '='
2550 m <- parseModuleId
2551 return (n, m)
2552
2553 setUnitIdInsts :: String -> DynFlags -> DynFlags
2554 setUnitIdInsts s d =
2555 d { thisUnitIdInsts_ = Just (parseUnitIdInsts s) }
2556
2557 setComponentId :: String -> DynFlags -> DynFlags
2558 setComponentId s d =
2559 d { thisComponentId_ = Just (ComponentId (fsLit s)) }
2560
2561 addPluginModuleName :: String -> DynFlags -> DynFlags
2562 addPluginModuleName name d = d { pluginModNames = (mkModuleName name) : (pluginModNames d) }
2563
2564 addPluginModuleNameOption :: String -> DynFlags -> DynFlags
2565 addPluginModuleNameOption optflag d = d { pluginModNameOpts = (mkModuleName m, option) : (pluginModNameOpts d) }
2566 where (m, rest) = break (== ':') optflag
2567 option = case rest of
2568 [] -> "" -- should probably signal an error
2569 (_:plug_opt) -> plug_opt -- ignore the ':' from break
2570
2571 addFrontendPluginOption :: String -> DynFlags -> DynFlags
2572 addFrontendPluginOption s d = d { frontendPluginOpts = s : frontendPluginOpts d }
2573
2574 parseDynLibLoaderMode f d =
2575 case splitAt 8 f of
2576 ("deploy", "") -> d { dynLibLoader = Deployable }
2577 ("sysdep", "") -> d { dynLibLoader = SystemDependent }
2578 _ -> throwGhcException (CmdLineError ("Unknown dynlib loader: " ++ f))
2579
2580 setDumpPrefixForce f d = d { dumpPrefixForce = f}
2581
2582 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
2583 -- Config.hs should really use Option.
2584 setPgmP f = let (pgm:args) = words f in alterSettings (\s -> s { sPgm_P = (pgm, map Option args)})
2585 addOptl f = alterSettings (\s -> s { sOpt_l = f : sOpt_l s})
2586 addOptc f = alterSettings (\s -> s { sOpt_c = f : sOpt_c s})
2587 addOptP f = alterSettings (\s -> s { sOpt_P = f : sOpt_P s
2588 , sOpt_P_fingerprint = fingerprintStrings (f : sOpt_P s)
2589 })
2590 -- See Note [Repeated -optP hashing]
2591 where
2592 fingerprintStrings ss = fingerprintFingerprints $ map fingerprintString ss
2593
2594
2595 setDepMakefile :: FilePath -> DynFlags -> DynFlags
2596 setDepMakefile f d = d { depMakefile = f }
2597
2598 setDepIncludePkgDeps :: Bool -> DynFlags -> DynFlags
2599 setDepIncludePkgDeps b d = d { depIncludePkgDeps = b }
2600
2601 addDepExcludeMod :: String -> DynFlags -> DynFlags
2602 addDepExcludeMod m d
2603 = d { depExcludeMods = mkModuleName m : depExcludeMods d }
2604
2605 addDepSuffix :: FilePath -> DynFlags -> DynFlags
2606 addDepSuffix s d = d { depSuffixes = s : depSuffixes d }
2607
2608 addCmdlineFramework f d = d { cmdlineFrameworks = f : cmdlineFrameworks d}
2609
2610 addGhcVersionFile :: FilePath -> DynFlags -> DynFlags
2611 addGhcVersionFile f d = d { ghcVersionFile = Just f }
2612
2613 addHaddockOpts f d = d { haddockOptions = Just f}
2614
2615 addGhciScript f d = d { ghciScripts = f : ghciScripts d}
2616
2617 setInteractivePrint f d = d { interactivePrint = Just f}
2618
2619 -- -----------------------------------------------------------------------------
2620 -- Command-line options
2621
2622 -- | When invoking external tools as part of the compilation pipeline, we
2623 -- pass these a sequence of options on the command-line. Rather than
2624 -- just using a list of Strings, we use a type that allows us to distinguish
2625 -- between filepaths and 'other stuff'. The reason for this is that
2626 -- this type gives us a handle on transforming filenames, and filenames only,
2627 -- to whatever format they're expected to be on a particular platform.
2628 data Option
2629 = FileOption -- an entry that _contains_ filename(s) / filepaths.
2630 String -- a non-filepath prefix that shouldn't be
2631 -- transformed (e.g., "/out=")
2632 String -- the filepath/filename portion
2633 | Option String
2634 deriving ( Eq )
2635
2636 showOpt :: Option -> String
2637 showOpt (FileOption pre f) = pre ++ f
2638 showOpt (Option s) = s
2639
2640 -----------------------------------------------------------------------------
2641 -- Setting the optimisation level
2642
2643 updOptLevel :: Int -> DynFlags -> DynFlags
2644 -- ^ Sets the 'DynFlags' to be appropriate to the optimisation level
2645 updOptLevel n dfs
2646 = dfs2{ optLevel = final_n }
2647 where
2648 final_n = max 0 (min 2 n) -- Clamp to 0 <= n <= 2
2649 dfs1 = foldr (flip gopt_unset) dfs remove_gopts
2650 dfs2 = foldr (flip gopt_set) dfs1 extra_gopts
2651
2652 extra_gopts = [ f | (ns,f) <- optLevelFlags, final_n `elem` ns ]
2653 remove_gopts = [ f | (ns,f) <- optLevelFlags, final_n `notElem` ns ]
2654
2655 {- **********************************************************************
2656 %* *
2657 DynFlags parser
2658 %* *
2659 %********************************************************************* -}
2660
2661 -- -----------------------------------------------------------------------------
2662 -- Parsing the dynamic flags.
2663
2664
2665 -- | Parse dynamic flags from a list of command line arguments. Returns the
2666 -- the parsed 'DynFlags', the left-over arguments, and a list of warnings.
2667 -- Throws a 'UsageError' if errors occurred during parsing (such as unknown
2668 -- flags or missing arguments).
2669 parseDynamicFlagsCmdLine :: MonadIO m => DynFlags -> [Located String]
2670 -> m (DynFlags, [Located String], [Warn])
2671 -- ^ Updated 'DynFlags', left-over arguments, and
2672 -- list of warnings.
2673 parseDynamicFlagsCmdLine = parseDynamicFlagsFull flagsAll True
2674
2675
2676 -- | Like 'parseDynamicFlagsCmdLine' but does not allow the package flags
2677 -- (-package, -hide-package, -ignore-package, -hide-all-packages, -package-db).
2678 -- Used to parse flags set in a modules pragma.
2679 parseDynamicFilePragma :: MonadIO m => DynFlags -> [Located String]
2680 -> m (DynFlags, [Located String], [Warn])
2681 -- ^ Updated 'DynFlags', left-over arguments, and
2682 -- list of warnings.
2683 parseDynamicFilePragma = parseDynamicFlagsFull flagsDynamic False
2684
2685
2686 -- | Parses the dynamically set flags for GHC. This is the most general form of
2687 -- the dynamic flag parser that the other methods simply wrap. It allows
2688 -- saying which flags are valid flags and indicating if we are parsing
2689 -- arguments from the command line or from a file pragma.
2690 parseDynamicFlagsFull :: MonadIO m
2691 => [Flag (CmdLineP DynFlags)] -- ^ valid flags to match against
2692 -> Bool -- ^ are the arguments from the command line?
2693 -> DynFlags -- ^ current dynamic flags
2694 -> [Located String] -- ^ arguments to parse
2695 -> m (DynFlags, [Located String], [Warn])
2696 parseDynamicFlagsFull activeFlags cmdline dflags0 args = do
2697 let ((leftover, errs, warns), dflags1)
2698 = runCmdLine (processArgs activeFlags args) dflags0
2699
2700 -- See Note [Handling errors when parsing commandline flags]
2701 unless (null errs) $ liftIO $ throwGhcExceptionIO $ errorsToGhcException $
2702 map ((showPpr dflags0 . getLoc &&& unLoc) . errMsg) $ errs
2703
2704 -- check for disabled flags in safe haskell
2705 let (dflags2, sh_warns) = safeFlagCheck cmdline dflags1
2706 dflags3 = updateWays dflags2
2707 theWays = ways dflags3
2708
2709 unless (allowed_combination theWays) $ liftIO $
2710 throwGhcExceptionIO (CmdLineError ("combination not supported: " ++
2711 intercalate "/" (map wayDesc theWays)))
2712
2713 let chooseOutput
2714 | isJust (outputFile dflags3) -- Only iff user specified -o ...
2715 , not (isJust (dynOutputFile dflags3)) -- but not -dyno
2716 = return $ dflags3 { dynOutputFile = Just $ dynOut (fromJust $ outputFile dflags3) }
2717 | otherwise
2718 = return dflags3
2719 where
2720 dynOut = flip addExtension (dynObjectSuf dflags3) . dropExtension
2721 dflags4 <- ifGeneratingDynamicToo dflags3 chooseOutput (return dflags3)
2722
2723 let (dflags5, consistency_warnings) = makeDynFlagsConsistent dflags4
2724
2725 -- Set timer stats & heap size
2726 when (enableTimeStats dflags5) $ liftIO enableTimingStats
2727 case (ghcHeapSize dflags5) of
2728 Just x -> liftIO (setHeapSize x)
2729 _ -> return ()
2730
2731 liftIO $ setUnsafeGlobalDynFlags dflags5
2732
2733 let warns' = map (Warn Cmd.NoReason) (consistency_warnings ++ sh_warns)
2734
2735 return (dflags5, leftover, warns' ++ warns)
2736
2737 -- | Write an error or warning to the 'LogOutput'.
2738 putLogMsg :: DynFlags -> WarnReason -> Severity -> SrcSpan -> PprStyle
2739 -> MsgDoc -> IO ()
2740 putLogMsg dflags = log_action dflags dflags
2741
2742 updateWays :: DynFlags -> DynFlags
2743 updateWays dflags
2744 = let theWays = sort $ nub $ ways dflags
2745 in dflags {
2746 ways = theWays,
2747 buildTag = mkBuildTag (filter (not . wayRTSOnly) theWays)
2748 }
2749
2750 -- | Check (and potentially disable) any extensions that aren't allowed
2751 -- in safe mode.
2752 --
2753 -- The bool is to indicate if we are parsing command line flags (false means
2754 -- file pragma). This allows us to generate better warnings.
2755 safeFlagCheck :: Bool -> DynFlags -> (DynFlags, [Located String])
2756 safeFlagCheck _ dflags | safeLanguageOn dflags = (dflagsUnset, warns)
2757 where
2758 -- Handle illegal flags under safe language.
2759 (dflagsUnset, warns) = foldl' check_method (dflags, []) unsafeFlags
2760
2761 check_method (df, warns) (str,loc,test,fix)
2762 | test df = (fix df, warns ++ safeFailure (loc df) str)
2763 | otherwise = (df, warns)
2764
2765 safeFailure loc str
2766 = [L loc $ str ++ " is not allowed in Safe Haskell; ignoring "
2767 ++ str]
2768
2769 safeFlagCheck cmdl dflags =
2770 case (safeInferOn dflags) of
2771 True | safeFlags -> (dflags', warn)
2772 True -> (dflags' { safeInferred = False }, warn)
2773 False -> (dflags', warn)
2774
2775 where
2776 -- dynflags and warn for when -fpackage-trust by itself with no safe
2777 -- haskell flag
2778 (dflags', warn)
2779 | safeHaskell dflags == Sf_None && not cmdl && packageTrustOn dflags
2780 = (gopt_unset dflags Opt_PackageTrust, pkgWarnMsg)
2781 | otherwise = (dflags, [])
2782
2783 pkgWarnMsg = [L (pkgTrustOnLoc dflags') $
2784 "-fpackage-trust ignored;" ++
2785 " must be specified with a Safe Haskell flag"]
2786
2787 -- Have we inferred Unsafe? See Note [HscMain . Safe Haskell Inference]
2788 safeFlags = all (\(_,_,t,_) -> not $ t dflags) unsafeFlagsForInfer
2789
2790
2791 {- **********************************************************************
2792 %* *
2793 DynFlags specifications
2794 %* *
2795 %********************************************************************* -}
2796
2797 -- | All dynamic flags option strings without the deprecated ones.
2798 -- These are the user facing strings for enabling and disabling options.
2799 allNonDeprecatedFlags :: [String]
2800 allNonDeprecatedFlags = allFlagsDeps False
2801
2802 -- | All flags with possibility to filter deprecated ones
2803 allFlagsDeps :: Bool -> [String]
2804 allFlagsDeps keepDeprecated = [ '-':flagName flag
2805 | (deprecated, flag) <- flagsAllDeps
2806 , keepDeprecated || not (isDeprecated deprecated)]
2807 where isDeprecated Deprecated = True
2808 isDeprecated _ = False
2809
2810 {-
2811 - Below we export user facing symbols for GHC dynamic flags for use with the
2812 - GHC API.
2813 -}
2814
2815 -- All dynamic flags present in GHC.
2816 flagsAll :: [Flag (CmdLineP DynFlags)]
2817 flagsAll = map snd flagsAllDeps
2818
2819 -- All dynamic flags present in GHC with deprecation information.
2820 flagsAllDeps :: [(Deprecation, Flag (CmdLineP DynFlags))]
2821 flagsAllDeps = package_flags_deps ++ dynamic_flags_deps
2822
2823
2824 -- All dynamic flags, minus package flags, present in GHC.
2825 flagsDynamic :: [Flag (CmdLineP DynFlags)]
2826 flagsDynamic = map snd dynamic_flags_deps
2827
2828 -- ALl package flags present in GHC.
2829 flagsPackage :: [Flag (CmdLineP DynFlags)]
2830 flagsPackage = map snd package_flags_deps
2831
2832 ----------------Helpers to make flags and keep deprecation information----------
2833
2834 type FlagMaker m = String -> OptKind m -> Flag m
2835 type DynFlagMaker = FlagMaker (CmdLineP DynFlags)
2836 data Deprecation = NotDeprecated | Deprecated deriving (Eq, Ord)
2837
2838 -- Make a non-deprecated flag
2839 make_ord_flag :: DynFlagMaker -> String -> OptKind (CmdLineP DynFlags)
2840 -> (Deprecation, Flag (CmdLineP DynFlags))
2841 make_ord_flag fm name kind = (NotDeprecated, fm name kind)
2842
2843 -- Make a deprecated flag
2844 make_dep_flag :: DynFlagMaker -> String -> OptKind (CmdLineP DynFlags) -> String
2845 -> (Deprecation, Flag (CmdLineP DynFlags))
2846 make_dep_flag fm name kind message = (Deprecated,
2847 fm name $ add_dep_message kind message)
2848
2849 add_dep_message :: OptKind (CmdLineP DynFlags) -> String
2850 -> OptKind (CmdLineP DynFlags)
2851 add_dep_message (NoArg f) message = NoArg $ f >> deprecate message
2852 add_dep_message (HasArg f) message = HasArg $ \s -> f s >> deprecate message
2853 add_dep_message (SepArg f) message = SepArg $ \s -> f s >> deprecate message
2854 add_dep_message (Prefix f) message = Prefix $ \s -> f s >> deprecate message
2855 add_dep_message (OptPrefix f) message =
2856 OptPrefix $ \s -> f s >> deprecate message
2857 add_dep_message (OptIntSuffix f) message =
2858 OptIntSuffix $ \oi -> f oi >> deprecate message
2859 add_dep_message (IntSuffix f) message =
2860 IntSuffix $ \i -> f i >> deprecate message
2861 add_dep_message (FloatSuffix f) message =
2862 FloatSuffix $ \fl -> f fl >> deprecate message
2863 add_dep_message (PassFlag f) message =
2864 PassFlag $ \s -> f s >> deprecate message
2865 add_dep_message (AnySuffix f) message =
2866 AnySuffix $ \s -> f s >> deprecate message
2867
2868 ----------------------- The main flags themselves ------------------------------
2869 -- See Note [Updating flag description in the User's Guide]
2870 -- See Note [Supporting CLI completion]
2871 dynamic_flags_deps :: [(Deprecation, Flag (CmdLineP DynFlags))]
2872 dynamic_flags_deps = [
2873 make_dep_flag defFlag "n" (NoArg $ return ())
2874 "The -n flag is deprecated and no longer has any effect"
2875 , make_ord_flag defFlag "cpp" (NoArg (setExtensionFlag LangExt.Cpp))
2876 , make_ord_flag defFlag "F" (NoArg (setGeneralFlag Opt_Pp))
2877 , (Deprecated, defFlag "#include"
2878 (HasArg (\_s ->
2879 deprecate ("-#include and INCLUDE pragmas are " ++
2880 "deprecated: They no longer have any effect"))))
2881 , make_ord_flag defFlag "v" (OptIntSuffix setVerbosity)
2882
2883 , make_ord_flag defGhcFlag "j" (OptIntSuffix
2884 (\n -> case n of
2885 Just n
2886 | n > 0 -> upd (\d -> d { parMakeCount = Just n })
2887 | otherwise -> addErr "Syntax: -j[n] where n > 0"
2888 Nothing -> upd (\d -> d { parMakeCount = Nothing })))
2889 -- When the number of parallel builds
2890 -- is omitted, it is the same
2891 -- as specifing that the number of
2892 -- parallel builds is equal to the
2893 -- result of getNumProcessors
2894 , make_ord_flag defFlag "instantiated-with" (sepArg setUnitIdInsts)
2895 , make_ord_flag defFlag "this-component-id" (sepArg setComponentId)
2896
2897 -- RTS options -------------------------------------------------------------
2898 , make_ord_flag defFlag "H" (HasArg (\s -> upd (\d ->
2899 d { ghcHeapSize = Just $ fromIntegral (decodeSize s)})))
2900
2901 , make_ord_flag defFlag "Rghc-timing" (NoArg (upd (\d ->
2902 d { enableTimeStats = True })))
2903
2904 ------- ways ---------------------------------------------------------------
2905 , make_ord_flag defGhcFlag "prof" (NoArg (addWay WayProf))
2906 , make_ord_flag defGhcFlag "eventlog" (NoArg (addWay WayEventLog))
2907 , make_dep_flag defGhcFlag "smp"
2908 (NoArg $ addWay WayThreaded) "Use -threaded instead"
2909 , make_ord_flag defGhcFlag "debug" (NoArg (addWay WayDebug))
2910 , make_ord_flag defGhcFlag "threaded" (NoArg (addWay WayThreaded))
2911
2912 , make_ord_flag defGhcFlag "ticky"
2913 (NoArg (setGeneralFlag Opt_Ticky >> addWay WayDebug))
2914
2915 -- -ticky enables ticky-ticky code generation, and also implies -debug which
2916 -- is required to get the RTS ticky support.
2917
2918 ----- Linker --------------------------------------------------------
2919 , make_ord_flag defGhcFlag "static" (NoArg removeWayDyn)
2920 , make_ord_flag defGhcFlag "dynamic" (NoArg (addWay WayDyn))
2921 , make_ord_flag defGhcFlag "rdynamic" $ noArg $
2922 #if defined(linux_HOST_OS)
2923 addOptl "-rdynamic"
2924 #elif defined (mingw32_HOST_OS)
2925 addOptl "-Wl,--export-all-symbols"
2926 #else
2927 -- ignored for compat w/ gcc:
2928 id
2929 #endif
2930 , make_ord_flag defGhcFlag "relative-dynlib-paths"
2931 (NoArg (setGeneralFlag Opt_RelativeDynlibPaths))
2932 , make_ord_flag defGhcFlag "copy-libs-when-linking"
2933 (NoArg (setGeneralFlag Opt_SingleLibFolder))
2934 , make_ord_flag defGhcFlag "pie" (NoArg (setGeneralFlag Opt_PICExecutable))
2935 , make_ord_flag defGhcFlag "no-pie" (NoArg (unSetGeneralFlag Opt_PICExecutable))
2936
2937 ------- Specific phases --------------------------------------------
2938 -- need to appear before -pgmL to be parsed as LLVM flags.
2939 , make_ord_flag defFlag "pgmlo"
2940 (hasArg (\f -> alterSettings (\s -> s { sPgm_lo = (f,[])})))
2941 , make_ord_flag defFlag "pgmlc"
2942 (hasArg (\f -> alterSettings (\s -> s { sPgm_lc = (f,[])})))
2943 , make_ord_flag defFlag "pgmi"
2944 (hasArg (\f -> alterSettings (\s -> s { sPgm_i = f})))
2945 , make_ord_flag defFlag "pgmL"
2946 (hasArg (\f -> alterSettings (\s -> s { sPgm_L = f})))
2947 , make_ord_flag defFlag "pgmP"
2948 (hasArg setPgmP)
2949 , make_ord_flag defFlag "pgmF"
2950 (hasArg (\f -> alterSettings (\s -> s { sPgm_F = f})))
2951 , make_ord_flag defFlag "pgmc"
2952 (hasArg (\f -> alterSettings (\s -> s { sPgm_c = (f,[]),
2953 -- Don't pass -no-pie with -pgmc
2954 -- (see Trac #15319)
2955 sGccSupportsNoPie = False})))
2956 , make_ord_flag defFlag "pgms"
2957 (hasArg (\f -> alterSettings (\s -> s { sPgm_s = (f,[])})))
2958 , make_ord_flag defFlag "pgma"
2959 (hasArg (\f -> alterSettings (\s -> s { sPgm_a = (f,[])})))
2960 , make_ord_flag defFlag "pgml"
2961 (hasArg (\f -> alterSettings (\s -> s { sPgm_l = (f,[])})))
2962 , make_ord_flag defFlag "pgmdll"
2963 (hasArg (\f -> alterSettings (\s -> s { sPgm_dll = (f,[])})))
2964 , make_ord_flag defFlag "pgmwindres"
2965 (hasArg (\f -> alterSettings (\s -> s { sPgm_windres = f})))
2966 , make_ord_flag defFlag "pgmlibtool"
2967 (hasArg (\f -> alterSettings (\s -> s { sPgm_libtool = f})))
2968 , make_ord_flag defFlag "pgmar"
2969 (hasArg (\f -> alterSettings (\s -> s { sPgm_ar = f})))
2970 , make_ord_flag defFlag "pgmranlib"
2971 (hasArg (\f -> alterSettings (\s -> s { sPgm_ranlib = f})))
2972
2973
2974 -- need to appear before -optl/-opta to be parsed as LLVM flags.
2975 , make_ord_flag defFlag "optlo"
2976 (hasArg (\f -> alterSettings (\s -> s { sOpt_lo = f : sOpt_lo s})))
2977 , make_ord_flag defFlag "optlc"
2978 (hasArg (\f -> alterSettings (\s -> s { sOpt_lc = f : sOpt_lc s})))
2979 , make_ord_flag defFlag "opti"
2980 (hasArg (\f -> alterSettings (\s -> s { sOpt_i = f : sOpt_i s})))
2981 , make_ord_flag defFlag "optL"
2982 (hasArg (\f -> alterSettings (\s -> s { sOpt_L = f : sOpt_L s})))
2983 , make_ord_flag defFlag "optP"
2984 (hasArg addOptP)
2985 , make_ord_flag defFlag "optF"
2986 (hasArg (\f -> alterSettings (\s -> s { sOpt_F = f : sOpt_F s})))
2987 , make_ord_flag defFlag "optc"
2988 (hasArg addOptc)
2989 , make_ord_flag defFlag "opta"
2990 (hasArg (\f -> alterSettings (\s -> s { sOpt_a = f : sOpt_a s})))
2991 , make_ord_flag defFlag "optl"
2992 (hasArg addOptl)
2993 , make_ord_flag defFlag "optwindres"
2994 (hasArg (\f ->
2995 alterSettings (\s -> s { sOpt_windres = f : sOpt_windres s})))
2996
2997 , make_ord_flag defGhcFlag "split-objs"
2998 (NoArg (if can_split
2999 then setGeneralFlag Opt_SplitObjs
3000 else addWarn "ignoring -split-objs"))
3001
3002 , make_ord_flag defGhcFlag "split-sections"
3003 (noArgM (\dflags -> do
3004 if platformHasSubsectionsViaSymbols (targetPlatform dflags)
3005 then do addErr $
3006 "-split-sections is not useful on this platform " ++
3007 "since it always uses subsections via symbols."
3008 return dflags
3009 else return (gopt_set dflags Opt_SplitSections)))
3010
3011 -------- ghc -M -----------------------------------------------------
3012 , make_ord_flag defGhcFlag "dep-suffix" (hasArg addDepSuffix)
3013 , make_ord_flag defGhcFlag "dep-makefile" (hasArg setDepMakefile)
3014 , make_ord_flag defGhcFlag "include-pkg-deps"
3015 (noArg (setDepIncludePkgDeps True))
3016 , make_ord_flag defGhcFlag "exclude-module" (hasArg addDepExcludeMod)
3017
3018 -------- Linking ----------------------------------------------------
3019 , make_ord_flag defGhcFlag "no-link"
3020 (noArg (\d -> d { ghcLink=NoLink }))
3021 , make_ord_flag defGhcFlag "shared"
3022 (noArg (\d -> d { ghcLink=LinkDynLib }))
3023 , make_ord_flag defGhcFlag "staticlib"
3024 (noArg (\d -> d { ghcLink=LinkStaticLib }))
3025 , make_ord_flag defGhcFlag "dynload" (hasArg parseDynLibLoaderMode)
3026 , make_ord_flag defGhcFlag "dylib-install-name" (hasArg setDylibInstallName)
3027
3028 ------- Libraries ---------------------------------------------------
3029 , make_ord_flag defFlag "L" (Prefix addLibraryPath)
3030 , make_ord_flag defFlag "l" (hasArg (addLdInputs . Option . ("-l" ++)))
3031
3032 ------- Frameworks --------------------------------------------------
3033 -- -framework-path should really be -F ...
3034 , make_ord_flag defFlag "framework-path" (HasArg addFrameworkPath)
3035 , make_ord_flag defFlag "framework" (hasArg addCmdlineFramework)
3036
3037 ------- Output Redirection ------------------------------------------
3038 , make_ord_flag defGhcFlag "odir" (hasArg setObjectDir)
3039 , make_ord_flag defGhcFlag "o" (sepArg (setOutputFile . Just))
3040 , make_ord_flag defGhcFlag "dyno"
3041 (sepArg (setDynOutputFile . Just))
3042 , make_ord_flag defGhcFlag "ohi"
3043 (hasArg (setOutputHi . Just ))
3044 , make_ord_flag defGhcFlag "osuf" (hasArg setObjectSuf)
3045 , make_ord_flag defGhcFlag "dynosuf" (hasArg setDynObjectSuf)
3046 , make_ord_flag defGhcFlag "hcsuf" (hasArg setHcSuf)
3047 , make_ord_flag defGhcFlag "hisuf" (hasArg setHiSuf)
3048 , make_ord_flag defGhcFlag "dynhisuf" (hasArg setDynHiSuf)
3049 , make_ord_flag defGhcFlag "hidir" (hasArg setHiDir)
3050 , make_ord_flag defGhcFlag "tmpdir" (hasArg setTmpDir)
3051 , make_ord_flag defGhcFlag "stubdir" (hasArg setStubDir)
3052 , make_ord_flag defGhcFlag "dumpdir" (hasArg setDumpDir)
3053 , make_ord_flag defGhcFlag "outputdir" (hasArg setOutputDir)
3054 , make_ord_flag defGhcFlag "ddump-file-prefix"
3055 (hasArg (setDumpPrefixForce . Just))
3056
3057 , make_ord_flag defGhcFlag "dynamic-too"
3058 (NoArg (setGeneralFlag Opt_BuildDynamicToo))
3059
3060 ------- Keeping temporary files -------------------------------------
3061 -- These can be singular (think ghc -c) or plural (think ghc --make)
3062 , make_ord_flag defGhcFlag "keep-hc-file"
3063 (NoArg (setGeneralFlag Opt_KeepHcFiles))
3064 , make_ord_flag defGhcFlag "keep-hc-files"
3065 (NoArg (setGeneralFlag Opt_KeepHcFiles))
3066 , make_ord_flag defGhcFlag "keep-hscpp-file"
3067 (NoArg (setGeneralFlag Opt_KeepHscppFiles))
3068 , make_ord_flag defGhcFlag "keep-hscpp-files"
3069 (NoArg (setGeneralFlag Opt_KeepHscppFiles))
3070 , make_ord_flag defGhcFlag "keep-s-file"
3071 (NoArg (setGeneralFlag Opt_KeepSFiles))
3072 , make_ord_flag defGhcFlag "keep-s-files"
3073 (NoArg (setGeneralFlag Opt_KeepSFiles))
3074 , make_ord_flag defGhcFlag "keep-llvm-file"
3075 (NoArg $ setObjTarget HscLlvm >> setGeneralFlag Opt_KeepLlvmFiles)
3076 , make_ord_flag defGhcFlag "keep-llvm-files"
3077 (NoArg $ setObjTarget HscLlvm >> setGeneralFlag Opt_KeepLlvmFiles)
3078 -- This only makes sense as plural
3079 , make_ord_flag defGhcFlag "keep-tmp-files"
3080 (NoArg (setGeneralFlag Opt_KeepTmpFiles))
3081 , make_ord_flag defGhcFlag "keep-hi-file"
3082 (NoArg (setGeneralFlag Opt_KeepHiFiles))
3083 , make_ord_flag defGhcFlag "no-keep-hi-file"
3084 (NoArg (unSetGeneralFlag Opt_KeepHiFiles))
3085 , make_ord_flag defGhcFlag "keep-hi-files"
3086 (NoArg (setGeneralFlag Opt_KeepHiFiles))
3087 , make_ord_flag defGhcFlag "no-keep-hi-files"
3088 (NoArg (unSetGeneralFlag Opt_KeepHiFiles))
3089 , make_ord_flag defGhcFlag "keep-o-file"
3090 (NoArg (setGeneralFlag Opt_KeepOFiles))
3091 , make_ord_flag defGhcFlag "no-keep-o-file"
3092 (NoArg (unSetGeneralFlag Opt_KeepOFiles))
3093 , make_ord_flag defGhcFlag "keep-o-files"
3094 (NoArg (setGeneralFlag Opt_KeepOFiles))
3095 , make_ord_flag defGhcFlag "no-keep-o-files"
3096 (NoArg (unSetGeneralFlag Opt_KeepOFiles))
3097
3098 ------- Miscellaneous ----------------------------------------------
3099 , make_ord_flag defGhcFlag "no-auto-link-packages"
3100 (NoArg (unSetGeneralFlag Opt_AutoLinkPackages))
3101 , make_ord_flag defGhcFlag "no-hs-main"
3102 (NoArg (setGeneralFlag Opt_NoHsMain))
3103 , make_ord_flag defGhcFlag "fno-state-hack"
3104 (NoArg (setGeneralFlag Opt_G_NoStateHack))
3105 , make_ord_flag defGhcFlag "fno-opt-coercion"
3106 (NoArg (setGeneralFlag Opt_G_NoOptCoercion))
3107 , make_ord_flag defGhcFlag "with-rtsopts"
3108 (HasArg setRtsOpts)
3109 , make_ord_flag defGhcFlag "rtsopts"
3110 (NoArg (setRtsOptsEnabled RtsOptsAll))
3111 , make_ord_flag defGhcFlag "rtsopts=all"
3112 (NoArg (setRtsOptsEnabled RtsOptsAll))
3113 , make_ord_flag defGhcFlag "rtsopts=some"
3114 (NoArg (setRtsOptsEnabled RtsOptsSafeOnly))
3115 , make_ord_flag defGhcFlag "rtsopts=none"
3116 (NoArg (setRtsOptsEnabled RtsOptsNone))
3117 , make_ord_flag defGhcFlag "rtsopts=ignore"
3118 (NoArg (setRtsOptsEnabled RtsOptsIgnore))
3119 , make_ord_flag defGhcFlag "rtsopts=ignoreAll"
3120 (NoArg (setRtsOptsEnabled RtsOptsIgnoreAll))
3121 , make_ord_flag defGhcFlag "no-rtsopts"
3122 (NoArg (setRtsOptsEnabled RtsOptsNone))
3123 , make_ord_flag defGhcFlag "no-rtsopts-suggestions"
3124 (noArg (\d -> d {rtsOptsSuggestions = False}))
3125 , make_ord_flag defGhcFlag "dhex-word-literals"
3126 (NoArg (setGeneralFlag Opt_HexWordLiterals))
3127
3128 , make_ord_flag defGhcFlag "ghcversion-file" (hasArg addGhcVersionFile)
3129 , make_ord_flag defGhcFlag "main-is" (SepArg setMainIs)
3130 , make_ord_flag defGhcFlag "haddock" (NoArg (setGeneralFlag Opt_Haddock))
3131 , make_ord_flag defGhcFlag "haddock-opts" (hasArg addHaddockOpts)
3132 , make_ord_flag defGhcFlag "hpcdir" (SepArg setOptHpcDir)
3133 , make_ord_flag defGhciFlag "ghci-script" (hasArg addGhciScript)
3134 , make_ord_flag defGhciFlag "interactive-print" (hasArg setInteractivePrint)
3135 , make_ord_flag defGhcFlag "ticky-allocd"
3136 (NoArg (setGeneralFlag Opt_Ticky_Allocd))
3137 , make_ord_flag defGhcFlag "ticky-LNE"
3138 (NoArg (setGeneralFlag Opt_Ticky_LNE))
3139 , make_ord_flag defGhcFlag "ticky-dyn-thunk"
3140 (NoArg (setGeneralFlag Opt_Ticky_Dyn_Thunk))
3141 ------- recompilation checker --------------------------------------
3142 , make_dep_flag defGhcFlag "recomp"
3143 (NoArg $ unSetGeneralFlag Opt_ForceRecomp)
3144 "Use -fno-force-recomp instead"
3145 , make_dep_flag defGhcFlag "no-recomp"
3146 (NoArg $ setGeneralFlag Opt_ForceRecomp) "Use -fforce-recomp instead"
3147 , make_ord_flag defFlag "fmax-errors"
3148 (intSuffix (\n d -> d { maxErrors = Just (max 1 n) }))
3149 , make_ord_flag defFlag "fno-max-errors"
3150 (noArg (\d -> d { maxErrors = Nothing }))
3151 , make_ord_flag defFlag "freverse-errors"
3152 (noArg (\d -> d {reverseErrors = True} ))
3153 , make_ord_flag defFlag "fno-reverse-errors"
3154 (noArg (\d -> d {reverseErrors = False} ))
3155
3156 ------ HsCpp opts ---------------------------------------------------
3157 , make_ord_flag defFlag "D" (AnySuffix (upd . addOptP))
3158 , make_ord_flag defFlag "U" (AnySuffix (upd . addOptP))
3159
3160 ------- Include/Import Paths ----------------------------------------
3161 , make_ord_flag defFlag "I" (Prefix addIncludePath)
3162 , make_ord_flag defFlag "i" (OptPrefix addImportPath)
3163
3164 ------ Output style options -----------------------------------------
3165 , make_ord_flag defFlag "dppr-user-length" (intSuffix (\n d ->
3166 d { pprUserLength = n }))
3167 , make_ord_flag defFlag "dppr-cols" (intSuffix (\n d ->
3168 d { pprCols = n }))
3169 , make_ord_flag defFlag "fdiagnostics-color=auto"
3170 (NoArg (upd (\d -> d { useColor = Auto })))
3171 , make_ord_flag defFlag "fdiagnostics-color=always"
3172 (NoArg (upd (\d -> d { useColor = Always })))
3173 , make_ord_flag defFlag "fdiagnostics-color=never"
3174 (NoArg (upd (\d -> d { useColor = Never })))
3175
3176 -- Suppress all that is suppressable in core dumps.
3177 -- Except for uniques, as some simplifier phases introduce new variables that
3178 -- have otherwise identical names.
3179 , make_ord_flag defGhcFlag "dsuppress-all"
3180 (NoArg $ do setGeneralFlag Opt_SuppressCoercions
3181 setGeneralFlag Opt_SuppressVarKinds
3182 setGeneralFlag Opt_SuppressModulePrefixes
3183 setGeneralFlag Opt_SuppressTypeApplications
3184 setGeneralFlag Opt_SuppressIdInfo
3185 setGeneralFlag Opt_SuppressTicks
3186 setGeneralFlag Opt_SuppressStgExts
3187 setGeneralFlag Opt_SuppressTypeSignatures
3188 setGeneralFlag Opt_SuppressTimestamps)
3189
3190 ------ Debugging ----------------------------------------------------
3191 , make_ord_flag defGhcFlag "dstg-stats"
3192 (NoArg (setGeneralFlag Opt_StgStats))
3193
3194 , make_ord_flag defGhcFlag "ddump-cmm"
3195 (setDumpFlag Opt_D_dump_cmm)
3196 , make_ord_flag defGhcFlag "ddump-cmm-from-stg"
3197 (setDumpFlag Opt_D_dump_cmm_from_stg)
3198 , make_ord_flag defGhcFlag "ddump-cmm-raw"
3199 (setDumpFlag Opt_D_dump_cmm_raw)
3200 , make_ord_flag defGhcFlag "ddump-cmm-verbose"
3201 (setDumpFlag Opt_D_dump_cmm_verbose)
3202 , make_ord_flag defGhcFlag "ddump-cmm-cfg"
3203 (setDumpFlag Opt_D_dump_cmm_cfg)
3204 , make_ord_flag defGhcFlag "ddump-cmm-cbe"
3205 (setDumpFlag Opt_D_dump_cmm_cbe)
3206 , make_ord_flag defGhcFlag "ddump-cmm-switch"
3207 (setDumpFlag Opt_D_dump_cmm_switch)
3208 , make_ord_flag defGhcFlag "ddump-cmm-proc"
3209 (setDumpFlag Opt_D_dump_cmm_proc)
3210 , make_ord_flag defGhcFlag "ddump-cmm-sp"
3211 (setDumpFlag Opt_D_dump_cmm_sp)
3212 , make_ord_flag defGhcFlag "ddump-cmm-sink"
3213 (setDumpFlag Opt_D_dump_cmm_sink)
3214 , make_ord_flag defGhcFlag "ddump-cmm-caf"
3215 (setDumpFlag Opt_D_dump_cmm_caf)
3216 , make_ord_flag defGhcFlag "ddump-cmm-procmap"
3217 (setDumpFlag Opt_D_dump_cmm_procmap)
3218 , make_ord_flag defGhcFlag "ddump-cmm-split"
3219 (setDumpFlag Opt_D_dump_cmm_split)
3220 , make_ord_flag defGhcFlag "ddump-cmm-info"
3221 (setDumpFlag Opt_D_dump_cmm_info)
3222 , make_ord_flag defGhcFlag "ddump-cmm-cps"
3223 (setDumpFlag Opt_D_dump_cmm_cps)
3224 , make_ord_flag defGhcFlag "ddump-cfg-weights"
3225 (setDumpFlag Opt_D_dump_cfg_weights)
3226 , make_ord_flag defGhcFlag "ddump-core-stats"
3227 (setDumpFlag Opt_D_dump_core_stats)
3228 , make_ord_flag defGhcFlag "ddump-asm"
3229 (setDumpFlag Opt_D_dump_asm)
3230 , make_ord_flag defGhcFlag "ddump-asm-native"
3231 (setDumpFlag Opt_D_dump_asm_native)
3232 , make_ord_flag defGhcFlag "ddump-asm-liveness"
3233 (setDumpFlag Opt_D_dump_asm_liveness)
3234 , make_ord_flag defGhcFlag "ddump-asm-regalloc"
3235 (setDumpFlag Opt_D_dump_asm_regalloc)
3236 , make_ord_flag defGhcFlag "ddump-asm-conflicts"
3237 (setDumpFlag Opt_D_dump_asm_conflicts)
3238 , make_ord_flag defGhcFlag "ddump-asm-regalloc-stages"
3239 (setDumpFlag Opt_D_dump_asm_regalloc_stages)
3240 , make_ord_flag defGhcFlag "ddump-asm-stats"
3241 (setDumpFlag Opt_D_dump_asm_stats)
3242 , make_ord_flag defGhcFlag "ddump-asm-expanded"
3243 (setDumpFlag Opt_D_dump_asm_expanded)
3244 , make_ord_flag defGhcFlag "ddump-llvm"
3245 (NoArg $ setObjTarget HscLlvm >> setDumpFlag' Opt_D_dump_llvm)
3246 , make_ord_flag defGhcFlag "ddump-deriv"
3247 (setDumpFlag Opt_D_dump_deriv)
3248 , make_ord_flag defGhcFlag "ddump-ds"
3249 (setDumpFlag Opt_D_dump_ds)
3250 , make_ord_flag defGhcFlag "ddump-ds-preopt"
3251 (setDumpFlag Opt_D_dump_ds_preopt)
3252 , make_ord_flag defGhcFlag "ddump-foreign"
3253 (setDumpFlag Opt_D_dump_foreign)
3254 , make_ord_flag defGhcFlag "ddump-inlinings"
3255 (setDumpFlag Opt_D_dump_inlinings)
3256 , make_ord_flag defGhcFlag "ddump-rule-firings"
3257 (setDumpFlag Opt_D_dump_rule_firings)
3258 , make_ord_flag defGhcFlag "ddump-rule-rewrites"
3259 (setDumpFlag Opt_D_dump_rule_rewrites)
3260 , make_ord_flag defGhcFlag "ddump-simpl-trace"
3261 (setDumpFlag Opt_D_dump_simpl_trace)
3262 , make_ord_flag defGhcFlag "ddump-occur-anal"
3263 (setDumpFlag Opt_D_dump_occur_anal)
3264 , make_ord_flag defGhcFlag "ddump-parsed"
3265 (setDumpFlag Opt_D_dump_parsed)
3266 , make_ord_flag defGhcFlag "ddump-parsed-ast"
3267 (setDumpFlag Opt_D_dump_parsed_ast)
3268 , make_ord_flag defGhcFlag "ddump-rn"
3269 (setDumpFlag Opt_D_dump_rn)
3270 , make_ord_flag defGhcFlag "ddump-rn-ast"
3271 (setDumpFlag Opt_D_dump_rn_ast)
3272 , make_ord_flag defGhcFlag "ddump-simpl"
3273 (setDumpFlag Opt_D_dump_simpl)
3274 , make_ord_flag defGhcFlag "ddump-simpl-iterations"
3275 (setDumpFlag Opt_D_dump_simpl_iterations)
3276 , make_ord_flag defGhcFlag "ddump-spec"
3277 (setDumpFlag Opt_D_dump_spec)
3278 , make_ord_flag defGhcFlag "ddump-prep"
3279 (setDumpFlag Opt_D_dump_prep)
3280 , make_ord_flag defGhcFlag "ddump-stg"
3281 (setDumpFlag Opt_D_dump_stg)
3282 , make_ord_flag defGhcFlag "ddump-call-arity"
3283 (setDumpFlag Opt_D_dump_call_arity)
3284 , make_ord_flag defGhcFlag "ddump-exitify"
3285 (setDumpFlag Opt_D_dump_exitify)
3286 , make_ord_flag defGhcFlag "ddump-stranal"
3287 (setDumpFlag Opt_D_dump_stranal)
3288 , make_ord_flag defGhcFlag "ddump-str-signatures"
3289 (setDumpFlag Opt_D_dump_str_signatures)
3290 , make_ord_flag defGhcFlag "ddump-tc"
3291 (setDumpFlag Opt_D_dump_tc)
3292 , make_ord_flag defGhcFlag "ddump-tc-ast"
3293 (setDumpFlag Opt_D_dump_tc_ast)
3294 , make_ord_flag defGhcFlag "ddump-types"
3295 (setDumpFlag Opt_D_dump_types)
3296 , make_ord_flag defGhcFlag "ddump-rules"
3297 (setDumpFlag Opt_D_dump_rules)
3298 , make_ord_flag defGhcFlag "ddump-cse"
3299 (setDumpFlag Opt_D_dump_cse)
3300 , make_ord_flag defGhcFlag "ddump-worker-wrapper"
3301 (setDumpFlag Opt_D_dump_worker_wrapper)
3302 , make_ord_flag defGhcFlag "ddump-rn-trace"
3303 (setDumpFlag Opt_D_dump_rn_trace)
3304 , make_ord_flag defGhcFlag "ddump-shape"
3305 (setDumpFlag Opt_D_dump_shape)
3306 , make_ord_flag defGhcFlag "ddump-if-trace"
3307 (setDumpFlag Opt_D_dump_if_trace)
3308 , make_ord_flag defGhcFlag "ddump-cs-trace"
3309 (setDumpFlag Opt_D_dump_cs_trace)
3310 , make_ord_flag defGhcFlag "ddump-tc-trace"
3311 (NoArg (do setDumpFlag' Opt_D_dump_tc_trace
3312 setDumpFlag' Opt_D_dump_cs_trace))
3313 , make_ord_flag defGhcFlag "ddump-ec-trace"
3314 (setDumpFlag Opt_D_dump_ec_trace)
3315 , make_ord_flag defGhcFlag "ddump-vt-trace"
3316 (setDumpFlag Opt_D_dump_vt_trace)
3317 , make_ord_flag defGhcFlag "ddump-splices"
3318 (setDumpFlag Opt_D_dump_splices)
3319 , make_ord_flag defGhcFlag "dth-dec-file"
3320 (setDumpFlag Opt_D_th_dec_file)
3321
3322 , make_ord_flag defGhcFlag "ddump-rn-stats"
3323 (setDumpFlag Opt_D_dump_rn_stats)
3324 , make_ord_flag defGhcFlag "ddump-opt-cmm"
3325 (setDumpFlag Opt_D_dump_opt_cmm)
3326 , make_ord_flag defGhcFlag "ddump-simpl-stats"
3327 (setDumpFlag Opt_D_dump_simpl_stats)
3328 , make_ord_flag defGhcFlag "ddump-bcos"
3329 (setDumpFlag Opt_D_dump_BCOs)
3330 , make_ord_flag defGhcFlag "dsource-stats"
3331 (setDumpFlag Opt_D_source_stats)
3332 , make_ord_flag defGhcFlag "dverbose-core2core"
3333 (NoArg $ setVerbosity (Just 2) >> setVerboseCore2Core)
3334 , make_ord_flag defGhcFlag "dverbose-stg2stg"
3335 (setDumpFlag Opt_D_verbose_stg2stg)
3336 , make_ord_flag defGhcFlag "ddump-hi"
3337 (setDumpFlag Opt_D_dump_hi)
3338 , make_ord_flag defGhcFlag "ddump-minimal-imports"
3339 (NoArg (setGeneralFlag Opt_D_dump_minimal_imports))
3340 , make_ord_flag defGhcFlag "ddump-hpc"
3341 (setDumpFlag Opt_D_dump_ticked) -- back compat
3342 , make_ord_flag defGhcFlag "ddump-ticked"
3343 (setDumpFlag Opt_D_dump_ticked)
3344 , make_ord_flag defGhcFlag "ddump-mod-cycles"
3345 (setDumpFlag Opt_D_dump_mod_cycles)
3346 , make_ord_flag defGhcFlag "ddump-mod-map"
3347 (setDumpFlag Opt_D_dump_mod_map)
3348 , make_ord_flag defGhcFlag "ddump-timings"
3349 (setDumpFlag Opt_D_dump_timings)
3350 , make_ord_flag defGhcFlag "ddump-view-pattern-commoning"
3351 (setDumpFlag Opt_D_dump_view_pattern_commoning)
3352 , make_ord_flag defGhcFlag "ddump-to-file"
3353 (NoArg (setGeneralFlag Opt_DumpToFile))
3354 , make_ord_flag defGhcFlag "ddump-hi-diffs"
3355 (setDumpFlag Opt_D_dump_hi_diffs)
3356 , make_ord_flag defGhcFlag "ddump-rtti"
3357 (setDumpFlag Opt_D_dump_rtti)
3358 , make_ord_flag defGhcFlag "dcore-lint"
3359 (NoArg (setGeneralFlag Opt_DoCoreLinting))
3360 , make_ord_flag defGhcFlag "dstg-lint"
3361 (NoArg (setGeneralFlag Opt_DoStgLinting))
3362 , make_ord_flag defGhcFlag "dcmm-lint"
3363 (NoArg (setGeneralFlag Opt_DoCmmLinting))
3364 , make_ord_flag defGhcFlag "dasm-lint"
3365 (NoArg (setGeneralFlag Opt_DoAsmLinting))
3366 , make_ord_flag defGhcFlag "dannot-lint"
3367 (NoArg (setGeneralFlag Opt_DoAnnotationLinting))
3368 , make_ord_flag defGhcFlag "dshow-passes"
3369 (NoArg $ forceRecompile >> (setVerbosity $ Just 2))
3370 , make_ord_flag defGhcFlag "dfaststring-stats"
3371 (NoArg (setGeneralFlag Opt_D_faststring_stats))
3372 , make_ord_flag defGhcFlag "dno-llvm-mangler"
3373 (NoArg (setGeneralFlag Opt_NoLlvmMangler)) -- hidden flag
3374 , make_ord_flag defGhcFlag "fast-llvm"
3375 (NoArg (setGeneralFlag Opt_FastLlvm)) -- hidden flag
3376 , make_ord_flag defGhcFlag "ddump-debug"
3377 (setDumpFlag Opt_D_dump_debug)
3378 , make_ord_flag defGhcFlag "ddump-json"
3379 (noArg (flip dopt_set Opt_D_dump_json . setJsonLogAction ) )
3380 , make_ord_flag defGhcFlag "dppr-debug"
3381 (setDumpFlag Opt_D_ppr_debug)
3382 , make_ord_flag defGhcFlag "ddebug-output"
3383 (noArg (flip dopt_unset Opt_D_no_debug_output))
3384 , make_ord_flag defGhcFlag "dno-debug-output"
3385 (setDumpFlag Opt_D_no_debug_output)
3386
3387 ------ Machine dependent (-m<blah>) stuff ---------------------------
3388
3389 , make_ord_flag defGhcFlag "msse" (noArg (\d ->
3390 d { sseVersion = Just SSE1 }))
3391 , make_ord_flag defGhcFlag "msse2" (noArg (\d ->
3392 d { sseVersion = Just SSE2 }))
3393 , make_ord_flag defGhcFlag "msse3" (noArg (\d ->
3394 d { sseVersion = Just SSE3 }))
3395 , make_ord_flag defGhcFlag "msse4" (noArg (\d ->
3396 d { sseVersion = Just SSE4 }))
3397 , make_ord_flag defGhcFlag "msse4.2" (noArg (\d ->
3398 d { sseVersion = Just SSE42 }))
3399 , make_ord_flag defGhcFlag "mbmi" (noArg (\d ->
3400 d { bmiVersion = Just BMI1 }))
3401 , make_ord_flag defGhcFlag "mbmi2" (noArg (\d ->
3402 d { bmiVersion = Just BMI2 }))
3403 , make_ord_flag defGhcFlag "mavx" (noArg (\d -> d { avx = True }))
3404 , make_ord_flag defGhcFlag "mavx2" (noArg (\d -> d { avx2 = True }))
3405 , make_ord_flag defGhcFlag "mavx512cd" (noArg (\d ->
3406 d { avx512cd = True }))
3407 , make_ord_flag defGhcFlag "mavx512er" (noArg (\d ->
3408 d { avx512er = True }))
3409 , make_ord_flag defGhcFlag "mavx512f" (noArg (\d -> d { avx512f = True }))
3410 , make_ord_flag defGhcFlag "mavx512pf" (noArg (\d ->
3411 d { avx512pf = True }))
3412
3413 ------ Warning opts -------------------------------------------------
3414 , make_ord_flag defFlag "W" (NoArg (mapM_ setWarningFlag minusWOpts))
3415 , make_ord_flag defFlag "Werror"
3416 (NoArg (do { setGeneralFlag Opt_WarnIsError
3417 ; mapM_ setFatalWarningFlag minusWeverythingOpts }))
3418 , make_ord_flag defFlag "Wwarn"
3419 (NoArg (do { unSetGeneralFlag Opt_WarnIsError
3420 ; mapM_ unSetFatalWarningFlag minusWeverythingOpts }))
3421 -- Opt_WarnIsError is still needed to pass -Werror
3422 -- to CPP; see runCpp in SysTools
3423 , make_dep_flag defFlag "Wnot" (NoArg (upd (\d ->
3424 d {warningFlags = EnumSet.empty})))
3425 "Use -w or -Wno-everything instead"
3426 , make_ord_flag defFlag "w" (NoArg (upd (\d ->
3427 d {warningFlags = EnumSet.empty})))
3428
3429 -- New-style uniform warning sets
3430 --
3431 -- Note that -Weverything > -Wall > -Wextra > -Wdefault > -Wno-everything
3432 , make_ord_flag defFlag "Weverything" (NoArg (mapM_
3433 setWarningFlag minusWeverythingOpts))
3434 , make_ord_flag defFlag "Wno-everything"
3435 (NoArg (upd (\d -> d {warningFlags = EnumSet.empty})))
3436
3437 , make_ord_flag defFlag "Wall" (NoArg (mapM_
3438 setWarningFlag minusWallOpts))
3439 , make_ord_flag defFlag "Wno-all" (NoArg (mapM_
3440 unSetWarningFlag minusWallOpts))
3441
3442 , make_ord_flag defFlag "Wextra" (NoArg (mapM_
3443 setWarningFlag minusWOpts))
3444 , make_ord_flag defFlag "Wno-extra" (NoArg (mapM_
3445 unSetWarningFlag minusWOpts))
3446
3447 , make_ord_flag defFlag "Wdefault" (NoArg (mapM_
3448 setWarningFlag standardWarnings))
3449 , make_ord_flag defFlag "Wno-default" (NoArg (mapM_
3450 unSetWarningFlag standardWarnings))
3451
3452 , make_ord_flag defFlag "Wcompat" (NoArg (mapM_
3453 setWarningFlag minusWcompatOpts))
3454 , make_ord_flag defFlag "Wno-compat" (NoArg (mapM_
3455 unSetWarningFlag minusWcompatOpts))
3456
3457 ------ Plugin flags ------------------------------------------------
3458 , make_ord_flag defGhcFlag "fplugin-opt" (hasArg addPluginModuleNameOption)
3459 , make_ord_flag defGhcFlag "fplugin" (hasArg addPluginModuleName)
3460 , make_ord_flag defGhcFlag "ffrontend-opt" (hasArg addFrontendPluginOption)
3461
3462 ------ Optimisation flags ------------------------------------------
3463 , make_dep_flag defGhcFlag "Onot" (noArgM $ setOptLevel 0 )
3464 "Use -O0 instead"
3465 , make_ord_flag defGhcFlag "O" (optIntSuffixM (\mb_n ->
3466 setOptLevel (mb_n `orElse` 1)))
3467 -- If the number is missing, use 1
3468
3469
3470 , make_ord_flag defFlag "fmax-relevant-binds"
3471 (intSuffix (\n d -> d { maxRelevantBinds = Just n }))
3472 , make_ord_flag defFlag "fno-max-relevant-binds"
3473 (noArg (\d -> d { maxRelevantBinds = Nothing }))
3474
3475 , make_ord_flag defFlag "fmax-valid-hole-fits"
3476 (intSuffix (\n d -> d { maxValidHoleFits = Just n }))
3477 , make_ord_flag defFlag "fno-max-valid-hole-fits"
3478 (noArg (\d -> d { maxValidHoleFits = Nothing }))
3479 , make_ord_flag defFlag "fmax-refinement-hole-fits"
3480 (intSuffix (\n d -> d { maxRefHoleFits = Just n }))
3481 , make_ord_flag defFlag "fno-max-refinement-hole-fits"
3482 (noArg (\d -> d { maxRefHoleFits = Nothing }))
3483 , make_ord_flag defFlag "frefinement-level-hole-fits"
3484 (intSuffix (\n d -> d { refLevelHoleFits = Just n }))
3485 , make_ord_flag defFlag "fno-refinement-level-hole-fits"
3486 (noArg (\d -> d { refLevelHoleFits = Nothing }))
3487
3488 , make_dep_flag defGhcFlag "fllvm-pass-vectors-in-regs"
3489 (noArg id)
3490 "vectors registers are now passed in registers by default."
3491 , make_ord_flag defFlag "fmax-uncovered-patterns"
3492 (intSuffix (\n d -> d { maxUncoveredPatterns = n }))
3493 , make_ord_flag defFlag "fsimplifier-phases"
3494 (intSuffix (\n d -> d { simplPhases = n }))
3495 , make_ord_flag defFlag "fmax-simplifier-iterations"
3496 (intSuffix (\n d -> d { maxSimplIterations = n }))
3497 , make_ord_flag defFlag "fmax-pmcheck-iterations"
3498 (intSuffix (\n d -> d{ maxPmCheckIterations = n }))
3499 , make_ord_flag defFlag "fsimpl-tick-factor"
3500 (intSuffix (\n d -> d { simplTickFactor = n }))
3501 , make_ord_flag defFlag "fspec-constr-threshold"
3502 (intSuffix (\n d -> d { specConstrThreshold = Just n }))
3503 , make_ord_flag defFlag "fno-spec-constr-threshold"
3504 (noArg (\d -> d { specConstrThreshold = Nothing }))
3505 , make_ord_flag defFlag "fspec-constr-count"
3506 (intSuffix (\n d -> d { specConstrCount = Just n }))
3507 , make_ord_flag defFlag "fno-spec-constr-count"
3508 (noArg (\d -> d { specConstrCount = Nothing }))
3509 , make_ord_flag defFlag "fspec-constr-recursive"
3510 (intSuffix (\n d -> d { specConstrRecursive = n }))
3511 , make_ord_flag defFlag "fliberate-case-threshold"
3512 (intSuffix (\n d -> d { liberateCaseThreshold = Just n }))
3513 , make_ord_flag defFlag "fno-liberate-case-threshold"
3514 (noArg (\d -> d { liberateCaseThreshold = Nothing }))
3515 , make_ord_flag defFlag "drule-check"
3516 (sepArg (\s d -> d { ruleCheck = Just s }))
3517 , make_ord_flag defFlag "dinline-check"
3518 (sepArg (\s d -> d { inlineCheck = Just s }))
3519 , make_ord_flag defFlag "freduction-depth"
3520 (intSuffix (\n d -> d { reductionDepth = treatZeroAsInf n }))
3521 , make_ord_flag defFlag "fconstraint-solver-iterations"
3522 (intSuffix (\n d -> d { solverIterations = treatZeroAsInf n }))
3523 , (Deprecated, defFlag "fcontext-stack"
3524 (intSuffixM (\n d ->
3525 do { deprecate $ "use -freduction-depth=" ++ show n ++ " instead"
3526 ; return $ d { reductionDepth = treatZeroAsInf n } })))
3527 , (Deprecated, defFlag "ftype-function-depth"
3528 (intSuffixM (\n d ->
3529 do { deprecate $ "use -freduction-depth=" ++ show n ++ " instead"
3530 ; return $ d { reductionDepth = treatZeroAsInf n } })))
3531 , make_ord_flag defFlag "fstrictness-before"
3532 (intSuffix (\n d -> d { strictnessBefore = n : strictnessBefore d }))
3533 , make_ord_flag defFlag "ffloat-lam-args"
3534 (intSuffix (\n d -> d { floatLamArgs = Just n }))
3535 , make_ord_flag defFlag "ffloat-all-lams"
3536 (noArg (\d -> d { floatLamArgs = Nothing }))
3537 , make_ord_flag defFlag "fstg-lift-lams-rec-args"
3538 (intSuffix (\n d -> d { liftLamsRecArgs = Just n }))
3539 , make_ord_flag defFlag "fstg-lift-lams-rec-args-any"
3540 (noArg (\d -> d { liftLamsRecArgs = Nothing }))
3541 , make_ord_flag defFlag "fstg-lift-lams-non-rec-args"
3542 (intSuffix (\n d -> d { liftLamsRecArgs = Just n }))
3543 , make_ord_flag defFlag "fstg-lift-lams-non-rec-args-any"
3544 (noArg (\d -> d { liftLamsRecArgs = Nothing }))
3545 , make_ord_flag defFlag "fstg-lift-lams-known"
3546 (noArg (\d -> d { liftLamsKnown = True }))
3547 , make_ord_flag defFlag "fno-stg-lift-lams-known"
3548 (noArg (\d -> d { liftLamsKnown = False }))
3549 , make_ord_flag defFlag "fproc-alignment"
3550 (intSuffix (\n d -> d { cmmProcAlignment = Just n }))
3551 , make_ord_flag defFlag "fblock-layout-weights"
3552 (HasArg (\s ->
3553 upd (\d -> d { cfgWeightInfo =
3554 parseCfgWeights s (cfgWeightInfo d)})))
3555 , make_ord_flag defFlag "fhistory-size"
3556 (intSuffix (\n d -> d { historySize = n }))
3557 , make_ord_flag defFlag "funfolding-creation-threshold"
3558 (intSuffix (\n d -> d {ufCreationThreshold = n}))
3559 , make_ord_flag defFlag "funfolding-use-threshold"
3560 (intSuffix (\n d -> d {ufUseThreshold = n}))
3561 , make_ord_flag defFlag "funfolding-fun-discount"
3562 (intSuffix (\n d -> d {ufFunAppDiscount = n}))
3563 , make_ord_flag defFlag "funfolding-dict-discount"
3564 (intSuffix (\n d -> d {ufDictDiscount = n}))
3565 , make_ord_flag defFlag "funfolding-keeness-factor"
3566 (floatSuffix (\n d -> d {ufKeenessFactor = n}))
3567 , make_ord_flag defFlag "fmax-worker-args"
3568 (intSuffix (\n d -> d {maxWorkerArgs = n}))
3569 , make_ord_flag defGhciFlag "fghci-hist-size"
3570 (intSuffix (\n d -> d {ghciHistSize = n}))
3571 , make_ord_flag defGhcFlag "fmax-inline-alloc-size"
3572 (intSuffix (\n d -> d { maxInlineAllocSize = n }))
3573 , make_ord_flag defGhcFlag "fmax-inline-memcpy-insns"
3574 (intSuffix (\n d -> d { maxInlineMemcpyInsns = n }))
3575 , make_ord_flag defGhcFlag "fmax-inline-memset-insns"
3576 (intSuffix (\n d -> d { maxInlineMemsetInsns = n }))
3577 , make_ord_flag defGhcFlag "dinitial-unique"
3578 (intSuffix (\n d -> d { initialUnique = n }))
3579 , make_ord_flag defGhcFlag "dunique-increment"
3580 (intSuffix (\n d -> d { uniqueIncrement = n }))
3581
3582 ------ Profiling ----------------------------------------------------
3583
3584 -- OLD profiling flags
3585 , make_dep_flag defGhcFlag "auto-all"
3586 (noArg (\d -> d { profAuto = ProfAutoAll } ))
3587 "Use -fprof-auto instead"
3588 , make_dep_flag defGhcFlag "no-auto-all"
3589 (noArg (\d -> d { profAuto = NoProfAuto } ))
3590 "Use -fno-prof-auto instead"
3591 , make_dep_flag defGhcFlag "auto"
3592 (noArg (\d -> d { profAuto = ProfAutoExports } ))
3593 "Use -fprof-auto-exported instead"
3594 , make_dep_flag defGhcFlag "no-auto"
3595 (noArg (\d -> d { profAuto = NoProfAuto } ))
3596 "Use -fno-prof-auto instead"
3597 , make_dep_flag defGhcFlag "caf-all"
3598 (NoArg (setGeneralFlag Opt_AutoSccsOnIndividualCafs))
3599 "Use -fprof-cafs instead"
3600 , make_dep_flag defGhcFlag "no-caf-all"
3601 (NoArg (unSetGeneralFlag Opt_AutoSccsOnIndividualCafs))
3602 "Use -fno-prof-cafs instead"
3603
3604 -- NEW profiling flags
3605 , make_ord_flag defGhcFlag "fprof-auto"
3606 (noArg (\d -> d { profAuto = ProfAutoAll } ))
3607 , make_ord_flag defGhcFlag "fprof-auto-top"
3608 (noArg (\d -> d { profAuto = ProfAutoTop } ))
3609 , make_ord_flag defGhcFlag "fprof-auto-exported"
3610 (noArg (\d -> d { profAuto = ProfAutoExports } ))
3611 , make_ord_flag defGhcFlag "fprof-auto-calls"
3612 (noArg (\d -> d { profAuto = ProfAutoCalls } ))
3613 , make_ord_flag defGhcFlag "fno-prof-auto"
3614 (noArg (\d -> d { profAuto = NoProfAuto } ))
3615
3616 ------ Compiler flags -----------------------------------------------
3617
3618 , make_ord_flag defGhcFlag "fasm" (NoArg (setObjTarget HscAsm))
3619 , make_ord_flag defGhcFlag "fvia-c" (NoArg
3620 (deprecate $ "The -fvia-c flag does nothing; " ++
3621 "it will be removed in a future GHC release"))
3622 , make_ord_flag defGhcFlag "fvia-C" (NoArg
3623 (deprecate $ "The -fvia-C flag does nothing; " ++
3624 "it will be removed in a future GHC release"))
3625 , make_ord_flag defGhcFlag "fllvm" (NoArg (setObjTarget HscLlvm))
3626
3627 , make_ord_flag defFlag "fno-code" (NoArg ((upd $ \d ->
3628 d { ghcLink=NoLink }) >> setTarget HscNothing))
3629 , make_ord_flag defFlag "fbyte-code" (NoArg (setTarget HscInterpreted))
3630 , make_ord_flag defFlag "fobject-code" (NoArg (setTargetWithPlatform
3631 defaultHscTarget))
3632 , make_dep_flag defFlag "fglasgow-exts"
3633 (NoArg enableGlasgowExts) "Use individual extensions instead"
3634 , make_dep_flag defFlag "fno-glasgow-exts"
3635 (NoArg disableGlasgowExts) "Use individual extensions instead"
3636 , make_ord_flag defFlag "Wunused-binds" (NoArg enableUnusedBinds)
3637 , make_ord_flag defFlag "Wno-unused-binds" (NoArg disableUnusedBinds)
3638 , make_ord_flag defHiddenFlag "fwarn-unused-binds" (NoArg enableUnusedBinds)
3639 , make_ord_flag defHiddenFlag "fno-warn-unused-binds" (NoArg
3640 disableUnusedBinds)
3641
3642 ------ Safe Haskell flags -------------------------------------------
3643 , make_ord_flag defFlag "fpackage-trust" (NoArg setPackageTrust)
3644 , make_ord_flag defFlag "fno-safe-infer" (noArg (\d ->
3645 d { safeInfer = False }))
3646 , make_ord_flag defGhcFlag "fPIC" (NoArg (setGeneralFlag Opt_PIC))
3647 , make_ord_flag defGhcFlag "fno-PIC" (NoArg (unSetGeneralFlag Opt_PIC))
3648 , make_ord_flag defGhcFlag "fPIE" (NoArg (setGeneralFlag Opt_PIC))
3649 , make_ord_flag defGhcFlag "fno-PIE" (NoArg (unSetGeneralFlag Opt_PIC))
3650
3651 ------ Debugging flags ----------------------------------------------
3652 , make_ord_flag defGhcFlag "g" (OptIntSuffix setDebugLevel)
3653 ]
3654 ++ map (mkFlag turnOn "" setGeneralFlag ) negatableFlagsDeps
3655 ++ map (mkFlag turnOff "no-" unSetGeneralFlag ) negatableFlagsDeps
3656 ++ map (mkFlag turnOn "d" setGeneralFlag ) dFlagsDeps
3657 ++ map (mkFlag turnOff "dno-" unSetGeneralFlag ) dFlagsDeps
3658 ++ map (mkFlag turnOn "f" setGeneralFlag ) fFlagsDeps
3659 ++ map (mkFlag turnOff "fno-" unSetGeneralFlag ) fFlagsDeps
3660 ++ map (mkFlag turnOn "W" setWarningFlag ) wWarningFlagsDeps
3661 ++ map (mkFlag turnOff "Wno-" unSetWarningFlag ) wWarningFlagsDeps
3662 ++ map (mkFlag turnOn "Werror=" setWErrorFlag ) wWarningFlagsDeps
3663 ++ map (mkFlag turnOn "Wwarn=" unSetFatalWarningFlag )
3664 wWarningFlagsDeps
3665 ++ map (mkFlag turnOn "Wno-error=" unSetFatalWarningFlag )
3666 wWarningFlagsDeps
3667 ++ map (mkFlag turnOn "fwarn-" setWarningFlag . hideFlag)
3668 wWarningFlagsDeps
3669 ++ map (mkFlag turnOff "fno-warn-" unSetWarningFlag . hideFlag)
3670 wWarningFlagsDeps
3671 ++ [ (NotDeprecated, unrecognisedWarning "W"),
3672 (Deprecated, unrecognisedWarning "fwarn-"),
3673 (Deprecated, unrecognisedWarning "fno-warn-") ]
3674 ++ [ make_ord_flag defFlag "Werror=compat"
3675 (NoArg (mapM_ setWErrorFlag minusWcompatOpts))
3676 , make_ord_flag defFlag "Wno-error=compat"
3677 (NoArg (mapM_ unSetFatalWarningFlag minusWcompatOpts))
3678 , make_ord_flag defFlag "Wwarn=compat"
3679 (NoArg (mapM_ unSetFatalWarningFlag minusWcompatOpts)) ]
3680 ++ map (mkFlag turnOn "f" setExtensionFlag ) fLangFlagsDeps
3681 ++ map (mkFlag turnOff "fno-" unSetExtensionFlag) fLangFlagsDeps
3682 ++ map (mkFlag turnOn "X" setExtensionFlag ) xFlagsDeps
3683 ++ map (mkFlag turnOff "XNo" unSetExtensionFlag) xFlagsDeps
3684 ++ map (mkFlag turnOn "X" setLanguage ) languageFlagsDeps
3685 ++ map (mkFlag turnOn "X" setSafeHaskell ) safeHaskellFlagsDeps
3686 ++ [ make_dep_flag defFlag "XGenerics"
3687 (NoArg $ return ())
3688 ("it does nothing; look into -XDefaultSignatures " ++
3689 "and -XDeriveGeneric for generic programming support.")
3690 , make_dep_flag defFlag "XNoGenerics"
3691 (NoArg $ return ())
3692 ("it does nothing; look into -XDefaultSignatures and " ++
3693 "-XDeriveGeneric for generic programming support.") ]
3694
3695 -- | This is where we handle unrecognised warning flags. We only issue a warning
3696 -- if -Wunrecognised-warning-flags is set. See Trac #11429 for context.
3697 unrecognisedWarning :: String -> Flag (CmdLineP DynFlags)
3698 unrecognisedWarning prefix = defHiddenFlag prefix (Prefix action)
3699 where
3700 action :: String -> EwM (CmdLineP DynFlags) ()
3701 action flag = do
3702 f <- wopt Opt_WarnUnrecognisedWarningFlags <$> liftEwM getCmdLineState
3703 when f $ addFlagWarn Cmd.ReasonUnrecognisedFlag $
3704 "unrecognised warning flag: -" ++ prefix ++ flag
3705
3706 -- See Note [Supporting CLI completion]
3707 package_flags_deps :: [(Deprecation, Flag (CmdLineP DynFlags))]
3708 package_flags_deps = [
3709 ------- Packages ----------------------------------------------------
3710 make_ord_flag defFlag "package-db"
3711 (HasArg (addPkgConfRef . PkgConfFile))
3712 , make_ord_flag defFlag "clear-package-db" (NoArg clearPkgConf)
3713 , make_ord_flag defFlag "no-global-package-db" (NoArg removeGlobalPkgConf)
3714 , make_ord_flag defFlag "no-user-package-db" (NoArg removeUserPkgConf)
3715 , make_ord_flag defFlag "global-package-db"
3716 (NoArg (addPkgConfRef GlobalPkgConf))
3717 , make_ord_flag defFlag "user-package-db"
3718 (NoArg (addPkgConfRef UserPkgConf))
3719 -- backwards compat with GHC<=7.4 :
3720 , make_dep_flag defFlag "package-conf"
3721 (HasArg $ addPkgConfRef . PkgConfFile) "Use -package-db instead"
3722 , make_dep_flag defFlag "no-user-package-conf"
3723 (NoArg removeUserPkgConf) "Use -no-user-package-db instead"
3724 , make_ord_flag defGhcFlag "package-name" (HasArg $ \name -> do
3725 upd (setUnitId name))
3726 -- TODO: Since we JUST deprecated
3727 -- -this-package-key, let's keep this
3728 -- undeprecated for another cycle.
3729 -- Deprecate this eventually.
3730 -- deprecate "Use -this-unit-id instead")
3731 , make_dep_flag defGhcFlag "this-package-key" (HasArg $ upd . setUnitId)
3732 "Use -this-unit-id instead"
3733 , make_ord_flag defGhcFlag "this-unit-id" (hasArg setUnitId)
3734 , make_ord_flag defFlag "package" (HasArg exposePackage)
3735 , make_ord_flag defFlag "plugin-package-id" (HasArg exposePluginPackageId)
3736 , make_ord_flag defFlag "plugin-package" (HasArg exposePluginPackage)
3737 , make_ord_flag defFlag "package-id" (HasArg exposePackageId)
3738 , make_ord_flag defFlag "hide-package" (HasArg hidePackage)
3739 , make_ord_flag defFlag "hide-all-packages"
3740 (NoArg (setGeneralFlag Opt_HideAllPackages))
3741 , make_ord_flag defFlag "hide-all-plugin-packages"
3742 (NoArg (setGeneralFlag Opt_HideAllPluginPackages))
3743 , make_ord_flag defFlag "package-env" (HasArg setPackageEnv)
3744 , make_ord_flag defFlag "ignore-package" (HasArg ignorePackage)
3745 , make_dep_flag defFlag "syslib" (HasArg exposePackage) "Use -package instead"
3746 , make_ord_flag defFlag "distrust-all-packages"
3747 (NoArg (setGeneralFlag Opt_DistrustAllPackages))
3748 , make_ord_flag defFlag "trust" (HasArg trustPackage)
3749 , make_ord_flag defFlag "distrust" (HasArg distrustPackage)
3750 ]
3751 where
3752 setPackageEnv env = upd $ \s -> s { packageEnv = Just env }
3753
3754 -- | Make a list of flags for shell completion.
3755 -- Filter all available flags into two groups, for interactive GHC vs all other.
3756 flagsForCompletion :: Bool -> [String]
3757 flagsForCompletion isInteractive
3758 = [ '-':flagName flag
3759 | flag <- flagsAll
3760 , modeFilter (flagGhcMode flag)
3761 ]
3762 where
3763 modeFilter AllModes = True
3764 modeFilter OnlyGhci = isInteractive
3765 modeFilter OnlyGhc = not isInteractive
3766 modeFilter HiddenFlag = False
3767
3768 type TurnOnFlag = Bool -- True <=> we are turning the flag on
3769 -- False <=> we are turning the flag off
3770 turnOn :: TurnOnFlag; turnOn = True
3771 turnOff :: TurnOnFlag; turnOff = False
3772
3773 data FlagSpec flag
3774 = FlagSpec
3775 { flagSpecName :: String -- ^ Flag in string form
3776 , flagSpecFlag :: flag -- ^ Flag in internal form
3777 , flagSpecAction :: (TurnOnFlag -> DynP ())
3778 -- ^ Extra action to run when the flag is found
3779 -- Typically, emit a warning or error
3780 , flagSpecGhcMode :: GhcFlagMode
3781 -- ^ In which ghc mode the flag has effect
3782 }
3783
3784 -- | Define a new flag.
3785 flagSpec :: String -> flag -> (Deprecation, FlagSpec flag)
3786 flagSpec name flag = flagSpec' name flag nop
3787
3788 -- | Define a new flag with an effect.
3789 flagSpec' :: String -> flag -> (TurnOnFlag -> DynP ())
3790 -> (Deprecation, FlagSpec flag)
3791 flagSpec' name flag act = (NotDeprecated, FlagSpec name flag act AllModes)
3792
3793 -- | Define a new deprecated flag with an effect.
3794 depFlagSpecOp :: String -> flag -> (TurnOnFlag -> DynP ()) -> String
3795 -> (Deprecation, FlagSpec flag)
3796 depFlagSpecOp name flag act dep =
3797 (Deprecated, snd (flagSpec' name flag (\f -> act f >> deprecate dep)))
3798
3799 -- | Define a new deprecated flag.
3800 depFlagSpec :: String -> flag -> String
3801 -> (Deprecation, FlagSpec flag)
3802 depFlagSpec name flag dep = depFlagSpecOp name flag nop dep
3803
3804 -- | Define a new deprecated flag with an effect where the deprecation message
3805 -- depends on the flag value
3806 depFlagSpecOp' :: String
3807 -> flag
3808 -> (TurnOnFlag -> DynP ())
3809 -> (TurnOnFlag -> String)
3810 -> (Deprecation, FlagSpec flag)
3811 depFlagSpecOp' name flag act dep =
3812 (Deprecated, FlagSpec name flag (\f -> act f >> (deprecate $ dep f))
3813 AllModes)
3814
3815 -- | Define a new deprecated flag where the deprecation message
3816 -- depends on the flag value
3817 depFlagSpec' :: String
3818 -> flag
3819 -> (TurnOnFlag -> String)
3820 -> (Deprecation, FlagSpec flag)
3821 depFlagSpec' name flag dep = depFlagSpecOp' name flag nop dep
3822
3823
3824 -- | Define a new deprecated flag where the deprecation message
3825 -- is shown depending on the flag value
3826 depFlagSpecCond :: String
3827 -> flag
3828 -> (TurnOnFlag -> Bool)
3829 -> String
3830 -> (Deprecation, FlagSpec flag)
3831 depFlagSpecCond name flag cond dep =
3832 (Deprecated, FlagSpec name flag (\f -> when (cond f) $ deprecate dep)
3833 AllModes)
3834
3835 -- | Define a new flag for GHCi.
3836 flagGhciSpec :: String -> flag -> (Deprecation, FlagSpec flag)