InitPreprocessor.cpp 36 KB

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