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