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