1 //===- LangOptions.h - C Language Family Language Options -------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
10 /// Defines the clang::LangOptions interface.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_BASIC_LANGOPTIONS_H
15 #define LLVM_CLANG_BASIC_LANGOPTIONS_H
17 #include "clang/Basic/CommentOptions.h"
18 #include "clang/Basic/LLVM.h"
19 #include "clang/Basic/LangStandard.h"
20 #include "clang/Basic/ObjCRuntime.h"
21 #include "clang/Basic/Sanitizers.h"
22 #include "clang/Basic/TargetCXXABI.h"
23 #include "clang/Basic/Visibility.h"
24 #include "llvm/ADT/FloatingPointMode.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/ADT/Triple.h"
32 /// Bitfields of LangOptions, split out from LangOptions in order to ensure that
33 /// this large collection of bitfields is a trivial class type.
34 class LangOptionsBase {
35 friend class CompilerInvocation;
38 // Define simple language options (with no accessors).
39 #define LANGOPT(Name, Bits, Default, Description) unsigned Name : Bits;
40 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description)
41 #include "clang/Basic/LangOptions.def"
44 // Define language options of enumeration type. These are private, and will
45 // have accessors (below).
46 #define LANGOPT(Name, Bits, Default, Description)
47 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
49 #include "clang/Basic/LangOptions.def"
52 /// In the Microsoft ABI, this controls the placement of virtual displacement
53 /// members used to implement virtual inheritance.
54 enum class MSVtorDispMode { Never, ForVBaseOverride, ForVFTable };
56 /// Keeps track of the various options that can be
57 /// enabled, which controls the dialect of C or C++ that is accepted.
58 class LangOptions : public LangOptionsBase {
60 using Visibility = clang::Visibility;
61 using RoundingMode = llvm::RoundingMode;
63 enum GCMode { NonGC, GCOnly, HybridGC };
64 enum StackProtectorMode { SSPOff, SSPOn, SSPStrong, SSPReq };
66 // Automatic variables live on the stack, and when trivial they're usually
67 // uninitialized because it's undefined behavior to use them without
69 enum class TrivialAutoVarInitKind { Uninitialized, Zero, Pattern };
71 enum SignedOverflowBehaviorTy {
72 // Default C standard behavior.
82 // FIXME: Unify with TUKind.
83 enum CompilingModuleKind {
84 /// Not compiling a module interface at all.
87 /// Compiling a module from a module map.
90 /// Compiling a module from a list of header files.
93 /// Compiling a C++ modules TS module interface unit.
97 enum PragmaMSPointersToMembersKind {
99 PPTMK_FullGeneralitySingleInheritance,
100 PPTMK_FullGeneralityMultipleInheritance,
101 PPTMK_FullGeneralityVirtualInheritance
104 using MSVtorDispMode = clang::MSVtorDispMode;
106 enum DefaultCallingConvention {
115 enum AddrSpaceMapMangling { ASMM_Target, ASMM_On, ASMM_Off };
117 // Corresponds to _MSC_VER
118 enum MSVCMajorVersion {
130 enum SYCLMajorVersion {
134 // The "default" SYCL version to be used when none is specified on the
135 // frontend command line.
136 SYCL_Default = SYCL_2020
139 /// Clang versions with different platform ABI conformance.
140 enum class ClangABI {
141 /// Attempt to be ABI-compatible with code generated by Clang 3.8.x
142 /// (SVN r257626). This causes <1 x long long> to be passed in an
143 /// integer register instead of an SSE register on x64_64.
146 /// Attempt to be ABI-compatible with code generated by Clang 4.0.x
147 /// (SVN r291814). This causes move operations to be ignored when
148 /// determining whether a class type can be passed or returned directly.
151 /// Attempt to be ABI-compatible with code generated by Clang 6.0.x
152 /// (SVN r321711). This causes determination of whether a type is
153 /// standard-layout to ignore collisions between empty base classes
154 /// and between base classes and member subobjects, which affects
155 /// whether we reuse base class tail padding in some ABIs.
158 /// Attempt to be ABI-compatible with code generated by Clang 7.0.x
159 /// (SVN r338536). This causes alignof (C++) and _Alignof (C11) to be
160 /// compatible with __alignof (i.e., return the preferred alignment)
161 /// rather than returning the required alignment.
164 /// Attempt to be ABI-compatible with code generated by Clang 9.0.x
165 /// (SVN r351319). This causes vectors of __int128 to be passed in memory
166 /// instead of passing in multiple scalar registers on x86_64 on Linux and
170 /// Attempt to be ABI-compatible with code generated by Clang 11.0.x
171 /// (git 2e10b7a39b93). This causes clang to pass unions with a 256-bit
172 /// vector member on the stack instead of using registers, to not properly
173 /// mangle substitutions for template names in some cases, and to mangle
174 /// declaration template arguments without a cast to the parameter type
175 /// even when that can lead to mangling collisions.
178 /// Attempt to be ABI-compatible with code generated by Clang 12.0.x
179 /// (git 8e464dd76bef). This causes clang to mangle lambdas within
180 /// global-scope inline variables incorrectly.
183 /// Conform to the underlying platform's C and C++ ABIs as closely
188 enum class CoreFoundationABI {
189 /// No interoperability ABI has been specified
191 /// CoreFoundation does not have any language interoperability
193 /// Interoperability with the ObjectiveC runtime
195 /// Interoperability with the latest known version of the Swift runtime
197 /// Interoperability with the Swift 5.0 runtime
199 /// Interoperability with the Swift 4.2 runtime
201 /// Interoperability with the Swift 4.1 runtime
206 // Disable the floating point pragma
209 // Enable the floating point pragma
212 // Aggressively fuse FP ops (E.g. FMA) disregarding pragmas.
215 // Aggressively fuse FP ops and honor pragmas.
219 /// Alias for RoundingMode::NearestTiesToEven.
220 static constexpr unsigned FPR_ToNearest =
221 static_cast<unsigned>(llvm::RoundingMode::NearestTiesToEven);
223 /// Possible floating point exception behavior.
224 enum FPExceptionModeKind {
225 /// Assume that floating-point exceptions are masked.
227 /// Transformations do not cause new exceptions but may hide some.
229 /// Strictly preserve the floating-point exception semantics.
233 /// Possible exception handling behavior.
234 enum class ExceptionHandlingKind { None, SjLj, WinEH, DwarfCFI, Wasm };
236 enum class LaxVectorConversionKind {
237 /// Permit no implicit vector bitcasts.
239 /// Permit vector bitcasts between integer vectors with different numbers
240 /// of elements but the same total bit-width.
242 /// Permit vector bitcasts between all vectors with the same total
247 enum class AltivecSrcCompatKind {
248 // All vector compares produce scalars except vector pixel and vector bool.
249 // The types vector pixel and vector bool return vector results.
251 // All vector compares produce vector results as in GCC.
253 // All vector compares produce scalars as in XL.
255 // Default clang behaviour.
259 enum class SignReturnAddressScopeKind {
260 /// No signing for any function.
262 /// Sign the return address of functions that spill LR.
264 /// Sign the return address of all functions,
268 enum class SignReturnAddressKeyKind {
269 /// Return address signing uses APIA key.
271 /// Return address signing uses APIB key.
275 enum class ThreadModelKind {
278 /// Single Threaded Environment.
282 enum class ExtendArgsKind {
283 /// Integer arguments are sign or zero extended to 32/64 bits
284 /// during default argument promotions.
290 /// The used language standard.
291 LangStandard::Kind LangStd;
293 /// Set of enabled sanitizers.
294 SanitizerSet Sanitize;
295 /// Is at least one coverage instrumentation type enabled.
296 bool SanitizeCoverage = false;
298 /// Paths to files specifying which objects
299 /// (files, functions, variables) should not be instrumented.
300 std::vector<std::string> NoSanitizeFiles;
302 /// Paths to the XRay "always instrument" files specifying which
303 /// objects (files, functions, variables) should be imbued with the XRay
304 /// "always instrument" attribute.
305 /// WARNING: This is a deprecated field and will go away in the future.
306 std::vector<std::string> XRayAlwaysInstrumentFiles;
308 /// Paths to the XRay "never instrument" files specifying which
309 /// objects (files, functions, variables) should be imbued with the XRay
310 /// "never instrument" attribute.
311 /// WARNING: This is a deprecated field and will go away in the future.
312 std::vector<std::string> XRayNeverInstrumentFiles;
314 /// Paths to the XRay attribute list files, specifying which objects
315 /// (files, functions, variables) should be imbued with the appropriate XRay
317 std::vector<std::string> XRayAttrListFiles;
319 /// Paths to special case list files specifying which entities
320 /// (files, functions) should or should not be instrumented.
321 std::vector<std::string> ProfileListFiles;
323 clang::ObjCRuntime ObjCRuntime;
325 CoreFoundationABI CFRuntime = CoreFoundationABI::Unspecified;
327 std::string ObjCConstantStringClass;
329 /// The name of the handler function to be called when -ftrapv is
332 /// If none is specified, abort (GCC-compatible behaviour).
333 std::string OverflowHandler;
335 /// The module currently being compiled as specified by -fmodule-name.
336 std::string ModuleName;
338 /// The name of the current module, of which the main source file
339 /// is a part. If CompilingModule is set, we are compiling the interface
340 /// of this module, otherwise we are compiling an implementation file of
341 /// it. This starts as ModuleName in case -fmodule-name is provided and
342 /// changes during compilation to reflect the current module.
343 std::string CurrentModule;
345 /// The names of any features to enable in module 'requires' decls
346 /// in addition to the hard-coded list in Module.cpp and the target features.
348 /// This list is sorted.
349 std::vector<std::string> ModuleFeatures;
351 /// Options for parsing comments.
352 CommentOptions CommentOpts;
354 /// A list of all -fno-builtin-* function names (e.g., memset).
355 std::vector<std::string> NoBuiltinFuncs;
357 /// A prefix map for __FILE__, __BASE_FILE__ and __builtin_FILE().
358 std::map<std::string, std::string, std::greater<std::string>> MacroPrefixMap;
360 /// Triples of the OpenMP targets that the host code codegen should
361 /// take into account in order to generate accurate offloading descriptors.
362 std::vector<llvm::Triple> OMPTargetTriples;
364 /// Name of the IR file that contains the result of the OpenMP target
365 /// host code generation.
366 std::string OMPHostIRFile;
368 /// The user provided compilation unit ID, if non-empty. This is used to
369 /// externalize static variables which is needed to support accessing static
370 /// device variables in host code for single source offloading languages
374 /// C++ ABI to compile with, if specified by the frontend through -fc++-abi=.
375 /// This overrides the default ABI used by the target.
376 llvm::Optional<TargetCXXABI::Kind> CXXABI;
378 /// Indicates whether the front-end is explicitly told that the
379 /// input is a header file (i.e. -x c-header).
380 bool IsHeaderFile = false;
384 // Define accessors/mutators for language options of enumeration type.
385 #define LANGOPT(Name, Bits, Default, Description)
386 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
387 Type get##Name() const { return static_cast<Type>(Name); } \
388 void set##Name(Type Value) { Name = static_cast<unsigned>(Value); }
389 #include "clang/Basic/LangOptions.def"
391 /// Are we compiling a module interface (.cppm or module map)?
392 bool isCompilingModule() const {
393 return getCompilingModule() != CMK_None;
396 /// Do we need to track the owning module for a local declaration?
397 bool trackLocalOwningModule() const {
398 return isCompilingModule() || ModulesLocalVisibility;
401 bool isSignedOverflowDefined() const {
402 return getSignedOverflowBehavior() == SOB_Defined;
405 bool isSubscriptPointerArithmetic() const {
406 return ObjCRuntime.isSubscriptPointerArithmetic() &&
407 !ObjCSubscriptingLegacyRuntime;
410 bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const {
411 return MSCompatibilityVersion >= MajorVersion * 100000U;
414 /// Reset all of the options that are not considered when building a
416 void resetNonModularOptions();
418 /// Is this a libc/libm function that is no longer recognized as a
419 /// builtin because a -fno-builtin-* option has been specified?
420 bool isNoBuiltinFunc(StringRef Name) const;
422 /// True if any ObjC types may have non-trivial lifetime qualifiers.
423 bool allowsNonTrivialObjCLifetimeQualifiers() const {
424 return ObjCAutoRefCount || ObjCWeak;
427 bool assumeFunctionsAreConvergent() const {
428 return ConvergentFunctions;
431 /// Return the OpenCL C or C++ version as a VersionTuple.
432 VersionTuple getOpenCLVersionTuple() const;
434 /// Check if return address signing is enabled.
435 bool hasSignReturnAddress() const {
436 return getSignReturnAddressScope() != SignReturnAddressScopeKind::None;
439 /// Check if return address signing uses AKey.
440 bool isSignReturnAddressWithAKey() const {
441 return getSignReturnAddressKey() == SignReturnAddressKeyKind::AKey;
444 /// Check if leaf functions are also signed.
445 bool isSignReturnAddressScopeAll() const {
446 return getSignReturnAddressScope() == SignReturnAddressScopeKind::All;
449 bool hasSjLjExceptions() const {
450 return getExceptionHandling() == ExceptionHandlingKind::SjLj;
453 bool hasSEHExceptions() const {
454 return getExceptionHandling() == ExceptionHandlingKind::WinEH;
457 bool hasDWARFExceptions() const {
458 return getExceptionHandling() == ExceptionHandlingKind::DwarfCFI;
461 bool hasWasmExceptions() const {
462 return getExceptionHandling() == ExceptionHandlingKind::Wasm;
465 bool isSYCL() const { return SYCLIsDevice || SYCLIsHost; }
467 /// Remap path prefix according to -fmacro-prefix-path option.
468 void remapPathPrefix(SmallString<256> &Path) const;
471 /// Floating point control options
472 class FPOptionsOverride;
475 // We start by defining the layout.
476 using storage_type = uint16_t;
478 using RoundingMode = llvm::RoundingMode;
480 static constexpr unsigned StorageBitSize = 8 * sizeof(storage_type);
482 // Define a fake option named "First" so that we have a PREVIOUS even for the
483 // real first option.
484 static constexpr storage_type FirstShift = 0, FirstWidth = 0;
485 #define OPTION(NAME, TYPE, WIDTH, PREVIOUS) \
486 static constexpr storage_type NAME##Shift = \
487 PREVIOUS##Shift + PREVIOUS##Width; \
488 static constexpr storage_type NAME##Width = WIDTH; \
489 static constexpr storage_type NAME##Mask = ((1 << NAME##Width) - 1) \
491 #include "clang/Basic/FPOptions.def"
493 static constexpr storage_type TotalWidth = 0
494 #define OPTION(NAME, TYPE, WIDTH, PREVIOUS) +WIDTH
495 #include "clang/Basic/FPOptions.def"
497 static_assert(TotalWidth <= StorageBitSize, "Too short type for FPOptions");
503 FPOptions() : Value(0) {
504 setFPContractMode(LangOptions::FPM_Off);
505 setRoundingMode(static_cast<RoundingMode>(LangOptions::FPR_ToNearest));
506 setFPExceptionMode(LangOptions::FPE_Ignore);
508 explicit FPOptions(const LangOptions &LO) {
510 // The language fp contract option FPM_FastHonorPragmas has the same effect
511 // as FPM_Fast in frontend. For simplicity, use FPM_Fast uniformly in
513 auto LangOptContractMode = LO.getDefaultFPContractMode();
514 if (LangOptContractMode == LangOptions::FPM_FastHonorPragmas)
515 LangOptContractMode = LangOptions::FPM_Fast;
516 setFPContractMode(LangOptContractMode);
517 setRoundingMode(LO.getFPRoundingMode());
518 setFPExceptionMode(LO.getFPExceptionMode());
519 setAllowFPReassociate(LO.AllowFPReassoc);
520 setNoHonorNaNs(LO.NoHonorNaNs);
521 setNoHonorInfs(LO.NoHonorInfs);
522 setNoSignedZero(LO.NoSignedZero);
523 setAllowReciprocal(LO.AllowRecip);
524 setAllowApproxFunc(LO.ApproxFunc);
525 if (getFPContractMode() == LangOptions::FPM_On &&
526 getRoundingMode() == llvm::RoundingMode::Dynamic &&
527 getFPExceptionMode() == LangOptions::FPE_Strict)
528 // If the FP settings are set to the "strict" model, then
529 // FENV access is set to true. (ffp-model=strict)
530 setAllowFEnvAccess(true);
532 setAllowFEnvAccess(LangOptions::FPM_Off);
535 bool allowFPContractWithinStatement() const {
536 return getFPContractMode() == LangOptions::FPM_On;
538 void setAllowFPContractWithinStatement() {
539 setFPContractMode(LangOptions::FPM_On);
542 bool allowFPContractAcrossStatement() const {
543 return getFPContractMode() == LangOptions::FPM_Fast;
545 void setAllowFPContractAcrossStatement() {
546 setFPContractMode(LangOptions::FPM_Fast);
549 bool isFPConstrained() const {
550 return getRoundingMode() != llvm::RoundingMode::NearestTiesToEven ||
551 getFPExceptionMode() != LangOptions::FPE_Ignore ||
552 getAllowFEnvAccess();
555 bool operator==(FPOptions other) const { return Value == other.Value; }
557 /// Return the default value of FPOptions that's used when trailing
558 /// storage isn't required.
559 static FPOptions defaultWithoutTrailingStorage(const LangOptions &LO);
561 storage_type getAsOpaqueInt() const { return Value; }
562 static FPOptions getFromOpaqueInt(storage_type Value) {
568 // We can define most of the accessors automatically:
569 #define OPTION(NAME, TYPE, WIDTH, PREVIOUS) \
570 TYPE get##NAME() const { \
571 return static_cast<TYPE>((Value & NAME##Mask) >> NAME##Shift); \
573 void set##NAME(TYPE value) { \
574 Value = (Value & ~NAME##Mask) | (storage_type(value) << NAME##Shift); \
576 #include "clang/Basic/FPOptions.def"
577 LLVM_DUMP_METHOD void dump();
580 /// Represents difference between two FPOptions values.
582 /// The effect of language constructs changing the set of floating point options
583 /// is usually a change of some FP properties while leaving others intact. This
584 /// class describes such changes by keeping information about what FP options
587 /// The integral set of FP options, described by the class FPOptions, may be
588 /// represented as a default FP option set, defined by language standard and
589 /// command line options, with the overrides introduced by pragmas.
591 /// The is implemented as a value of the new FPOptions plus a mask showing which
592 /// fields are actually set in it.
593 class FPOptionsOverride {
594 FPOptions Options = FPOptions::getFromOpaqueInt(0);
595 FPOptions::storage_type OverrideMask = 0;
598 using RoundingMode = llvm::RoundingMode;
600 /// The type suitable for storing values of FPOptionsOverride. Must be twice
601 /// as wide as bit size of FPOption.
602 using storage_type = uint32_t;
603 static_assert(sizeof(storage_type) >= 2 * sizeof(FPOptions::storage_type),
604 "Too short type for FPOptionsOverride");
606 /// Bit mask selecting bits of OverrideMask in serialized representation of
607 /// FPOptionsOverride.
608 static constexpr storage_type OverrideMaskBits =
609 (static_cast<storage_type>(1) << FPOptions::StorageBitSize) - 1;
611 FPOptionsOverride() {}
612 FPOptionsOverride(const LangOptions &LO)
613 : Options(LO), OverrideMask(OverrideMaskBits) {}
614 FPOptionsOverride(FPOptions FPO)
615 : Options(FPO), OverrideMask(OverrideMaskBits) {}
617 bool requiresTrailingStorage() const { return OverrideMask != 0; }
619 void setAllowFPContractWithinStatement() {
620 setFPContractModeOverride(LangOptions::FPM_On);
623 void setAllowFPContractAcrossStatement() {
624 setFPContractModeOverride(LangOptions::FPM_Fast);
627 void setDisallowFPContract() {
628 setFPContractModeOverride(LangOptions::FPM_Off);
631 void setFPPreciseEnabled(bool Value) {
632 setAllowFPReassociateOverride(!Value);
633 setNoHonorNaNsOverride(!Value);
634 setNoHonorInfsOverride(!Value);
635 setNoSignedZeroOverride(!Value);
636 setAllowReciprocalOverride(!Value);
637 setAllowApproxFuncOverride(!Value);
639 /* Precise mode implies fp_contract=on and disables ffast-math */
640 setAllowFPContractWithinStatement();
642 /* Precise mode disabled sets fp_contract=fast and enables ffast-math */
643 setAllowFPContractAcrossStatement();
646 storage_type getAsOpaqueInt() const {
647 return (static_cast<storage_type>(Options.getAsOpaqueInt())
648 << FPOptions::StorageBitSize) |
651 static FPOptionsOverride getFromOpaqueInt(storage_type I) {
652 FPOptionsOverride Opts;
653 Opts.OverrideMask = I & OverrideMaskBits;
654 Opts.Options = FPOptions::getFromOpaqueInt(I >> FPOptions::StorageBitSize);
658 FPOptions applyOverrides(FPOptions Base) {
660 FPOptions::getFromOpaqueInt((Base.getAsOpaqueInt() & ~OverrideMask) |
661 (Options.getAsOpaqueInt() & OverrideMask));
665 FPOptions applyOverrides(const LangOptions &LO) {
666 return applyOverrides(FPOptions(LO));
669 bool operator==(FPOptionsOverride other) const {
670 return Options == other.Options && OverrideMask == other.OverrideMask;
672 bool operator!=(FPOptionsOverride other) const { return !(*this == other); }
674 #define OPTION(NAME, TYPE, WIDTH, PREVIOUS) \
675 bool has##NAME##Override() const { \
676 return OverrideMask & FPOptions::NAME##Mask; \
678 TYPE get##NAME##Override() const { \
679 assert(has##NAME##Override()); \
680 return Options.get##NAME(); \
682 void clear##NAME##Override() { \
683 /* Clear the actual value so that we don't have spurious differences when \
684 * testing equality. */ \
685 Options.set##NAME(TYPE(0)); \
686 OverrideMask &= ~FPOptions::NAME##Mask; \
688 void set##NAME##Override(TYPE value) { \
689 Options.set##NAME(value); \
690 OverrideMask |= FPOptions::NAME##Mask; \
692 #include "clang/Basic/FPOptions.def"
693 LLVM_DUMP_METHOD void dump();
696 /// Describes the kind of translation unit being processed.
697 enum TranslationUnitKind {
698 /// The translation unit is a complete translation unit.
701 /// The translation unit is a prefix to a translation unit, and is
705 /// The translation unit is a module.
708 /// The translation unit is a is a complete translation unit that we might
709 /// incrementally extend later.
715 #endif // LLVM_CLANG_BASIC_LANGOPTIONS_H