xref: /llvm-project/clang/lib/Frontend/InitPreprocessor.cpp (revision dbd4d4c8375ee79dd9da290695f292ddcb65c3d3)
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/Frontend/Utils.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/MacroBuilder.h"
17 #include "clang/Basic/SourceManager.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/Lex/HeaderSearch.h"
23 #include "clang/Lex/Preprocessor.h"
24 #include "clang/Lex/PreprocessorOptions.h"
25 #include "clang/Serialization/ASTReader.h"
26 #include "llvm/ADT/APFloat.h"
27 #include "llvm/Support/FileSystem.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/Path.h"
30 using namespace clang;
31 
32 static bool MacroBodyEndsInBackslash(StringRef MacroBody) {
33   while (!MacroBody.empty() && isWhitespace(MacroBody.back()))
34     MacroBody = MacroBody.drop_back();
35   return !MacroBody.empty() && MacroBody.back() == '\\';
36 }
37 
38 // Append a #define line to Buf for Macro.  Macro should be of the form XXX,
39 // in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
40 // "#define XXX Y z W".  To get a #define with no value, use "XXX=".
41 static void DefineBuiltinMacro(MacroBuilder &Builder, StringRef Macro,
42                                DiagnosticsEngine &Diags) {
43   std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
44   StringRef MacroName = MacroPair.first;
45   StringRef MacroBody = MacroPair.second;
46   if (MacroName.size() != Macro.size()) {
47     // Per GCC -D semantics, the macro ends at \n if it exists.
48     StringRef::size_type End = MacroBody.find_first_of("\n\r");
49     if (End != StringRef::npos)
50       Diags.Report(diag::warn_fe_macro_contains_embedded_newline)
51         << MacroName;
52     MacroBody = MacroBody.substr(0, End);
53     // We handle macro bodies which end in a backslash by appending an extra
54     // backslash+newline.  This makes sure we don't accidentally treat the
55     // backslash as a line continuation marker.
56     if (MacroBodyEndsInBackslash(MacroBody))
57       Builder.defineMacro(MacroName, Twine(MacroBody) + "\\\n");
58     else
59       Builder.defineMacro(MacroName, MacroBody);
60   } else {
61     // Push "macroname 1".
62     Builder.defineMacro(Macro);
63   }
64 }
65 
66 /// AddImplicitInclude - Add an implicit \#include of the specified file to the
67 /// predefines buffer.
68 static void AddImplicitInclude(MacroBuilder &Builder, StringRef File,
69                                FileManager &FileMgr) {
70   Builder.append(Twine("#include \"") +
71                  HeaderSearch::NormalizeDashIncludePath(File, FileMgr) + "\"");
72 }
73 
74 static void AddImplicitIncludeMacros(MacroBuilder &Builder,
75                                      StringRef File,
76                                      FileManager &FileMgr) {
77   Builder.append(Twine("#__include_macros \"") +
78                  HeaderSearch::NormalizeDashIncludePath(File, FileMgr) + "\"");
79   // Marker token to stop the __include_macros fetch loop.
80   Builder.append("##"); // ##?
81 }
82 
83 /// AddImplicitIncludePTH - Add an implicit \#include using the original file
84 /// used to generate a PTH cache.
85 static void AddImplicitIncludePTH(MacroBuilder &Builder, Preprocessor &PP,
86                                   StringRef ImplicitIncludePTH) {
87   PTHManager *P = PP.getPTHManager();
88   // Null check 'P' in the corner case where it couldn't be created.
89   const char *OriginalFile = P ? P->getOriginalSourceFile() : nullptr;
90 
91   if (!OriginalFile) {
92     PP.getDiagnostics().Report(diag::err_fe_pth_file_has_no_source_header)
93       << ImplicitIncludePTH;
94     return;
95   }
96 
97   AddImplicitInclude(Builder, OriginalFile, PP.getFileManager());
98 }
99 
100 /// \brief Add an implicit \#include using the original file used to generate
101 /// a PCH file.
102 static void AddImplicitIncludePCH(MacroBuilder &Builder, Preprocessor &PP,
103                                   StringRef ImplicitIncludePCH) {
104   std::string OriginalFile =
105     ASTReader::getOriginalSourceFile(ImplicitIncludePCH, PP.getFileManager(),
106                                      PP.getDiagnostics());
107   if (OriginalFile.empty())
108     return;
109 
110   AddImplicitInclude(Builder, OriginalFile, PP.getFileManager());
111 }
112 
113 /// PickFP - This is used to pick a value based on the FP semantics of the
114 /// specified FP model.
115 template <typename T>
116 static T PickFP(const llvm::fltSemantics *Sem, T IEEESingleVal,
117                 T IEEEDoubleVal, T X87DoubleExtendedVal, T PPCDoubleDoubleVal,
118                 T IEEEQuadVal) {
119   if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEsingle)
120     return IEEESingleVal;
121   if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEdouble)
122     return IEEEDoubleVal;
123   if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::x87DoubleExtended)
124     return X87DoubleExtendedVal;
125   if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::PPCDoubleDouble)
126     return PPCDoubleDoubleVal;
127   assert(Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEquad);
128   return IEEEQuadVal;
129 }
130 
131 static void DefineFloatMacros(MacroBuilder &Builder, StringRef Prefix,
132                               const llvm::fltSemantics *Sem, StringRef Ext) {
133   const char *DenormMin, *Epsilon, *Max, *Min;
134   DenormMin = PickFP(Sem, "1.40129846e-45", "4.9406564584124654e-324",
135                      "3.64519953188247460253e-4951",
136                      "4.94065645841246544176568792868221e-324",
137                      "6.47517511943802511092443895822764655e-4966");
138   int Digits = PickFP(Sem, 6, 15, 18, 31, 33);
139   Epsilon = PickFP(Sem, "1.19209290e-7", "2.2204460492503131e-16",
140                    "1.08420217248550443401e-19",
141                    "4.94065645841246544176568792868221e-324",
142                    "1.92592994438723585305597794258492732e-34");
143   int MantissaDigits = PickFP(Sem, 24, 53, 64, 106, 113);
144   int Min10Exp = PickFP(Sem, -37, -307, -4931, -291, -4931);
145   int Max10Exp = PickFP(Sem, 38, 308, 4932, 308, 4932);
146   int MinExp = PickFP(Sem, -125, -1021, -16381, -968, -16381);
147   int MaxExp = PickFP(Sem, 128, 1024, 16384, 1024, 16384);
148   Min = PickFP(Sem, "1.17549435e-38", "2.2250738585072014e-308",
149                "3.36210314311209350626e-4932",
150                "2.00416836000897277799610805135016e-292",
151                "3.36210314311209350626267781732175260e-4932");
152   Max = PickFP(Sem, "3.40282347e+38", "1.7976931348623157e+308",
153                "1.18973149535723176502e+4932",
154                "1.79769313486231580793728971405301e+308",
155                "1.18973149535723176508575932662800702e+4932");
156 
157   SmallString<32> DefPrefix;
158   DefPrefix = "__";
159   DefPrefix += Prefix;
160   DefPrefix += "_";
161 
162   Builder.defineMacro(DefPrefix + "DENORM_MIN__", Twine(DenormMin)+Ext);
163   Builder.defineMacro(DefPrefix + "HAS_DENORM__");
164   Builder.defineMacro(DefPrefix + "DIG__", Twine(Digits));
165   Builder.defineMacro(DefPrefix + "EPSILON__", Twine(Epsilon)+Ext);
166   Builder.defineMacro(DefPrefix + "HAS_INFINITY__");
167   Builder.defineMacro(DefPrefix + "HAS_QUIET_NAN__");
168   Builder.defineMacro(DefPrefix + "MANT_DIG__", Twine(MantissaDigits));
169 
170   Builder.defineMacro(DefPrefix + "MAX_10_EXP__", Twine(Max10Exp));
171   Builder.defineMacro(DefPrefix + "MAX_EXP__", Twine(MaxExp));
172   Builder.defineMacro(DefPrefix + "MAX__", Twine(Max)+Ext);
173 
174   Builder.defineMacro(DefPrefix + "MIN_10_EXP__","("+Twine(Min10Exp)+")");
175   Builder.defineMacro(DefPrefix + "MIN_EXP__", "("+Twine(MinExp)+")");
176   Builder.defineMacro(DefPrefix + "MIN__", Twine(Min)+Ext);
177 }
178 
179 
180 /// DefineTypeSize - Emit a macro to the predefines buffer that declares a macro
181 /// named MacroName with the max value for a type with width 'TypeWidth' a
182 /// signedness of 'isSigned' and with a value suffix of 'ValSuffix' (e.g. LL).
183 static void DefineTypeSize(StringRef MacroName, unsigned TypeWidth,
184                            StringRef ValSuffix, bool isSigned,
185                            MacroBuilder &Builder) {
186   llvm::APInt MaxVal = isSigned ? llvm::APInt::getSignedMaxValue(TypeWidth)
187                                 : llvm::APInt::getMaxValue(TypeWidth);
188   Builder.defineMacro(MacroName, MaxVal.toString(10, isSigned) + ValSuffix);
189 }
190 
191 /// DefineTypeSize - An overloaded helper that uses TargetInfo to determine
192 /// the width, suffix, and signedness of the given type
193 static void DefineTypeSize(StringRef MacroName, TargetInfo::IntType Ty,
194                            const TargetInfo &TI, MacroBuilder &Builder) {
195   DefineTypeSize(MacroName, TI.getTypeWidth(Ty), TI.getTypeConstantSuffix(Ty),
196                  TI.isTypeSigned(Ty), Builder);
197 }
198 
199 static void DefineType(const Twine &MacroName, TargetInfo::IntType Ty,
200                        MacroBuilder &Builder) {
201   Builder.defineMacro(MacroName, TargetInfo::getTypeName(Ty));
202 }
203 
204 static void DefineTypeWidth(StringRef MacroName, TargetInfo::IntType Ty,
205                             const TargetInfo &TI, MacroBuilder &Builder) {
206   Builder.defineMacro(MacroName, Twine(TI.getTypeWidth(Ty)));
207 }
208 
209 static void DefineTypeSizeof(StringRef MacroName, unsigned BitWidth,
210                              const TargetInfo &TI, MacroBuilder &Builder) {
211   Builder.defineMacro(MacroName,
212                       Twine(BitWidth / TI.getCharWidth()));
213 }
214 
215 static void DefineExactWidthIntType(TargetInfo::IntType Ty,
216                                const TargetInfo &TI, MacroBuilder &Builder) {
217   int TypeWidth = TI.getTypeWidth(Ty);
218 
219   // Use the target specified int64 type, when appropriate, so that [u]int64_t
220   // ends up being defined in terms of the correct type.
221   if (TypeWidth == 64)
222     Ty = TI.getInt64Type();
223 
224   DefineType("__INT" + Twine(TypeWidth) + "_TYPE__", Ty, Builder);
225 
226   StringRef ConstSuffix(TargetInfo::getTypeConstantSuffix(Ty));
227   if (!ConstSuffix.empty())
228     Builder.defineMacro("__INT" + Twine(TypeWidth) + "_C_SUFFIX__",
229                         ConstSuffix);
230 }
231 
232 /// Get the value the ATOMIC_*_LOCK_FREE macro should have for a type with
233 /// the specified properties.
234 static const char *getLockFreeValue(unsigned TypeWidth, unsigned TypeAlign,
235                                     unsigned InlineWidth) {
236   // Fully-aligned, power-of-2 sizes no larger than the inline
237   // width will be inlined as lock-free operations.
238   if (TypeWidth == TypeAlign && (TypeWidth & (TypeWidth - 1)) == 0 &&
239       TypeWidth <= InlineWidth)
240     return "2"; // "always lock free"
241   // We cannot be certain what operations the lib calls might be
242   // able to implement as lock-free on future processors.
243   return "1"; // "sometimes lock free"
244 }
245 
246 /// \brief Add definitions required for a smooth interaction between
247 /// Objective-C++ automated reference counting and libstdc++ (4.2).
248 static void AddObjCXXARCLibstdcxxDefines(const LangOptions &LangOpts,
249                                          MacroBuilder &Builder) {
250   Builder.defineMacro("_GLIBCXX_PREDEFINED_OBJC_ARC_IS_SCALAR");
251 
252   std::string Result;
253   {
254     // Provide specializations for the __is_scalar type trait so that
255     // lifetime-qualified objects are not considered "scalar" types, which
256     // libstdc++ uses as an indicator of the presence of trivial copy, assign,
257     // default-construct, and destruct semantics (none of which hold for
258     // lifetime-qualified objects in ARC).
259     llvm::raw_string_ostream Out(Result);
260 
261     Out << "namespace std {\n"
262         << "\n"
263         << "struct __true_type;\n"
264         << "struct __false_type;\n"
265         << "\n";
266 
267     Out << "template<typename _Tp> struct __is_scalar;\n"
268         << "\n";
269 
270     Out << "template<typename _Tp>\n"
271         << "struct __is_scalar<__attribute__((objc_ownership(strong))) _Tp> {\n"
272         << "  enum { __value = 0 };\n"
273         << "  typedef __false_type __type;\n"
274         << "};\n"
275         << "\n";
276 
277     if (LangOpts.ObjCARCWeak) {
278       Out << "template<typename _Tp>\n"
279           << "struct __is_scalar<__attribute__((objc_ownership(weak))) _Tp> {\n"
280           << "  enum { __value = 0 };\n"
281           << "  typedef __false_type __type;\n"
282           << "};\n"
283           << "\n";
284     }
285 
286     Out << "template<typename _Tp>\n"
287         << "struct __is_scalar<__attribute__((objc_ownership(autoreleasing)))"
288         << " _Tp> {\n"
289         << "  enum { __value = 0 };\n"
290         << "  typedef __false_type __type;\n"
291         << "};\n"
292         << "\n";
293 
294     Out << "}\n";
295   }
296   Builder.append(Result);
297 }
298 
299 static void InitializeStandardPredefinedMacros(const TargetInfo &TI,
300                                                const LangOptions &LangOpts,
301                                                const FrontendOptions &FEOpts,
302                                                MacroBuilder &Builder) {
303   if (!LangOpts.MSVCCompat && !LangOpts.TraditionalCPP)
304     Builder.defineMacro("__STDC__");
305   if (LangOpts.Freestanding)
306     Builder.defineMacro("__STDC_HOSTED__", "0");
307   else
308     Builder.defineMacro("__STDC_HOSTED__");
309 
310   if (!LangOpts.CPlusPlus) {
311     if (LangOpts.C11)
312       Builder.defineMacro("__STDC_VERSION__", "201112L");
313     else if (LangOpts.C99)
314       Builder.defineMacro("__STDC_VERSION__", "199901L");
315     else if (!LangOpts.GNUMode && LangOpts.Digraphs)
316       Builder.defineMacro("__STDC_VERSION__", "199409L");
317   } else {
318     // FIXME: Use correct value for C++17.
319     if (LangOpts.CPlusPlus1z)
320       Builder.defineMacro("__cplusplus", "201406L");
321     // C++1y [cpp.predefined]p1:
322     //   The name __cplusplus is defined to the value 201402L when compiling a
323     //   C++ translation unit.
324     else if (LangOpts.CPlusPlus1y)
325       Builder.defineMacro("__cplusplus", "201402L");
326     // C++11 [cpp.predefined]p1:
327     //   The name __cplusplus is defined to the value 201103L when compiling a
328     //   C++ translation unit.
329     else if (LangOpts.CPlusPlus11)
330       Builder.defineMacro("__cplusplus", "201103L");
331     // C++03 [cpp.predefined]p1:
332     //   The name __cplusplus is defined to the value 199711L when compiling a
333     //   C++ translation unit.
334     else
335       Builder.defineMacro("__cplusplus", "199711L");
336   }
337 
338   // In C11 these are environment macros. In C++11 they are only defined
339   // as part of <cuchar>. To prevent breakage when mixing C and C++
340   // code, define these macros unconditionally. We can define them
341   // unconditionally, as Clang always uses UTF-16 and UTF-32 for 16-bit
342   // and 32-bit character literals.
343   Builder.defineMacro("__STDC_UTF_16__", "1");
344   Builder.defineMacro("__STDC_UTF_32__", "1");
345 
346   if (LangOpts.ObjC1)
347     Builder.defineMacro("__OBJC__");
348 
349   // Not "standard" per se, but available even with the -undef flag.
350   if (LangOpts.AsmPreprocessor)
351     Builder.defineMacro("__ASSEMBLER__");
352 }
353 
354 /// Initialize the predefined C++ language feature test macros defined in
355 /// ISO/IEC JTC1/SC22/WG21 (C++) SD-6: "SG10 Feature Test Recommendations".
356 static void InitializeCPlusPlusFeatureTestMacros(const LangOptions &LangOpts,
357                                                  MacroBuilder &Builder) {
358   // C++11 features.
359   if (LangOpts.CPlusPlus11) {
360     Builder.defineMacro("__cpp_unicode_characters", "200704");
361     Builder.defineMacro("__cpp_raw_strings", "200710");
362     Builder.defineMacro("__cpp_unicode_literals", "200710");
363     Builder.defineMacro("__cpp_user_defined_literals", "200809");
364     Builder.defineMacro("__cpp_lambdas", "200907");
365     Builder.defineMacro("__cpp_constexpr",
366                         LangOpts.CPlusPlus1y ? "201304" : "200704");
367     Builder.defineMacro("__cpp_static_assert", "200410");
368     Builder.defineMacro("__cpp_decltype", "200707");
369     Builder.defineMacro("__cpp_attributes", "200809");
370     Builder.defineMacro("__cpp_rvalue_references", "200610");
371     Builder.defineMacro("__cpp_variadic_templates", "200704");
372   }
373 
374   // C++14 features.
375   if (LangOpts.CPlusPlus1y) {
376     Builder.defineMacro("__cpp_binary_literals", "201304");
377     Builder.defineMacro("__cpp_init_captures", "201304");
378     Builder.defineMacro("__cpp_generic_lambdas", "201304");
379     Builder.defineMacro("__cpp_decltype_auto", "201304");
380     Builder.defineMacro("__cpp_return_type_deduction", "201304");
381     Builder.defineMacro("__cpp_aggregate_nsdmi", "201304");
382     Builder.defineMacro("__cpp_variable_templates", "201304");
383   }
384 }
385 
386 static void InitializePredefinedMacros(const TargetInfo &TI,
387                                        const LangOptions &LangOpts,
388                                        const FrontendOptions &FEOpts,
389                                        MacroBuilder &Builder) {
390   // Compiler version introspection macros.
391   Builder.defineMacro("__llvm__");  // LLVM Backend
392   Builder.defineMacro("__clang__"); // Clang Frontend
393 #define TOSTR2(X) #X
394 #define TOSTR(X) TOSTR2(X)
395   Builder.defineMacro("__clang_major__", TOSTR(CLANG_VERSION_MAJOR));
396   Builder.defineMacro("__clang_minor__", TOSTR(CLANG_VERSION_MINOR));
397 #ifdef CLANG_VERSION_PATCHLEVEL
398   Builder.defineMacro("__clang_patchlevel__", TOSTR(CLANG_VERSION_PATCHLEVEL));
399 #else
400   Builder.defineMacro("__clang_patchlevel__", "0");
401 #endif
402   Builder.defineMacro("__clang_version__",
403                       "\"" CLANG_VERSION_STRING " "
404                       + getClangFullRepositoryVersion() + "\"");
405 #undef TOSTR
406 #undef TOSTR2
407   if (!LangOpts.MSVCCompat) {
408     // Currently claim to be compatible with GCC 4.2.1-5621, but only if we're
409     // not compiling for MSVC compatibility
410     Builder.defineMacro("__GNUC_MINOR__", "2");
411     Builder.defineMacro("__GNUC_PATCHLEVEL__", "1");
412     Builder.defineMacro("__GNUC__", "4");
413     Builder.defineMacro("__GXX_ABI_VERSION", "1002");
414   }
415 
416   // Define macros for the C11 / C++11 memory orderings
417   Builder.defineMacro("__ATOMIC_RELAXED", "0");
418   Builder.defineMacro("__ATOMIC_CONSUME", "1");
419   Builder.defineMacro("__ATOMIC_ACQUIRE", "2");
420   Builder.defineMacro("__ATOMIC_RELEASE", "3");
421   Builder.defineMacro("__ATOMIC_ACQ_REL", "4");
422   Builder.defineMacro("__ATOMIC_SEQ_CST", "5");
423 
424   // Support for #pragma redefine_extname (Sun compatibility)
425   Builder.defineMacro("__PRAGMA_REDEFINE_EXTNAME", "1");
426 
427   // As sad as it is, enough software depends on the __VERSION__ for version
428   // checks that it is necessary to report 4.2.1 (the base GCC version we claim
429   // compatibility with) first.
430   Builder.defineMacro("__VERSION__", "\"4.2.1 Compatible " +
431                       Twine(getClangFullCPPVersion()) + "\"");
432 
433   // Initialize language-specific preprocessor defines.
434 
435   // Standard conforming mode?
436   if (!LangOpts.GNUMode)
437     Builder.defineMacro("__STRICT_ANSI__");
438 
439   if (LangOpts.CPlusPlus11)
440     Builder.defineMacro("__GXX_EXPERIMENTAL_CXX0X__");
441 
442   if (LangOpts.ObjC1) {
443     if (LangOpts.ObjCRuntime.isNonFragile()) {
444       Builder.defineMacro("__OBJC2__");
445 
446       if (LangOpts.ObjCExceptions)
447         Builder.defineMacro("OBJC_ZEROCOST_EXCEPTIONS");
448     }
449 
450     if (LangOpts.getGC() != LangOptions::NonGC)
451       Builder.defineMacro("__OBJC_GC__");
452 
453     if (LangOpts.ObjCRuntime.isNeXTFamily())
454       Builder.defineMacro("__NEXT_RUNTIME__");
455 
456     if (LangOpts.ObjCRuntime.getKind() == ObjCRuntime::ObjFW) {
457       VersionTuple tuple = LangOpts.ObjCRuntime.getVersion();
458 
459       unsigned minor = 0;
460       if (tuple.getMinor().hasValue())
461         minor = tuple.getMinor().getValue();
462 
463       unsigned subminor = 0;
464       if (tuple.getSubminor().hasValue())
465         subminor = tuple.getSubminor().getValue();
466 
467       Builder.defineMacro("__OBJFW_RUNTIME_ABI__",
468                           Twine(tuple.getMajor() * 10000 + minor * 100 +
469                                 subminor));
470     }
471 
472     Builder.defineMacro("IBOutlet", "__attribute__((iboutlet))");
473     Builder.defineMacro("IBOutletCollection(ClassName)",
474                         "__attribute__((iboutletcollection(ClassName)))");
475     Builder.defineMacro("IBAction", "void)__attribute__((ibaction)");
476   }
477 
478   if (LangOpts.CPlusPlus)
479     InitializeCPlusPlusFeatureTestMacros(LangOpts, Builder);
480 
481   // darwin_constant_cfstrings controls this. This is also dependent
482   // on other things like the runtime I believe.  This is set even for C code.
483   if (!LangOpts.NoConstantCFStrings)
484       Builder.defineMacro("__CONSTANT_CFSTRINGS__");
485 
486   if (LangOpts.ObjC2)
487     Builder.defineMacro("OBJC_NEW_PROPERTIES");
488 
489   if (LangOpts.PascalStrings)
490     Builder.defineMacro("__PASCAL_STRINGS__");
491 
492   if (LangOpts.Blocks) {
493     Builder.defineMacro("__block", "__attribute__((__blocks__(byref)))");
494     Builder.defineMacro("__BLOCKS__");
495   }
496 
497   if (!LangOpts.MSVCCompat && LangOpts.CXXExceptions)
498     Builder.defineMacro("__EXCEPTIONS");
499   if (LangOpts.RTTI)
500     Builder.defineMacro("__GXX_RTTI");
501   if (LangOpts.SjLjExceptions)
502     Builder.defineMacro("__USING_SJLJ_EXCEPTIONS__");
503 
504   if (LangOpts.Deprecated)
505     Builder.defineMacro("__DEPRECATED");
506 
507   if (LangOpts.CPlusPlus) {
508     Builder.defineMacro("__GNUG__", "4");
509     Builder.defineMacro("__GXX_WEAK__");
510     Builder.defineMacro("__private_extern__", "extern");
511   }
512 
513   if (LangOpts.MicrosoftExt) {
514     if (LangOpts.WChar) {
515       // wchar_t supported as a keyword.
516       Builder.defineMacro("_WCHAR_T_DEFINED");
517       Builder.defineMacro("_NATIVE_WCHAR_T_DEFINED");
518     }
519   }
520 
521   if (LangOpts.Optimize)
522     Builder.defineMacro("__OPTIMIZE__");
523   if (LangOpts.OptimizeSize)
524     Builder.defineMacro("__OPTIMIZE_SIZE__");
525 
526   if (LangOpts.FastMath)
527     Builder.defineMacro("__FAST_MATH__");
528 
529   // Initialize target-specific preprocessor defines.
530 
531   // __BYTE_ORDER__ was added in GCC 4.6. It's analogous
532   // to the macro __BYTE_ORDER (no trailing underscores)
533   // from glibc's <endian.h> header.
534   // We don't support the PDP-11 as a target, but include
535   // the define so it can still be compared against.
536   Builder.defineMacro("__ORDER_LITTLE_ENDIAN__", "1234");
537   Builder.defineMacro("__ORDER_BIG_ENDIAN__",    "4321");
538   Builder.defineMacro("__ORDER_PDP_ENDIAN__",    "3412");
539   if (TI.isBigEndian()) {
540     Builder.defineMacro("__BYTE_ORDER__", "__ORDER_BIG_ENDIAN__");
541     Builder.defineMacro("__BIG_ENDIAN__");
542   } else {
543     Builder.defineMacro("__BYTE_ORDER__", "__ORDER_LITTLE_ENDIAN__");
544     Builder.defineMacro("__LITTLE_ENDIAN__");
545   }
546 
547   if (TI.getPointerWidth(0) == 64 && TI.getLongWidth() == 64
548       && TI.getIntWidth() == 32) {
549     Builder.defineMacro("_LP64");
550     Builder.defineMacro("__LP64__");
551   }
552 
553   // Define type sizing macros based on the target properties.
554   assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far");
555   Builder.defineMacro("__CHAR_BIT__", "8");
556 
557   DefineTypeSize("__SCHAR_MAX__", TargetInfo::SignedChar, TI, Builder);
558   DefineTypeSize("__SHRT_MAX__", TargetInfo::SignedShort, TI, Builder);
559   DefineTypeSize("__INT_MAX__", TargetInfo::SignedInt, TI, Builder);
560   DefineTypeSize("__LONG_MAX__", TargetInfo::SignedLong, TI, Builder);
561   DefineTypeSize("__LONG_LONG_MAX__", TargetInfo::SignedLongLong, TI, Builder);
562   DefineTypeSize("__WCHAR_MAX__", TI.getWCharType(), TI, Builder);
563   DefineTypeSize("__INTMAX_MAX__", TI.getIntMaxType(), TI, Builder);
564   DefineTypeSize("__SIZE_MAX__", TI.getSizeType(), TI, Builder);
565 
566   DefineTypeSizeof("__SIZEOF_DOUBLE__", TI.getDoubleWidth(), TI, Builder);
567   DefineTypeSizeof("__SIZEOF_FLOAT__", TI.getFloatWidth(), TI, Builder);
568   DefineTypeSizeof("__SIZEOF_INT__", TI.getIntWidth(), TI, Builder);
569   DefineTypeSizeof("__SIZEOF_LONG__", TI.getLongWidth(), TI, Builder);
570   DefineTypeSizeof("__SIZEOF_LONG_DOUBLE__",TI.getLongDoubleWidth(),TI,Builder);
571   DefineTypeSizeof("__SIZEOF_LONG_LONG__", TI.getLongLongWidth(), TI, Builder);
572   DefineTypeSizeof("__SIZEOF_POINTER__", TI.getPointerWidth(0), TI, Builder);
573   DefineTypeSizeof("__SIZEOF_SHORT__", TI.getShortWidth(), TI, Builder);
574   DefineTypeSizeof("__SIZEOF_PTRDIFF_T__",
575                    TI.getTypeWidth(TI.getPtrDiffType(0)), TI, Builder);
576   DefineTypeSizeof("__SIZEOF_SIZE_T__",
577                    TI.getTypeWidth(TI.getSizeType()), TI, Builder);
578   DefineTypeSizeof("__SIZEOF_WCHAR_T__",
579                    TI.getTypeWidth(TI.getWCharType()), TI, Builder);
580   DefineTypeSizeof("__SIZEOF_WINT_T__",
581                    TI.getTypeWidth(TI.getWIntType()), TI, Builder);
582   if (TI.hasInt128Type())
583     DefineTypeSizeof("__SIZEOF_INT128__", 128, TI, Builder);
584 
585   DefineType("__INTMAX_TYPE__", TI.getIntMaxType(), Builder);
586   DefineType("__UINTMAX_TYPE__", TI.getUIntMaxType(), Builder);
587   DefineTypeWidth("__INTMAX_WIDTH__",  TI.getIntMaxType(), TI, Builder);
588   DefineType("__PTRDIFF_TYPE__", TI.getPtrDiffType(0), Builder);
589   DefineTypeWidth("__PTRDIFF_WIDTH__", TI.getPtrDiffType(0), TI, Builder);
590   DefineType("__INTPTR_TYPE__", TI.getIntPtrType(), Builder);
591   DefineTypeWidth("__INTPTR_WIDTH__", TI.getIntPtrType(), TI, Builder);
592   DefineType("__SIZE_TYPE__", TI.getSizeType(), Builder);
593   DefineTypeWidth("__SIZE_WIDTH__", TI.getSizeType(), TI, Builder);
594   DefineType("__WCHAR_TYPE__", TI.getWCharType(), Builder);
595   DefineTypeWidth("__WCHAR_WIDTH__", TI.getWCharType(), TI, Builder);
596   DefineType("__WINT_TYPE__", TI.getWIntType(), Builder);
597   DefineTypeWidth("__WINT_WIDTH__", TI.getWIntType(), TI, Builder);
598   DefineTypeWidth("__SIG_ATOMIC_WIDTH__", TI.getSigAtomicType(), TI, Builder);
599   DefineType("__CHAR16_TYPE__", TI.getChar16Type(), Builder);
600   DefineType("__CHAR32_TYPE__", TI.getChar32Type(), Builder);
601 
602   DefineFloatMacros(Builder, "FLT", &TI.getFloatFormat(), "F");
603   DefineFloatMacros(Builder, "DBL", &TI.getDoubleFormat(), "");
604   DefineFloatMacros(Builder, "LDBL", &TI.getLongDoubleFormat(), "L");
605 
606   // Define a __POINTER_WIDTH__ macro for stdint.h.
607   Builder.defineMacro("__POINTER_WIDTH__",
608                       Twine((int)TI.getPointerWidth(0)));
609 
610   if (!LangOpts.CharIsSigned)
611     Builder.defineMacro("__CHAR_UNSIGNED__");
612 
613   if (!TargetInfo::isTypeSigned(TI.getWCharType()))
614     Builder.defineMacro("__WCHAR_UNSIGNED__");
615 
616   if (!TargetInfo::isTypeSigned(TI.getWIntType()))
617     Builder.defineMacro("__WINT_UNSIGNED__");
618 
619   // Define exact-width integer types for stdint.h
620   Builder.defineMacro("__INT" + Twine(TI.getCharWidth()) + "_TYPE__",
621                       "char");
622 
623   if (TI.getShortWidth() > TI.getCharWidth())
624     DefineExactWidthIntType(TargetInfo::SignedShort, TI, Builder);
625 
626   if (TI.getIntWidth() > TI.getShortWidth())
627     DefineExactWidthIntType(TargetInfo::SignedInt, TI, Builder);
628 
629   if (TI.getLongWidth() > TI.getIntWidth())
630     DefineExactWidthIntType(TargetInfo::SignedLong, TI, Builder);
631 
632   if (TI.getLongLongWidth() > TI.getLongWidth())
633     DefineExactWidthIntType(TargetInfo::SignedLongLong, TI, Builder);
634 
635   if (const char *Prefix = TI.getUserLabelPrefix())
636     Builder.defineMacro("__USER_LABEL_PREFIX__", Prefix);
637 
638   if (LangOpts.FastMath || LangOpts.FiniteMathOnly)
639     Builder.defineMacro("__FINITE_MATH_ONLY__", "1");
640   else
641     Builder.defineMacro("__FINITE_MATH_ONLY__", "0");
642 
643   if (LangOpts.GNUInline)
644     Builder.defineMacro("__GNUC_GNU_INLINE__");
645   else
646     Builder.defineMacro("__GNUC_STDC_INLINE__");
647 
648   // The value written by __atomic_test_and_set.
649   // FIXME: This is target-dependent.
650   Builder.defineMacro("__GCC_ATOMIC_TEST_AND_SET_TRUEVAL", "1");
651 
652   // Used by libstdc++ to implement ATOMIC_<foo>_LOCK_FREE.
653   unsigned InlineWidthBits = TI.getMaxAtomicInlineWidth();
654 #define DEFINE_LOCK_FREE_MACRO(TYPE, Type) \
655   Builder.defineMacro("__GCC_ATOMIC_" #TYPE "_LOCK_FREE", \
656                       getLockFreeValue(TI.get##Type##Width(), \
657                                        TI.get##Type##Align(), \
658                                        InlineWidthBits));
659   DEFINE_LOCK_FREE_MACRO(BOOL, Bool);
660   DEFINE_LOCK_FREE_MACRO(CHAR, Char);
661   DEFINE_LOCK_FREE_MACRO(CHAR16_T, Char16);
662   DEFINE_LOCK_FREE_MACRO(CHAR32_T, Char32);
663   DEFINE_LOCK_FREE_MACRO(WCHAR_T, WChar);
664   DEFINE_LOCK_FREE_MACRO(SHORT, Short);
665   DEFINE_LOCK_FREE_MACRO(INT, Int);
666   DEFINE_LOCK_FREE_MACRO(LONG, Long);
667   DEFINE_LOCK_FREE_MACRO(LLONG, LongLong);
668   Builder.defineMacro("__GCC_ATOMIC_POINTER_LOCK_FREE",
669                       getLockFreeValue(TI.getPointerWidth(0),
670                                        TI.getPointerAlign(0),
671                                        InlineWidthBits));
672 #undef DEFINE_LOCK_FREE_MACRO
673 
674   if (LangOpts.NoInlineDefine)
675     Builder.defineMacro("__NO_INLINE__");
676 
677   if (unsigned PICLevel = LangOpts.PICLevel) {
678     Builder.defineMacro("__PIC__", Twine(PICLevel));
679     Builder.defineMacro("__pic__", Twine(PICLevel));
680   }
681   if (unsigned PIELevel = LangOpts.PIELevel) {
682     Builder.defineMacro("__PIE__", Twine(PIELevel));
683     Builder.defineMacro("__pie__", Twine(PIELevel));
684   }
685 
686   // Macros to control C99 numerics and <float.h>
687   Builder.defineMacro("__FLT_EVAL_METHOD__", Twine(TI.getFloatEvalMethod()));
688   Builder.defineMacro("__FLT_RADIX__", "2");
689   int Dig = PickFP(&TI.getLongDoubleFormat(), -1/*FIXME*/, 17, 21, 33, 36);
690   Builder.defineMacro("__DECIMAL_DIG__", Twine(Dig));
691 
692   if (LangOpts.getStackProtector() == LangOptions::SSPOn)
693     Builder.defineMacro("__SSP__");
694   else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
695     Builder.defineMacro("__SSP_STRONG__", "2");
696   else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
697     Builder.defineMacro("__SSP_ALL__", "3");
698 
699   if (FEOpts.ProgramAction == frontend::RewriteObjC)
700     Builder.defineMacro("__weak", "__attribute__((objc_gc(weak)))");
701 
702   // Define a macro that exists only when using the static analyzer.
703   if (FEOpts.ProgramAction == frontend::RunAnalysis)
704     Builder.defineMacro("__clang_analyzer__");
705 
706   if (LangOpts.FastRelaxedMath)
707     Builder.defineMacro("__FAST_RELAXED_MATH__");
708 
709   if (LangOpts.ObjCAutoRefCount) {
710     Builder.defineMacro("__weak", "__attribute__((objc_ownership(weak)))");
711     Builder.defineMacro("__strong", "__attribute__((objc_ownership(strong)))");
712     Builder.defineMacro("__autoreleasing",
713                         "__attribute__((objc_ownership(autoreleasing)))");
714     Builder.defineMacro("__unsafe_unretained",
715                         "__attribute__((objc_ownership(none)))");
716   }
717 
718   // OpenMP definition
719   if (LangOpts.OpenMP) {
720     // OpenMP 2.2:
721     //   In implementations that support a preprocessor, the _OPENMP
722     //   macro name is defined to have the decimal value yyyymm where
723     //   yyyy and mm are the year and the month designations of the
724     //   version of the OpenMP API that the implementation support.
725     Builder.defineMacro("_OPENMP", "201307");
726   }
727 
728   // Get other target #defines.
729   TI.getTargetDefines(LangOpts, Builder);
730 }
731 
732 // Initialize the remapping of files to alternative contents, e.g.,
733 // those specified through other files.
734 static void InitializeFileRemapping(DiagnosticsEngine &Diags,
735                                     SourceManager &SourceMgr,
736                                     FileManager &FileMgr,
737                                     const PreprocessorOptions &InitOpts) {
738   // Remap files in the source manager (with buffers).
739   for (PreprocessorOptions::const_remapped_file_buffer_iterator
740          Remap = InitOpts.remapped_file_buffer_begin(),
741          RemapEnd = InitOpts.remapped_file_buffer_end();
742        Remap != RemapEnd;
743        ++Remap) {
744     // Create the file entry for the file that we're mapping from.
745     const FileEntry *FromFile = FileMgr.getVirtualFile(Remap->first,
746                                                 Remap->second->getBufferSize(),
747                                                        0);
748     if (!FromFile) {
749       Diags.Report(diag::err_fe_remap_missing_from_file)
750         << Remap->first;
751       if (!InitOpts.RetainRemappedFileBuffers)
752         delete Remap->second;
753       continue;
754     }
755 
756     // Override the contents of the "from" file with the contents of
757     // the "to" file.
758     SourceMgr.overrideFileContents(FromFile, Remap->second,
759                                    InitOpts.RetainRemappedFileBuffers);
760   }
761 
762   // Remap files in the source manager (with other files).
763   for (PreprocessorOptions::const_remapped_file_iterator
764          Remap = InitOpts.remapped_file_begin(),
765          RemapEnd = InitOpts.remapped_file_end();
766        Remap != RemapEnd;
767        ++Remap) {
768     // Find the file that we're mapping to.
769     const FileEntry *ToFile = FileMgr.getFile(Remap->second);
770     if (!ToFile) {
771       Diags.Report(diag::err_fe_remap_missing_to_file)
772       << Remap->first << Remap->second;
773       continue;
774     }
775 
776     // Create the file entry for the file that we're mapping from.
777     const FileEntry *FromFile = FileMgr.getVirtualFile(Remap->first,
778                                                        ToFile->getSize(), 0);
779     if (!FromFile) {
780       Diags.Report(diag::err_fe_remap_missing_from_file)
781       << Remap->first;
782       continue;
783     }
784 
785     // Override the contents of the "from" file with the contents of
786     // the "to" file.
787     SourceMgr.overrideFileContents(FromFile, ToFile);
788   }
789 
790   SourceMgr.setOverridenFilesKeepOriginalName(
791                                         InitOpts.RemappedFilesKeepOriginalName);
792 }
793 
794 /// InitializePreprocessor - Initialize the preprocessor getting it and the
795 /// environment ready to process a single file. This returns true on error.
796 ///
797 void clang::InitializePreprocessor(Preprocessor &PP,
798                                    const PreprocessorOptions &InitOpts,
799                                    const HeaderSearchOptions &HSOpts,
800                                    const FrontendOptions &FEOpts) {
801   const LangOptions &LangOpts = PP.getLangOpts();
802   std::string PredefineBuffer;
803   PredefineBuffer.reserve(4080);
804   llvm::raw_string_ostream Predefines(PredefineBuffer);
805   MacroBuilder Builder(Predefines);
806 
807   InitializeFileRemapping(PP.getDiagnostics(), PP.getSourceManager(),
808                           PP.getFileManager(), InitOpts);
809 
810   // Emit line markers for various builtin sections of the file.  We don't do
811   // this in asm preprocessor mode, because "# 4" is not a line marker directive
812   // in this mode.
813   if (!PP.getLangOpts().AsmPreprocessor)
814     Builder.append("# 1 \"<built-in>\" 3");
815 
816   // Install things like __POWERPC__, __GNUC__, etc into the macro table.
817   if (InitOpts.UsePredefines) {
818     InitializePredefinedMacros(PP.getTargetInfo(), LangOpts, FEOpts, Builder);
819 
820     // Install definitions to make Objective-C++ ARC work well with various
821     // C++ Standard Library implementations.
822     if (LangOpts.ObjC1 && LangOpts.CPlusPlus && LangOpts.ObjCAutoRefCount) {
823       switch (InitOpts.ObjCXXARCStandardLibrary) {
824       case ARCXX_nolib:
825         case ARCXX_libcxx:
826         break;
827 
828       case ARCXX_libstdcxx:
829         AddObjCXXARCLibstdcxxDefines(LangOpts, Builder);
830         break;
831       }
832     }
833   }
834 
835   // Even with predefines off, some macros are still predefined.
836   // These should all be defined in the preprocessor according to the
837   // current language configuration.
838   InitializeStandardPredefinedMacros(PP.getTargetInfo(), PP.getLangOpts(),
839                                      FEOpts, Builder);
840 
841   // Add on the predefines from the driver.  Wrap in a #line directive to report
842   // that they come from the command line.
843   if (!PP.getLangOpts().AsmPreprocessor)
844     Builder.append("# 1 \"<command line>\" 1");
845 
846   // Process #define's and #undef's in the order they are given.
847   for (unsigned i = 0, e = InitOpts.Macros.size(); i != e; ++i) {
848     if (InitOpts.Macros[i].second)  // isUndef
849       Builder.undefineMacro(InitOpts.Macros[i].first);
850     else
851       DefineBuiltinMacro(Builder, InitOpts.Macros[i].first,
852                          PP.getDiagnostics());
853   }
854 
855   // If -imacros are specified, include them now.  These are processed before
856   // any -include directives.
857   for (unsigned i = 0, e = InitOpts.MacroIncludes.size(); i != e; ++i)
858     AddImplicitIncludeMacros(Builder, InitOpts.MacroIncludes[i],
859                              PP.getFileManager());
860 
861   // Process -include-pch/-include-pth directives.
862   if (!InitOpts.ImplicitPCHInclude.empty())
863     AddImplicitIncludePCH(Builder, PP, InitOpts.ImplicitPCHInclude);
864   if (!InitOpts.ImplicitPTHInclude.empty())
865     AddImplicitIncludePTH(Builder, PP, InitOpts.ImplicitPTHInclude);
866 
867   // Process -include directives.
868   for (unsigned i = 0, e = InitOpts.Includes.size(); i != e; ++i) {
869     const std::string &Path = InitOpts.Includes[i];
870     AddImplicitInclude(Builder, Path, PP.getFileManager());
871   }
872 
873   // Exit the command line and go back to <built-in> (2 is LC_LEAVE).
874   if (!PP.getLangOpts().AsmPreprocessor)
875     Builder.append("# 1 \"<built-in>\" 2");
876 
877   // Instruct the preprocessor to skip the preamble.
878   PP.setSkipMainFilePreamble(InitOpts.PrecompiledPreambleBytes.first,
879                              InitOpts.PrecompiledPreambleBytes.second);
880 
881   // Copy PredefinedBuffer into the Preprocessor.
882   PP.setPredefines(Predefines.str());
883 
884   // Initialize the header search object.
885   ApplyHeaderSearchOptions(PP.getHeaderSearchInfo(), HSOpts,
886                            PP.getLangOpts(),
887                            PP.getTargetInfo().getTriple());
888 }
889