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