InitPreprocessor.cpp 31 KB

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