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