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