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