xref: /llvm-project/clang/include/clang/Basic/LangOptions.h (revision 54928a10c8dba7c07c6224c1ead5c02a335890e6)
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 
17 #include "clang/Basic/CFProtectionOptions.h"
18 #include "clang/Basic/CommentOptions.h"
19 #include "clang/Basic/LLVM.h"
20 #include "clang/Basic/LangStandard.h"
21 #include "clang/Basic/ObjCRuntime.h"
22 #include "clang/Basic/Sanitizers.h"
23 #include "clang/Basic/TargetCXXABI.h"
24 #include "clang/Basic/Visibility.h"
25 #include "llvm/ADT/FloatingPointMode.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/TargetParser/Triple.h"
28 #include <optional>
29 #include <string>
30 #include <vector>
31 
32 namespace clang {
33 
34 /// In the Microsoft ABI, this controls the placement of virtual displacement
35 /// members used to implement virtual inheritance.
36 enum class MSVtorDispMode { Never, ForVBaseOverride, ForVFTable };
37 
38 /// Shader programs run in specific pipeline stages.
39 /// The order of these values matters, and must be kept in sync with the
40 /// Triple Environment enum in llvm::Triple. The ordering is enforced in
41 ///  static_asserts in Triple.cpp and in clang/Basic/HLSLRuntime.h.
42 enum class ShaderStage {
43   Pixel = 0,
44   Vertex,
45   Geometry,
46   Hull,
47   Domain,
48   Compute,
49   Library,
50   RayGeneration,
51   Intersection,
52   AnyHit,
53   ClosestHit,
54   Miss,
55   Callable,
56   Mesh,
57   Amplification,
58   Invalid,
59 };
60 
61 enum class PointerAuthenticationMode : unsigned {
62   None,
63   Strip,
64   SignAndStrip,
65   SignAndAuth
66 };
67 
68 /// Bitfields of LangOptions, split out from LangOptions in order to ensure that
69 /// this large collection of bitfields is a trivial class type.
70 class LangOptionsBase {
71   friend class CompilerInvocation;
72   friend class CompilerInvocationBase;
73 
74 public:
75   using Visibility = clang::Visibility;
76   using RoundingMode = llvm::RoundingMode;
77   using CFBranchLabelSchemeKind = clang::CFBranchLabelSchemeKind;
78 
79   enum GCMode { NonGC, GCOnly, HybridGC };
80   enum StackProtectorMode { SSPOff, SSPOn, SSPStrong, SSPReq };
81 
82   // Automatic variables live on the stack, and when trivial they're usually
83   // uninitialized because it's undefined behavior to use them without
84   // initializing them.
85   enum class TrivialAutoVarInitKind { Uninitialized, Zero, Pattern };
86 
87   enum SignedOverflowBehaviorTy {
88     // Default C standard behavior.
89     SOB_Undefined,
90 
91     // -fwrapv
92     SOB_Defined,
93 
94     // -ftrapv
95     SOB_Trapping
96   };
97 
98   // FIXME: Unify with TUKind.
99   enum CompilingModuleKind {
100     /// Not compiling a module interface at all.
101     CMK_None,
102 
103     /// Compiling a module from a module map.
104     CMK_ModuleMap,
105 
106     /// Compiling a module header unit.
107     CMK_HeaderUnit,
108 
109     /// Compiling a C++ modules interface unit.
110     CMK_ModuleInterface,
111   };
112 
113   enum PragmaMSPointersToMembersKind {
114     PPTMK_BestCase,
115     PPTMK_FullGeneralitySingleInheritance,
116     PPTMK_FullGeneralityMultipleInheritance,
117     PPTMK_FullGeneralityVirtualInheritance
118   };
119 
120   using MSVtorDispMode = clang::MSVtorDispMode;
121 
122   enum DefaultCallingConvention {
123     DCC_None,
124     DCC_CDecl,
125     DCC_FastCall,
126     DCC_StdCall,
127     DCC_VectorCall,
128     DCC_RegCall,
129     DCC_RtdCall
130   };
131 
132   enum AddrSpaceMapMangling { ASMM_Target, ASMM_On, ASMM_Off };
133 
134   // Corresponds to _MSC_VER
135   enum MSVCMajorVersion {
136     MSVC2010 = 1600,
137     MSVC2012 = 1700,
138     MSVC2013 = 1800,
139     MSVC2015 = 1900,
140     MSVC2017 = 1910,
141     MSVC2017_5 = 1912,
142     MSVC2017_7 = 1914,
143     MSVC2019 = 1920,
144     MSVC2019_5 = 1925,
145     MSVC2019_8 = 1928,
146     MSVC2022_3 = 1933,
147     MSVC2022_9 = 1939,
148   };
149 
150   enum SYCLMajorVersion {
151     SYCL_None,
152     SYCL_2017,
153     SYCL_2020,
154     // The "default" SYCL version to be used when none is specified on the
155     // frontend command line.
156     SYCL_Default = SYCL_2020
157   };
158 
159   enum HLSLLangStd {
160     HLSL_Unset = 0,
161     HLSL_2015 = 2015,
162     HLSL_2016 = 2016,
163     HLSL_2017 = 2017,
164     HLSL_2018 = 2018,
165     HLSL_2021 = 2021,
166     HLSL_202x = 2028,
167     HLSL_202y = 2029,
168   };
169 
170   /// Clang versions with different platform ABI conformance.
171   enum class ClangABI {
172     /// Attempt to be ABI-compatible with code generated by Clang 3.8.x
173     /// (SVN r257626). This causes <1 x long long> to be passed in an
174     /// integer register instead of an SSE register on x64_64.
175     Ver3_8,
176 
177     /// Attempt to be ABI-compatible with code generated by Clang 4.0.x
178     /// (SVN r291814). This causes move operations to be ignored when
179     /// determining whether a class type can be passed or returned directly.
180     Ver4,
181 
182     /// Attempt to be ABI-compatible with code generated by Clang 6.0.x
183     /// (SVN r321711). This causes determination of whether a type is
184     /// standard-layout to ignore collisions between empty base classes
185     /// and between base classes and member subobjects, which affects
186     /// whether we reuse base class tail padding in some ABIs.
187     Ver6,
188 
189     /// Attempt to be ABI-compatible with code generated by Clang 7.0.x
190     /// (SVN r338536). This causes alignof (C++) and _Alignof (C11) to be
191     /// compatible with __alignof (i.e., return the preferred alignment)
192     /// rather than returning the required alignment.
193     Ver7,
194 
195     /// Attempt to be ABI-compatible with code generated by Clang 9.0.x
196     /// (SVN r351319). This causes vectors of __int128 to be passed in memory
197     /// instead of passing in multiple scalar registers on x86_64 on Linux and
198     /// NetBSD.
199     Ver9,
200 
201     /// Attempt to be ABI-compatible with code generated by Clang 11.0.x
202     /// (git 2e10b7a39b93). This causes clang to pass unions with a 256-bit
203     /// vector member on the stack instead of using registers, to not properly
204     /// mangle substitutions for template names in some cases, and to mangle
205     /// declaration template arguments without a cast to the parameter type
206     /// even when that can lead to mangling collisions.
207     Ver11,
208 
209     /// Attempt to be ABI-compatible with code generated by Clang 12.0.x
210     /// (git 8e464dd76bef). This causes clang to mangle lambdas within
211     /// global-scope inline variables incorrectly.
212     Ver12,
213 
214     /// Attempt to be ABI-compatible with code generated by Clang 14.0.x.
215     /// This causes clang to:
216     ///   - mangle dependent nested names incorrectly.
217     ///   - make trivial only those defaulted copy constructors with a
218     ///     parameter-type-list equivalent to the parameter-type-list of an
219     ///     implicit declaration.
220     Ver14,
221 
222     /// Attempt to be ABI-compatible with code generated by Clang 15.0.x.
223     /// This causes clang to:
224     ///   - Reverse the implementation for DR692, DR1395 and DR1432.
225     ///   - pack non-POD members of packed structs.
226     ///   - consider classes with defaulted special member functions non-pod.
227     Ver15,
228 
229     /// Attempt to be ABI-compatible with code generated by Clang 17.0.x.
230     /// This causes clang to revert some fixes to its implementation of the
231     /// Itanium name mangling scheme, with the consequence that overloaded
232     /// function templates are mangled the same if they differ only by:
233     ///   - constraints
234     ///   - whether a non-type template parameter has a deduced type
235     ///   - the parameter list of a template template parameter
236     Ver17,
237 
238     /// Attempt to be ABI-compatible with code generated by Clang 18.0.x.
239     /// This causes clang to revert some fixes to the mangling of lambdas
240     /// in the initializers of members of local classes.
241     Ver18,
242 
243     /// Attempt to be ABI-compatible with code generated by Clang 19.0.x.
244     /// This causes clang to:
245     ///   - Incorrectly mangle the 'base type' substitutions of the CXX
246     ///   construction vtable because it hasn't added 'type' as a substitution.
247     ///   - Skip mangling enclosing class templates of member-like friend
248     ///   function templates.
249     Ver19,
250 
251     /// Conform to the underlying platform's C and C++ ABIs as closely
252     /// as we can.
253     Latest
254   };
255 
256   enum class CoreFoundationABI {
257     /// No interoperability ABI has been specified
258     Unspecified,
259     /// CoreFoundation does not have any language interoperability
260     Standalone,
261     /// Interoperability with the ObjectiveC runtime
262     ObjectiveC,
263     /// Interoperability with the latest known version of the Swift runtime
264     Swift,
265     /// Interoperability with the Swift 5.0 runtime
266     Swift5_0,
267     /// Interoperability with the Swift 4.2 runtime
268     Swift4_2,
269     /// Interoperability with the Swift 4.1 runtime
270     Swift4_1,
271   };
272 
273   enum FPModeKind {
274     // Disable the floating point pragma
275     FPM_Off,
276 
277     // Enable the floating point pragma
278     FPM_On,
279 
280     // Aggressively fuse FP ops (E.g. FMA) disregarding pragmas.
281     FPM_Fast,
282 
283     // Aggressively fuse FP ops and honor pragmas.
284     FPM_FastHonorPragmas
285   };
286 
287   /// Possible floating point exception behavior.
288   enum FPExceptionModeKind {
289     /// Assume that floating-point exceptions are masked.
290     FPE_Ignore,
291     /// Transformations do not cause new exceptions but may hide some.
292     FPE_MayTrap,
293     /// Strictly preserve the floating-point exception semantics.
294     FPE_Strict,
295     /// Used internally to represent initial unspecified value.
296     FPE_Default
297   };
298 
299   /// Possible float expression evaluation method choices.
300   enum FPEvalMethodKind {
301     /// The evaluation method cannot be determined or is inconsistent for this
302     /// target.
303     FEM_Indeterminable = -1,
304     /// Use the declared type for fp arithmetic.
305     FEM_Source = 0,
306     /// Use the type double for fp arithmetic.
307     FEM_Double = 1,
308     /// Use extended type for fp arithmetic.
309     FEM_Extended = 2,
310     /// Used only for FE option processing; this is only used to indicate that
311     /// the user did not specify an explicit evaluation method on the command
312     /// line and so the target should be queried for its default evaluation
313     /// method instead.
314     FEM_UnsetOnCommandLine = 3
315   };
316 
317   enum ExcessPrecisionKind { FPP_Standard, FPP_Fast, FPP_None };
318 
319   /// Possible exception handling behavior.
320   enum class ExceptionHandlingKind { None, SjLj, WinEH, DwarfCFI, Wasm };
321 
322   enum class LaxVectorConversionKind {
323     /// Permit no implicit vector bitcasts.
324     None,
325     /// Permit vector bitcasts between integer vectors with different numbers
326     /// of elements but the same total bit-width.
327     Integer,
328     /// Permit vector bitcasts between all vectors with the same total
329     /// bit-width.
330     All,
331   };
332 
333   enum class AltivecSrcCompatKind {
334     // All vector compares produce scalars except vector pixel and vector bool.
335     // The types vector pixel and vector bool return vector results.
336     Mixed,
337     // All vector compares produce vector results as in GCC.
338     GCC,
339     // All vector compares produce scalars as in XL.
340     XL,
341     // Default clang behaviour.
342     Default = Mixed,
343   };
344 
345   enum class SignReturnAddressScopeKind {
346     /// No signing for any function.
347     None,
348     /// Sign the return address of functions that spill LR.
349     NonLeaf,
350     /// Sign the return address of all functions,
351     All
352   };
353 
354   enum class SignReturnAddressKeyKind {
355     /// Return address signing uses APIA key.
356     AKey,
357     /// Return address signing uses APIB key.
358     BKey
359   };
360 
361   enum class ThreadModelKind {
362     /// POSIX Threads.
363     POSIX,
364     /// Single Threaded Environment.
365     Single
366   };
367 
368   enum class ExtendArgsKind {
369     /// Integer arguments are sign or zero extended to 32/64 bits
370     /// during default argument promotions.
371     ExtendTo32,
372     ExtendTo64
373   };
374 
375   enum class GPUDefaultStreamKind {
376     /// Legacy default stream
377     Legacy,
378     /// Per-thread default stream
379     PerThread,
380   };
381 
382   /// Exclude certain code patterns from being instrumented by arithmetic
383   /// overflow sanitizers
384   enum OverflowPatternExclusionKind {
385     /// Don't exclude any overflow patterns from sanitizers
386     None = 1 << 0,
387     /// Exclude all overflow patterns (below)
388     All = 1 << 1,
389     /// if (a + b < a)
390     AddSignedOverflowTest = 1 << 2,
391     /// if (a + b < a)
392     AddUnsignedOverflowTest = 1 << 3,
393     /// -1UL
394     NegUnsignedConst = 1 << 4,
395     /// while (count--)
396     PostDecrInWhile = 1 << 5,
397   };
398 
399   enum class DefaultVisiblityExportMapping {
400     None,
401     /// map only explicit default visibilities to exported
402     Explicit,
403     /// map all default visibilities to exported
404     All,
405   };
406 
407   enum class VisibilityForcedKinds {
408     /// Force hidden visibility
409     ForceHidden,
410     /// Force protected visibility
411     ForceProtected,
412     /// Force default visibility
413     ForceDefault,
414     /// Don't alter the visibility
415     Source,
416   };
417 
418   enum class VisibilityFromDLLStorageClassKinds {
419     /// Keep the IR-gen assigned visibility.
420     Keep,
421     /// Override the IR-gen assigned visibility with default visibility.
422     Default,
423     /// Override the IR-gen assigned visibility with hidden visibility.
424     Hidden,
425     /// Override the IR-gen assigned visibility with protected visibility.
426     Protected,
427   };
428 
429   enum class StrictFlexArraysLevelKind {
430     /// Any trailing array member is a FAM.
431     Default = 0,
432     /// Any trailing array member of undefined, 0, or 1 size is a FAM.
433     OneZeroOrIncomplete = 1,
434     /// Any trailing array member of undefined or 0 size is a FAM.
435     ZeroOrIncomplete = 2,
436     /// Any trailing array member of undefined size is a FAM.
437     IncompleteOnly = 3,
438   };
439 
440   /// Controls the various implementations for complex multiplication and
441   // division.
442   enum ComplexRangeKind {
443     /// Implementation of complex division and multiplication using a call to
444     ///  runtime library functions(generally the case, but the BE might
445     /// sometimes replace the library call if it knows enough about the
446     /// potential range of the inputs). Overflow and non-finite values are
447     /// handled by the library implementation. This is the default value.
448     CX_Full,
449 
450     /// Implementation of complex division offering an improved handling
451     /// for overflow in intermediate calculations with no special handling for
452     /// NaN and infinite values.
453     CX_Improved,
454 
455     /// Implementation of complex division using algebraic formulas at
456     /// higher precision. Overflow is handled. Non-finite values are handled in
457     /// some cases. If the target hardware does not have native support for a
458     /// higher precision data type, an implementation for the complex operation
459     /// will be used to provide improved guards against intermediate overflow,
460     /// but overflow and underflow may still occur in some cases. NaN and
461     /// infinite values are not handled.
462     CX_Promoted,
463 
464     /// Implementation of complex division and multiplication using
465     /// algebraic formulas at source precision. No special handling to avoid
466     /// overflow. NaN and infinite values are not handled.
467     CX_Basic,
468 
469     /// No range rule is enabled.
470     CX_None
471   };
472 
473   /// Controls which variables have static destructors registered.
474   enum class RegisterStaticDestructorsKind {
475     /// Register static destructors for all variables.
476     All,
477     /// Register static destructors only for thread-local variables.
478     ThreadLocal,
479     /// Don't register static destructors for any variables.
480     None,
481   };
482 
483   // Define simple language options (with no accessors).
484 #define LANGOPT(Name, Bits, Default, Description) unsigned Name : Bits;
485 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description)
486 #include "clang/Basic/LangOptions.def"
487 
488 protected:
489   // Define language options of enumeration type. These are private, and will
490   // have accessors (below).
491 #define LANGOPT(Name, Bits, Default, Description)
492 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
493   LLVM_PREFERRED_TYPE(Type) \
494   unsigned Name : Bits;
495 #include "clang/Basic/LangOptions.def"
496 };
497 
498 /// Keeps track of the various options that can be
499 /// enabled, which controls the dialect of C or C++ that is accepted.
500 class LangOptions : public LangOptionsBase {
501 public:
502   /// The used language standard.
503   LangStandard::Kind LangStd;
504 
505   /// Set of enabled sanitizers.
506   SanitizerSet Sanitize;
507   /// Is at least one coverage instrumentation type enabled.
508   bool SanitizeCoverage = false;
509 
510   /// Paths to files specifying which objects
511   /// (files, functions, variables) should not be instrumented.
512   std::vector<std::string> NoSanitizeFiles;
513 
514   /// Paths to the XRay "always instrument" files specifying which
515   /// objects (files, functions, variables) should be imbued with the XRay
516   /// "always instrument" attribute.
517   /// WARNING: This is a deprecated field and will go away in the future.
518   std::vector<std::string> XRayAlwaysInstrumentFiles;
519 
520   /// Paths to the XRay "never instrument" files specifying which
521   /// objects (files, functions, variables) should be imbued with the XRay
522   /// "never instrument" attribute.
523   /// WARNING: This is a deprecated field and will go away in the future.
524   std::vector<std::string> XRayNeverInstrumentFiles;
525 
526   /// Paths to the XRay attribute list files, specifying which objects
527   /// (files, functions, variables) should be imbued with the appropriate XRay
528   /// attribute(s).
529   std::vector<std::string> XRayAttrListFiles;
530 
531   /// Paths to special case list files specifying which entities
532   /// (files, functions) should or should not be instrumented.
533   std::vector<std::string> ProfileListFiles;
534 
535   clang::ObjCRuntime ObjCRuntime;
536 
537   CoreFoundationABI CFRuntime = CoreFoundationABI::Unspecified;
538 
539   std::string ObjCConstantStringClass;
540 
541   /// The name of the handler function to be called when -ftrapv is
542   /// specified.
543   ///
544   /// If none is specified, abort (GCC-compatible behaviour).
545   std::string OverflowHandler;
546 
547   /// The module currently being compiled as specified by -fmodule-name.
548   std::string ModuleName;
549 
550   /// The name of the current module, of which the main source file
551   /// is a part. If CompilingModule is set, we are compiling the interface
552   /// of this module, otherwise we are compiling an implementation file of
553   /// it. This starts as ModuleName in case -fmodule-name is provided and
554   /// changes during compilation to reflect the current module.
555   std::string CurrentModule;
556 
557   /// The names of any features to enable in module 'requires' decls
558   /// in addition to the hard-coded list in Module.cpp and the target features.
559   ///
560   /// This list is sorted.
561   std::vector<std::string> ModuleFeatures;
562 
563   /// Options for parsing comments.
564   CommentOptions CommentOpts;
565 
566   /// A list of all -fno-builtin-* function names (e.g., memset).
567   std::vector<std::string> NoBuiltinFuncs;
568 
569   /// A prefix map for __FILE__, __BASE_FILE__ and __builtin_FILE().
570   std::map<std::string, std::string, std::greater<std::string>> MacroPrefixMap;
571 
572   /// Triples of the OpenMP targets that the host code codegen should
573   /// take into account in order to generate accurate offloading descriptors.
574   std::vector<llvm::Triple> OMPTargetTriples;
575 
576   /// Name of the IR file that contains the result of the OpenMP target
577   /// host code generation.
578   std::string OMPHostIRFile;
579 
580   /// The user provided compilation unit ID, if non-empty. This is used to
581   /// externalize static variables which is needed to support accessing static
582   /// device variables in host code for single source offloading languages
583   /// like CUDA/HIP.
584   std::string CUID;
585 
586   /// C++ ABI to compile with, if specified by the frontend through -fc++-abi=.
587   /// This overrides the default ABI used by the target.
588   std::optional<TargetCXXABI::Kind> CXXABI;
589 
590   /// Indicates whether the front-end is explicitly told that the
591   /// input is a header file (i.e. -x c-header).
592   bool IsHeaderFile = false;
593 
594   /// The default stream kind used for HIP kernel launching.
595   GPUDefaultStreamKind GPUDefaultStream;
596 
597   /// Which overflow patterns should be excluded from sanitizer instrumentation
598   unsigned OverflowPatternExclusionMask = 0;
599 
600   std::vector<std::string> OverflowPatternExclusionValues;
601 
602   /// The seed used by the randomize structure layout feature.
603   std::string RandstructSeed;
604 
605   /// Indicates whether to use target's platform-specific file separator when
606   /// __FILE__ macro is used and when concatenating filename with directory or
607   /// to use build environment environment's platform-specific file separator.
608   ///
609   /// The plaform-specific path separator is the backslash(\) for Windows and
610   /// forward slash (/) elsewhere.
611   bool UseTargetPathSeparator = false;
612 
613   // Indicates whether we should keep all nullptr checks for pointers
614   // received as a result of a standard operator new (-fcheck-new)
615   bool CheckNew = false;
616 
617   // In OpenACC mode, contains a user provided override for the _OPENACC macro.
618   // This exists so that we can override the macro value and test our incomplete
619   // implementation on real-world examples.
620   std::string OpenACCMacroOverride;
621 
622   // Indicates if the wasm-opt binary must be ignored in the case of a
623   // WebAssembly target.
624   bool NoWasmOpt = false;
625 
626   LangOptions();
627 
628   /// Set language defaults for the given input language and
629   /// language standard in the given LangOptions object.
630   ///
631   /// \param Opts - The LangOptions object to set up.
632   /// \param Lang - The input language.
633   /// \param T - The target triple.
634   /// \param Includes - If the language requires extra headers to be implicitly
635   ///                   included, they will be appended to this list.
636   /// \param LangStd - The input language standard.
637   static void
638   setLangDefaults(LangOptions &Opts, Language Lang, const llvm::Triple &T,
639                   std::vector<std::string> &Includes,
640                   LangStandard::Kind LangStd = LangStandard::lang_unspecified);
641 
642   // Define accessors/mutators for language options of enumeration type.
643 #define LANGOPT(Name, Bits, Default, Description)
644 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
645   Type get##Name() const { return static_cast<Type>(Name); } \
646   void set##Name(Type Value) { Name = static_cast<unsigned>(Value); }
647 #include "clang/Basic/LangOptions.def"
648 
649   /// Are we compiling a module?
650   bool isCompilingModule() const {
651     return getCompilingModule() != CMK_None;
652   }
653 
654   /// Are we compiling a module implementation?
655   bool isCompilingModuleImplementation() const {
656     return !isCompilingModule() && !ModuleName.empty();
657   }
658 
659   /// Do we need to track the owning module for a local declaration?
660   bool trackLocalOwningModule() const {
661     return isCompilingModule() || ModulesLocalVisibility;
662   }
663 
664   bool isSignedOverflowDefined() const {
665     return getSignedOverflowBehavior() == SOB_Defined;
666   }
667 
668   bool isSubscriptPointerArithmetic() const {
669     return ObjCRuntime.isSubscriptPointerArithmetic() &&
670            !ObjCSubscriptingLegacyRuntime;
671   }
672 
673   bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const {
674     return MSCompatibilityVersion >= MajorVersion * 100000U;
675   }
676 
677   bool isOverflowPatternExcluded(OverflowPatternExclusionKind Kind) const {
678     if (OverflowPatternExclusionMask & OverflowPatternExclusionKind::None)
679       return false;
680     if (OverflowPatternExclusionMask & OverflowPatternExclusionKind::All)
681       return true;
682     return OverflowPatternExclusionMask & Kind;
683   }
684 
685   /// Reset all of the options that are not considered when building a
686   /// module.
687   void resetNonModularOptions();
688 
689   /// Is this a libc/libm function that is no longer recognized as a
690   /// builtin because a -fno-builtin-* option has been specified?
691   bool isNoBuiltinFunc(StringRef Name) const;
692 
693   /// True if any ObjC types may have non-trivial lifetime qualifiers.
694   bool allowsNonTrivialObjCLifetimeQualifiers() const {
695     return ObjCAutoRefCount || ObjCWeak;
696   }
697 
698   bool assumeFunctionsAreConvergent() const {
699     return ConvergentFunctions;
700   }
701 
702   /// Return true if atomicrmw operations targeting allocations in private
703   /// memory are undefined.
704   bool threadPrivateMemoryAtomicsAreUndefined() const {
705     // Should be false for OpenMP.
706     // TODO: Should this be true for SYCL?
707     return OpenCL || CUDA;
708   }
709 
710   /// Return the OpenCL C or C++ version as a VersionTuple.
711   VersionTuple getOpenCLVersionTuple() const;
712 
713   /// Return the OpenCL version that kernel language is compatible with
714   unsigned getOpenCLCompatibleVersion() const;
715 
716   /// Return the OpenCL C or C++ for OpenCL language name and version
717   /// as a string.
718   std::string getOpenCLVersionString() const;
719 
720   /// Returns true if functions without prototypes or functions with an
721   /// identifier list (aka K&R C functions) are not allowed.
722   bool requiresStrictPrototypes() const {
723     return CPlusPlus || C23 || DisableKNRFunctions;
724   }
725 
726   /// Returns true if implicit function declarations are allowed in the current
727   /// language mode.
728   bool implicitFunctionsAllowed() const {
729     return !requiresStrictPrototypes() && !OpenCL;
730   }
731 
732   /// Returns true if the language supports calling the 'atexit' function.
733   bool hasAtExit() const { return !(OpenMP && OpenMPIsTargetDevice); }
734 
735   /// Returns true if implicit int is part of the language requirements.
736   bool isImplicitIntRequired() const { return !CPlusPlus && !C99; }
737 
738   /// Returns true if implicit int is supported at all.
739   bool isImplicitIntAllowed() const { return !CPlusPlus && !C23; }
740 
741   /// Check if return address signing is enabled.
742   bool hasSignReturnAddress() const {
743     return getSignReturnAddressScope() != SignReturnAddressScopeKind::None;
744   }
745 
746   /// Check if return address signing uses AKey.
747   bool isSignReturnAddressWithAKey() const {
748     return getSignReturnAddressKey() == SignReturnAddressKeyKind::AKey;
749   }
750 
751   /// Check if leaf functions are also signed.
752   bool isSignReturnAddressScopeAll() const {
753     return getSignReturnAddressScope() == SignReturnAddressScopeKind::All;
754   }
755 
756   bool hasSjLjExceptions() const {
757     return getExceptionHandling() == ExceptionHandlingKind::SjLj;
758   }
759 
760   bool hasSEHExceptions() const {
761     return getExceptionHandling() == ExceptionHandlingKind::WinEH;
762   }
763 
764   bool hasDWARFExceptions() const {
765     return getExceptionHandling() == ExceptionHandlingKind::DwarfCFI;
766   }
767 
768   bool hasWasmExceptions() const {
769     return getExceptionHandling() == ExceptionHandlingKind::Wasm;
770   }
771 
772   bool isSYCL() const { return SYCLIsDevice || SYCLIsHost; }
773 
774   bool hasDefaultVisibilityExportMapping() const {
775     return getDefaultVisibilityExportMapping() !=
776            DefaultVisiblityExportMapping::None;
777   }
778 
779   bool isExplicitDefaultVisibilityExportMapping() const {
780     return getDefaultVisibilityExportMapping() ==
781            DefaultVisiblityExportMapping::Explicit;
782   }
783 
784   bool isAllDefaultVisibilityExportMapping() const {
785     return getDefaultVisibilityExportMapping() ==
786            DefaultVisiblityExportMapping::All;
787   }
788 
789   bool hasGlobalAllocationFunctionVisibility() const {
790     return getGlobalAllocationFunctionVisibility() !=
791            VisibilityForcedKinds::Source;
792   }
793 
794   bool hasDefaultGlobalAllocationFunctionVisibility() const {
795     return getGlobalAllocationFunctionVisibility() ==
796            VisibilityForcedKinds::ForceDefault;
797   }
798 
799   bool hasProtectedGlobalAllocationFunctionVisibility() const {
800     return getGlobalAllocationFunctionVisibility() ==
801            VisibilityForcedKinds::ForceProtected;
802   }
803 
804   bool hasHiddenGlobalAllocationFunctionVisibility() const {
805     return getGlobalAllocationFunctionVisibility() ==
806            VisibilityForcedKinds::ForceHidden;
807   }
808 
809   /// Remap path prefix according to -fmacro-prefix-path option.
810   void remapPathPrefix(SmallVectorImpl<char> &Path) const;
811 
812   RoundingMode getDefaultRoundingMode() const {
813     return RoundingMath ? RoundingMode::Dynamic
814                         : RoundingMode::NearestTiesToEven;
815   }
816 
817   FPExceptionModeKind getDefaultExceptionMode() const {
818     FPExceptionModeKind EM = getFPExceptionMode();
819     if (EM == FPExceptionModeKind::FPE_Default)
820       return FPExceptionModeKind::FPE_Ignore;
821     return EM;
822   }
823 };
824 
825 /// Floating point control options
826 class FPOptionsOverride;
827 class FPOptions {
828 public:
829   // We start by defining the layout.
830   using storage_type = uint32_t;
831 
832   using RoundingMode = llvm::RoundingMode;
833 
834   static constexpr unsigned StorageBitSize = 8 * sizeof(storage_type);
835 
836   // Define a fake option named "First" so that we have a PREVIOUS even for the
837   // real first option.
838   static constexpr storage_type FirstShift = 0, FirstWidth = 0;
839 #define OPTION(NAME, TYPE, WIDTH, PREVIOUS)                                    \
840   static constexpr storage_type NAME##Shift =                                  \
841       PREVIOUS##Shift + PREVIOUS##Width;                                       \
842   static constexpr storage_type NAME##Width = WIDTH;                           \
843   static constexpr storage_type NAME##Mask = ((1 << NAME##Width) - 1)          \
844                                              << NAME##Shift;
845 #include "clang/Basic/FPOptions.def"
846 
847   static constexpr storage_type TotalWidth = 0
848 #define OPTION(NAME, TYPE, WIDTH, PREVIOUS) +WIDTH
849 #include "clang/Basic/FPOptions.def"
850       ;
851   static_assert(TotalWidth <= StorageBitSize, "Too short type for FPOptions");
852 
853 private:
854   storage_type Value;
855 
856   FPOptionsOverride getChangesSlow(const FPOptions &Base) const;
857 
858 public:
859   FPOptions() : Value(0) {
860     setFPContractMode(LangOptions::FPM_Off);
861     setConstRoundingMode(RoundingMode::Dynamic);
862     setSpecifiedExceptionMode(LangOptions::FPE_Default);
863   }
864   explicit FPOptions(const LangOptions &LO) {
865     Value = 0;
866     // The language fp contract option FPM_FastHonorPragmas has the same effect
867     // as FPM_Fast in frontend. For simplicity, use FPM_Fast uniformly in
868     // frontend.
869     auto LangOptContractMode = LO.getDefaultFPContractMode();
870     if (LangOptContractMode == LangOptions::FPM_FastHonorPragmas)
871       LangOptContractMode = LangOptions::FPM_Fast;
872     setFPContractMode(LangOptContractMode);
873     setRoundingMath(LO.RoundingMath);
874     setConstRoundingMode(LangOptions::RoundingMode::Dynamic);
875     setSpecifiedExceptionMode(LO.getFPExceptionMode());
876     setAllowFPReassociate(LO.AllowFPReassoc);
877     setNoHonorNaNs(LO.NoHonorNaNs);
878     setNoHonorInfs(LO.NoHonorInfs);
879     setNoSignedZero(LO.NoSignedZero);
880     setAllowReciprocal(LO.AllowRecip);
881     setAllowApproxFunc(LO.ApproxFunc);
882     if (getFPContractMode() == LangOptions::FPM_On &&
883         getRoundingMode() == llvm::RoundingMode::Dynamic &&
884         getExceptionMode() == LangOptions::FPE_Strict)
885       // If the FP settings are set to the "strict" model, then
886       // FENV access is set to true. (ffp-model=strict)
887       setAllowFEnvAccess(true);
888     else
889       setAllowFEnvAccess(LangOptions::FPM_Off);
890     setComplexRange(LO.getComplexRange());
891   }
892 
893   bool allowFPContractWithinStatement() const {
894     return getFPContractMode() == LangOptions::FPM_On;
895   }
896   void setAllowFPContractWithinStatement() {
897     setFPContractMode(LangOptions::FPM_On);
898   }
899 
900   bool allowFPContractAcrossStatement() const {
901     return getFPContractMode() == LangOptions::FPM_Fast;
902   }
903   void setAllowFPContractAcrossStatement() {
904     setFPContractMode(LangOptions::FPM_Fast);
905   }
906 
907   bool isFPConstrained() const {
908     return getRoundingMode() != llvm::RoundingMode::NearestTiesToEven ||
909            getExceptionMode() != LangOptions::FPE_Ignore ||
910            getAllowFEnvAccess();
911   }
912 
913   RoundingMode getRoundingMode() const {
914     RoundingMode RM = getConstRoundingMode();
915     if (RM == RoundingMode::Dynamic) {
916       // C23: 7.6.2p3  If the FE_DYNAMIC mode is specified and FENV_ACCESS is
917       // "off", the translator may assume that the default rounding mode is in
918       // effect.
919       if (!getAllowFEnvAccess() && !getRoundingMath())
920         RM = RoundingMode::NearestTiesToEven;
921     }
922     return RM;
923   }
924 
925   LangOptions::FPExceptionModeKind getExceptionMode() const {
926     LangOptions::FPExceptionModeKind EM = getSpecifiedExceptionMode();
927     if (EM == LangOptions::FPExceptionModeKind::FPE_Default) {
928       if (getAllowFEnvAccess())
929         return LangOptions::FPExceptionModeKind::FPE_Strict;
930       else
931         return LangOptions::FPExceptionModeKind::FPE_Ignore;
932     }
933     return EM;
934   }
935 
936   bool operator==(FPOptions other) const { return Value == other.Value; }
937 
938   /// Return the default value of FPOptions that's used when trailing
939   /// storage isn't required.
940   static FPOptions defaultWithoutTrailingStorage(const LangOptions &LO);
941 
942   storage_type getAsOpaqueInt() const { return Value; }
943   static FPOptions getFromOpaqueInt(storage_type Value) {
944     FPOptions Opts;
945     Opts.Value = Value;
946     return Opts;
947   }
948 
949   /// Return difference with the given option set.
950   FPOptionsOverride getChangesFrom(const FPOptions &Base) const;
951 
952   void applyChanges(FPOptionsOverride FPO);
953 
954   // We can define most of the accessors automatically:
955 #define OPTION(NAME, TYPE, WIDTH, PREVIOUS)                                    \
956   TYPE get##NAME() const {                                                     \
957     return static_cast<TYPE>((Value & NAME##Mask) >> NAME##Shift);             \
958   }                                                                            \
959   void set##NAME(TYPE value) {                                                 \
960     Value = (Value & ~NAME##Mask) | (storage_type(value) << NAME##Shift);      \
961   }
962 #include "clang/Basic/FPOptions.def"
963   LLVM_DUMP_METHOD void dump();
964 };
965 
966 /// Represents difference between two FPOptions values.
967 ///
968 /// The effect of language constructs changing the set of floating point options
969 /// is usually a change of some FP properties while leaving others intact. This
970 /// class describes such changes by keeping information about what FP options
971 /// are overridden.
972 ///
973 /// The integral set of FP options, described by the class FPOptions, may be
974 /// represented as a default FP option set, defined by language standard and
975 /// command line options, with the overrides introduced by pragmas.
976 ///
977 /// The is implemented as a value of the new FPOptions plus a mask showing which
978 /// fields are actually set in it.
979 class FPOptionsOverride {
980   FPOptions Options = FPOptions::getFromOpaqueInt(0);
981   FPOptions::storage_type OverrideMask = 0;
982 
983 public:
984   using RoundingMode = llvm::RoundingMode;
985 
986   /// The type suitable for storing values of FPOptionsOverride. Must be twice
987   /// as wide as bit size of FPOption.
988   using storage_type = uint64_t;
989   static_assert(sizeof(storage_type) >= 2 * sizeof(FPOptions::storage_type),
990                 "Too short type for FPOptionsOverride");
991 
992   /// Bit mask selecting bits of OverrideMask in serialized representation of
993   /// FPOptionsOverride.
994   static constexpr storage_type OverrideMaskBits =
995       (static_cast<storage_type>(1) << FPOptions::StorageBitSize) - 1;
996 
997   FPOptionsOverride() {}
998   FPOptionsOverride(const LangOptions &LO)
999       : Options(LO), OverrideMask(OverrideMaskBits) {}
1000   FPOptionsOverride(FPOptions FPO)
1001       : Options(FPO), OverrideMask(OverrideMaskBits) {}
1002   FPOptionsOverride(FPOptions FPO, FPOptions::storage_type Mask)
1003       : Options(FPO), OverrideMask(Mask) {}
1004 
1005   bool requiresTrailingStorage() const { return OverrideMask != 0; }
1006 
1007   void setAllowFPContractWithinStatement() {
1008     setFPContractModeOverride(LangOptions::FPM_On);
1009   }
1010 
1011   void setAllowFPContractAcrossStatement() {
1012     setFPContractModeOverride(LangOptions::FPM_Fast);
1013   }
1014 
1015   void setDisallowFPContract() {
1016     setFPContractModeOverride(LangOptions::FPM_Off);
1017   }
1018 
1019   void setFPPreciseEnabled(bool Value) {
1020     setAllowFPReassociateOverride(!Value);
1021     setNoHonorNaNsOverride(!Value);
1022     setNoHonorInfsOverride(!Value);
1023     setNoSignedZeroOverride(!Value);
1024     setAllowReciprocalOverride(!Value);
1025     setAllowApproxFuncOverride(!Value);
1026     setMathErrnoOverride(Value);
1027     if (Value)
1028       /* Precise mode implies fp_contract=on and disables ffast-math */
1029       setAllowFPContractWithinStatement();
1030     else
1031       /* Precise mode disabled sets fp_contract=fast and enables ffast-math */
1032       setAllowFPContractAcrossStatement();
1033   }
1034 
1035   void setDisallowOptimizations() { setFPPreciseEnabled(true); }
1036 
1037   storage_type getAsOpaqueInt() const {
1038     return (static_cast<storage_type>(Options.getAsOpaqueInt())
1039             << FPOptions::StorageBitSize) |
1040            OverrideMask;
1041   }
1042   static FPOptionsOverride getFromOpaqueInt(storage_type I) {
1043     FPOptionsOverride Opts;
1044     Opts.OverrideMask = I & OverrideMaskBits;
1045     Opts.Options = FPOptions::getFromOpaqueInt(I >> FPOptions::StorageBitSize);
1046     return Opts;
1047   }
1048 
1049   FPOptions applyOverrides(FPOptions Base) {
1050     FPOptions Result =
1051         FPOptions::getFromOpaqueInt((Base.getAsOpaqueInt() & ~OverrideMask) |
1052                                      (Options.getAsOpaqueInt() & OverrideMask));
1053     return Result;
1054   }
1055 
1056   FPOptions applyOverrides(const LangOptions &LO) {
1057     return applyOverrides(FPOptions(LO));
1058   }
1059 
1060   bool operator==(FPOptionsOverride other) const {
1061     return Options == other.Options && OverrideMask == other.OverrideMask;
1062   }
1063   bool operator!=(FPOptionsOverride other) const { return !(*this == other); }
1064 
1065 #define OPTION(NAME, TYPE, WIDTH, PREVIOUS)                                    \
1066   bool has##NAME##Override() const {                                           \
1067     return OverrideMask & FPOptions::NAME##Mask;                               \
1068   }                                                                            \
1069   TYPE get##NAME##Override() const {                                           \
1070     assert(has##NAME##Override());                                             \
1071     return Options.get##NAME();                                                \
1072   }                                                                            \
1073   void clear##NAME##Override() {                                               \
1074     /* Clear the actual value so that we don't have spurious differences when  \
1075      * testing equality. */                                                    \
1076     Options.set##NAME(TYPE(0));                                                \
1077     OverrideMask &= ~FPOptions::NAME##Mask;                                    \
1078   }                                                                            \
1079   void set##NAME##Override(TYPE value) {                                       \
1080     Options.set##NAME(value);                                                  \
1081     OverrideMask |= FPOptions::NAME##Mask;                                     \
1082   }
1083 #include "clang/Basic/FPOptions.def"
1084   LLVM_DUMP_METHOD void dump();
1085 };
1086 
1087 inline FPOptionsOverride FPOptions::getChangesFrom(const FPOptions &Base) const {
1088   if (Value == Base.Value)
1089     return FPOptionsOverride();
1090   return getChangesSlow(Base);
1091 }
1092 
1093 inline void FPOptions::applyChanges(FPOptionsOverride FPO) {
1094   *this = FPO.applyOverrides(*this);
1095 }
1096 
1097 /// Describes the kind of translation unit being processed.
1098 enum TranslationUnitKind {
1099   /// The translation unit is a complete translation unit.
1100   TU_Complete,
1101 
1102   /// The translation unit is a prefix to a translation unit, and is
1103   /// not complete.
1104   TU_Prefix,
1105 
1106   /// The translation unit is a clang module.
1107   TU_ClangModule,
1108 
1109   /// The translation unit is a is a complete translation unit that we might
1110   /// incrementally extend later.
1111   TU_Incremental
1112 };
1113 
1114 } // namespace clang
1115 
1116 #endif // LLVM_CLANG_BASIC_LANGOPTIONS_H
1117