clang  8.0.0svn
InitPreprocessor.cpp
Go to the documentation of this file.
1 //===--- InitPreprocessor.cpp - PP initialization code. ---------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the clang::InitializePreprocessor function.
11 //
12 //===----------------------------------------------------------------------===//
13 
17 #include "clang/Basic/SyncScope.h"
18 #include "clang/Basic/TargetInfo.h"
19 #include "clang/Basic/Version.h"
22 #include "clang/Frontend/Utils.h"
23 #include "clang/Lex/HeaderSearch.h"
24 #include "clang/Lex/Preprocessor.h"
27 #include "llvm/ADT/APFloat.h"
28 using namespace clang;
29 
30 static bool MacroBodyEndsInBackslash(StringRef MacroBody) {
31  while (!MacroBody.empty() && isWhitespace(MacroBody.back()))
32  MacroBody = MacroBody.drop_back();
33  return !MacroBody.empty() && MacroBody.back() == '\\';
34 }
35 
36 // Append a #define line to Buf for Macro. Macro should be of the form XXX,
37 // in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
38 // "#define XXX Y z W". To get a #define with no value, use "XXX=".
39 static void DefineBuiltinMacro(MacroBuilder &Builder, StringRef Macro,
40  DiagnosticsEngine &Diags) {
41  std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
42  StringRef MacroName = MacroPair.first;
43  StringRef MacroBody = MacroPair.second;
44  if (MacroName.size() != Macro.size()) {
45  // Per GCC -D semantics, the macro ends at \n if it exists.
46  StringRef::size_type End = MacroBody.find_first_of("\n\r");
47  if (End != StringRef::npos)
48  Diags.Report(diag::warn_fe_macro_contains_embedded_newline)
49  << MacroName;
50  MacroBody = MacroBody.substr(0, End);
51  // We handle macro bodies which end in a backslash by appending an extra
52  // backslash+newline. This makes sure we don't accidentally treat the
53  // backslash as a line continuation marker.
54  if (MacroBodyEndsInBackslash(MacroBody))
55  Builder.defineMacro(MacroName, Twine(MacroBody) + "\\\n");
56  else
57  Builder.defineMacro(MacroName, MacroBody);
58  } else {
59  // Push "macroname 1".
60  Builder.defineMacro(Macro);
61  }
62 }
63 
64 /// AddImplicitInclude - Add an implicit \#include of the specified file to the
65 /// predefines buffer.
66 /// As these includes are generated by -include arguments the header search
67 /// logic is going to search relatively to the current working directory.
68 static void AddImplicitInclude(MacroBuilder &Builder, StringRef File) {
69  Builder.append(Twine("#include \"") + File + "\"");
70 }
71 
72 static void AddImplicitIncludeMacros(MacroBuilder &Builder, StringRef File) {
73  Builder.append(Twine("#__include_macros \"") + File + "\"");
74  // Marker token to stop the __include_macros fetch loop.
75  Builder.append("##"); // ##?
76 }
77 
78 /// Add an implicit \#include using the original file used to generate
79 /// a PCH file.
81  const PCHContainerReader &PCHContainerRdr,
82  StringRef ImplicitIncludePCH) {
83  std::string OriginalFile =
84  ASTReader::getOriginalSourceFile(ImplicitIncludePCH, PP.getFileManager(),
85  PCHContainerRdr, PP.getDiagnostics());
86  if (OriginalFile.empty())
87  return;
88 
89  AddImplicitInclude(Builder, OriginalFile);
90 }
91 
92 /// PickFP - This is used to pick a value based on the FP semantics of the
93 /// specified FP model.
94 template <typename T>
95 static T PickFP(const llvm::fltSemantics *Sem, T IEEEHalfVal, T IEEESingleVal,
96  T IEEEDoubleVal, T X87DoubleExtendedVal, T PPCDoubleDoubleVal,
97  T IEEEQuadVal) {
98  if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEhalf())
99  return IEEEHalfVal;
100  if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEsingle())
101  return IEEESingleVal;
102  if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEdouble())
103  return IEEEDoubleVal;
104  if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::x87DoubleExtended())
105  return X87DoubleExtendedVal;
106  if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::PPCDoubleDouble())
107  return PPCDoubleDoubleVal;
108  assert(Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEquad());
109  return IEEEQuadVal;
110 }
111 
112 static void DefineFloatMacros(MacroBuilder &Builder, StringRef Prefix,
113  const llvm::fltSemantics *Sem, StringRef Ext) {
114  const char *DenormMin, *Epsilon, *Max, *Min;
115  DenormMin = PickFP(Sem, "5.9604644775390625e-8", "1.40129846e-45",
116  "4.9406564584124654e-324", "3.64519953188247460253e-4951",
117  "4.94065645841246544176568792868221e-324",
118  "6.47517511943802511092443895822764655e-4966");
119  int Digits = PickFP(Sem, 3, 6, 15, 18, 31, 33);
120  int DecimalDigits = PickFP(Sem, 5, 9, 17, 21, 33, 36);
121  Epsilon = PickFP(Sem, "9.765625e-4", "1.19209290e-7",
122  "2.2204460492503131e-16", "1.08420217248550443401e-19",
123  "4.94065645841246544176568792868221e-324",
124  "1.92592994438723585305597794258492732e-34");
125  int MantissaDigits = PickFP(Sem, 11, 24, 53, 64, 106, 113);
126  int Min10Exp = PickFP(Sem, -13, -37, -307, -4931, -291, -4931);
127  int Max10Exp = PickFP(Sem, 4, 38, 308, 4932, 308, 4932);
128  int MinExp = PickFP(Sem, -14, -125, -1021, -16381, -968, -16381);
129  int MaxExp = PickFP(Sem, 15, 128, 1024, 16384, 1024, 16384);
130  Min = PickFP(Sem, "6.103515625e-5", "1.17549435e-38", "2.2250738585072014e-308",
131  "3.36210314311209350626e-4932",
132  "2.00416836000897277799610805135016e-292",
133  "3.36210314311209350626267781732175260e-4932");
134  Max = PickFP(Sem, "6.5504e+4", "3.40282347e+38", "1.7976931348623157e+308",
135  "1.18973149535723176502e+4932",
136  "1.79769313486231580793728971405301e+308",
137  "1.18973149535723176508575932662800702e+4932");
138 
139  SmallString<32> DefPrefix;
140  DefPrefix = "__";
141  DefPrefix += Prefix;
142  DefPrefix += "_";
143 
144  Builder.defineMacro(DefPrefix + "DENORM_MIN__", Twine(DenormMin)+Ext);
145  Builder.defineMacro(DefPrefix + "HAS_DENORM__");
146  Builder.defineMacro(DefPrefix + "DIG__", Twine(Digits));
147  Builder.defineMacro(DefPrefix + "DECIMAL_DIG__", Twine(DecimalDigits));
148  Builder.defineMacro(DefPrefix + "EPSILON__", Twine(Epsilon)+Ext);
149  Builder.defineMacro(DefPrefix + "HAS_INFINITY__");
150  Builder.defineMacro(DefPrefix + "HAS_QUIET_NAN__");
151  Builder.defineMacro(DefPrefix + "MANT_DIG__", Twine(MantissaDigits));
152 
153  Builder.defineMacro(DefPrefix + "MAX_10_EXP__", Twine(Max10Exp));
154  Builder.defineMacro(DefPrefix + "MAX_EXP__", Twine(MaxExp));
155  Builder.defineMacro(DefPrefix + "MAX__", Twine(Max)+Ext);
156 
157  Builder.defineMacro(DefPrefix + "MIN_10_EXP__","("+Twine(Min10Exp)+")");
158  Builder.defineMacro(DefPrefix + "MIN_EXP__", "("+Twine(MinExp)+")");
159  Builder.defineMacro(DefPrefix + "MIN__", Twine(Min)+Ext);
160 }
161 
162 
163 /// DefineTypeSize - Emit a macro to the predefines buffer that declares a macro
164 /// named MacroName with the max value for a type with width 'TypeWidth' a
165 /// signedness of 'isSigned' and with a value suffix of 'ValSuffix' (e.g. LL).
166 static void DefineTypeSize(const Twine &MacroName, unsigned TypeWidth,
167  StringRef ValSuffix, bool isSigned,
168  MacroBuilder &Builder) {
169  llvm::APInt MaxVal = isSigned ? llvm::APInt::getSignedMaxValue(TypeWidth)
170  : llvm::APInt::getMaxValue(TypeWidth);
171  Builder.defineMacro(MacroName, MaxVal.toString(10, isSigned) + ValSuffix);
172 }
173 
174 /// DefineTypeSize - An overloaded helper that uses TargetInfo to determine
175 /// the width, suffix, and signedness of the given type
176 static void DefineTypeSize(const Twine &MacroName, TargetInfo::IntType Ty,
177  const TargetInfo &TI, MacroBuilder &Builder) {
178  DefineTypeSize(MacroName, TI.getTypeWidth(Ty), TI.getTypeConstantSuffix(Ty),
179  TI.isTypeSigned(Ty), Builder);
180 }
181 
182 static void DefineFmt(const Twine &Prefix, TargetInfo::IntType Ty,
183  const TargetInfo &TI, MacroBuilder &Builder) {
184  bool IsSigned = TI.isTypeSigned(Ty);
185  StringRef FmtModifier = TI.getTypeFormatModifier(Ty);
186  for (const char *Fmt = IsSigned ? "di" : "ouxX"; *Fmt; ++Fmt) {
187  Builder.defineMacro(Prefix + "_FMT" + Twine(*Fmt) + "__",
188  Twine("\"") + FmtModifier + Twine(*Fmt) + "\"");
189  }
190 }
191 
192 static void DefineType(const Twine &MacroName, TargetInfo::IntType Ty,
193  MacroBuilder &Builder) {
194  Builder.defineMacro(MacroName, TargetInfo::getTypeName(Ty));
195 }
196 
197 static void DefineTypeWidth(StringRef MacroName, TargetInfo::IntType Ty,
198  const TargetInfo &TI, MacroBuilder &Builder) {
199  Builder.defineMacro(MacroName, Twine(TI.getTypeWidth(Ty)));
200 }
201 
202 static void DefineTypeSizeof(StringRef MacroName, unsigned BitWidth,
203  const TargetInfo &TI, MacroBuilder &Builder) {
204  Builder.defineMacro(MacroName,
205  Twine(BitWidth / TI.getCharWidth()));
206 }
207 
209  const TargetInfo &TI,
210  MacroBuilder &Builder) {
211  int TypeWidth = TI.getTypeWidth(Ty);
212  bool IsSigned = TI.isTypeSigned(Ty);
213 
214  // Use the target specified int64 type, when appropriate, so that [u]int64_t
215  // ends up being defined in terms of the correct type.
216  if (TypeWidth == 64)
217  Ty = IsSigned ? TI.getInt64Type() : TI.getUInt64Type();
218 
219  const char *Prefix = IsSigned ? "__INT" : "__UINT";
220 
221  DefineType(Prefix + Twine(TypeWidth) + "_TYPE__", Ty, Builder);
222  DefineFmt(Prefix + Twine(TypeWidth), Ty, TI, Builder);
223 
224  StringRef ConstSuffix(TI.getTypeConstantSuffix(Ty));
225  Builder.defineMacro(Prefix + Twine(TypeWidth) + "_C_SUFFIX__", ConstSuffix);
226 }
227 
229  const TargetInfo &TI,
230  MacroBuilder &Builder) {
231  int TypeWidth = TI.getTypeWidth(Ty);
232  bool IsSigned = TI.isTypeSigned(Ty);
233 
234  // Use the target specified int64 type, when appropriate, so that [u]int64_t
235  // ends up being defined in terms of the correct type.
236  if (TypeWidth == 64)
237  Ty = IsSigned ? TI.getInt64Type() : TI.getUInt64Type();
238 
239  const char *Prefix = IsSigned ? "__INT" : "__UINT";
240  DefineTypeSize(Prefix + Twine(TypeWidth) + "_MAX__", Ty, TI, Builder);
241 }
242 
243 static void DefineLeastWidthIntType(unsigned TypeWidth, bool IsSigned,
244  const TargetInfo &TI,
245  MacroBuilder &Builder) {
246  TargetInfo::IntType Ty = TI.getLeastIntTypeByWidth(TypeWidth, IsSigned);
247  if (Ty == TargetInfo::NoInt)
248  return;
249 
250  const char *Prefix = IsSigned ? "__INT_LEAST" : "__UINT_LEAST";
251  DefineType(Prefix + Twine(TypeWidth) + "_TYPE__", Ty, Builder);
252  DefineTypeSize(Prefix + Twine(TypeWidth) + "_MAX__", Ty, TI, Builder);
253  DefineFmt(Prefix + Twine(TypeWidth), Ty, TI, Builder);
254 }
255 
256 static void DefineFastIntType(unsigned TypeWidth, bool IsSigned,
257  const TargetInfo &TI, MacroBuilder &Builder) {
258  // stdint.h currently defines the fast int types as equivalent to the least
259  // types.
260  TargetInfo::IntType Ty = TI.getLeastIntTypeByWidth(TypeWidth, IsSigned);
261  if (Ty == TargetInfo::NoInt)
262  return;
263 
264  const char *Prefix = IsSigned ? "__INT_FAST" : "__UINT_FAST";
265  DefineType(Prefix + Twine(TypeWidth) + "_TYPE__", Ty, Builder);
266  DefineTypeSize(Prefix + Twine(TypeWidth) + "_MAX__", Ty, TI, Builder);
267 
268  DefineFmt(Prefix + Twine(TypeWidth), Ty, TI, Builder);
269 }
270 
271 
272 /// Get the value the ATOMIC_*_LOCK_FREE macro should have for a type with
273 /// the specified properties.
274 static const char *getLockFreeValue(unsigned TypeWidth, unsigned TypeAlign,
275  unsigned InlineWidth) {
276  // Fully-aligned, power-of-2 sizes no larger than the inline
277  // width will be inlined as lock-free operations.
278  if (TypeWidth == TypeAlign && (TypeWidth & (TypeWidth - 1)) == 0 &&
279  TypeWidth <= InlineWidth)
280  return "2"; // "always lock free"
281  // We cannot be certain what operations the lib calls might be
282  // able to implement as lock-free on future processors.
283  return "1"; // "sometimes lock free"
284 }
285 
286 /// Add definitions required for a smooth interaction between
287 /// Objective-C++ automated reference counting and libstdc++ (4.2).
288 static void AddObjCXXARCLibstdcxxDefines(const LangOptions &LangOpts,
289  MacroBuilder &Builder) {
290  Builder.defineMacro("_GLIBCXX_PREDEFINED_OBJC_ARC_IS_SCALAR");
291 
292  std::string Result;
293  {
294  // Provide specializations for the __is_scalar type trait so that
295  // lifetime-qualified objects are not considered "scalar" types, which
296  // libstdc++ uses as an indicator of the presence of trivial copy, assign,
297  // default-construct, and destruct semantics (none of which hold for
298  // lifetime-qualified objects in ARC).
299  llvm::raw_string_ostream Out(Result);
300 
301  Out << "namespace std {\n"
302  << "\n"
303  << "struct __true_type;\n"
304  << "struct __false_type;\n"
305  << "\n";
306 
307  Out << "template<typename _Tp> struct __is_scalar;\n"
308  << "\n";
309 
310  if (LangOpts.ObjCAutoRefCount) {
311  Out << "template<typename _Tp>\n"
312  << "struct __is_scalar<__attribute__((objc_ownership(strong))) _Tp> {\n"
313  << " enum { __value = 0 };\n"
314  << " typedef __false_type __type;\n"
315  << "};\n"
316  << "\n";
317  }
318 
319  if (LangOpts.ObjCWeak) {
320  Out << "template<typename _Tp>\n"
321  << "struct __is_scalar<__attribute__((objc_ownership(weak))) _Tp> {\n"
322  << " enum { __value = 0 };\n"
323  << " typedef __false_type __type;\n"
324  << "};\n"
325  << "\n";
326  }
327 
328  if (LangOpts.ObjCAutoRefCount) {
329  Out << "template<typename _Tp>\n"
330  << "struct __is_scalar<__attribute__((objc_ownership(autoreleasing)))"
331  << " _Tp> {\n"
332  << " enum { __value = 0 };\n"
333  << " typedef __false_type __type;\n"
334  << "};\n"
335  << "\n";
336  }
337 
338  Out << "}\n";
339  }
340  Builder.append(Result);
341 }
342 
344  const LangOptions &LangOpts,
345  const FrontendOptions &FEOpts,
346  MacroBuilder &Builder) {
347  if (!LangOpts.MSVCCompat && !LangOpts.TraditionalCPP)
348  Builder.defineMacro("__STDC__");
349  if (LangOpts.Freestanding)
350  Builder.defineMacro("__STDC_HOSTED__", "0");
351  else
352  Builder.defineMacro("__STDC_HOSTED__");
353 
354  if (!LangOpts.CPlusPlus) {
355  if (LangOpts.C17)
356  Builder.defineMacro("__STDC_VERSION__", "201710L");
357  else if (LangOpts.C11)
358  Builder.defineMacro("__STDC_VERSION__", "201112L");
359  else if (LangOpts.C99)
360  Builder.defineMacro("__STDC_VERSION__", "199901L");
361  else if (!LangOpts.GNUMode && LangOpts.Digraphs)
362  Builder.defineMacro("__STDC_VERSION__", "199409L");
363  } else {
364  // FIXME: Use correct value for C++20.
365  if (LangOpts.CPlusPlus2a)
366  Builder.defineMacro("__cplusplus", "201707L");
367  // C++17 [cpp.predefined]p1:
368  // The name __cplusplus is defined to the value 201703L when compiling a
369  // C++ translation unit.
370  else if (LangOpts.CPlusPlus17)
371  Builder.defineMacro("__cplusplus", "201703L");
372  // C++1y [cpp.predefined]p1:
373  // The name __cplusplus is defined to the value 201402L when compiling a
374  // C++ translation unit.
375  else if (LangOpts.CPlusPlus14)
376  Builder.defineMacro("__cplusplus", "201402L");
377  // C++11 [cpp.predefined]p1:
378  // The name __cplusplus is defined to the value 201103L when compiling a
379  // C++ translation unit.
380  else if (LangOpts.CPlusPlus11)
381  Builder.defineMacro("__cplusplus", "201103L");
382  // C++03 [cpp.predefined]p1:
383  // The name __cplusplus is defined to the value 199711L when compiling a
384  // C++ translation unit.
385  else
386  Builder.defineMacro("__cplusplus", "199711L");
387 
388  // C++1z [cpp.predefined]p1:
389  // An integer literal of type std::size_t whose value is the alignment
390  // guaranteed by a call to operator new(std::size_t)
391  //
392  // We provide this in all language modes, since it seems generally useful.
393  Builder.defineMacro("__STDCPP_DEFAULT_NEW_ALIGNMENT__",
394  Twine(TI.getNewAlign() / TI.getCharWidth()) +
396  }
397 
398  // In C11 these are environment macros. In C++11 they are only defined
399  // as part of <cuchar>. To prevent breakage when mixing C and C++
400  // code, define these macros unconditionally. We can define them
401  // unconditionally, as Clang always uses UTF-16 and UTF-32 for 16-bit
402  // and 32-bit character literals.
403  Builder.defineMacro("__STDC_UTF_16__", "1");
404  Builder.defineMacro("__STDC_UTF_32__", "1");
405 
406  if (LangOpts.ObjC)
407  Builder.defineMacro("__OBJC__");
408 
409  // OpenCL v1.0/1.1 s6.9, v1.2/2.0 s6.10: Preprocessor Directives and Macros.
410  if (LangOpts.OpenCL) {
411  if (LangOpts.CPlusPlus) {
412  if (LangOpts.OpenCLCPlusPlusVersion == 100)
413  Builder.defineMacro("__OPENCL_CPP_VERSION__", "100");
414  else
415  llvm_unreachable("Unsupported OpenCL C++ version");
416  Builder.defineMacro("__CL_CPP_VERSION_1_0__", "100");
417  } else {
418  // OpenCL v1.0 and v1.1 do not have a predefined macro to indicate the
419  // language standard with which the program is compiled. __OPENCL_VERSION__
420  // is for the OpenCL version supported by the OpenCL device, which is not
421  // necessarily the language standard with which the program is compiled.
422  // A shared OpenCL header file requires a macro to indicate the language
423  // standard. As a workaround, __OPENCL_C_VERSION__ is defined for
424  // OpenCL v1.0 and v1.1.
425  switch (LangOpts.OpenCLVersion) {
426  case 100:
427  Builder.defineMacro("__OPENCL_C_VERSION__", "100");
428  break;
429  case 110:
430  Builder.defineMacro("__OPENCL_C_VERSION__", "110");
431  break;
432  case 120:
433  Builder.defineMacro("__OPENCL_C_VERSION__", "120");
434  break;
435  case 200:
436  Builder.defineMacro("__OPENCL_C_VERSION__", "200");
437  break;
438  default:
439  llvm_unreachable("Unsupported OpenCL version");
440  }
441  Builder.defineMacro("CL_VERSION_1_0", "100");
442  Builder.defineMacro("CL_VERSION_1_1", "110");
443  Builder.defineMacro("CL_VERSION_1_2", "120");
444  Builder.defineMacro("CL_VERSION_2_0", "200");
445 
446  if (TI.isLittleEndian())
447  Builder.defineMacro("__ENDIAN_LITTLE__");
448 
449  if (LangOpts.FastRelaxedMath)
450  Builder.defineMacro("__FAST_RELAXED_MATH__");
451  }
452  }
453  // Not "standard" per se, but available even with the -undef flag.
454  if (LangOpts.AsmPreprocessor)
455  Builder.defineMacro("__ASSEMBLER__");
456  if (LangOpts.CUDA && !LangOpts.HIP)
457  Builder.defineMacro("__CUDA__");
458  if (LangOpts.HIP) {
459  Builder.defineMacro("__HIP__");
460  Builder.defineMacro("__HIPCC__");
461  if (LangOpts.CUDAIsDevice)
462  Builder.defineMacro("__HIP_DEVICE_COMPILE__");
463  }
464 }
465 
466 /// Initialize the predefined C++ language feature test macros defined in
467 /// ISO/IEC JTC1/SC22/WG21 (C++) SD-6: "SG10 Feature Test Recommendations".
469  MacroBuilder &Builder) {
470  // C++98 features.
471  if (LangOpts.RTTI)
472  Builder.defineMacro("__cpp_rtti", "199711L");
473  if (LangOpts.CXXExceptions)
474  Builder.defineMacro("__cpp_exceptions", "199711L");
475 
476  // C++11 features.
477  if (LangOpts.CPlusPlus11) {
478  Builder.defineMacro("__cpp_unicode_characters", "200704L");
479  Builder.defineMacro("__cpp_raw_strings", "200710L");
480  Builder.defineMacro("__cpp_unicode_literals", "200710L");
481  Builder.defineMacro("__cpp_user_defined_literals", "200809L");
482  Builder.defineMacro("__cpp_lambdas", "200907L");
483  Builder.defineMacro("__cpp_constexpr",
484  LangOpts.CPlusPlus17 ? "201603L" :
485  LangOpts.CPlusPlus14 ? "201304L" : "200704");
486  Builder.defineMacro("__cpp_range_based_for",
487  LangOpts.CPlusPlus17 ? "201603L" : "200907");
488  Builder.defineMacro("__cpp_static_assert",
489  LangOpts.CPlusPlus17 ? "201411L" : "200410");
490  Builder.defineMacro("__cpp_decltype", "200707L");
491  Builder.defineMacro("__cpp_attributes", "200809L");
492  Builder.defineMacro("__cpp_rvalue_references", "200610L");
493  Builder.defineMacro("__cpp_variadic_templates", "200704L");
494  Builder.defineMacro("__cpp_initializer_lists", "200806L");
495  Builder.defineMacro("__cpp_delegating_constructors", "200604L");
496  Builder.defineMacro("__cpp_nsdmi", "200809L");
497  Builder.defineMacro("__cpp_inheriting_constructors", "201511L");
498  Builder.defineMacro("__cpp_ref_qualifiers", "200710L");
499  Builder.defineMacro("__cpp_alias_templates", "200704L");
500  }
501  if (LangOpts.ThreadsafeStatics)
502  Builder.defineMacro("__cpp_threadsafe_static_init", "200806L");
503 
504  // C++14 features.
505  if (LangOpts.CPlusPlus14) {
506  Builder.defineMacro("__cpp_binary_literals", "201304L");
507  Builder.defineMacro("__cpp_digit_separators", "201309L");
508  Builder.defineMacro("__cpp_init_captures", "201304L");
509  Builder.defineMacro("__cpp_generic_lambdas", "201304L");
510  Builder.defineMacro("__cpp_decltype_auto", "201304L");
511  Builder.defineMacro("__cpp_return_type_deduction", "201304L");
512  Builder.defineMacro("__cpp_aggregate_nsdmi", "201304L");
513  Builder.defineMacro("__cpp_variable_templates", "201304L");
514  }
515  if (LangOpts.SizedDeallocation)
516  Builder.defineMacro("__cpp_sized_deallocation", "201309L");
517 
518  // C++17 features.
519  if (LangOpts.CPlusPlus17) {
520  Builder.defineMacro("__cpp_hex_float", "201603L");
521  Builder.defineMacro("__cpp_inline_variables", "201606L");
522  Builder.defineMacro("__cpp_noexcept_function_type", "201510L");
523  Builder.defineMacro("__cpp_capture_star_this", "201603L");
524  Builder.defineMacro("__cpp_if_constexpr", "201606L");
525  Builder.defineMacro("__cpp_deduction_guides", "201703L");
526  Builder.defineMacro("__cpp_template_auto", "201606L"); // (old name)
527  Builder.defineMacro("__cpp_namespace_attributes", "201411L");
528  Builder.defineMacro("__cpp_enumerator_attributes", "201411L");
529  Builder.defineMacro("__cpp_nested_namespace_definitions", "201411L");
530  Builder.defineMacro("__cpp_variadic_using", "201611L");
531  Builder.defineMacro("__cpp_aggregate_bases", "201603L");
532  Builder.defineMacro("__cpp_structured_bindings", "201606L");
533  Builder.defineMacro("__cpp_nontype_template_args", "201411L");
534  Builder.defineMacro("__cpp_fold_expressions", "201603L");
535  Builder.defineMacro("__cpp_guaranteed_copy_elision", "201606L");
536  Builder.defineMacro("__cpp_nontype_template_parameter_auto", "201606L");
537  }
538  if (LangOpts.AlignedAllocation && !LangOpts.AlignedAllocationUnavailable)
539  Builder.defineMacro("__cpp_aligned_new", "201606L");
540  if (LangOpts.RelaxedTemplateTemplateArgs)
541  Builder.defineMacro("__cpp_template_template_args", "201611L");
542 
543  // C++20 features.
544  if (LangOpts.Char8)
545  Builder.defineMacro("__cpp_char8_t", "201811L");
546 
547  // TS features.
548  if (LangOpts.ConceptsTS)
549  Builder.defineMacro("__cpp_experimental_concepts", "1L");
550  if (LangOpts.CoroutinesTS)
551  Builder.defineMacro("__cpp_coroutines", "201703L");
552 }
553 
555  const LangOptions &LangOpts,
556  const FrontendOptions &FEOpts,
557  MacroBuilder &Builder) {
558  // Compiler version introspection macros.
559  Builder.defineMacro("__llvm__"); // LLVM Backend
560  Builder.defineMacro("__clang__"); // Clang Frontend
561 #define TOSTR2(X) #X
562 #define TOSTR(X) TOSTR2(X)
563  Builder.defineMacro("__clang_major__", TOSTR(CLANG_VERSION_MAJOR));
564  Builder.defineMacro("__clang_minor__", TOSTR(CLANG_VERSION_MINOR));
565  Builder.defineMacro("__clang_patchlevel__", TOSTR(CLANG_VERSION_PATCHLEVEL));
566 #undef TOSTR
567 #undef TOSTR2
568  Builder.defineMacro("__clang_version__",
569  "\"" CLANG_VERSION_STRING " "
570  + getClangFullRepositoryVersion() + "\"");
571  if (!LangOpts.MSVCCompat) {
572  // Currently claim to be compatible with GCC 4.2.1-5621, but only if we're
573  // not compiling for MSVC compatibility
574  Builder.defineMacro("__GNUC_MINOR__", "2");
575  Builder.defineMacro("__GNUC_PATCHLEVEL__", "1");
576  Builder.defineMacro("__GNUC__", "4");
577  Builder.defineMacro("__GXX_ABI_VERSION", "1002");
578  }
579 
580  // Define macros for the C11 / C++11 memory orderings
581  Builder.defineMacro("__ATOMIC_RELAXED", "0");
582  Builder.defineMacro("__ATOMIC_CONSUME", "1");
583  Builder.defineMacro("__ATOMIC_ACQUIRE", "2");
584  Builder.defineMacro("__ATOMIC_RELEASE", "3");
585  Builder.defineMacro("__ATOMIC_ACQ_REL", "4");
586  Builder.defineMacro("__ATOMIC_SEQ_CST", "5");
587 
588  // Define macros for the OpenCL memory scope.
589  // The values should match AtomicScopeOpenCLModel::ID enum.
590  static_assert(
591  static_cast<unsigned>(AtomicScopeOpenCLModel::WorkGroup) == 1 &&
592  static_cast<unsigned>(AtomicScopeOpenCLModel::Device) == 2 &&
593  static_cast<unsigned>(AtomicScopeOpenCLModel::AllSVMDevices) == 3 &&
594  static_cast<unsigned>(AtomicScopeOpenCLModel::SubGroup) == 4,
595  "Invalid OpenCL memory scope enum definition");
596  Builder.defineMacro("__OPENCL_MEMORY_SCOPE_WORK_ITEM", "0");
597  Builder.defineMacro("__OPENCL_MEMORY_SCOPE_WORK_GROUP", "1");
598  Builder.defineMacro("__OPENCL_MEMORY_SCOPE_DEVICE", "2");
599  Builder.defineMacro("__OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES", "3");
600  Builder.defineMacro("__OPENCL_MEMORY_SCOPE_SUB_GROUP", "4");
601 
602  // Support for #pragma redefine_extname (Sun compatibility)
603  Builder.defineMacro("__PRAGMA_REDEFINE_EXTNAME", "1");
604 
605  // As sad as it is, enough software depends on the __VERSION__ for version
606  // checks that it is necessary to report 4.2.1 (the base GCC version we claim
607  // compatibility with) first.
608  Builder.defineMacro("__VERSION__", "\"4.2.1 Compatible " +
609  Twine(getClangFullCPPVersion()) + "\"");
610 
611  // Initialize language-specific preprocessor defines.
612 
613  // Standard conforming mode?
614  if (!LangOpts.GNUMode && !LangOpts.MSVCCompat)
615  Builder.defineMacro("__STRICT_ANSI__");
616 
617  if (!LangOpts.MSVCCompat && LangOpts.CPlusPlus11)
618  Builder.defineMacro("__GXX_EXPERIMENTAL_CXX0X__");
619 
620  if (LangOpts.ObjC) {
621  if (LangOpts.ObjCRuntime.isNonFragile()) {
622  Builder.defineMacro("__OBJC2__");
623 
624  if (LangOpts.ObjCExceptions)
625  Builder.defineMacro("OBJC_ZEROCOST_EXCEPTIONS");
626  }
627 
628  if (LangOpts.getGC() != LangOptions::NonGC)
629  Builder.defineMacro("__OBJC_GC__");
630 
631  if (LangOpts.ObjCRuntime.isNeXTFamily())
632  Builder.defineMacro("__NEXT_RUNTIME__");
633 
634  if (LangOpts.ObjCRuntime.getKind() == ObjCRuntime::GNUstep) {
635  auto version = LangOpts.ObjCRuntime.getVersion();
636  std::string versionString = "1";
637  // Don't rely on the tuple argument, because we can be asked to target
638  // later ABIs than we actually support, so clamp these values to those
639  // currently supported
640  if (version >= VersionTuple(2, 0))
641  Builder.defineMacro("__OBJC_GNUSTEP_RUNTIME_ABI__", "20");
642  else
643  Builder.defineMacro("__OBJC_GNUSTEP_RUNTIME_ABI__",
644  "1" + Twine(std::min(8U, version.getMinor().getValueOr(0))));
645  }
646 
647  if (LangOpts.ObjCRuntime.getKind() == ObjCRuntime::ObjFW) {
648  VersionTuple tuple = LangOpts.ObjCRuntime.getVersion();
649 
650  unsigned minor = 0;
651  if (tuple.getMinor().hasValue())
652  minor = tuple.getMinor().getValue();
653 
654  unsigned subminor = 0;
655  if (tuple.getSubminor().hasValue())
656  subminor = tuple.getSubminor().getValue();
657 
658  Builder.defineMacro("__OBJFW_RUNTIME_ABI__",
659  Twine(tuple.getMajor() * 10000 + minor * 100 +
660  subminor));
661  }
662 
663  Builder.defineMacro("IBOutlet", "__attribute__((iboutlet))");
664  Builder.defineMacro("IBOutletCollection(ClassName)",
665  "__attribute__((iboutletcollection(ClassName)))");
666  Builder.defineMacro("IBAction", "void)__attribute__((ibaction)");
667  Builder.defineMacro("IBInspectable", "");
668  Builder.defineMacro("IB_DESIGNABLE", "");
669  }
670 
671  // Define a macro that describes the Objective-C boolean type even for C
672  // and C++ since BOOL can be used from non Objective-C code.
673  Builder.defineMacro("__OBJC_BOOL_IS_BOOL",
674  Twine(TI.useSignedCharForObjCBool() ? "0" : "1"));
675 
676  if (LangOpts.CPlusPlus)
677  InitializeCPlusPlusFeatureTestMacros(LangOpts, Builder);
678 
679  // darwin_constant_cfstrings controls this. This is also dependent
680  // on other things like the runtime I believe. This is set even for C code.
681  if (!LangOpts.NoConstantCFStrings)
682  Builder.defineMacro("__CONSTANT_CFSTRINGS__");
683 
684  if (LangOpts.ObjC)
685  Builder.defineMacro("OBJC_NEW_PROPERTIES");
686 
687  if (LangOpts.PascalStrings)
688  Builder.defineMacro("__PASCAL_STRINGS__");
689 
690  if (LangOpts.Blocks) {
691  Builder.defineMacro("__block", "__attribute__((__blocks__(byref)))");
692  Builder.defineMacro("__BLOCKS__");
693  }
694 
695  if (!LangOpts.MSVCCompat && LangOpts.Exceptions)
696  Builder.defineMacro("__EXCEPTIONS");
697  if (!LangOpts.MSVCCompat && LangOpts.RTTI)
698  Builder.defineMacro("__GXX_RTTI");
699 
700  if (LangOpts.SjLjExceptions)
701  Builder.defineMacro("__USING_SJLJ_EXCEPTIONS__");
702  else if (LangOpts.SEHExceptions)
703  Builder.defineMacro("__SEH__");
704  else if (LangOpts.DWARFExceptions &&
705  (TI.getTriple().isThumb() || TI.getTriple().isARM()))
706  Builder.defineMacro("__ARM_DWARF_EH__");
707 
708  if (LangOpts.Deprecated)
709  Builder.defineMacro("__DEPRECATED");
710 
711  if (!LangOpts.MSVCCompat && LangOpts.CPlusPlus) {
712  Builder.defineMacro("__GNUG__", "4");
713  Builder.defineMacro("__GXX_WEAK__");
714  Builder.defineMacro("__private_extern__", "extern");
715  }
716 
717  if (LangOpts.MicrosoftExt) {
718  if (LangOpts.WChar) {
719  // wchar_t supported as a keyword.
720  Builder.defineMacro("_WCHAR_T_DEFINED");
721  Builder.defineMacro("_NATIVE_WCHAR_T_DEFINED");
722  }
723  }
724 
725  if (LangOpts.Optimize)
726  Builder.defineMacro("__OPTIMIZE__");
727  if (LangOpts.OptimizeSize)
728  Builder.defineMacro("__OPTIMIZE_SIZE__");
729 
730  if (LangOpts.FastMath)
731  Builder.defineMacro("__FAST_MATH__");
732 
733  // Initialize target-specific preprocessor defines.
734 
735  // __BYTE_ORDER__ was added in GCC 4.6. It's analogous
736  // to the macro __BYTE_ORDER (no trailing underscores)
737  // from glibc's <endian.h> header.
738  // We don't support the PDP-11 as a target, but include
739  // the define so it can still be compared against.
740  Builder.defineMacro("__ORDER_LITTLE_ENDIAN__", "1234");
741  Builder.defineMacro("__ORDER_BIG_ENDIAN__", "4321");
742  Builder.defineMacro("__ORDER_PDP_ENDIAN__", "3412");
743  if (TI.isBigEndian()) {
744  Builder.defineMacro("__BYTE_ORDER__", "__ORDER_BIG_ENDIAN__");
745  Builder.defineMacro("__BIG_ENDIAN__");
746  } else {
747  Builder.defineMacro("__BYTE_ORDER__", "__ORDER_LITTLE_ENDIAN__");
748  Builder.defineMacro("__LITTLE_ENDIAN__");
749  }
750 
751  if (TI.getPointerWidth(0) == 64 && TI.getLongWidth() == 64
752  && TI.getIntWidth() == 32) {
753  Builder.defineMacro("_LP64");
754  Builder.defineMacro("__LP64__");
755  }
756 
757  if (TI.getPointerWidth(0) == 32 && TI.getLongWidth() == 32
758  && TI.getIntWidth() == 32) {
759  Builder.defineMacro("_ILP32");
760  Builder.defineMacro("__ILP32__");
761  }
762 
763  // Define type sizing macros based on the target properties.
764  assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far");
765  Builder.defineMacro("__CHAR_BIT__", Twine(TI.getCharWidth()));
766 
767  DefineTypeSize("__SCHAR_MAX__", TargetInfo::SignedChar, TI, Builder);
768  DefineTypeSize("__SHRT_MAX__", TargetInfo::SignedShort, TI, Builder);
769  DefineTypeSize("__INT_MAX__", TargetInfo::SignedInt, TI, Builder);
770  DefineTypeSize("__LONG_MAX__", TargetInfo::SignedLong, TI, Builder);
771  DefineTypeSize("__LONG_LONG_MAX__", TargetInfo::SignedLongLong, TI, Builder);
772  DefineTypeSize("__WCHAR_MAX__", TI.getWCharType(), TI, Builder);
773  DefineTypeSize("__WINT_MAX__", TI.getWIntType(), TI, Builder);
774  DefineTypeSize("__INTMAX_MAX__", TI.getIntMaxType(), TI, Builder);
775  DefineTypeSize("__SIZE_MAX__", TI.getSizeType(), TI, Builder);
776 
777  DefineTypeSize("__UINTMAX_MAX__", TI.getUIntMaxType(), TI, Builder);
778  DefineTypeSize("__PTRDIFF_MAX__", TI.getPtrDiffType(0), TI, Builder);
779  DefineTypeSize("__INTPTR_MAX__", TI.getIntPtrType(), TI, Builder);
780  DefineTypeSize("__UINTPTR_MAX__", TI.getUIntPtrType(), TI, Builder);
781 
782  DefineTypeSizeof("__SIZEOF_DOUBLE__", TI.getDoubleWidth(), TI, Builder);
783  DefineTypeSizeof("__SIZEOF_FLOAT__", TI.getFloatWidth(), TI, Builder);
784  DefineTypeSizeof("__SIZEOF_INT__", TI.getIntWidth(), TI, Builder);
785  DefineTypeSizeof("__SIZEOF_LONG__", TI.getLongWidth(), TI, Builder);
786  DefineTypeSizeof("__SIZEOF_LONG_DOUBLE__",TI.getLongDoubleWidth(),TI,Builder);
787  DefineTypeSizeof("__SIZEOF_LONG_LONG__", TI.getLongLongWidth(), TI, Builder);
788  DefineTypeSizeof("__SIZEOF_POINTER__", TI.getPointerWidth(0), TI, Builder);
789  DefineTypeSizeof("__SIZEOF_SHORT__", TI.getShortWidth(), TI, Builder);
790  DefineTypeSizeof("__SIZEOF_PTRDIFF_T__",
791  TI.getTypeWidth(TI.getPtrDiffType(0)), TI, Builder);
792  DefineTypeSizeof("__SIZEOF_SIZE_T__",
793  TI.getTypeWidth(TI.getSizeType()), TI, Builder);
794  DefineTypeSizeof("__SIZEOF_WCHAR_T__",
795  TI.getTypeWidth(TI.getWCharType()), TI, Builder);
796  DefineTypeSizeof("__SIZEOF_WINT_T__",
797  TI.getTypeWidth(TI.getWIntType()), TI, Builder);
798  if (TI.hasInt128Type())
799  DefineTypeSizeof("__SIZEOF_INT128__", 128, TI, Builder);
800 
801  DefineType("__INTMAX_TYPE__", TI.getIntMaxType(), Builder);
802  DefineFmt("__INTMAX", TI.getIntMaxType(), TI, Builder);
803  Builder.defineMacro("__INTMAX_C_SUFFIX__",
805  DefineType("__UINTMAX_TYPE__", TI.getUIntMaxType(), Builder);
806  DefineFmt("__UINTMAX", TI.getUIntMaxType(), TI, Builder);
807  Builder.defineMacro("__UINTMAX_C_SUFFIX__",
809  DefineTypeWidth("__INTMAX_WIDTH__", TI.getIntMaxType(), TI, Builder);
810  DefineType("__PTRDIFF_TYPE__", TI.getPtrDiffType(0), Builder);
811  DefineFmt("__PTRDIFF", TI.getPtrDiffType(0), TI, Builder);
812  DefineTypeWidth("__PTRDIFF_WIDTH__", TI.getPtrDiffType(0), TI, Builder);
813  DefineType("__INTPTR_TYPE__", TI.getIntPtrType(), Builder);
814  DefineFmt("__INTPTR", TI.getIntPtrType(), TI, Builder);
815  DefineTypeWidth("__INTPTR_WIDTH__", TI.getIntPtrType(), TI, Builder);
816  DefineType("__SIZE_TYPE__", TI.getSizeType(), Builder);
817  DefineFmt("__SIZE", TI.getSizeType(), TI, Builder);
818  DefineTypeWidth("__SIZE_WIDTH__", TI.getSizeType(), TI, Builder);
819  DefineType("__WCHAR_TYPE__", TI.getWCharType(), Builder);
820  DefineTypeWidth("__WCHAR_WIDTH__", TI.getWCharType(), TI, Builder);
821  DefineType("__WINT_TYPE__", TI.getWIntType(), Builder);
822  DefineTypeWidth("__WINT_WIDTH__", TI.getWIntType(), TI, Builder);
823  DefineTypeWidth("__SIG_ATOMIC_WIDTH__", TI.getSigAtomicType(), TI, Builder);
824  DefineTypeSize("__SIG_ATOMIC_MAX__", TI.getSigAtomicType(), TI, Builder);
825  DefineType("__CHAR16_TYPE__", TI.getChar16Type(), Builder);
826  DefineType("__CHAR32_TYPE__", TI.getChar32Type(), Builder);
827 
828  DefineTypeWidth("__UINTMAX_WIDTH__", TI.getUIntMaxType(), TI, Builder);
829  DefineType("__UINTPTR_TYPE__", TI.getUIntPtrType(), Builder);
830  DefineFmt("__UINTPTR", TI.getUIntPtrType(), TI, Builder);
831  DefineTypeWidth("__UINTPTR_WIDTH__", TI.getUIntPtrType(), TI, Builder);
832 
833  DefineFloatMacros(Builder, "FLT16", &TI.getHalfFormat(), "F16");
834  DefineFloatMacros(Builder, "FLT", &TI.getFloatFormat(), "F");
835  DefineFloatMacros(Builder, "DBL", &TI.getDoubleFormat(), "");
836  DefineFloatMacros(Builder, "LDBL", &TI.getLongDoubleFormat(), "L");
837 
838  // Define a __POINTER_WIDTH__ macro for stdint.h.
839  Builder.defineMacro("__POINTER_WIDTH__",
840  Twine((int)TI.getPointerWidth(0)));
841 
842  // Define __BIGGEST_ALIGNMENT__ to be compatible with gcc.
843  Builder.defineMacro("__BIGGEST_ALIGNMENT__",
844  Twine(TI.getSuitableAlign() / TI.getCharWidth()) );
845 
846  if (!LangOpts.CharIsSigned)
847  Builder.defineMacro("__CHAR_UNSIGNED__");
848 
850  Builder.defineMacro("__WCHAR_UNSIGNED__");
851 
853  Builder.defineMacro("__WINT_UNSIGNED__");
854 
855  // Define exact-width integer types for stdint.h
857 
858  if (TI.getShortWidth() > TI.getCharWidth())
860 
861  if (TI.getIntWidth() > TI.getShortWidth())
863 
864  if (TI.getLongWidth() > TI.getIntWidth())
866 
867  if (TI.getLongLongWidth() > TI.getLongWidth())
869 
873 
874  if (TI.getShortWidth() > TI.getCharWidth()) {
878  }
879 
880  if (TI.getIntWidth() > TI.getShortWidth()) {
884  }
885 
886  if (TI.getLongWidth() > TI.getIntWidth()) {
890  }
891 
892  if (TI.getLongLongWidth() > TI.getLongWidth()) {
896  }
897 
898  DefineLeastWidthIntType(8, true, TI, Builder);
899  DefineLeastWidthIntType(8, false, TI, Builder);
900  DefineLeastWidthIntType(16, true, TI, Builder);
901  DefineLeastWidthIntType(16, false, TI, Builder);
902  DefineLeastWidthIntType(32, true, TI, Builder);
903  DefineLeastWidthIntType(32, false, TI, Builder);
904  DefineLeastWidthIntType(64, true, TI, Builder);
905  DefineLeastWidthIntType(64, false, TI, Builder);
906 
907  DefineFastIntType(8, true, TI, Builder);
908  DefineFastIntType(8, false, TI, Builder);
909  DefineFastIntType(16, true, TI, Builder);
910  DefineFastIntType(16, false, TI, Builder);
911  DefineFastIntType(32, true, TI, Builder);
912  DefineFastIntType(32, false, TI, Builder);
913  DefineFastIntType(64, true, TI, Builder);
914  DefineFastIntType(64, false, TI, Builder);
915 
916  char UserLabelPrefix[2] = {TI.getDataLayout().getGlobalPrefix(), 0};
917  Builder.defineMacro("__USER_LABEL_PREFIX__", UserLabelPrefix);
918 
919  if (LangOpts.FastMath || LangOpts.FiniteMathOnly)
920  Builder.defineMacro("__FINITE_MATH_ONLY__", "1");
921  else
922  Builder.defineMacro("__FINITE_MATH_ONLY__", "0");
923 
924  if (!LangOpts.MSVCCompat) {
925  if (LangOpts.GNUInline || LangOpts.CPlusPlus)
926  Builder.defineMacro("__GNUC_GNU_INLINE__");
927  else
928  Builder.defineMacro("__GNUC_STDC_INLINE__");
929 
930  // The value written by __atomic_test_and_set.
931  // FIXME: This is target-dependent.
932  Builder.defineMacro("__GCC_ATOMIC_TEST_AND_SET_TRUEVAL", "1");
933  }
934 
935  auto addLockFreeMacros = [&](const llvm::Twine &Prefix) {
936  // Used by libc++ and libstdc++ to implement ATOMIC_<foo>_LOCK_FREE.
937  unsigned InlineWidthBits = TI.getMaxAtomicInlineWidth();
938 #define DEFINE_LOCK_FREE_MACRO(TYPE, Type) \
939  Builder.defineMacro(Prefix + #TYPE "_LOCK_FREE", \
940  getLockFreeValue(TI.get##Type##Width(), \
941  TI.get##Type##Align(), \
942  InlineWidthBits));
944  DEFINE_LOCK_FREE_MACRO(CHAR, Char);
945  if (LangOpts.Char8)
946  DEFINE_LOCK_FREE_MACRO(CHAR8_T, Char); // Treat char8_t like char.
947  DEFINE_LOCK_FREE_MACRO(CHAR16_T, Char16);
948  DEFINE_LOCK_FREE_MACRO(CHAR32_T, Char32);
949  DEFINE_LOCK_FREE_MACRO(WCHAR_T, WChar);
950  DEFINE_LOCK_FREE_MACRO(SHORT, Short);
951  DEFINE_LOCK_FREE_MACRO(INT, Int);
952  DEFINE_LOCK_FREE_MACRO(LONG, Long);
953  DEFINE_LOCK_FREE_MACRO(LLONG, LongLong);
954  Builder.defineMacro(Prefix + "POINTER_LOCK_FREE",
956  TI.getPointerAlign(0),
957  InlineWidthBits));
958 #undef DEFINE_LOCK_FREE_MACRO
959  };
960  addLockFreeMacros("__CLANG_ATOMIC_");
961  if (!LangOpts.MSVCCompat)
962  addLockFreeMacros("__GCC_ATOMIC_");
963 
964  if (LangOpts.NoInlineDefine)
965  Builder.defineMacro("__NO_INLINE__");
966 
967  if (unsigned PICLevel = LangOpts.PICLevel) {
968  Builder.defineMacro("__PIC__", Twine(PICLevel));
969  Builder.defineMacro("__pic__", Twine(PICLevel));
970  if (LangOpts.PIE) {
971  Builder.defineMacro("__PIE__", Twine(PICLevel));
972  Builder.defineMacro("__pie__", Twine(PICLevel));
973  }
974  }
975 
976  // Macros to control C99 numerics and <float.h>
977  Builder.defineMacro("__FLT_EVAL_METHOD__", Twine(TI.getFloatEvalMethod()));
978  Builder.defineMacro("__FLT_RADIX__", "2");
979  Builder.defineMacro("__DECIMAL_DIG__", "__LDBL_DECIMAL_DIG__");
980 
981  if (LangOpts.getStackProtector() == LangOptions::SSPOn)
982  Builder.defineMacro("__SSP__");
983  else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
984  Builder.defineMacro("__SSP_STRONG__", "2");
985  else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
986  Builder.defineMacro("__SSP_ALL__", "3");
987 
988  // Define a macro that exists only when using the static analyzer.
989  if (FEOpts.ProgramAction == frontend::RunAnalysis)
990  Builder.defineMacro("__clang_analyzer__");
991 
992  if (LangOpts.FastRelaxedMath)
993  Builder.defineMacro("__FAST_RELAXED_MATH__");
994 
995  if (FEOpts.ProgramAction == frontend::RewriteObjC ||
996  LangOpts.getGC() != LangOptions::NonGC) {
997  Builder.defineMacro("__weak", "__attribute__((objc_gc(weak)))");
998  Builder.defineMacro("__strong", "__attribute__((objc_gc(strong)))");
999  Builder.defineMacro("__autoreleasing", "");
1000  Builder.defineMacro("__unsafe_unretained", "");
1001  } else if (LangOpts.ObjC) {
1002  Builder.defineMacro("__weak", "__attribute__((objc_ownership(weak)))");
1003  Builder.defineMacro("__strong", "__attribute__((objc_ownership(strong)))");
1004  Builder.defineMacro("__autoreleasing",
1005  "__attribute__((objc_ownership(autoreleasing)))");
1006  Builder.defineMacro("__unsafe_unretained",
1007  "__attribute__((objc_ownership(none)))");
1008  }
1009 
1010  // On Darwin, there are __double_underscored variants of the type
1011  // nullability qualifiers.
1012  if (TI.getTriple().isOSDarwin()) {
1013  Builder.defineMacro("__nonnull", "_Nonnull");
1014  Builder.defineMacro("__null_unspecified", "_Null_unspecified");
1015  Builder.defineMacro("__nullable", "_Nullable");
1016  }
1017 
1018  // Add a macro to differentiate between regular iOS/tvOS/watchOS targets and
1019  // the corresponding simulator targets.
1020  if (TI.getTriple().isOSDarwin() && TI.getTriple().isSimulatorEnvironment())
1021  Builder.defineMacro("__APPLE_EMBEDDED_SIMULATOR__", "1");
1022 
1023  // OpenMP definition
1024  // OpenMP 2.2:
1025  // In implementations that support a preprocessor, the _OPENMP
1026  // macro name is defined to have the decimal value yyyymm where
1027  // yyyy and mm are the year and the month designations of the
1028  // version of the OpenMP API that the implementation support.
1029  if (!LangOpts.OpenMPSimd) {
1030  switch (LangOpts.OpenMP) {
1031  case 0:
1032  break;
1033  case 40:
1034  Builder.defineMacro("_OPENMP", "201307");
1035  break;
1036  case 45:
1037  Builder.defineMacro("_OPENMP", "201511");
1038  break;
1039  default:
1040  // Default version is OpenMP 3.1
1041  Builder.defineMacro("_OPENMP", "201107");
1042  break;
1043  }
1044  }
1045 
1046  // CUDA device path compilaton
1047  if (LangOpts.CUDAIsDevice && !LangOpts.HIP) {
1048  // The CUDA_ARCH value is set for the GPU target specified in the NVPTX
1049  // backend's target defines.
1050  Builder.defineMacro("__CUDA_ARCH__");
1051  }
1052 
1053  // We need to communicate this to our CUDA header wrapper, which in turn
1054  // informs the proper CUDA headers of this choice.
1055  if (LangOpts.CUDADeviceApproxTranscendentals || LangOpts.FastMath) {
1056  Builder.defineMacro("__CLANG_CUDA_APPROX_TRANSCENDENTALS__");
1057  }
1058 
1059  // OpenCL definitions.
1060  if (LangOpts.OpenCL) {
1061 #define OPENCLEXT(Ext) \
1062  if (TI.getSupportedOpenCLOpts().isSupported(#Ext, \
1063  LangOpts.OpenCLVersion)) \
1064  Builder.defineMacro(#Ext);
1065 #include "clang/Basic/OpenCLExtensions.def"
1066 
1067  auto Arch = TI.getTriple().getArch();
1068  if (Arch == llvm::Triple::spir || Arch == llvm::Triple::spir64)
1069  Builder.defineMacro("__IMAGE_SUPPORT__");
1070  }
1071 
1072  if (TI.hasInt128Type() && LangOpts.CPlusPlus && LangOpts.GNUMode) {
1073  // For each extended integer type, g++ defines a macro mapping the
1074  // index of the type (0 in this case) in some list of extended types
1075  // to the type.
1076  Builder.defineMacro("__GLIBCXX_TYPE_INT_N_0", "__int128");
1077  Builder.defineMacro("__GLIBCXX_BITSIZE_INT_N_0", "128");
1078  }
1079 
1080  // Get other target #defines.
1081  TI.getTargetDefines(LangOpts, Builder);
1082 }
1083 
1084 /// InitializePreprocessor - Initialize the preprocessor getting it and the
1085 /// environment ready to process a single file. This returns true on error.
1086 ///
1088  Preprocessor &PP, const PreprocessorOptions &InitOpts,
1089  const PCHContainerReader &PCHContainerRdr,
1090  const FrontendOptions &FEOpts) {
1091  const LangOptions &LangOpts = PP.getLangOpts();
1092  std::string PredefineBuffer;
1093  PredefineBuffer.reserve(4080);
1094  llvm::raw_string_ostream Predefines(PredefineBuffer);
1095  MacroBuilder Builder(Predefines);
1096 
1097  // Emit line markers for various builtin sections of the file. We don't do
1098  // this in asm preprocessor mode, because "# 4" is not a line marker directive
1099  // in this mode.
1100  if (!PP.getLangOpts().AsmPreprocessor)
1101  Builder.append("# 1 \"<built-in>\" 3");
1102 
1103  // Install things like __POWERPC__, __GNUC__, etc into the macro table.
1104  if (InitOpts.UsePredefines) {
1105  // FIXME: This will create multiple definitions for most of the predefined
1106  // macros. This is not the right way to handle this.
1107  if ((LangOpts.CUDA || LangOpts.OpenMPIsDevice) && PP.getAuxTargetInfo())
1108  InitializePredefinedMacros(*PP.getAuxTargetInfo(), LangOpts, FEOpts,
1109  Builder);
1110 
1111  InitializePredefinedMacros(PP.getTargetInfo(), LangOpts, FEOpts, Builder);
1112 
1113  // Install definitions to make Objective-C++ ARC work well with various
1114  // C++ Standard Library implementations.
1115  if (LangOpts.ObjC && LangOpts.CPlusPlus &&
1116  (LangOpts.ObjCAutoRefCount || LangOpts.ObjCWeak)) {
1117  switch (InitOpts.ObjCXXARCStandardLibrary) {
1118  case ARCXX_nolib:
1119  case ARCXX_libcxx:
1120  break;
1121 
1122  case ARCXX_libstdcxx:
1123  AddObjCXXARCLibstdcxxDefines(LangOpts, Builder);
1124  break;
1125  }
1126  }
1127  }
1128 
1129  // Even with predefines off, some macros are still predefined.
1130  // These should all be defined in the preprocessor according to the
1131  // current language configuration.
1133  FEOpts, Builder);
1134 
1135  // Add on the predefines from the driver. Wrap in a #line directive to report
1136  // that they come from the command line.
1137  if (!PP.getLangOpts().AsmPreprocessor)
1138  Builder.append("# 1 \"<command line>\" 1");
1139 
1140  // Process #define's and #undef's in the order they are given.
1141  for (unsigned i = 0, e = InitOpts.Macros.size(); i != e; ++i) {
1142  if (InitOpts.Macros[i].second) // isUndef
1143  Builder.undefineMacro(InitOpts.Macros[i].first);
1144  else
1145  DefineBuiltinMacro(Builder, InitOpts.Macros[i].first,
1146  PP.getDiagnostics());
1147  }
1148 
1149  // Exit the command line and go back to <built-in> (2 is LC_LEAVE).
1150  if (!PP.getLangOpts().AsmPreprocessor)
1151  Builder.append("# 1 \"<built-in>\" 2");
1152 
1153  // If -imacros are specified, include them now. These are processed before
1154  // any -include directives.
1155  for (unsigned i = 0, e = InitOpts.MacroIncludes.size(); i != e; ++i)
1156  AddImplicitIncludeMacros(Builder, InitOpts.MacroIncludes[i]);
1157 
1158  // Process -include-pch/-include-pth directives.
1159  if (!InitOpts.ImplicitPCHInclude.empty())
1160  AddImplicitIncludePCH(Builder, PP, PCHContainerRdr,
1161  InitOpts.ImplicitPCHInclude);
1162 
1163  // Process -include directives.
1164  for (unsigned i = 0, e = InitOpts.Includes.size(); i != e; ++i) {
1165  const std::string &Path = InitOpts.Includes[i];
1166  AddImplicitInclude(Builder, Path);
1167  }
1168 
1169  // Instruct the preprocessor to skip the preamble.
1171  InitOpts.PrecompiledPreambleBytes.second);
1172 
1173  // Copy PredefinedBuffer into the Preprocessor.
1174  PP.setPredefines(Predefines.str());
1175 }
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
Definition: TargetInfo.cpp:213
IntType getInt64Type() const
Definition: TargetInfo.h:291
unsigned getFloatWidth() const
getFloatWidth/Align/Format - Return the size/align/format of &#39;float&#39;.
Definition: TargetInfo.h:562
std::vector< std::pair< std::string, bool > > Macros
Defines the clang::MacroBuilder utility class.
unsigned getLongWidth() const
getLongWidth/Align - Return the size of &#39;signed long&#39; and &#39;unsigned long&#39; for this target...
Definition: TargetInfo.h:388
Defines the clang::FileManager interface and associated types.
unsigned getSuitableAlign() const
Return the alignment that is suitable for storing any object with a fundamental alignment requirement...
Definition: TargetInfo.h:522
bool isBigEndian() const
Definition: TargetInfo.h:1213
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:949
Defines the SourceManager interface.
virtual IntType getLeastIntTypeByWidth(unsigned BitWidth, bool IsSigned) const
Return the smallest integer type with at least the specified width.
Definition: TargetInfo.cpp:244
FileManager & getFileManager() const
Definition: Preprocessor.h:818
static T PickFP(const llvm::fltSemantics *Sem, T IEEEHalfVal, T IEEESingleVal, T IEEEDoubleVal, T X87DoubleExtendedVal, T PPCDoubleDoubleVal, T IEEEQuadVal)
PickFP - This is used to pick a value based on the FP semantics of the specified FP model...
static void DefineFmt(const Twine &Prefix, TargetInfo::IntType Ty, const TargetInfo &TI, MacroBuilder &Builder)
std::vector< std::string > Includes
static void AddImplicitIncludeMacros(MacroBuilder &Builder, StringRef File)
StringRef getOriginalSourceFile()
Retrieve the name of the original source file name for the primary module file.
Definition: ASTReader.h:1668
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1292
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
unsigned getCharWidth() const
Definition: TargetInfo.h:370
const llvm::fltSemantics & getHalfFormat() const
Definition: TargetInfo.h:559
static void DefineTypeSizeof(StringRef MacroName, unsigned BitWidth, const TargetInfo &TI, MacroBuilder &Builder)
void setPredefines(const char *P)
Set the predefines for this Preprocessor.
static void AddImplicitIncludePCH(MacroBuilder &Builder, Preprocessor &PP, const PCHContainerReader &PCHContainerRdr, StringRef ImplicitIncludePCH)
Add an implicit #include using the original file used to generate a PCH file.
uint64_t getPointerWidth(unsigned AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:348
#define TOSTR(X)
const char * getTypeConstantSuffix(IntType T) const
Return the constant suffix for the specified integer type enum.
Definition: TargetInfo.cpp:170
static void AddObjCXXARCLibstdcxxDefines(const LangOptions &LangOpts, MacroBuilder &Builder)
Add definitions required for a smooth interaction between Objective-C++ automated reference counting ...
IntType getChar32Type() const
Definition: TargetInfo.h:290
unsigned getNewAlign() const
Return the largest alignment for which a suitably-sized allocation with &#39;::operator new(size_t)&#39; is g...
Definition: TargetInfo.h:537
const TargetInfo & getTargetInfo() const
Definition: Preprocessor.h:816
void undefineMacro(const Twine &Name)
Append a #undef line for Name.
Definition: MacroBuilder.h:36
IntType getSizeType() const
Definition: TargetInfo.h:258
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:50
const LangOptions & getLangOpts() const
Definition: Preprocessor.h:815
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
Definition: TargetInfo.cpp:302
bool isNonFragile() const
Does this runtime follow the set of implied behaviors for a "non-fragile" ABI?
Definition: ObjCRuntime.h:82
bool isNeXTFamily() const
Is this runtime basically of the NeXT family of runtimes?
Definition: ObjCRuntime.h:135
LLVM_READONLY bool isWhitespace(unsigned char c)
Return true if this character is horizontal or vertical ASCII whitespace: &#39; &#39;, &#39;\t&#39;, &#39;\f&#39;, &#39;\v&#39;, &#39;\n&#39;, &#39;\r&#39;.
Definition: CharInfo.h:88
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:149
static void InitializePredefinedMacros(const TargetInfo &TI, const LangOptions &LangOpts, const FrontendOptions &FEOpts, MacroBuilder &Builder)
void append(const Twine &Str)
Directly append Str and a newline to the underlying buffer.
Definition: MacroBuilder.h:41
unsigned getShortWidth() const
Return the size of &#39;signed short&#39; and &#39;unsigned short&#39; for this target, in bits.
Definition: TargetInfo.h:375
static void DefineType(const Twine &MacroName, TargetInfo::IntType Ty, MacroBuilder &Builder)
const TargetInfo * getAuxTargetInfo() const
Definition: Preprocessor.h:817
static void DefineFloatMacros(MacroBuilder &Builder, StringRef Prefix, const llvm::fltSemantics *Sem, StringRef Ext)
static void AddImplicitInclude(MacroBuilder &Builder, StringRef File)
AddImplicitInclude - Add an implicit #include of the specified file to the predefines buffer...
static void DefineExactWidthIntTypeSize(TargetInfo::IntType Ty, const TargetInfo &TI, MacroBuilder &Builder)
This abstract interface provides operations for unwrapping containers for serialized ASTs (precompile...
bool isLittleEndian() const
Definition: TargetInfo.h:1214
const llvm::fltSemantics & getDoubleFormat() const
Definition: TargetInfo.h:569
static void DefineExactWidthIntType(TargetInfo::IntType Ty, const TargetInfo &TI, MacroBuilder &Builder)
const llvm::fltSemantics & getLongDoubleFormat() const
Definition: TargetInfo.h:575
Exposes information about the current target.
Definition: TargetInfo.h:54
static void DefineLeastWidthIntType(unsigned TypeWidth, bool IsSigned, const TargetInfo &TI, MacroBuilder &Builder)
SourceLocation End
IntType getUIntPtrType() const
Definition: TargetInfo.h:284
unsigned getIntWidth() const
getIntWidth/Align - Return the size of &#39;signed int&#39; and &#39;unsigned int&#39; for this target, in bits.
Definition: TargetInfo.h:383
static void DefineTypeSize(const Twine &MacroName, unsigned TypeWidth, StringRef ValSuffix, bool isSigned, MacroBuilder &Builder)
DefineTypeSize - Emit a macro to the predefines buffer that declares a macro named MacroName with the...
Defines version macros and version-related utility functions for Clang.
Defines the clang::Preprocessor interface.
IntType getChar16Type() const
Definition: TargetInfo.h:289
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:199
&#39;gnustep&#39; is the modern non-fragile GNUstep runtime.
Definition: ObjCRuntime.h:56
IntType getUIntMaxType() const
Definition: TargetInfo.h:274
unsigned getDoubleWidth() const
getDoubleWidth/Align/Format - Return the size/align/format of &#39;double&#39;.
Definition: TargetInfo.h:567
static const char * getTypeName(IntType T)
Return the user string for the specified integer type enum.
Definition: TargetInfo.cpp:152
static const char * getLockFreeValue(unsigned TypeWidth, unsigned TypeAlign, unsigned InlineWidth)
Get the value the ATOMIC_*_LOCK_FREE macro should have for a type with the specified properties...
static bool MacroBodyEndsInBackslash(StringRef MacroBody)
IntType getPtrDiffType(unsigned AddrSpace) const
Definition: TargetInfo.h:277
IntType getSigAtomicType() const
Definition: TargetInfo.h:295
static void DefineFastIntType(unsigned TypeWidth, bool IsSigned, const TargetInfo &TI, MacroBuilder &Builder)
static void InitializeStandardPredefinedMacros(const TargetInfo &TI, const LangOptions &LangOpts, const FrontendOptions &FEOpts, MacroBuilder &Builder)
unsigned getMaxAtomicInlineWidth() const
Return the maximum width lock-free atomic operation which can be inlined given the supported features...
Definition: TargetInfo.h:604
static void DefineBuiltinMacro(MacroBuilder &Builder, StringRef Macro, DiagnosticsEngine &Diags)
static void InitializeCPlusPlusFeatureTestMacros(const LangOptions &LangOpts, MacroBuilder &Builder)
Initialize the predefined C++ language feature test macros defined in ISO/IEC JTC1/SC22/WG21 (C++) SD...
IntType getWIntType() const
Definition: TargetInfo.h:288
std::string ImplicitPCHInclude
The implicit PCH included at the start of the translation unit, or empty.
&#39;objfw&#39; is the Objective-C runtime included in ObjFW
Definition: ObjCRuntime.h:59
unsigned getLongLongWidth() const
getLongLongWidth/Align - Return the size of &#39;signed long long&#39; and &#39;unsigned long long&#39; for this targ...
Definition: TargetInfo.h:393
Kind getKind() const
Definition: ObjCRuntime.h:77
IntType getIntMaxType() const
Definition: TargetInfo.h:273
std::string getClangFullRepositoryVersion()
Retrieves the full repository version that is an amalgamation of the information in getClangRepositor...
Definition: Version.cpp:90
const llvm::DataLayout & getDataLayout() const
Definition: TargetInfo.h:953
virtual unsigned getFloatEvalMethod() const
Return the value for the C99 FLT_EVAL_METHOD macro.
Definition: TargetInfo.h:592
IntType getUInt64Type() const
Definition: TargetInfo.h:292
const VersionTuple & getVersion() const
Definition: ObjCRuntime.h:78
unsigned getLongDoubleWidth() const
getLongDoubleWidth/Align/Format - Return the size/align/format of &#39;long double&#39;.
Definition: TargetInfo.h:573
std::vector< std::string > MacroIncludes
IntType
===-— Target Data Type Query Methods ----------------------------—===//
Definition: TargetInfo.h:157
Dataflow Directional Tag Classes.
static const char * getTypeFormatModifier(IntType T)
Return the printf format modifier for the specified integer type enum.
Definition: TargetInfo.cpp:195
bool UsePredefines
Initialize the preprocessor with the compiler and target specific predefines.
frontend::ActionKind ProgramAction
The frontend action to perform.
FrontendOptions - Options for controlling the behavior of the frontend.
#define DEFINE_LOCK_FREE_MACRO(TYPE, Type)
bool useSignedCharForObjCBool() const
Check if the Objective-C built-in boolean type should be signed char.
Definition: TargetInfo.h:651
virtual void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const =0
===-— Other target property query methods --------------------——===//
ObjCXXARCStandardLibraryKind ObjCXXARCStandardLibrary
The Objective-C++ ARC standard library that we should support, by providing appropriate definitions t...
std::string getClangFullCPPVersion()
Retrieves a string representing the complete clang version suitable for use in the CPP VERSION macro...
Definition: Version.cpp:139
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition: TargetInfo.h:510
Provides definitions for the atomic synchronization scopes.
DiagnosticsEngine & getDiagnostics() const
Definition: Preprocessor.h:812
const llvm::fltSemantics & getFloatFormat() const
Definition: TargetInfo.h:564
void InitializePreprocessor(Preprocessor &PP, const PreprocessorOptions &PPOpts, const PCHContainerReader &PCHContainerRdr, const FrontendOptions &FEOpts)
InitializePreprocessor - Initialize the preprocessor getting it and the environment ready to process ...
IntType getWCharType() const
Definition: TargetInfo.h:287
Run one or more source code analyses.
uint64_t getPointerAlign(unsigned AddrSpace) const
Definition: TargetInfo.h:351
std::pair< unsigned, bool > PrecompiledPreambleBytes
If non-zero, the implicit PCH include is actually a precompiled preamble that covers this number of b...
Defines the clang::TargetInfo interface.
IntType getIntPtrType() const
Definition: TargetInfo.h:283
__DEVICE__ int min(int __a, int __b)
void defineMacro(const Twine &Name, const Twine &Value="1")
Append a #define line for macro of the form "\#define Name Value\n".
Definition: MacroBuilder.h:30
void setSkipMainFilePreamble(unsigned Bytes, bool StartOfLine)
Instruct the preprocessor to skip part of the main source file.
static void DefineTypeWidth(StringRef MacroName, TargetInfo::IntType Ty, const TargetInfo &TI, MacroBuilder &Builder)
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:125