clang 24.0.0git
LangOptions.h
Go to the documentation of this file.
1//===- LangOptions.h - C Language Family Language Options -------*- C++ -*-===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// Defines the clang::LangOptions interface.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_BASIC_LANGOPTIONS_H
15#define LLVM_CLANG_BASIC_LANGOPTIONS_H
16
19#include "clang/Basic/LLVM.h"
25#include "llvm/ADT/FloatingPointMode.h"
26#include "llvm/ADT/StringRef.h"
27#include "llvm/BinaryFormat/DXContainer.h"
28#include "llvm/Frontend/OpenMP/OMPVersion.h"
29#include "llvm/Support/AllocToken.h"
30#include "llvm/TargetParser/Triple.h"
31#include <optional>
32#include <string>
33#include <vector>
34
35namespace clang {
36
37/// In the Microsoft ABI, this controls the placement of virtual displacement
38/// members used to implement virtual inheritance.
40
41/// Shader programs run in specific pipeline stages.
42/// The order of these values matters, and must be kept in sync with the
43/// Triple Environment enum in llvm::Triple. The ordering is enforced in
44/// static_asserts in Triple.cpp and in clang/Basic/HLSLRuntime.h.
63
70
71/// Bitfields of LangOptions, split out from LangOptions in order to ensure that
72/// this large collection of bitfields is a trivial class type.
74 friend class CompilerInvocation;
76
77public:
79 using RoundingMode = llvm::RoundingMode;
81
82 /// For ASTs produced with different option value, signifies their level of
83 /// compatibility.
84 enum class CompatibilityKind {
85 /// Does affect the construction of the AST in a way that does prevent
86 /// module interoperability.
88 /// Does affect the construction of the AST in a way that doesn't prevent
89 /// interoperability (that is, the value can be different between an
90 /// explicit module and the user of that module).
92 /// Does not affect the construction of the AST in any way (that is, the
93 /// value can be different between an implicit module and the user of that
94 /// module).
96 };
97
100
101 // Automatic variables live on the stack, and when trivial they're usually
102 // uninitialized because it's undefined behavior to use them without
103 // initializing them.
105
107 // Default C standard behavior.
109
110 // -fwrapv
112
113 // -ftrapv
115 };
116
117 // Used by __attribute__((overflow_behavior())) to describe overflow behavior
118 // on a per-type basis.
120 // Default C standard behavior (type dependent).
122
123 // __attribute__((overflow_behavior("wrap")))
125
126 // __attribute__((overflow_behavior("trap")))
128
129 // Signed types defined as wrapping via -fwrapv can still be instrumented
130 // by sanitizers (PR82432). This field is needed to disambiguate canonical
131 // wrapping type behaviors from -fwrapv behaviors.
132 // -fwrapv
134 };
135
136 // FIXME: Unify with TUKind.
138 /// Not compiling a module interface at all.
140
141 /// Compiling a module from a module map.
143
144 /// Compiling a module header unit.
146
147 /// Compiling a C++ modules interface unit.
149 };
150
157
159
169
171
172 // Corresponds to _MSC_VER
174 MSVC2010 = 1600,
175 MSVC2012 = 1700,
176 MSVC2013 = 1800,
177 MSVC2015 = 1900,
178 MSVC2017 = 1910,
182 MSVC2019 = 1920,
187 };
188
193 // The "default" SYCL version to be used when none is specified on the
194 // frontend command line.
196 };
197
200 HLSL_2015 = 2015,
201 HLSL_2016 = 2016,
202 HLSL_2017 = 2017,
203 HLSL_2018 = 2018,
204 HLSL_2021 = 2021,
205 HLSL_202x = 2028,
206 HLSL_202y = 2029,
207 };
208
209 /// Clang versions with different platform ABI conformance.
210 enum class ClangABI {
211#define ABI_VER_MAJOR_MINOR(Major, Minor) Ver##Major##_##Minor,
212#define ABI_VER_MAJOR(Major) Ver##Major,
213#define ABI_VER_LATEST(Latest) Latest
214#include "clang/Basic/ABIVersions.def"
215 };
216
217 enum class CoreFoundationABI {
218 /// No interoperability ABI has been specified
220 /// CoreFoundation does not have any language interoperability
222 /// Interoperability with the ObjectiveC runtime
224 /// Interoperability with the latest known version of the Swift runtime
226 /// Interoperability with the Swift 5.0 runtime
228 /// Interoperability with the Swift 4.2 runtime
230 /// Interoperability with the Swift 4.1 runtime
232 };
233
235 // Disable the floating point pragma
237
238 // Enable the floating point pragma
240
241 // Aggressively fuse FP ops (E.g. FMA) disregarding pragmas.
243
244 // Aggressively fuse FP ops and honor pragmas.
246 };
247
248 /// Possible floating point exception behavior.
250 /// Assume that floating-point exceptions are masked.
252 /// Transformations do not cause new exceptions but may hide some.
254 /// Strictly preserve the floating-point exception semantics.
256 /// Used internally to represent initial unspecified value.
258 };
259
260 /// Possible float expression evaluation method choices.
261 enum FPEvalMethodKind : unsigned {
262 /// Use the declared type for fp arithmetic.
264 /// Use the type double for fp arithmetic.
266 /// Use extended type for fp arithmetic.
268 /// Used only for FE option processing; this is only used to indicate that
269 /// the user did not specify an explicit evaluation method on the command
270 /// line and so the target should be queried for its default evaluation
271 /// method instead.
273 };
274
275 enum class MatrixMemoryLayout : unsigned {
276 // Use column-major layout for matrices
278 // Use row-major layout for matrices
280 };
281
283
285 /// Permit no implicit vector bitcasts.
287 /// Permit vector bitcasts between integer vectors with different numbers
288 /// of elements but the same total bit-width.
290 /// Permit vector bitcasts between all vectors with the same total
291 /// bit-width.
293 };
294
296 // All vector compares produce scalars except vector pixel and vector bool.
297 // The types vector pixel and vector bool return vector results.
299 // All vector compares produce vector results as in GCC.
301 // All vector compares produce scalars as in XL.
303 // Default clang behaviour.
305 };
306
308 /// No signing for any function.
310 /// Sign the return address of functions that spill LR.
312 /// Sign the return address of all functions,
314 };
315
317 /// Return address signing uses APIA key.
319 /// Return address signing uses APIB key.
321 };
322
323 enum class ThreadModelKind {
324 /// POSIX Threads.
326 /// Single Threaded Environment.
328 };
329
330 enum class ExtendArgsKind {
331 /// Integer arguments are sign or zero extended to 32/64 bits
332 /// during default argument promotions.
335 };
336
338 /// Legacy default stream
340 /// Per-thread default stream
342 };
343
344 /// Exclude certain code patterns from being instrumented by arithmetic
345 /// overflow sanitizers
347 /// Don't exclude any overflow patterns from sanitizers
348 None = 1 << 0,
349 /// Exclude all overflow patterns (below)
350 All = 1 << 1,
351 /// if (a + b < a)
353 /// if (a + b < a)
355 /// -1UL
357 /// while (count--)
359 };
360
363 /// map only explicit default visibilities to exported
365 /// map all default visibilities to exported
367 };
368
370 /// Force hidden visibility
372 /// Force protected visibility
374 /// Force default visibility
376 /// Don't alter the visibility
378 };
379
381 /// Keep the IR-gen assigned visibility.
383 /// Override the IR-gen assigned visibility with default visibility.
385 /// Override the IR-gen assigned visibility with hidden visibility.
387 /// Override the IR-gen assigned visibility with protected visibility.
389 };
390
392 /// Any trailing array member is a FAM.
394 /// Any trailing array member of undefined, 0, or 1 size is a FAM.
396 /// Any trailing array member of undefined or 0 size is a FAM.
398 /// Any trailing array member of undefined size is a FAM.
400 };
401
402 /// Controls the various implementations for complex multiplication and
403 // division.
405 /// Implementation of complex division and multiplication using a call to
406 /// runtime library functions(generally the case, but the BE might
407 /// sometimes replace the library call if it knows enough about the
408 /// potential range of the inputs). Overflow and non-finite values are
409 /// handled by the library implementation. This is the default value.
411
412 /// Implementation of complex division offering an improved handling
413 /// for overflow in intermediate calculations with no special handling for
414 /// NaN and infinite values.
416
417 /// Implementation of complex division using algebraic formulas at
418 /// higher precision. Overflow is handled. Non-finite values are handled in
419 /// some cases. If the target hardware does not have native support for a
420 /// higher precision data type, an implementation for the complex operation
421 /// will be used to provide improved guards against intermediate overflow,
422 /// but overflow and underflow may still occur in some cases. NaN and
423 /// infinite values are not handled.
425
426 /// Implementation of complex division and multiplication using
427 /// algebraic formulas at source precision. No special handling to avoid
428 /// overflow. NaN and infinite values are not handled.
430
431 /// No range rule is enabled.
433 };
434
435 /// Controls which variables have static destructors registered.
437 /// Register static destructors for all variables.
439 /// Register static destructors only for thread-local variables.
441 /// Don't register static destructors for any variables.
443 };
444
446 /// Use default layout rules of the target.
448 /// Use Itanium rules for bit-field layout and fundamental types alignment.
450 /// Use Microsoft C++ ABI rules for bit-field layout and fundamental types
451 /// alignment.
453 };
454
455 // Define simple language options (with no accessors).
456#define LANGOPT(Name, Bits, Default, Compatibility, Description) \
457 unsigned Name : Bits;
458#define ENUM_LANGOPT(Name, Type, Bits, Default, Compatibility, Description)
459#include "clang/Basic/LangOptions.def"
460
461protected:
462 // Define language options of enumeration type. These are private, and will
463 // have accessors (below).
464#define LANGOPT(Name, Bits, Default, Compatibility, Description)
465#define ENUM_LANGOPT(Name, Type, Bits, Default, Compatibility, Description) \
466 LLVM_PREFERRED_TYPE(Type) \
467 unsigned Name : Bits;
468#include "clang/Basic/LangOptions.def"
469};
470
471/// Keeps track of the various options that can be
472/// enabled, which controls the dialect of C or C++ that is accepted.
474public:
475 /// The used language standard.
477
478 /// Set of enabled sanitizers.
480 /// Is at least one coverage instrumentation type enabled.
481 bool SanitizeCoverage = false;
482 /// Set of (UBSan) sanitizers that when enabled do not cause
483 /// `__has_feature(undefined_behavior_sanitizer)` to evaluate true.
485
486 /// Paths to files specifying which objects
487 /// (files, functions, variables) should not be instrumented.
488 std::vector<std::string> NoSanitizeFiles;
489
490 /// Paths to the XRay "always instrument" files specifying which
491 /// objects (files, functions, variables) should be imbued with the XRay
492 /// "always instrument" attribute.
493 /// WARNING: This is a deprecated field and will go away in the future.
494 std::vector<std::string> XRayAlwaysInstrumentFiles;
495
496 /// Paths to the XRay "never instrument" files specifying which
497 /// objects (files, functions, variables) should be imbued with the XRay
498 /// "never instrument" attribute.
499 /// WARNING: This is a deprecated field and will go away in the future.
500 std::vector<std::string> XRayNeverInstrumentFiles;
501
502 /// Paths to the XRay attribute list files, specifying which objects
503 /// (files, functions, variables) should be imbued with the appropriate XRay
504 /// attribute(s).
505 std::vector<std::string> XRayAttrListFiles;
506
507 /// Paths to special case list files specifying which entities
508 /// (files, functions) should or should not be instrumented.
509 std::vector<std::string> ProfileListFiles;
510
512
514
521
522 /// The name of the handler function to be called when -ftrapv is
523 /// specified.
524 ///
525 /// If none is specified, abort (GCC-compatible behaviour).
526 std::string OverflowHandler;
527
528 /// The module currently being compiled as specified by -fmodule-name.
529 std::string ModuleName;
530
531 /// The name of the current module, of which the main source file
532 /// is a part. If CompilingModule is set, we are compiling the interface
533 /// of this module, otherwise we are compiling an implementation file of
534 /// it. This starts as ModuleName in case -fmodule-name is provided and
535 /// changes during compilation to reflect the current module.
536 std::string CurrentModule;
537
538 /// The names of any features to enable in module 'requires' decls
539 /// in addition to the hard-coded list in Module.cpp and the target features.
540 ///
541 /// This list is sorted.
542 std::vector<std::string> ModuleFeatures;
543
544 /// Options for parsing comments.
546
547 /// A list of all -fno-builtin-* function names (e.g., memset).
548 std::vector<std::string> NoBuiltinFuncs;
549
550 /// A prefix map for __FILE__, __BASE_FILE__ and __builtin_FILE().
551 std::map<std::string, std::string, std::greater<std::string>> MacroPrefixMap;
552
553 /// Macro name to use in lifetimebound fix-it suggestions.
555
556 /// Triples of the OpenMP targets that the host code codegen should
557 /// take into account in order to generate accurate offloading descriptors.
558 std::vector<llvm::Triple> OMPTargetTriples;
559
560 /// Name of the IR file that contains the result of the OpenMP target
561 /// host code generation.
562 std::string OMPHostIRFile;
563
564 /// The user provided compilation unit ID, if non-empty. This is used to
565 /// externalize static variables which is needed to support accessing static
566 /// device variables in host code for single source offloading languages
567 /// like CUDA/HIP.
568 std::string CUID;
569
570 /// C++ ABI to compile with, if specified by the frontend through -fc++-abi=.
571 /// This overrides the default ABI used by the target.
572 std::optional<TargetCXXABI::Kind> CXXABI;
573
574 /// Indicates whether the front-end is explicitly told that the
575 /// input is a header file (i.e. -x c-header).
576 bool IsHeaderFile = false;
577
578 /// The default stream kind used for HIP kernel launching.
580
581 /// Which overflow patterns should be excluded from sanitizer instrumentation
583
584 std::vector<std::string> OverflowPatternExclusionValues;
585
586 /// The seed used by the randomize structure layout feature.
587 std::string RandstructSeed;
588
589 /// Indicates whether to use target's platform-specific file separator when
590 /// __FILE__ macro is used and when concatenating filename with directory or
591 /// to use build environment environment's platform-specific file separator.
592 ///
593 /// The plaform-specific path separator is the backslash(\‍) for Windows and
594 /// forward slash (/) elsewhere.
596
597 // Indicates whether we should keep all nullptr checks for pointers
598 // received as a result of a standard operator new (-fcheck-new)
599 bool CheckNew = false;
600
601 /// The HLSL root signature version for dxil.
602 llvm::dxbc::RootSignatureVersion HLSLRootSigVer;
603
604 /// The HLSL root signature that will be used to overide the root signature
605 /// used for the shader entry point.
607
608 // Indicates if the wasm-opt binary must be ignored in the case of a
609 // WebAssembly target.
610 bool NoWasmOpt = false;
611
612 /// Atomic code-generation options.
613 /// These flags are set directly from the command-line options.
614 bool AtomicRemoteMemory = false;
617
618 /// Maximum number of allocation tokens (0 = target SIZE_MAX), nullopt if none
619 /// set (use target SIZE_MAX).
620 std::optional<uint64_t> AllocTokenMax;
621
622 /// The allocation token mode.
623 std::optional<llvm::AllocTokenMode> AllocTokenMode;
624
625 /// Name of the literal encoding to convert the internal encoding to.
626 std::string LiteralEncoding;
627
628 LangOptions();
629
630 /// Set language defaults for the given input language and
631 /// language standard in the given LangOptions object.
632 ///
633 /// \param Opts - The LangOptions object to set up.
634 /// \param Lang - The input language.
635 /// \param T - The target triple.
636 /// \param Includes - If the language requires extra headers to be implicitly
637 /// included, they will be appended to this list.
638 /// \param LangStd - The input language standard.
639 static void
640 setLangDefaults(LangOptions &Opts, Language Lang, const llvm::Triple &T,
641 std::vector<std::string> &Includes,
643
644 // Define accessors/mutators for language options of enumeration type.
645#define LANGOPT(Name, Bits, Default, Compatibility, Description)
646#define ENUM_LANGOPT(Name, Type, Bits, Default, Compatibility, Description) \
647 Type get##Name() const { return static_cast<Type>(Name); } \
648 void set##Name(Type Value) { \
649 assert(static_cast<unsigned>(Value) < (1u << Bits)); \
650 Name = static_cast<unsigned>(Value); \
651 }
652#include "clang/Basic/LangOptions.def"
653
654 /// Are we compiling a module?
655 bool isCompilingModule() const {
656 return getCompilingModule() != CMK_None;
657 }
658
659 /// Are we compiling a module implementation?
661 return !isCompilingModule() && !ModuleName.empty();
662 }
663
664 /// Do we need to track the owning module for a local declaration?
666 return isCompilingModule() || ModulesLocalVisibility;
667 }
668
670 return getSignedOverflowBehavior() == SOB_Defined;
671 }
672
674 return ObjCRuntime.isSubscriptPointerArithmetic() &&
675 !ObjCSubscriptingLegacyRuntime;
676 }
677
678 bool isCompatibleWith(ClangABI Version) const {
679 return getClangABICompat() <= Version;
680 }
681
682 bool isCompatibleWithMSVC() const { return MSCompatibilityVersion > 0; }
683
684 bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const {
685 return MSCompatibilityVersion >= MajorVersion * 100000U;
686 }
687
695
696 /// Reset all of the options that are not considered when building a
697 /// module.
699
700 /// Is this a libc/libm function that is no longer recognized as a
701 /// builtin because a -fno-builtin-* option has been specified?
702 bool isNoBuiltinFunc(StringRef Name) const;
703
704 /// True if any ObjC types may have non-trivial lifetime qualifiers.
706 return ObjCAutoRefCount || ObjCWeak;
707 }
708
710 return ConvergentFunctions;
711 }
712
713 /// Return true if atomicrmw operations targeting allocations in private
714 /// memory are undefined.
716 // Should be false for OpenMP.
717 // TODO: Should this be true for SYCL?
718 return OpenCL || CUDA;
719 }
720
721 /// Return the OpenCL C or C++ version as a VersionTuple.
722 VersionTuple getOpenCLVersionTuple() const;
723
724 /// Return the OpenCL version that kernel language is compatible with
725 unsigned getOpenCLCompatibleVersion() const;
726
727 /// Return the OpenCL C or C++ for OpenCL language name and version
728 /// as a string.
729 std::string getOpenCLVersionString() const;
730
731 /// Returns true if functions without prototypes or functions with an
732 /// identifier list (aka K&R C functions) are not allowed.
734 return CPlusPlus || C23 || DisableKNRFunctions;
735 }
736
737 /// Returns true if implicit function declarations are allowed in the current
738 /// language mode.
740 return !requiresStrictPrototypes() && !OpenCL;
741 }
742
743 /// Returns true if the language supports calling the 'atexit' function.
744 bool hasAtExit() const { return !(OpenMP && OpenMPIsTargetDevice); }
745
746 /// Returns true if implicit int is part of the language requirements.
747 bool isImplicitIntRequired() const { return !CPlusPlus && !C99; }
748
749 /// Returns true if implicit int is supported at all.
750 bool isImplicitIntAllowed() const { return !CPlusPlus && !C23; }
751
752 /// Check if return address signing is enabled.
753 bool hasSignReturnAddress() const {
754 return getSignReturnAddressScope() != SignReturnAddressScopeKind::None;
755 }
756
757 /// Check if return address signing uses AKey.
759 return getSignReturnAddressKey() == SignReturnAddressKeyKind::AKey;
760 }
761
762 /// Check if leaf functions are also signed.
764 return getSignReturnAddressScope() == SignReturnAddressScopeKind::All;
765 }
766
767 bool isSYCL() const { return SYCLIsDevice || SYCLIsHost; }
768
770 return getDefaultVisibilityExportMapping() !=
772 }
773
775 return getDefaultVisibilityExportMapping() ==
777 }
778
780 return getDefaultVisibilityExportMapping() ==
782 }
783
785 return getGlobalAllocationFunctionVisibility() !=
787 }
788
790 return getGlobalAllocationFunctionVisibility() ==
792 }
793
795 return getGlobalAllocationFunctionVisibility() ==
797 }
798
800 return getGlobalAllocationFunctionVisibility() ==
802 }
803
804 bool allowArrayReturnTypes() const { return HLSL; }
805
806 /// Remap path prefix according to -fmacro-prefix-path option.
807 void remapPathPrefix(SmallVectorImpl<char> &Path) const;
808
810 return RoundingMath ? RoundingMode::Dynamic
811 : RoundingMode::NearestTiesToEven;
812 }
813
815 FPExceptionModeKind EM = getFPExceptionMode();
818 return EM;
819 }
820
821 /// True when compiling for an offloading target device.
822 bool isTargetDevice() const {
823 return OpenMPIsTargetDevice || CUDAIsDevice || SYCLIsDevice;
824 }
825
826 /// Return the OpenMP version.
827 llvm::omp::Version getOpenMPVersion() const {
828 return llvm::omp::Version(OpenMP);
829 }
830
831 /// Returns the most applicable C standard-compliant language version code.
832 /// If none could be determined, returns \ref std::nullopt.
833 std::optional<uint32_t> getCLangStd() const;
834
835 /// Returns the most applicable C++ standard-compliant language
836 /// version code.
837 /// If none could be determined, returns \ref std::nullopt.
838 std::optional<uint32_t> getCPlusPlusLangStd() const;
839};
840
841/// Floating point control options
842class FPOptionsOverride;
844public:
845 // We start by defining the layout.
847
848 using RoundingMode = llvm::RoundingMode;
849
850 static constexpr unsigned StorageBitSize = 8 * sizeof(storage_type);
851
852 // Define a fake option named "First" so that we have a PREVIOUS even for the
853 // real first option.
854 static constexpr storage_type FirstShift = 0, FirstWidth = 0;
855#define FP_OPTION(NAME, TYPE, WIDTH, PREVIOUS) \
856 static constexpr storage_type NAME##Shift = \
857 PREVIOUS##Shift + PREVIOUS##Width; \
858 static constexpr storage_type NAME##Width = WIDTH; \
859 static constexpr storage_type NAME##Mask = ((1 << NAME##Width) - 1) \
860 << NAME##Shift;
861#include "clang/Basic/FPOptions.def"
862
863 static constexpr storage_type TotalWidth = 0
864#define FP_OPTION(NAME, TYPE, WIDTH, PREVIOUS) +WIDTH
865#include "clang/Basic/FPOptions.def"
866 ;
867 static_assert(TotalWidth <= StorageBitSize, "Too short type for FPOptions");
868
869private:
870 storage_type Value;
871
872 FPOptionsOverride getChangesSlow(const FPOptions &Base) const;
873
874public:
875 FPOptions() : Value(0) {
876 setFPContractMode(LangOptions::FPM_Off);
877 setConstRoundingMode(RoundingMode::Dynamic);
878 setSpecifiedExceptionMode(LangOptions::FPE_Default);
879 }
880 explicit FPOptions(const LangOptions &LO) {
881 Value = 0;
882 // The language fp contract option FPM_FastHonorPragmas has the same effect
883 // as FPM_Fast in frontend. For simplicity, use FPM_Fast uniformly in
884 // frontend.
885 auto LangOptContractMode = LO.getDefaultFPContractMode();
886 if (LangOptContractMode == LangOptions::FPM_FastHonorPragmas)
887 LangOptContractMode = LangOptions::FPM_Fast;
888 setFPContractMode(LangOptContractMode);
889 setRoundingMath(LO.RoundingMath);
890 setConstRoundingMode(LangOptions::RoundingMode::Dynamic);
891 setSpecifiedExceptionMode(LO.getFPExceptionMode());
892 setAllowFPReassociate(LO.AllowFPReassoc);
893 setNoHonorNaNs(LO.NoHonorNaNs);
894 setNoHonorInfs(LO.NoHonorInfs);
895 setNoSignedZero(LO.NoSignedZero);
896 setAllowReciprocal(LO.AllowRecip);
897 setAllowApproxFunc(LO.ApproxFunc);
898 if (getFPContractMode() == LangOptions::FPM_On &&
899 getRoundingMode() == llvm::RoundingMode::Dynamic &&
901 // If the FP settings are set to the "strict" model, then
902 // FENV access is set to true. (ffp-model=strict)
903 setAllowFEnvAccess(true);
904 else
905 setAllowFEnvAccess(LangOptions::FPM_Off);
906 setComplexRange(LO.getComplexRange());
907 }
908
910 return getFPContractMode() == LangOptions::FPM_On;
911 }
913 setFPContractMode(LangOptions::FPM_On);
914 }
915
917 return getFPContractMode() == LangOptions::FPM_Fast;
918 }
920 setFPContractMode(LangOptions::FPM_Fast);
921 }
922
923 bool isFPConstrained() const {
924 return getRoundingMode() != llvm::RoundingMode::NearestTiesToEven ||
926 getAllowFEnvAccess();
927 }
928
930 RoundingMode RM = getConstRoundingMode();
931 if (RM == RoundingMode::Dynamic) {
932 // C23: 7.6.2p3 If the FE_DYNAMIC mode is specified and FENV_ACCESS is
933 // "off", the translator may assume that the default rounding mode is in
934 // effect.
935 if (!getAllowFEnvAccess() && !getRoundingMath())
936 RM = RoundingMode::NearestTiesToEven;
937 }
938 return RM;
939 }
940
942 LangOptions::FPExceptionModeKind EM = getSpecifiedExceptionMode();
944 if (getAllowFEnvAccess())
946 else
948 }
949 return EM;
950 }
951
952 bool operator==(FPOptions other) const { return Value == other.Value; }
953
954 /// Return the default value of FPOptions that's used when trailing
955 /// storage isn't required.
957
958 storage_type getAsOpaqueInt() const { return Value; }
960 FPOptions Opts;
961 Opts.Value = Value;
962 return Opts;
963 }
964
965 /// Return difference with the given option set.
967
969
970 // We can define most of the accessors automatically:
971 // TODO: consider enforcing the assertion that value fits within bits
972 // statically.
973#define FP_OPTION(NAME, TYPE, WIDTH, PREVIOUS) \
974 TYPE get##NAME() const { \
975 return static_cast<TYPE>((Value & NAME##Mask) >> NAME##Shift); \
976 } \
977 void set##NAME(TYPE value) { \
978 assert(storage_type(value) < (1u << WIDTH)); \
979 Value = (Value & ~NAME##Mask) | (storage_type(value) << NAME##Shift); \
980 }
981#include "clang/Basic/FPOptions.def"
982 LLVM_DUMP_METHOD void dump();
983};
984
985/// Represents difference between two FPOptions values.
986///
987/// The effect of language constructs changing the set of floating point options
988/// is usually a change of some FP properties while leaving others intact. This
989/// class describes such changes by keeping information about what FP options
990/// are overridden.
991///
992/// The integral set of FP options, described by the class FPOptions, may be
993/// represented as a default FP option set, defined by language standard and
994/// command line options, with the overrides introduced by pragmas.
995///
996/// The is implemented as a value of the new FPOptions plus a mask showing which
997/// fields are actually set in it.
998///
999/// NOTE: This type is serialized into the AST format (e.g. for defaulted
1000/// functions). When adding a new field here or in FPOptions, ensure that the
1001/// AST VERSION_MAJOR is bumped if it changes the layout or size.
1004 FPOptions::storage_type OverrideMask = 0;
1005
1006public:
1007 using RoundingMode = llvm::RoundingMode;
1008
1009 /// The type suitable for storing values of FPOptionsOverride. Must be twice
1010 /// as wide as bit size of FPOption.
1011 using storage_type = uint64_t;
1012 static_assert(sizeof(storage_type) >= 2 * sizeof(FPOptions::storage_type),
1013 "Too short type for FPOptionsOverride");
1014
1015 /// Bit mask selecting bits of OverrideMask in serialized representation of
1016 /// FPOptionsOverride.
1018 (static_cast<storage_type>(1) << FPOptions::StorageBitSize) - 1;
1019
1022 : Options(LO), OverrideMask(OverrideMaskBits) {}
1024 : Options(FPO), OverrideMask(OverrideMaskBits) {}
1026 : Options(FPO), OverrideMask(Mask) {}
1027
1028 bool requiresTrailingStorage() const { return OverrideMask != 0; }
1029
1031 setFPContractModeOverride(LangOptions::FPM_On);
1032 }
1033
1035 setFPContractModeOverride(LangOptions::FPM_Fast);
1036 }
1037
1039 setFPContractModeOverride(LangOptions::FPM_Off);
1040 }
1041
1043 setAllowFPReassociateOverride(!Value);
1044 setNoHonorNaNsOverride(!Value);
1045 setNoHonorInfsOverride(!Value);
1046 setNoSignedZeroOverride(!Value);
1047 setAllowReciprocalOverride(!Value);
1048 setAllowApproxFuncOverride(!Value);
1049 setMathErrnoOverride(Value);
1050 if (Value)
1051 /* Precise mode implies fp_contract=on and disables ffast-math */
1053 else
1054 /* Precise mode disabled sets fp_contract=fast and enables ffast-math */
1056 }
1057
1059
1061 return (static_cast<storage_type>(Options.getAsOpaqueInt())
1063 OverrideMask;
1064 }
1066 FPOptionsOverride Opts;
1067 Opts.OverrideMask = I & OverrideMaskBits;
1069 return Opts;
1070 }
1071
1074 FPOptions::getFromOpaqueInt((Base.getAsOpaqueInt() & ~OverrideMask) |
1075 (Options.getAsOpaqueInt() & OverrideMask));
1076 return Result;
1077 }
1078
1080 return applyOverrides(FPOptions(LO));
1081 }
1082
1083 bool operator==(FPOptionsOverride other) const {
1084 return Options == other.Options && OverrideMask == other.OverrideMask;
1085 }
1086 bool operator!=(FPOptionsOverride other) const { return !(*this == other); }
1087
1088#define FP_OPTION(NAME, TYPE, WIDTH, PREVIOUS) \
1089 bool has##NAME##Override() const { \
1090 return OverrideMask & FPOptions::NAME##Mask; \
1091 } \
1092 TYPE get##NAME##Override() const { \
1093 assert(has##NAME##Override()); \
1094 return Options.get##NAME(); \
1095 } \
1096 void clear##NAME##Override() { \
1097 /* Clear the actual value so that we don't have spurious differences when \
1098 * testing equality. */ \
1099 Options.set##NAME(TYPE(0)); \
1100 OverrideMask &= ~FPOptions::NAME##Mask; \
1101 } \
1102 void set##NAME##Override(TYPE value) { \
1103 Options.set##NAME(value); \
1104 OverrideMask |= FPOptions::NAME##Mask; \
1105 }
1106#include "clang/Basic/FPOptions.def"
1107 LLVM_DUMP_METHOD void dump();
1108};
1111 if (Value == Base.Value)
1112 return FPOptionsOverride();
1113 return getChangesSlow(Base);
1114}
1117 *this = FPO.applyOverrides(*this);
1118}
1119
1120// The three atomic code-generation options.
1121// The canonical (positive) names are:
1122// "remote_memory", "fine_grained_memory", and "ignore_denormal_mode".
1123// In attribute or command-line parsing, a token prefixed with "no_" inverts its
1124// value.
1126 RemoteMemory, // enable remote memory.
1127 FineGrainedMemory, // enable fine-grained memory.
1128 IgnoreDenormalMode, // ignore floating-point denormals.
1130};
1132struct AtomicOptions {
1133 // Bitfields for each option.
1134 unsigned remote_memory : 1;
1136 unsigned ignore_denormal_mode : 1;
1141 AtomicOptions(const LangOptions &LO)
1142 : remote_memory(LO.AtomicRemoteMemory),
1143 fine_grained_memory(LO.AtomicFineGrainedMemory),
1144 ignore_denormal_mode(LO.AtomicIgnoreDenormalMode) {}
1146 bool getOption(AtomicOptionKind Kind) const {
1147 switch (Kind) {
1149 return remote_memory;
1151 return fine_grained_memory;
1153 return ignore_denormal_mode;
1154 }
1155 llvm_unreachable("Invalid AtomicOptionKind");
1156 }
1158 void setOption(AtomicOptionKind Kind, bool Value) {
1159 switch (Kind) {
1162 return;
1165 return;
1168 return;
1169 }
1170 llvm_unreachable("Invalid AtomicOptionKind");
1171 }
1173 LLVM_DUMP_METHOD void dump() const {
1174 llvm::errs() << "\n remote_memory: " << remote_memory
1175 << "\n fine_grained_memory: " << fine_grained_memory
1176 << "\n ignore_denormal_mode: " << ignore_denormal_mode << "\n";
1177 }
1178};
1179
1180/// Describes the kind of translation unit being processed.
1182 /// The translation unit is a complete translation unit.
1184
1185 /// The translation unit is a prefix to a translation unit, and is
1186 /// not complete.
1187 TU_Prefix,
1188
1189 /// The translation unit is a clang module.
1191
1192 /// The translation unit is a is a complete translation unit that we might
1193 /// incrementally extend later.
1195};
1196
1197} // namespace clang
1198
1199#endif // LLVM_CLANG_BASIC_LANGOPTIONS_H
Defines the clang::CommentOptions interface.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines types useful for describing an Objective-C runtime.
Defines the clang::SanitizerKind enum.
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we're targeting.
Defines the clang::Visibility enumeration and various utility functions.
Represents difference between two FPOptions values.
static FPOptionsOverride getFromOpaqueInt(storage_type I)
bool operator!=(FPOptionsOverride other) const
FPOptionsOverride(FPOptions FPO)
LLVM_DUMP_METHOD void dump()
void setFPPreciseEnabled(bool Value)
FPOptionsOverride(FPOptions FPO, FPOptions::storage_type Mask)
FPOptions applyOverrides(FPOptions Base)
bool operator==(FPOptionsOverride other) const
llvm::RoundingMode RoundingMode
static constexpr storage_type OverrideMaskBits
Bit mask selecting bits of OverrideMask in serialized representation of FPOptionsOverride.
storage_type getAsOpaqueInt() const
FPOptions applyOverrides(const LangOptions &LO)
uint64_t storage_type
The type suitable for storing values of FPOptionsOverride.
FPOptionsOverride(const LangOptions &LO)
bool requiresTrailingStorage() const
void applyChanges(FPOptionsOverride FPO)
bool isFPConstrained() const
static constexpr storage_type FirstShift
FPOptionsOverride getChangesFrom(const FPOptions &Base) const
Return difference with the given option set.
storage_type getAsOpaqueInt() const
static constexpr storage_type TotalWidth
LangOptions::FPExceptionModeKind getExceptionMode() const
FPOptions(const LangOptions &LO)
static constexpr storage_type FirstWidth
void setAllowFPContractWithinStatement()
static FPOptions defaultWithoutTrailingStorage(const LangOptions &LO)
Return the default value of FPOptions that's used when trailing storage isn't required.
static FPOptions getFromOpaqueInt(storage_type Value)
bool allowFPContractAcrossStatement() const
uint32_t storage_type
bool operator==(FPOptions other) const
bool allowFPContractWithinStatement() const
LLVM_DUMP_METHOD void dump()
void setAllowFPContractAcrossStatement()
static constexpr unsigned StorageBitSize
llvm::RoundingMode RoundingMode
RoundingMode getRoundingMode() const
Bitfields of LangOptions, split out from LangOptions in order to ensure that this large collection of...
Definition LangOptions.h:73
FPEvalMethodKind
Possible float expression evaluation method choices.
@ FEM_Extended
Use extended type for fp arithmetic.
@ FEM_Double
Use the type double for fp arithmetic.
@ FEM_UnsetOnCommandLine
Used only for FE option processing; this is only used to indicate that the user did not specify an ex...
@ FEM_Source
Use the declared type for fp arithmetic.
@ NonLeaf
Sign the return address of functions that spill LR.
@ All
Sign the return address of all functions,.
@ CMK_None
Not compiling a module interface at all.
@ CMK_HeaderUnit
Compiling a module header unit.
@ CMK_ModuleMap
Compiling a module from a module map.
@ CMK_ModuleInterface
Compiling a C++ modules interface unit.
ComplexRangeKind
Controls the various implementations for complex multiplication and.
@ CX_Full
Implementation of complex division and multiplication using a call to runtime library functions(gener...
@ CX_Basic
Implementation of complex division and multiplication using algebraic formulas at source precision.
@ CX_Promoted
Implementation of complex division using algebraic formulas at higher precision.
@ CX_None
No range rule is enabled.
@ CX_Improved
Implementation of complex division offering an improved handling for overflow in intermediate calcula...
@ Swift5_0
Interoperability with the Swift 5.0 runtime.
@ ObjectiveC
Interoperability with the ObjectiveC runtime.
@ Standalone
CoreFoundation does not have any language interoperability.
@ Unspecified
No interoperability ABI has been specified.
@ Swift
Interoperability with the latest known version of the Swift runtime.
@ Swift4_2
Interoperability with the Swift 4.2 runtime.
@ Swift4_1
Interoperability with the Swift 4.1 runtime.
llvm::RoundingMode RoundingMode
Definition LangOptions.h:79
clang::MSVtorDispMode MSVtorDispMode
@ PerThread
Per-thread default stream.
@ ForceProtected
Force protected visibility.
@ BKey
Return address signing uses APIB key.
@ AKey
Return address signing uses APIA key.
@ ExtendTo32
Integer arguments are sign or zero extended to 32/64 bits during default argument promotions.
@ Single
Single Threaded Environment.
@ Integer
Permit vector bitcasts between integer vectors with different numbers of elements but the same total ...
@ ZeroOrIncomplete
Any trailing array member of undefined or 0 size is a FAM.
@ OneZeroOrIncomplete
Any trailing array member of undefined, 0, or 1 size is a FAM.
@ IncompleteOnly
Any trailing array member of undefined size is a FAM.
@ Microsoft
Use Microsoft C++ ABI rules for bit-field layout and fundamental types alignment.
@ Itanium
Use Itanium rules for bit-field layout and fundamental types alignment.
friend class CompilerInvocationBase
Definition LangOptions.h:75
OverflowPatternExclusionKind
Exclude certain code patterns from being instrumented by arithmetic overflow sanitizers.
@ None
Don't exclude any overflow patterns from sanitizers.
@ AddUnsignedOverflowTest
if (a + b < a)
@ All
Exclude all overflow patterns (below)
@ AddSignedOverflowTest
if (a + b < a)
@ PostDecrInWhile
while (count–)
clang::Visibility Visibility
Definition LangOptions.h:78
@ Explicit
map only explicit default visibilities to exported
@ All
map all default visibilities to exported
CompatibilityKind
For ASTs produced with different option value, signifies their level of compatibility.
Definition LangOptions.h:84
@ NotCompatible
Does affect the construction of the AST in a way that does prevent module interoperability.
Definition LangOptions.h:87
@ Compatible
Does affect the construction of the AST in a way that doesn't prevent interoperability (that is,...
Definition LangOptions.h:91
@ Benign
Does not affect the construction of the AST in any way (that is, the value can be different between a...
Definition LangOptions.h:95
FPExceptionModeKind
Possible floating point exception behavior.
@ FPE_Default
Used internally to represent initial unspecified value.
@ FPE_Strict
Strictly preserve the floating-point exception semantics.
@ FPE_MayTrap
Transformations do not cause new exceptions but may hide some.
@ FPE_Ignore
Assume that floating-point exceptions are masked.
clang::CFBranchLabelSchemeKind CFBranchLabelSchemeKind
Definition LangOptions.h:80
friend class CompilerInvocation
Definition LangOptions.h:74
@ Protected
Override the IR-gen assigned visibility with protected visibility.
@ Hidden
Override the IR-gen assigned visibility with hidden visibility.
ClangABI
Clang versions with different platform ABI conformance.
RegisterStaticDestructorsKind
Controls which variables have static destructors registered.
@ ThreadLocal
Register static destructors only for thread-local variables.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
SanitizerSet UBSanFeatureIgnoredSanitize
Set of (UBSan) sanitizers that when enabled do not cause __has_feature(undefined_behavior_sanitizer) ...
bool isSignReturnAddressWithAKey() const
Check if return address signing uses AKey.
void resetNonModularOptions()
Reset all of the options that are not considered when building a module.
std::vector< std::string > OverflowPatternExclusionValues
std::optional< TargetCXXABI::Kind > CXXABI
C++ ABI to compile with, if specified by the frontend through -fc++-abi=.
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
std::vector< std::string > NoBuiltinFuncs
A list of all -fno-builtin-* function names (e.g., memset).
std::string ModuleName
The module currently being compiled as specified by -fmodule-name.
std::vector< std::string > XRayNeverInstrumentFiles
Paths to the XRay "never instrument" files specifying which objects (files, functions,...
FPExceptionModeKind getDefaultExceptionMode() const
bool requiresStrictPrototypes() const
Returns true if functions without prototypes or functions with an identifier list (aka K&R C function...
bool isImplicitIntAllowed() const
Returns true if implicit int is supported at all.
bool isCompilingModuleImplementation() const
Are we compiling a module implementation?
bool isNoBuiltinFunc(StringRef Name) const
Is this a libc/libm function that is no longer recognized as a builtin because a -fno-builtin-* optio...
clang::ObjCRuntime ObjCRuntime
CoreFoundationABI CFRuntime
std::string getOpenCLVersionString() const
Return the OpenCL C or C++ for OpenCL language name and version as a string.
unsigned OverflowPatternExclusionMask
Which overflow patterns should be excluded from sanitizer instrumentation.
bool IsHeaderFile
Indicates whether the front-end is explicitly told that the input is a header file (i....
bool hasDefaultVisibilityExportMapping() const
llvm::omp::Version getOpenMPVersion() const
Return the OpenMP version.
SanitizerSet Sanitize
Set of enabled sanitizers.
std::string LiteralEncoding
Name of the literal encoding to convert the internal encoding to.
std::optional< llvm::AllocTokenMode > AllocTokenMode
The allocation token mode.
CommentOptions CommentOpts
Options for parsing comments.
bool isExplicitDefaultVisibilityExportMapping() const
std::vector< std::string > XRayAlwaysInstrumentFiles
Paths to the XRay "always instrument" files specifying which objects (files, functions,...
bool hasAtExit() const
Returns true if the language supports calling the 'atexit' function.
bool trackLocalOwningModule() const
Do we need to track the owning module for a local declaration?
bool isAllDefaultVisibilityExportMapping() const
bool isSubscriptPointerArithmetic() const
bool UseTargetPathSeparator
Indicates whether to use target's platform-specific file separator when FILE macro is used and when c...
std::string ObjCConstantIntegerNumberClass
bool isSignedOverflowDefined() const
bool hasDefaultGlobalAllocationFunctionVisibility() const
bool hasGlobalAllocationFunctionVisibility() const
VersionTuple getOpenCLVersionTuple() const
Return the OpenCL C or C++ version as a VersionTuple.
std::string ObjCConstantDoubleNumberClass
bool implicitFunctionsAllowed() const
Returns true if implicit function declarations are allowed in the current language mode.
bool hasSignReturnAddress() const
Check if return address signing is enabled.
std::string LifetimeSafetyLifetimeBoundMacro
Macro name to use in lifetimebound fix-it suggestions.
static void setLangDefaults(LangOptions &Opts, Language Lang, const llvm::Triple &T, std::vector< std::string > &Includes, LangStandard::Kind LangStd=LangStandard::lang_unspecified)
Set language defaults for the given input language and language standard in the given LangOptions obj...
bool isCompatibleWith(ClangABI Version) const
bool isCompatibleWithMSVC() const
bool assumeFunctionsAreConvergent() const
std::string OMPHostIRFile
Name of the IR file that contains the result of the OpenMP target host code generation.
bool allowsNonTrivialObjCLifetimeQualifiers() const
True if any ObjC types may have non-trivial lifetime qualifiers.
bool isOverflowPatternExcluded(OverflowPatternExclusionKind Kind) const
bool allowArrayReturnTypes() const
std::string OverflowHandler
The name of the handler function to be called when -ftrapv is specified.
std::string HLSLRootSigOverride
The HLSL root signature that will be used to overide the root signature used for the shader entry poi...
bool hasHiddenGlobalAllocationFunctionVisibility() const
std::string RandstructSeed
The seed used by the randomize structure layout feature.
std::map< std::string, std::string, std::greater< std::string > > MacroPrefixMap
A prefix map for FILE, BASE_FILE and __builtin_FILE().
std::vector< std::string > ProfileListFiles
Paths to special case list files specifying which entities (files, functions) should or should not be...
void remapPathPrefix(SmallVectorImpl< char > &Path) const
Remap path prefix according to -fmacro-prefix-path option.
bool isTargetDevice() const
True when compiling for an offloading target device.
std::optional< uint64_t > AllocTokenMax
Maximum number of allocation tokens (0 = target SIZE_MAX), nullopt if none set (use target SIZE_MAX).
bool hasProtectedGlobalAllocationFunctionVisibility() const
std::optional< uint32_t > getCPlusPlusLangStd() const
Returns the most applicable C++ standard-compliant language version code.
LangStandard::Kind LangStd
The used language standard.
llvm::dxbc::RootSignatureVersion HLSLRootSigVer
The HLSL root signature version for dxil.
std::optional< uint32_t > getCLangStd() const
Returns the most applicable C standard-compliant language version code.
RoundingMode getDefaultRoundingMode() const
bool isCompilingModule() const
Are we compiling a module?
bool isImplicitIntRequired() const
Returns true if implicit int is part of the language requirements.
bool isSignReturnAddressScopeAll() const
Check if leaf functions are also signed.
bool isSYCL() const
std::string ObjCConstantArrayClass
std::string ObjCConstantStringClass
std::string CUID
The user provided compilation unit ID, if non-empty.
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
std::string ObjCConstantDictionaryClass
std::string ObjCConstantFloatNumberClass
GPUDefaultStreamKind GPUDefaultStream
The default stream kind used for HIP kernel launching.
bool AtomicRemoteMemory
Atomic code-generation options.
bool threadPrivateMemoryAtomicsAreUndefined() const
Return true if atomicrmw operations targeting allocations in private memory are undefined.
std::vector< std::string > XRayAttrListFiles
Paths to the XRay attribute list files, specifying which objects (files, functions,...
bool SanitizeCoverage
Is at least one coverage instrumentation type enabled.
std::vector< llvm::Triple > OMPTargetTriples
Triples of the OpenMP targets that the host code codegen should take into account in order to generat...
std::vector< std::string > NoSanitizeFiles
Paths to files specifying which objects (files, functions, variables) should not be instrumented.
std::string CurrentModule
The name of the current module, of which the main source file is a part.
std::vector< std::string > ModuleFeatures
The names of any features to enable in module 'requires' decls in addition to the hard-coded list in ...
The basic abstraction for the target Objective-C runtime.
Definition ObjCRuntime.h:28
Top level wrappers for InstallAPI frontend operations.
@ CPlusPlus
Language
The language for the input, used to select and validate the language standard and possible actions.
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
MSVtorDispMode
In the Microsoft ABI, this controls the placement of virtual displacement members used to implement v...
Definition LangOptions.h:39
ShaderStage
Shader programs run in specific pipeline stages.
Definition LangOptions.h:45
TranslationUnitKind
Describes the kind of translation unit being processed.
@ TU_Incremental
The translation unit is a is a complete translation unit that we might incrementally extend later.
@ TU_Complete
The translation unit is a complete translation unit.
@ TU_ClangModule
The translation unit is a clang module.
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
PointerAuthenticationMode
Definition LangOptions.h:64
@ None
The alignment was not explicit in code.
Definition ASTContext.h:176
Visibility
Describes the different kinds of visibility that a declaration may have.
Definition Visibility.h:34
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 uint32_t
void setOption(AtomicOptionKind Kind, bool Value)
LLVM_DUMP_METHOD void dump() const
unsigned ignore_denormal_mode
bool getOption(AtomicOptionKind Kind) const
Options for controlling comment parsing.