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