InitPreprocessor.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194
  1. //===--- InitPreprocessor.cpp - PP initialization code. ---------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the clang::InitializePreprocessor function.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Basic/FileManager.h"
  13. #include "clang/Basic/MacroBuilder.h"
  14. #include "clang/Basic/SourceManager.h"
  15. #include "clang/Basic/SyncScope.h"
  16. #include "clang/Basic/TargetInfo.h"
  17. #include "clang/Basic/Version.h"
  18. #include "clang/Frontend/FrontendDiagnostic.h"
  19. #include "clang/Frontend/FrontendOptions.h"
  20. #include "clang/Frontend/Utils.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. using namespace clang;
  27. static bool MacroBodyEndsInBackslash(StringRef MacroBody) {
  28. while (!MacroBody.empty() && isWhitespace(MacroBody.back()))
  29. MacroBody = MacroBody.drop_back();
  30. return !MacroBody.empty() && MacroBody.back() == '\\';
  31. }
  32. // Append a #define line to Buf for Macro. Macro should be of the form XXX,
  33. // in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
  34. // "#define XXX Y z W". To get a #define with no value, use "XXX=".
  35. static void DefineBuiltinMacro(MacroBuilder &Builder, StringRef Macro,
  36. DiagnosticsEngine &Diags) {
  37. std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
  38. StringRef MacroName = MacroPair.first;
  39. StringRef MacroBody = MacroPair.second;
  40. if (MacroName.size() != Macro.size()) {
  41. // Per GCC -D semantics, the macro ends at \n if it exists.
  42. StringRef::size_type End = MacroBody.find_first_of("\n\r");
  43. if (End != StringRef::npos)
  44. Diags.Report(diag::warn_fe_macro_contains_embedded_newline)
  45. << MacroName;
  46. MacroBody = MacroBody.substr(0, End);
  47. // We handle macro bodies which end in a backslash by appending an extra
  48. // backslash+newline. This makes sure we don't accidentally treat the
  49. // backslash as a line continuation marker.
  50. if (MacroBodyEndsInBackslash(MacroBody))
  51. Builder.defineMacro(MacroName, Twine(MacroBody) + "\\\n");
  52. else
  53. Builder.defineMacro(MacroName, MacroBody);
  54. } else {
  55. // Push "macroname 1".
  56. Builder.defineMacro(Macro);
  57. }
  58. }
  59. /// AddImplicitInclude - Add an implicit \#include of the specified file to the
  60. /// predefines buffer.
  61. /// As these includes are generated by -include arguments the header search
  62. /// logic is going to search relatively to the current working directory.
  63. static void AddImplicitInclude(MacroBuilder &Builder, StringRef File) {
  64. Builder.append(Twine("#include \"") + File + "\"");
  65. }
  66. static void AddImplicitIncludeMacros(MacroBuilder &Builder, StringRef File) {
  67. Builder.append(Twine("#__include_macros \"") + File + "\"");
  68. // Marker token to stop the __include_macros fetch loop.
  69. Builder.append("##"); // ##?
  70. }
  71. /// Add an implicit \#include using the original file used to generate
  72. /// a PCH file.
  73. static void AddImplicitIncludePCH(MacroBuilder &Builder, Preprocessor &PP,
  74. const PCHContainerReader &PCHContainerRdr,
  75. StringRef ImplicitIncludePCH) {
  76. std::string OriginalFile =
  77. ASTReader::getOriginalSourceFile(ImplicitIncludePCH, PP.getFileManager(),
  78. PCHContainerRdr, PP.getDiagnostics());
  79. if (OriginalFile.empty())
  80. return;
  81. AddImplicitInclude(Builder, OriginalFile);
  82. }
  83. /// PickFP - This is used to pick a value based on the FP semantics of the
  84. /// specified FP model.
  85. template <typename T>
  86. static T PickFP(const llvm::fltSemantics *Sem, T IEEEHalfVal, T IEEESingleVal,
  87. T IEEEDoubleVal, T X87DoubleExtendedVal, T PPCDoubleDoubleVal,
  88. T IEEEQuadVal) {
  89. if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEhalf())
  90. return IEEEHalfVal;
  91. if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEsingle())
  92. return IEEESingleVal;
  93. if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEdouble())
  94. return IEEEDoubleVal;
  95. if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::x87DoubleExtended())
  96. return X87DoubleExtendedVal;
  97. if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::PPCDoubleDouble())
  98. return PPCDoubleDoubleVal;
  99. assert(Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEquad());
  100. return IEEEQuadVal;
  101. }
  102. static void DefineFloatMacros(MacroBuilder &Builder, StringRef Prefix,
  103. const llvm::fltSemantics *Sem, StringRef Ext) {
  104. const char *DenormMin, *Epsilon, *Max, *Min;
  105. DenormMin = PickFP(Sem, "5.9604644775390625e-8", "1.40129846e-45",
  106. "4.9406564584124654e-324", "3.64519953188247460253e-4951",
  107. "4.94065645841246544176568792868221e-324",
  108. "6.47517511943802511092443895822764655e-4966");
  109. int Digits = PickFP(Sem, 3, 6, 15, 18, 31, 33);
  110. int DecimalDigits = PickFP(Sem, 5, 9, 17, 21, 33, 36);
  111. Epsilon = PickFP(Sem, "9.765625e-4", "1.19209290e-7",
  112. "2.2204460492503131e-16", "1.08420217248550443401e-19",
  113. "4.94065645841246544176568792868221e-324",
  114. "1.92592994438723585305597794258492732e-34");
  115. int MantissaDigits = PickFP(Sem, 11, 24, 53, 64, 106, 113);
  116. int Min10Exp = PickFP(Sem, -4, -37, -307, -4931, -291, -4931);
  117. int Max10Exp = PickFP(Sem, 4, 38, 308, 4932, 308, 4932);
  118. int MinExp = PickFP(Sem, -13, -125, -1021, -16381, -968, -16381);
  119. int MaxExp = PickFP(Sem, 16, 128, 1024, 16384, 1024, 16384);
  120. Min = PickFP(Sem, "6.103515625e-5", "1.17549435e-38", "2.2250738585072014e-308",
  121. "3.36210314311209350626e-4932",
  122. "2.00416836000897277799610805135016e-292",
  123. "3.36210314311209350626267781732175260e-4932");
  124. Max = PickFP(Sem, "6.5504e+4", "3.40282347e+38", "1.7976931348623157e+308",
  125. "1.18973149535723176502e+4932",
  126. "1.79769313486231580793728971405301e+308",
  127. "1.18973149535723176508575932662800702e+4932");
  128. SmallString<32> DefPrefix;
  129. DefPrefix = "__";
  130. DefPrefix += Prefix;
  131. DefPrefix += "_";
  132. Builder.defineMacro(DefPrefix + "DENORM_MIN__", Twine(DenormMin)+Ext);
  133. Builder.defineMacro(DefPrefix + "HAS_DENORM__");
  134. Builder.defineMacro(DefPrefix + "DIG__", Twine(Digits));
  135. Builder.defineMacro(DefPrefix + "DECIMAL_DIG__", Twine(DecimalDigits));
  136. Builder.defineMacro(DefPrefix + "EPSILON__", Twine(Epsilon)+Ext);
  137. Builder.defineMacro(DefPrefix + "HAS_INFINITY__");
  138. Builder.defineMacro(DefPrefix + "HAS_QUIET_NAN__");
  139. Builder.defineMacro(DefPrefix + "MANT_DIG__", Twine(MantissaDigits));
  140. Builder.defineMacro(DefPrefix + "MAX_10_EXP__", Twine(Max10Exp));
  141. Builder.defineMacro(DefPrefix + "MAX_EXP__", Twine(MaxExp));
  142. Builder.defineMacro(DefPrefix + "MAX__", Twine(Max)+Ext);
  143. Builder.defineMacro(DefPrefix + "MIN_10_EXP__","("+Twine(Min10Exp)+")");
  144. Builder.defineMacro(DefPrefix + "MIN_EXP__", "("+Twine(MinExp)+")");
  145. Builder.defineMacro(DefPrefix + "MIN__", Twine(Min)+Ext);
  146. }
  147. /// DefineTypeSize - Emit a macro to the predefines buffer that declares a macro
  148. /// named MacroName with the max value for a type with width 'TypeWidth' a
  149. /// signedness of 'isSigned' and with a value suffix of 'ValSuffix' (e.g. LL).
  150. static void DefineTypeSize(const Twine &MacroName, unsigned TypeWidth,
  151. StringRef ValSuffix, bool isSigned,
  152. MacroBuilder &Builder) {
  153. llvm::APInt MaxVal = isSigned ? llvm::APInt::getSignedMaxValue(TypeWidth)
  154. : llvm::APInt::getMaxValue(TypeWidth);
  155. Builder.defineMacro(MacroName, MaxVal.toString(10, isSigned) + ValSuffix);
  156. }
  157. /// DefineTypeSize - An overloaded helper that uses TargetInfo to determine
  158. /// the width, suffix, and signedness of the given type
  159. static void DefineTypeSize(const Twine &MacroName, TargetInfo::IntType Ty,
  160. const TargetInfo &TI, MacroBuilder &Builder) {
  161. DefineTypeSize(MacroName, TI.getTypeWidth(Ty), TI.getTypeConstantSuffix(Ty),
  162. TI.isTypeSigned(Ty), Builder);
  163. }
  164. static void DefineFmt(const Twine &Prefix, TargetInfo::IntType Ty,
  165. const TargetInfo &TI, MacroBuilder &Builder) {
  166. bool IsSigned = TI.isTypeSigned(Ty);
  167. StringRef FmtModifier = TI.getTypeFormatModifier(Ty);
  168. for (const char *Fmt = IsSigned ? "di" : "ouxX"; *Fmt; ++Fmt) {
  169. Builder.defineMacro(Prefix + "_FMT" + Twine(*Fmt) + "__",
  170. Twine("\"") + FmtModifier + Twine(*Fmt) + "\"");
  171. }
  172. }
  173. static void DefineType(const Twine &MacroName, TargetInfo::IntType Ty,
  174. MacroBuilder &Builder) {
  175. Builder.defineMacro(MacroName, TargetInfo::getTypeName(Ty));
  176. }
  177. static void DefineTypeWidth(StringRef MacroName, TargetInfo::IntType Ty,
  178. const TargetInfo &TI, MacroBuilder &Builder) {
  179. Builder.defineMacro(MacroName, Twine(TI.getTypeWidth(Ty)));
  180. }
  181. static void DefineTypeSizeof(StringRef MacroName, unsigned BitWidth,
  182. const TargetInfo &TI, MacroBuilder &Builder) {
  183. Builder.defineMacro(MacroName,
  184. Twine(BitWidth / TI.getCharWidth()));
  185. }
  186. static void DefineExactWidthIntType(TargetInfo::IntType Ty,
  187. const TargetInfo &TI,
  188. MacroBuilder &Builder) {
  189. int TypeWidth = TI.getTypeWidth(Ty);
  190. bool IsSigned = TI.isTypeSigned(Ty);
  191. // Use the target specified int64 type, when appropriate, so that [u]int64_t
  192. // ends up being defined in terms of the correct type.
  193. if (TypeWidth == 64)
  194. Ty = IsSigned ? TI.getInt64Type() : TI.getUInt64Type();
  195. const char *Prefix = IsSigned ? "__INT" : "__UINT";
  196. DefineType(Prefix + Twine(TypeWidth) + "_TYPE__", Ty, Builder);
  197. DefineFmt(Prefix + Twine(TypeWidth), Ty, TI, Builder);
  198. StringRef ConstSuffix(TI.getTypeConstantSuffix(Ty));
  199. Builder.defineMacro(Prefix + Twine(TypeWidth) + "_C_SUFFIX__", ConstSuffix);
  200. }
  201. static void DefineExactWidthIntTypeSize(TargetInfo::IntType Ty,
  202. const TargetInfo &TI,
  203. MacroBuilder &Builder) {
  204. int TypeWidth = TI.getTypeWidth(Ty);
  205. bool IsSigned = TI.isTypeSigned(Ty);
  206. // Use the target specified int64 type, when appropriate, so that [u]int64_t
  207. // ends up being defined in terms of the correct type.
  208. if (TypeWidth == 64)
  209. Ty = IsSigned ? TI.getInt64Type() : TI.getUInt64Type();
  210. const char *Prefix = IsSigned ? "__INT" : "__UINT";
  211. DefineTypeSize(Prefix + Twine(TypeWidth) + "_MAX__", Ty, TI, Builder);
  212. }
  213. static void DefineLeastWidthIntType(unsigned TypeWidth, bool IsSigned,
  214. const TargetInfo &TI,
  215. MacroBuilder &Builder) {
  216. TargetInfo::IntType Ty = TI.getLeastIntTypeByWidth(TypeWidth, IsSigned);
  217. if (Ty == TargetInfo::NoInt)
  218. return;
  219. const char *Prefix = IsSigned ? "__INT_LEAST" : "__UINT_LEAST";
  220. DefineType(Prefix + Twine(TypeWidth) + "_TYPE__", Ty, Builder);
  221. DefineTypeSize(Prefix + Twine(TypeWidth) + "_MAX__", Ty, TI, Builder);
  222. DefineFmt(Prefix + Twine(TypeWidth), Ty, TI, Builder);
  223. }
  224. static void DefineFastIntType(unsigned TypeWidth, bool IsSigned,
  225. const TargetInfo &TI, MacroBuilder &Builder) {
  226. // stdint.h currently defines the fast int types as equivalent to the least
  227. // types.
  228. TargetInfo::IntType Ty = TI.getLeastIntTypeByWidth(TypeWidth, IsSigned);
  229. if (Ty == TargetInfo::NoInt)
  230. return;
  231. const char *Prefix = IsSigned ? "__INT_FAST" : "__UINT_FAST";
  232. DefineType(Prefix + Twine(TypeWidth) + "_TYPE__", Ty, Builder);
  233. DefineTypeSize(Prefix + Twine(TypeWidth) + "_MAX__", Ty, TI, Builder);
  234. DefineFmt(Prefix + Twine(TypeWidth), Ty, TI, Builder);
  235. }
  236. /// Get the value the ATOMIC_*_LOCK_FREE macro should have for a type with
  237. /// the specified properties.
  238. static const char *getLockFreeValue(unsigned TypeWidth, unsigned TypeAlign,
  239. unsigned InlineWidth) {
  240. // Fully-aligned, power-of-2 sizes no larger than the inline
  241. // width will be inlined as lock-free operations.
  242. if (TypeWidth == TypeAlign && (TypeWidth & (TypeWidth - 1)) == 0 &&
  243. TypeWidth <= InlineWidth)
  244. return "2"; // "always lock free"
  245. // We cannot be certain what operations the lib calls might be
  246. // able to implement as lock-free on future processors.
  247. return "1"; // "sometimes lock free"
  248. }
  249. /// Add definitions required for a smooth interaction between
  250. /// Objective-C++ automated reference counting and libstdc++ (4.2).
  251. static void AddObjCXXARCLibstdcxxDefines(const LangOptions &LangOpts,
  252. MacroBuilder &Builder) {
  253. Builder.defineMacro("_GLIBCXX_PREDEFINED_OBJC_ARC_IS_SCALAR");
  254. std::string Result;
  255. {
  256. // Provide specializations for the __is_scalar type trait so that
  257. // lifetime-qualified objects are not considered "scalar" types, which
  258. // libstdc++ uses as an indicator of the presence of trivial copy, assign,
  259. // default-construct, and destruct semantics (none of which hold for
  260. // lifetime-qualified objects in ARC).
  261. llvm::raw_string_ostream Out(Result);
  262. Out << "namespace std {\n"
  263. << "\n"
  264. << "struct __true_type;\n"
  265. << "struct __false_type;\n"
  266. << "\n";
  267. Out << "template<typename _Tp> struct __is_scalar;\n"
  268. << "\n";
  269. if (LangOpts.ObjCAutoRefCount) {
  270. Out << "template<typename _Tp>\n"
  271. << "struct __is_scalar<__attribute__((objc_ownership(strong))) _Tp> {\n"
  272. << " enum { __value = 0 };\n"
  273. << " typedef __false_type __type;\n"
  274. << "};\n"
  275. << "\n";
  276. }
  277. if (LangOpts.ObjCWeak) {
  278. Out << "template<typename _Tp>\n"
  279. << "struct __is_scalar<__attribute__((objc_ownership(weak))) _Tp> {\n"
  280. << " enum { __value = 0 };\n"
  281. << " typedef __false_type __type;\n"
  282. << "};\n"
  283. << "\n";
  284. }
  285. if (LangOpts.ObjCAutoRefCount) {
  286. Out << "template<typename _Tp>\n"
  287. << "struct __is_scalar<__attribute__((objc_ownership(autoreleasing)))"
  288. << " _Tp> {\n"
  289. << " enum { __value = 0 };\n"
  290. << " typedef __false_type __type;\n"
  291. << "};\n"
  292. << "\n";
  293. }
  294. Out << "}\n";
  295. }
  296. Builder.append(Result);
  297. }
  298. static void InitializeStandardPredefinedMacros(const TargetInfo &TI,
  299. const LangOptions &LangOpts,
  300. const FrontendOptions &FEOpts,
  301. MacroBuilder &Builder) {
  302. if (!LangOpts.MSVCCompat && !LangOpts.TraditionalCPP)
  303. Builder.defineMacro("__STDC__");
  304. if (LangOpts.Freestanding)
  305. Builder.defineMacro("__STDC_HOSTED__", "0");
  306. else
  307. Builder.defineMacro("__STDC_HOSTED__");
  308. if (!LangOpts.CPlusPlus) {
  309. if (LangOpts.C17)
  310. Builder.defineMacro("__STDC_VERSION__", "201710L");
  311. else if (LangOpts.C11)
  312. Builder.defineMacro("__STDC_VERSION__", "201112L");
  313. else if (LangOpts.C99)
  314. Builder.defineMacro("__STDC_VERSION__", "199901L");
  315. else if (!LangOpts.GNUMode && LangOpts.Digraphs)
  316. Builder.defineMacro("__STDC_VERSION__", "199409L");
  317. } else {
  318. // FIXME: Use correct value for C++20.
  319. if (LangOpts.CPlusPlus2a)
  320. Builder.defineMacro("__cplusplus", "201707L");
  321. // C++17 [cpp.predefined]p1:
  322. // The name __cplusplus is defined to the value 201703L when compiling a
  323. // C++ translation unit.
  324. else if (LangOpts.CPlusPlus17)
  325. Builder.defineMacro("__cplusplus", "201703L");
  326. // C++1y [cpp.predefined]p1:
  327. // The name __cplusplus is defined to the value 201402L when compiling a
  328. // C++ translation unit.
  329. else if (LangOpts.CPlusPlus14)
  330. Builder.defineMacro("__cplusplus", "201402L");
  331. // C++11 [cpp.predefined]p1:
  332. // The name __cplusplus is defined to the value 201103L when compiling a
  333. // C++ translation unit.
  334. else if (LangOpts.CPlusPlus11)
  335. Builder.defineMacro("__cplusplus", "201103L");
  336. // C++03 [cpp.predefined]p1:
  337. // The name __cplusplus is defined to the value 199711L when compiling a
  338. // C++ translation unit.
  339. else
  340. Builder.defineMacro("__cplusplus", "199711L");
  341. // C++1z [cpp.predefined]p1:
  342. // An integer literal of type std::size_t whose value is the alignment
  343. // guaranteed by a call to operator new(std::size_t)
  344. //
  345. // We provide this in all language modes, since it seems generally useful.
  346. Builder.defineMacro("__STDCPP_DEFAULT_NEW_ALIGNMENT__",
  347. Twine(TI.getNewAlign() / TI.getCharWidth()) +
  348. TI.getTypeConstantSuffix(TI.getSizeType()));
  349. }
  350. // In C11 these are environment macros. In C++11 they are only defined
  351. // as part of <cuchar>. To prevent breakage when mixing C and C++
  352. // code, define these macros unconditionally. We can define them
  353. // unconditionally, as Clang always uses UTF-16 and UTF-32 for 16-bit
  354. // and 32-bit character literals.
  355. Builder.defineMacro("__STDC_UTF_16__", "1");
  356. Builder.defineMacro("__STDC_UTF_32__", "1");
  357. if (LangOpts.ObjC)
  358. Builder.defineMacro("__OBJC__");
  359. // OpenCL v1.0/1.1 s6.9, v1.2/2.0 s6.10: Preprocessor Directives and Macros.
  360. if (LangOpts.OpenCL) {
  361. if (LangOpts.CPlusPlus) {
  362. if (LangOpts.OpenCLCPlusPlusVersion == 100)
  363. Builder.defineMacro("__OPENCL_CPP_VERSION__", "100");
  364. else
  365. llvm_unreachable("Unsupported C++ version for OpenCL");
  366. Builder.defineMacro("__CL_CPP_VERSION_1_0__", "100");
  367. } else {
  368. // OpenCL v1.0 and v1.1 do not have a predefined macro to indicate the
  369. // language standard with which the program is compiled. __OPENCL_VERSION__
  370. // is for the OpenCL version supported by the OpenCL device, which is not
  371. // necessarily the language standard with which the program is compiled.
  372. // A shared OpenCL header file requires a macro to indicate the language
  373. // standard. As a workaround, __OPENCL_C_VERSION__ is defined for
  374. // OpenCL v1.0 and v1.1.
  375. switch (LangOpts.OpenCLVersion) {
  376. case 100:
  377. Builder.defineMacro("__OPENCL_C_VERSION__", "100");
  378. break;
  379. case 110:
  380. Builder.defineMacro("__OPENCL_C_VERSION__", "110");
  381. break;
  382. case 120:
  383. Builder.defineMacro("__OPENCL_C_VERSION__", "120");
  384. break;
  385. case 200:
  386. Builder.defineMacro("__OPENCL_C_VERSION__", "200");
  387. break;
  388. default:
  389. llvm_unreachable("Unsupported OpenCL version");
  390. }
  391. }
  392. Builder.defineMacro("CL_VERSION_1_0", "100");
  393. Builder.defineMacro("CL_VERSION_1_1", "110");
  394. Builder.defineMacro("CL_VERSION_1_2", "120");
  395. Builder.defineMacro("CL_VERSION_2_0", "200");
  396. if (TI.isLittleEndian())
  397. Builder.defineMacro("__ENDIAN_LITTLE__");
  398. if (LangOpts.FastRelaxedMath)
  399. Builder.defineMacro("__FAST_RELAXED_MATH__");
  400. }
  401. // Not "standard" per se, but available even with the -undef flag.
  402. if (LangOpts.AsmPreprocessor)
  403. Builder.defineMacro("__ASSEMBLER__");
  404. if (LangOpts.CUDA && !LangOpts.HIP)
  405. Builder.defineMacro("__CUDA__");
  406. if (LangOpts.HIP) {
  407. Builder.defineMacro("__HIP__");
  408. Builder.defineMacro("__HIPCC__");
  409. if (LangOpts.CUDAIsDevice)
  410. Builder.defineMacro("__HIP_DEVICE_COMPILE__");
  411. }
  412. }
  413. /// Initialize the predefined C++ language feature test macros defined in
  414. /// ISO/IEC JTC1/SC22/WG21 (C++) SD-6: "SG10 Feature Test Recommendations".
  415. static void InitializeCPlusPlusFeatureTestMacros(const LangOptions &LangOpts,
  416. MacroBuilder &Builder) {
  417. // C++98 features.
  418. if (LangOpts.RTTI)
  419. Builder.defineMacro("__cpp_rtti", "199711L");
  420. if (LangOpts.CXXExceptions)
  421. Builder.defineMacro("__cpp_exceptions", "199711L");
  422. // C++11 features.
  423. if (LangOpts.CPlusPlus11) {
  424. Builder.defineMacro("__cpp_unicode_characters", "200704L");
  425. Builder.defineMacro("__cpp_raw_strings", "200710L");
  426. Builder.defineMacro("__cpp_unicode_literals", "200710L");
  427. Builder.defineMacro("__cpp_user_defined_literals", "200809L");
  428. Builder.defineMacro("__cpp_lambdas", "200907L");
  429. Builder.defineMacro("__cpp_constexpr",
  430. LangOpts.CPlusPlus2a ? "201907L" :
  431. LangOpts.CPlusPlus17 ? "201603L" :
  432. LangOpts.CPlusPlus14 ? "201304L" : "200704");
  433. Builder.defineMacro("__cpp_range_based_for",
  434. LangOpts.CPlusPlus17 ? "201603L" : "200907");
  435. Builder.defineMacro("__cpp_static_assert",
  436. LangOpts.CPlusPlus17 ? "201411L" : "200410");
  437. Builder.defineMacro("__cpp_decltype", "200707L");
  438. Builder.defineMacro("__cpp_attributes", "200809L");
  439. Builder.defineMacro("__cpp_rvalue_references", "200610L");
  440. Builder.defineMacro("__cpp_variadic_templates", "200704L");
  441. Builder.defineMacro("__cpp_initializer_lists", "200806L");
  442. Builder.defineMacro("__cpp_delegating_constructors", "200604L");
  443. Builder.defineMacro("__cpp_nsdmi", "200809L");
  444. Builder.defineMacro("__cpp_inheriting_constructors", "201511L");
  445. Builder.defineMacro("__cpp_ref_qualifiers", "200710L");
  446. Builder.defineMacro("__cpp_alias_templates", "200704L");
  447. }
  448. if (LangOpts.ThreadsafeStatics)
  449. Builder.defineMacro("__cpp_threadsafe_static_init", "200806L");
  450. // C++14 features.
  451. if (LangOpts.CPlusPlus14) {
  452. Builder.defineMacro("__cpp_binary_literals", "201304L");
  453. Builder.defineMacro("__cpp_digit_separators", "201309L");
  454. Builder.defineMacro("__cpp_init_captures", "201304L");
  455. Builder.defineMacro("__cpp_generic_lambdas", "201304L");
  456. Builder.defineMacro("__cpp_decltype_auto", "201304L");
  457. Builder.defineMacro("__cpp_return_type_deduction", "201304L");
  458. Builder.defineMacro("__cpp_aggregate_nsdmi", "201304L");
  459. Builder.defineMacro("__cpp_variable_templates", "201304L");
  460. }
  461. if (LangOpts.SizedDeallocation)
  462. Builder.defineMacro("__cpp_sized_deallocation", "201309L");
  463. // C++17 features.
  464. if (LangOpts.CPlusPlus17) {
  465. Builder.defineMacro("__cpp_hex_float", "201603L");
  466. Builder.defineMacro("__cpp_inline_variables", "201606L");
  467. Builder.defineMacro("__cpp_noexcept_function_type", "201510L");
  468. Builder.defineMacro("__cpp_capture_star_this", "201603L");
  469. Builder.defineMacro("__cpp_if_constexpr", "201606L");
  470. Builder.defineMacro("__cpp_deduction_guides", "201703L");
  471. Builder.defineMacro("__cpp_template_auto", "201606L"); // (old name)
  472. Builder.defineMacro("__cpp_namespace_attributes", "201411L");
  473. Builder.defineMacro("__cpp_enumerator_attributes", "201411L");
  474. Builder.defineMacro("__cpp_nested_namespace_definitions", "201411L");
  475. Builder.defineMacro("__cpp_variadic_using", "201611L");
  476. Builder.defineMacro("__cpp_aggregate_bases", "201603L");
  477. Builder.defineMacro("__cpp_structured_bindings", "201606L");
  478. Builder.defineMacro("__cpp_nontype_template_args", "201411L");
  479. Builder.defineMacro("__cpp_fold_expressions", "201603L");
  480. Builder.defineMacro("__cpp_guaranteed_copy_elision", "201606L");
  481. Builder.defineMacro("__cpp_nontype_template_parameter_auto", "201606L");
  482. }
  483. if (LangOpts.AlignedAllocation && !LangOpts.AlignedAllocationUnavailable)
  484. Builder.defineMacro("__cpp_aligned_new", "201606L");
  485. if (LangOpts.RelaxedTemplateTemplateArgs)
  486. Builder.defineMacro("__cpp_template_template_args", "201611L");
  487. // C++20 features.
  488. if (LangOpts.CPlusPlus2a) {
  489. Builder.defineMacro("__cpp_conditional_explicit", "201806L");
  490. Builder.defineMacro("__cpp_constexpr_dynamic_alloc", "201907L");
  491. Builder.defineMacro("__cpp_constinit", "201907L");
  492. }
  493. if (LangOpts.Char8)
  494. Builder.defineMacro("__cpp_char8_t", "201811L");
  495. Builder.defineMacro("__cpp_impl_destroying_delete", "201806L");
  496. // TS features.
  497. if (LangOpts.ConceptsTS)
  498. Builder.defineMacro("__cpp_experimental_concepts", "1L");
  499. if (LangOpts.Coroutines)
  500. Builder.defineMacro("__cpp_coroutines", "201703L");
  501. }
  502. static void InitializePredefinedMacros(const TargetInfo &TI,
  503. const LangOptions &LangOpts,
  504. const FrontendOptions &FEOpts,
  505. MacroBuilder &Builder) {
  506. // Compiler version introspection macros.
  507. Builder.defineMacro("__llvm__"); // LLVM Backend
  508. Builder.defineMacro("__clang__"); // Clang Frontend
  509. #define TOSTR2(X) #X
  510. #define TOSTR(X) TOSTR2(X)
  511. Builder.defineMacro("__clang_major__", TOSTR(CLANG_VERSION_MAJOR));
  512. Builder.defineMacro("__clang_minor__", TOSTR(CLANG_VERSION_MINOR));
  513. Builder.defineMacro("__clang_patchlevel__", TOSTR(CLANG_VERSION_PATCHLEVEL));
  514. #undef TOSTR
  515. #undef TOSTR2
  516. Builder.defineMacro("__clang_version__",
  517. "\"" CLANG_VERSION_STRING " "
  518. + getClangFullRepositoryVersion() + "\"");
  519. if (LangOpts.GNUCVersion != 0) {
  520. // Major, minor, patch, are given two decimal places each, so 4.2.1 becomes
  521. // 40201.
  522. unsigned GNUCMajor = LangOpts.GNUCVersion / 100 / 100;
  523. unsigned GNUCMinor = LangOpts.GNUCVersion / 100 % 100;
  524. unsigned GNUCPatch = LangOpts.GNUCVersion % 100;
  525. Builder.defineMacro("__GNUC__", Twine(GNUCMajor));
  526. Builder.defineMacro("__GNUC_MINOR__", Twine(GNUCMinor));
  527. Builder.defineMacro("__GNUC_PATCHLEVEL__", Twine(GNUCPatch));
  528. Builder.defineMacro("__GXX_ABI_VERSION", "1002");
  529. if (LangOpts.CPlusPlus) {
  530. Builder.defineMacro("__GNUG__", Twine(GNUCMajor));
  531. Builder.defineMacro("__GXX_WEAK__");
  532. }
  533. }
  534. // Define macros for the C11 / C++11 memory orderings
  535. Builder.defineMacro("__ATOMIC_RELAXED", "0");
  536. Builder.defineMacro("__ATOMIC_CONSUME", "1");
  537. Builder.defineMacro("__ATOMIC_ACQUIRE", "2");
  538. Builder.defineMacro("__ATOMIC_RELEASE", "3");
  539. Builder.defineMacro("__ATOMIC_ACQ_REL", "4");
  540. Builder.defineMacro("__ATOMIC_SEQ_CST", "5");
  541. // Define macros for the OpenCL memory scope.
  542. // The values should match AtomicScopeOpenCLModel::ID enum.
  543. static_assert(
  544. static_cast<unsigned>(AtomicScopeOpenCLModel::WorkGroup) == 1 &&
  545. static_cast<unsigned>(AtomicScopeOpenCLModel::Device) == 2 &&
  546. static_cast<unsigned>(AtomicScopeOpenCLModel::AllSVMDevices) == 3 &&
  547. static_cast<unsigned>(AtomicScopeOpenCLModel::SubGroup) == 4,
  548. "Invalid OpenCL memory scope enum definition");
  549. Builder.defineMacro("__OPENCL_MEMORY_SCOPE_WORK_ITEM", "0");
  550. Builder.defineMacro("__OPENCL_MEMORY_SCOPE_WORK_GROUP", "1");
  551. Builder.defineMacro("__OPENCL_MEMORY_SCOPE_DEVICE", "2");
  552. Builder.defineMacro("__OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES", "3");
  553. Builder.defineMacro("__OPENCL_MEMORY_SCOPE_SUB_GROUP", "4");
  554. // Support for #pragma redefine_extname (Sun compatibility)
  555. Builder.defineMacro("__PRAGMA_REDEFINE_EXTNAME", "1");
  556. // Previously this macro was set to a string aiming to achieve compatibility
  557. // with GCC 4.2.1. Now, just return the full Clang version
  558. Builder.defineMacro("__VERSION__", "\"" +
  559. Twine(getClangFullCPPVersion()) + "\"");
  560. // Initialize language-specific preprocessor defines.
  561. // Standard conforming mode?
  562. if (!LangOpts.GNUMode && !LangOpts.MSVCCompat)
  563. Builder.defineMacro("__STRICT_ANSI__");
  564. if (LangOpts.GNUCVersion && LangOpts.CPlusPlus11)
  565. Builder.defineMacro("__GXX_EXPERIMENTAL_CXX0X__");
  566. if (LangOpts.ObjC) {
  567. if (LangOpts.ObjCRuntime.isNonFragile()) {
  568. Builder.defineMacro("__OBJC2__");
  569. if (LangOpts.ObjCExceptions)
  570. Builder.defineMacro("OBJC_ZEROCOST_EXCEPTIONS");
  571. }
  572. if (LangOpts.getGC() != LangOptions::NonGC)
  573. Builder.defineMacro("__OBJC_GC__");
  574. if (LangOpts.ObjCRuntime.isNeXTFamily())
  575. Builder.defineMacro("__NEXT_RUNTIME__");
  576. if (LangOpts.ObjCRuntime.getKind() == ObjCRuntime::GNUstep) {
  577. auto version = LangOpts.ObjCRuntime.getVersion();
  578. std::string versionString = "1";
  579. // Don't rely on the tuple argument, because we can be asked to target
  580. // later ABIs than we actually support, so clamp these values to those
  581. // currently supported
  582. if (version >= VersionTuple(2, 0))
  583. Builder.defineMacro("__OBJC_GNUSTEP_RUNTIME_ABI__", "20");
  584. else
  585. Builder.defineMacro("__OBJC_GNUSTEP_RUNTIME_ABI__",
  586. "1" + Twine(std::min(8U, version.getMinor().getValueOr(0))));
  587. }
  588. if (LangOpts.ObjCRuntime.getKind() == ObjCRuntime::ObjFW) {
  589. VersionTuple tuple = LangOpts.ObjCRuntime.getVersion();
  590. unsigned minor = 0;
  591. if (tuple.getMinor().hasValue())
  592. minor = tuple.getMinor().getValue();
  593. unsigned subminor = 0;
  594. if (tuple.getSubminor().hasValue())
  595. subminor = tuple.getSubminor().getValue();
  596. Builder.defineMacro("__OBJFW_RUNTIME_ABI__",
  597. Twine(tuple.getMajor() * 10000 + minor * 100 +
  598. subminor));
  599. }
  600. Builder.defineMacro("IBOutlet", "__attribute__((iboutlet))");
  601. Builder.defineMacro("IBOutletCollection(ClassName)",
  602. "__attribute__((iboutletcollection(ClassName)))");
  603. Builder.defineMacro("IBAction", "void)__attribute__((ibaction)");
  604. Builder.defineMacro("IBInspectable", "");
  605. Builder.defineMacro("IB_DESIGNABLE", "");
  606. }
  607. // Define a macro that describes the Objective-C boolean type even for C
  608. // and C++ since BOOL can be used from non Objective-C code.
  609. Builder.defineMacro("__OBJC_BOOL_IS_BOOL",
  610. Twine(TI.useSignedCharForObjCBool() ? "0" : "1"));
  611. if (LangOpts.CPlusPlus)
  612. InitializeCPlusPlusFeatureTestMacros(LangOpts, Builder);
  613. // darwin_constant_cfstrings controls this. This is also dependent
  614. // on other things like the runtime I believe. This is set even for C code.
  615. if (!LangOpts.NoConstantCFStrings)
  616. Builder.defineMacro("__CONSTANT_CFSTRINGS__");
  617. if (LangOpts.ObjC)
  618. Builder.defineMacro("OBJC_NEW_PROPERTIES");
  619. if (LangOpts.PascalStrings)
  620. Builder.defineMacro("__PASCAL_STRINGS__");
  621. if (LangOpts.Blocks) {
  622. Builder.defineMacro("__block", "__attribute__((__blocks__(byref)))");
  623. Builder.defineMacro("__BLOCKS__");
  624. }
  625. if (!LangOpts.MSVCCompat && LangOpts.Exceptions)
  626. Builder.defineMacro("__EXCEPTIONS");
  627. if (LangOpts.GNUCVersion && LangOpts.RTTI)
  628. Builder.defineMacro("__GXX_RTTI");
  629. if (LangOpts.SjLjExceptions)
  630. Builder.defineMacro("__USING_SJLJ_EXCEPTIONS__");
  631. else if (LangOpts.SEHExceptions)
  632. Builder.defineMacro("__SEH__");
  633. else if (LangOpts.DWARFExceptions &&
  634. (TI.getTriple().isThumb() || TI.getTriple().isARM()))
  635. Builder.defineMacro("__ARM_DWARF_EH__");
  636. if (LangOpts.Deprecated)
  637. Builder.defineMacro("__DEPRECATED");
  638. if (!LangOpts.MSVCCompat && LangOpts.CPlusPlus)
  639. Builder.defineMacro("__private_extern__", "extern");
  640. if (LangOpts.MicrosoftExt) {
  641. if (LangOpts.WChar) {
  642. // wchar_t supported as a keyword.
  643. Builder.defineMacro("_WCHAR_T_DEFINED");
  644. Builder.defineMacro("_NATIVE_WCHAR_T_DEFINED");
  645. }
  646. }
  647. if (LangOpts.Optimize)
  648. Builder.defineMacro("__OPTIMIZE__");
  649. if (LangOpts.OptimizeSize)
  650. Builder.defineMacro("__OPTIMIZE_SIZE__");
  651. if (LangOpts.FastMath)
  652. Builder.defineMacro("__FAST_MATH__");
  653. // Initialize target-specific preprocessor defines.
  654. // __BYTE_ORDER__ was added in GCC 4.6. It's analogous
  655. // to the macro __BYTE_ORDER (no trailing underscores)
  656. // from glibc's <endian.h> header.
  657. // We don't support the PDP-11 as a target, but include
  658. // the define so it can still be compared against.
  659. Builder.defineMacro("__ORDER_LITTLE_ENDIAN__", "1234");
  660. Builder.defineMacro("__ORDER_BIG_ENDIAN__", "4321");
  661. Builder.defineMacro("__ORDER_PDP_ENDIAN__", "3412");
  662. if (TI.isBigEndian()) {
  663. Builder.defineMacro("__BYTE_ORDER__", "__ORDER_BIG_ENDIAN__");
  664. Builder.defineMacro("__BIG_ENDIAN__");
  665. } else {
  666. Builder.defineMacro("__BYTE_ORDER__", "__ORDER_LITTLE_ENDIAN__");
  667. Builder.defineMacro("__LITTLE_ENDIAN__");
  668. }
  669. if (TI.getPointerWidth(0) == 64 && TI.getLongWidth() == 64
  670. && TI.getIntWidth() == 32) {
  671. Builder.defineMacro("_LP64");
  672. Builder.defineMacro("__LP64__");
  673. }
  674. if (TI.getPointerWidth(0) == 32 && TI.getLongWidth() == 32
  675. && TI.getIntWidth() == 32) {
  676. Builder.defineMacro("_ILP32");
  677. Builder.defineMacro("__ILP32__");
  678. }
  679. // Define type sizing macros based on the target properties.
  680. assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far");
  681. Builder.defineMacro("__CHAR_BIT__", Twine(TI.getCharWidth()));
  682. DefineTypeSize("__SCHAR_MAX__", TargetInfo::SignedChar, TI, Builder);
  683. DefineTypeSize("__SHRT_MAX__", TargetInfo::SignedShort, TI, Builder);
  684. DefineTypeSize("__INT_MAX__", TargetInfo::SignedInt, TI, Builder);
  685. DefineTypeSize("__LONG_MAX__", TargetInfo::SignedLong, TI, Builder);
  686. DefineTypeSize("__LONG_LONG_MAX__", TargetInfo::SignedLongLong, TI, Builder);
  687. DefineTypeSize("__WCHAR_MAX__", TI.getWCharType(), TI, Builder);
  688. DefineTypeSize("__WINT_MAX__", TI.getWIntType(), TI, Builder);
  689. DefineTypeSize("__INTMAX_MAX__", TI.getIntMaxType(), TI, Builder);
  690. DefineTypeSize("__SIZE_MAX__", TI.getSizeType(), TI, Builder);
  691. DefineTypeSize("__UINTMAX_MAX__", TI.getUIntMaxType(), TI, Builder);
  692. DefineTypeSize("__PTRDIFF_MAX__", TI.getPtrDiffType(0), TI, Builder);
  693. DefineTypeSize("__INTPTR_MAX__", TI.getIntPtrType(), TI, Builder);
  694. DefineTypeSize("__UINTPTR_MAX__", TI.getUIntPtrType(), TI, Builder);
  695. DefineTypeSizeof("__SIZEOF_DOUBLE__", TI.getDoubleWidth(), TI, Builder);
  696. DefineTypeSizeof("__SIZEOF_FLOAT__", TI.getFloatWidth(), TI, Builder);
  697. DefineTypeSizeof("__SIZEOF_INT__", TI.getIntWidth(), TI, Builder);
  698. DefineTypeSizeof("__SIZEOF_LONG__", TI.getLongWidth(), TI, Builder);
  699. DefineTypeSizeof("__SIZEOF_LONG_DOUBLE__",TI.getLongDoubleWidth(),TI,Builder);
  700. DefineTypeSizeof("__SIZEOF_LONG_LONG__", TI.getLongLongWidth(), TI, Builder);
  701. DefineTypeSizeof("__SIZEOF_POINTER__", TI.getPointerWidth(0), TI, Builder);
  702. DefineTypeSizeof("__SIZEOF_SHORT__", TI.getShortWidth(), TI, Builder);
  703. DefineTypeSizeof("__SIZEOF_PTRDIFF_T__",
  704. TI.getTypeWidth(TI.getPtrDiffType(0)), TI, Builder);
  705. DefineTypeSizeof("__SIZEOF_SIZE_T__",
  706. TI.getTypeWidth(TI.getSizeType()), TI, Builder);
  707. DefineTypeSizeof("__SIZEOF_WCHAR_T__",
  708. TI.getTypeWidth(TI.getWCharType()), TI, Builder);
  709. DefineTypeSizeof("__SIZEOF_WINT_T__",
  710. TI.getTypeWidth(TI.getWIntType()), TI, Builder);
  711. if (TI.hasInt128Type())
  712. DefineTypeSizeof("__SIZEOF_INT128__", 128, TI, Builder);
  713. DefineType("__INTMAX_TYPE__", TI.getIntMaxType(), Builder);
  714. DefineFmt("__INTMAX", TI.getIntMaxType(), TI, Builder);
  715. Builder.defineMacro("__INTMAX_C_SUFFIX__",
  716. TI.getTypeConstantSuffix(TI.getIntMaxType()));
  717. DefineType("__UINTMAX_TYPE__", TI.getUIntMaxType(), Builder);
  718. DefineFmt("__UINTMAX", TI.getUIntMaxType(), TI, Builder);
  719. Builder.defineMacro("__UINTMAX_C_SUFFIX__",
  720. TI.getTypeConstantSuffix(TI.getUIntMaxType()));
  721. DefineTypeWidth("__INTMAX_WIDTH__", TI.getIntMaxType(), TI, Builder);
  722. DefineType("__PTRDIFF_TYPE__", TI.getPtrDiffType(0), Builder);
  723. DefineFmt("__PTRDIFF", TI.getPtrDiffType(0), TI, Builder);
  724. DefineTypeWidth("__PTRDIFF_WIDTH__", TI.getPtrDiffType(0), TI, Builder);
  725. DefineType("__INTPTR_TYPE__", TI.getIntPtrType(), Builder);
  726. DefineFmt("__INTPTR", TI.getIntPtrType(), TI, Builder);
  727. DefineTypeWidth("__INTPTR_WIDTH__", TI.getIntPtrType(), TI, Builder);
  728. DefineType("__SIZE_TYPE__", TI.getSizeType(), Builder);
  729. DefineFmt("__SIZE", TI.getSizeType(), TI, Builder);
  730. DefineTypeWidth("__SIZE_WIDTH__", TI.getSizeType(), TI, Builder);
  731. DefineType("__WCHAR_TYPE__", TI.getWCharType(), Builder);
  732. DefineTypeWidth("__WCHAR_WIDTH__", TI.getWCharType(), TI, Builder);
  733. DefineType("__WINT_TYPE__", TI.getWIntType(), Builder);
  734. DefineTypeWidth("__WINT_WIDTH__", TI.getWIntType(), TI, Builder);
  735. DefineTypeWidth("__SIG_ATOMIC_WIDTH__", TI.getSigAtomicType(), TI, Builder);
  736. DefineTypeSize("__SIG_ATOMIC_MAX__", TI.getSigAtomicType(), TI, Builder);
  737. DefineType("__CHAR16_TYPE__", TI.getChar16Type(), Builder);
  738. DefineType("__CHAR32_TYPE__", TI.getChar32Type(), Builder);
  739. DefineTypeWidth("__UINTMAX_WIDTH__", TI.getUIntMaxType(), TI, Builder);
  740. DefineType("__UINTPTR_TYPE__", TI.getUIntPtrType(), Builder);
  741. DefineFmt("__UINTPTR", TI.getUIntPtrType(), TI, Builder);
  742. DefineTypeWidth("__UINTPTR_WIDTH__", TI.getUIntPtrType(), TI, Builder);
  743. if (TI.hasFloat16Type())
  744. DefineFloatMacros(Builder, "FLT16", &TI.getHalfFormat(), "F16");
  745. DefineFloatMacros(Builder, "FLT", &TI.getFloatFormat(), "F");
  746. DefineFloatMacros(Builder, "DBL", &TI.getDoubleFormat(), "");
  747. DefineFloatMacros(Builder, "LDBL", &TI.getLongDoubleFormat(), "L");
  748. // Define a __POINTER_WIDTH__ macro for stdint.h.
  749. Builder.defineMacro("__POINTER_WIDTH__",
  750. Twine((int)TI.getPointerWidth(0)));
  751. // Define __BIGGEST_ALIGNMENT__ to be compatible with gcc.
  752. Builder.defineMacro("__BIGGEST_ALIGNMENT__",
  753. Twine(TI.getSuitableAlign() / TI.getCharWidth()) );
  754. if (!LangOpts.CharIsSigned)
  755. Builder.defineMacro("__CHAR_UNSIGNED__");
  756. if (!TargetInfo::isTypeSigned(TI.getWCharType()))
  757. Builder.defineMacro("__WCHAR_UNSIGNED__");
  758. if (!TargetInfo::isTypeSigned(TI.getWIntType()))
  759. Builder.defineMacro("__WINT_UNSIGNED__");
  760. // Define exact-width integer types for stdint.h
  761. DefineExactWidthIntType(TargetInfo::SignedChar, TI, Builder);
  762. if (TI.getShortWidth() > TI.getCharWidth())
  763. DefineExactWidthIntType(TargetInfo::SignedShort, TI, Builder);
  764. if (TI.getIntWidth() > TI.getShortWidth())
  765. DefineExactWidthIntType(TargetInfo::SignedInt, TI, Builder);
  766. if (TI.getLongWidth() > TI.getIntWidth())
  767. DefineExactWidthIntType(TargetInfo::SignedLong, TI, Builder);
  768. if (TI.getLongLongWidth() > TI.getLongWidth())
  769. DefineExactWidthIntType(TargetInfo::SignedLongLong, TI, Builder);
  770. DefineExactWidthIntType(TargetInfo::UnsignedChar, TI, Builder);
  771. DefineExactWidthIntTypeSize(TargetInfo::UnsignedChar, TI, Builder);
  772. DefineExactWidthIntTypeSize(TargetInfo::SignedChar, TI, Builder);
  773. if (TI.getShortWidth() > TI.getCharWidth()) {
  774. DefineExactWidthIntType(TargetInfo::UnsignedShort, TI, Builder);
  775. DefineExactWidthIntTypeSize(TargetInfo::UnsignedShort, TI, Builder);
  776. DefineExactWidthIntTypeSize(TargetInfo::SignedShort, TI, Builder);
  777. }
  778. if (TI.getIntWidth() > TI.getShortWidth()) {
  779. DefineExactWidthIntType(TargetInfo::UnsignedInt, TI, Builder);
  780. DefineExactWidthIntTypeSize(TargetInfo::UnsignedInt, TI, Builder);
  781. DefineExactWidthIntTypeSize(TargetInfo::SignedInt, TI, Builder);
  782. }
  783. if (TI.getLongWidth() > TI.getIntWidth()) {
  784. DefineExactWidthIntType(TargetInfo::UnsignedLong, TI, Builder);
  785. DefineExactWidthIntTypeSize(TargetInfo::UnsignedLong, TI, Builder);
  786. DefineExactWidthIntTypeSize(TargetInfo::SignedLong, TI, Builder);
  787. }
  788. if (TI.getLongLongWidth() > TI.getLongWidth()) {
  789. DefineExactWidthIntType(TargetInfo::UnsignedLongLong, TI, Builder);
  790. DefineExactWidthIntTypeSize(TargetInfo::UnsignedLongLong, TI, Builder);
  791. DefineExactWidthIntTypeSize(TargetInfo::SignedLongLong, TI, Builder);
  792. }
  793. DefineLeastWidthIntType(8, true, TI, Builder);
  794. DefineLeastWidthIntType(8, false, TI, Builder);
  795. DefineLeastWidthIntType(16, true, TI, Builder);
  796. DefineLeastWidthIntType(16, false, TI, Builder);
  797. DefineLeastWidthIntType(32, true, TI, Builder);
  798. DefineLeastWidthIntType(32, false, TI, Builder);
  799. DefineLeastWidthIntType(64, true, TI, Builder);
  800. DefineLeastWidthIntType(64, false, TI, Builder);
  801. DefineFastIntType(8, true, TI, Builder);
  802. DefineFastIntType(8, false, TI, Builder);
  803. DefineFastIntType(16, true, TI, Builder);
  804. DefineFastIntType(16, false, TI, Builder);
  805. DefineFastIntType(32, true, TI, Builder);
  806. DefineFastIntType(32, false, TI, Builder);
  807. DefineFastIntType(64, true, TI, Builder);
  808. DefineFastIntType(64, false, TI, Builder);
  809. char UserLabelPrefix[2] = {TI.getDataLayout().getGlobalPrefix(), 0};
  810. Builder.defineMacro("__USER_LABEL_PREFIX__", UserLabelPrefix);
  811. if (LangOpts.FastMath || LangOpts.FiniteMathOnly)
  812. Builder.defineMacro("__FINITE_MATH_ONLY__", "1");
  813. else
  814. Builder.defineMacro("__FINITE_MATH_ONLY__", "0");
  815. if (LangOpts.GNUCVersion) {
  816. if (LangOpts.GNUInline || LangOpts.CPlusPlus)
  817. Builder.defineMacro("__GNUC_GNU_INLINE__");
  818. else
  819. Builder.defineMacro("__GNUC_STDC_INLINE__");
  820. // The value written by __atomic_test_and_set.
  821. // FIXME: This is target-dependent.
  822. Builder.defineMacro("__GCC_ATOMIC_TEST_AND_SET_TRUEVAL", "1");
  823. }
  824. auto addLockFreeMacros = [&](const llvm::Twine &Prefix) {
  825. // Used by libc++ and libstdc++ to implement ATOMIC_<foo>_LOCK_FREE.
  826. unsigned InlineWidthBits = TI.getMaxAtomicInlineWidth();
  827. #define DEFINE_LOCK_FREE_MACRO(TYPE, Type) \
  828. Builder.defineMacro(Prefix + #TYPE "_LOCK_FREE", \
  829. getLockFreeValue(TI.get##Type##Width(), \
  830. TI.get##Type##Align(), \
  831. InlineWidthBits));
  832. DEFINE_LOCK_FREE_MACRO(BOOL, Bool);
  833. DEFINE_LOCK_FREE_MACRO(CHAR, Char);
  834. if (LangOpts.Char8)
  835. DEFINE_LOCK_FREE_MACRO(CHAR8_T, Char); // Treat char8_t like char.
  836. DEFINE_LOCK_FREE_MACRO(CHAR16_T, Char16);
  837. DEFINE_LOCK_FREE_MACRO(CHAR32_T, Char32);
  838. DEFINE_LOCK_FREE_MACRO(WCHAR_T, WChar);
  839. DEFINE_LOCK_FREE_MACRO(SHORT, Short);
  840. DEFINE_LOCK_FREE_MACRO(INT, Int);
  841. DEFINE_LOCK_FREE_MACRO(LONG, Long);
  842. DEFINE_LOCK_FREE_MACRO(LLONG, LongLong);
  843. Builder.defineMacro(Prefix + "POINTER_LOCK_FREE",
  844. getLockFreeValue(TI.getPointerWidth(0),
  845. TI.getPointerAlign(0),
  846. InlineWidthBits));
  847. #undef DEFINE_LOCK_FREE_MACRO
  848. };
  849. addLockFreeMacros("__CLANG_ATOMIC_");
  850. if (LangOpts.GNUCVersion)
  851. addLockFreeMacros("__GCC_ATOMIC_");
  852. if (LangOpts.NoInlineDefine)
  853. Builder.defineMacro("__NO_INLINE__");
  854. if (unsigned PICLevel = LangOpts.PICLevel) {
  855. Builder.defineMacro("__PIC__", Twine(PICLevel));
  856. Builder.defineMacro("__pic__", Twine(PICLevel));
  857. if (LangOpts.PIE) {
  858. Builder.defineMacro("__PIE__", Twine(PICLevel));
  859. Builder.defineMacro("__pie__", Twine(PICLevel));
  860. }
  861. }
  862. // Macros to control C99 numerics and <float.h>
  863. Builder.defineMacro("__FLT_EVAL_METHOD__", Twine(TI.getFloatEvalMethod()));
  864. Builder.defineMacro("__FLT_RADIX__", "2");
  865. Builder.defineMacro("__DECIMAL_DIG__", "__LDBL_DECIMAL_DIG__");
  866. if (LangOpts.getStackProtector() == LangOptions::SSPOn)
  867. Builder.defineMacro("__SSP__");
  868. else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
  869. Builder.defineMacro("__SSP_STRONG__", "2");
  870. else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
  871. Builder.defineMacro("__SSP_ALL__", "3");
  872. // Define a macro that exists only when using the static analyzer.
  873. if (FEOpts.ProgramAction == frontend::RunAnalysis)
  874. Builder.defineMacro("__clang_analyzer__");
  875. if (LangOpts.FastRelaxedMath)
  876. Builder.defineMacro("__FAST_RELAXED_MATH__");
  877. if (FEOpts.ProgramAction == frontend::RewriteObjC ||
  878. LangOpts.getGC() != LangOptions::NonGC) {
  879. Builder.defineMacro("__weak", "__attribute__((objc_gc(weak)))");
  880. Builder.defineMacro("__strong", "__attribute__((objc_gc(strong)))");
  881. Builder.defineMacro("__autoreleasing", "");
  882. Builder.defineMacro("__unsafe_unretained", "");
  883. } else if (LangOpts.ObjC) {
  884. Builder.defineMacro("__weak", "__attribute__((objc_ownership(weak)))");
  885. Builder.defineMacro("__strong", "__attribute__((objc_ownership(strong)))");
  886. Builder.defineMacro("__autoreleasing",
  887. "__attribute__((objc_ownership(autoreleasing)))");
  888. Builder.defineMacro("__unsafe_unretained",
  889. "__attribute__((objc_ownership(none)))");
  890. }
  891. // On Darwin, there are __double_underscored variants of the type
  892. // nullability qualifiers.
  893. if (TI.getTriple().isOSDarwin()) {
  894. Builder.defineMacro("__nonnull", "_Nonnull");
  895. Builder.defineMacro("__null_unspecified", "_Null_unspecified");
  896. Builder.defineMacro("__nullable", "_Nullable");
  897. }
  898. // Add a macro to differentiate between regular iOS/tvOS/watchOS targets and
  899. // the corresponding simulator targets.
  900. if (TI.getTriple().isOSDarwin() && TI.getTriple().isSimulatorEnvironment())
  901. Builder.defineMacro("__APPLE_EMBEDDED_SIMULATOR__", "1");
  902. // OpenMP definition
  903. // OpenMP 2.2:
  904. // In implementations that support a preprocessor, the _OPENMP
  905. // macro name is defined to have the decimal value yyyymm where
  906. // yyyy and mm are the year and the month designations of the
  907. // version of the OpenMP API that the implementation support.
  908. if (!LangOpts.OpenMPSimd) {
  909. switch (LangOpts.OpenMP) {
  910. case 0:
  911. break;
  912. case 31:
  913. Builder.defineMacro("_OPENMP", "201107");
  914. break;
  915. case 40:
  916. Builder.defineMacro("_OPENMP", "201307");
  917. break;
  918. case 50:
  919. Builder.defineMacro("_OPENMP", "201811");
  920. break;
  921. default:
  922. // Default version is OpenMP 4.5
  923. Builder.defineMacro("_OPENMP", "201511");
  924. break;
  925. }
  926. }
  927. // CUDA device path compilaton
  928. if (LangOpts.CUDAIsDevice && !LangOpts.HIP) {
  929. // The CUDA_ARCH value is set for the GPU target specified in the NVPTX
  930. // backend's target defines.
  931. Builder.defineMacro("__CUDA_ARCH__");
  932. }
  933. // We need to communicate this to our CUDA header wrapper, which in turn
  934. // informs the proper CUDA headers of this choice.
  935. if (LangOpts.CUDADeviceApproxTranscendentals || LangOpts.FastMath) {
  936. Builder.defineMacro("__CLANG_CUDA_APPROX_TRANSCENDENTALS__");
  937. }
  938. // Define a macro indicating that the source file is being compiled with a
  939. // SYCL device compiler which doesn't produce host binary.
  940. if (LangOpts.SYCLIsDevice) {
  941. Builder.defineMacro("__SYCL_DEVICE_ONLY__", "1");
  942. }
  943. // OpenCL definitions.
  944. if (LangOpts.OpenCL) {
  945. #define OPENCLEXT(Ext) \
  946. if (TI.getSupportedOpenCLOpts().isSupported(#Ext, LangOpts)) \
  947. Builder.defineMacro(#Ext);
  948. #include "clang/Basic/OpenCLExtensions.def"
  949. if (TI.getTriple().isSPIR())
  950. Builder.defineMacro("__IMAGE_SUPPORT__");
  951. }
  952. if (TI.hasInt128Type() && LangOpts.CPlusPlus && LangOpts.GNUMode) {
  953. // For each extended integer type, g++ defines a macro mapping the
  954. // index of the type (0 in this case) in some list of extended types
  955. // to the type.
  956. Builder.defineMacro("__GLIBCXX_TYPE_INT_N_0", "__int128");
  957. Builder.defineMacro("__GLIBCXX_BITSIZE_INT_N_0", "128");
  958. }
  959. // Get other target #defines.
  960. TI.getTargetDefines(LangOpts, Builder);
  961. }
  962. /// InitializePreprocessor - Initialize the preprocessor getting it and the
  963. /// environment ready to process a single file. This returns true on error.
  964. ///
  965. void clang::InitializePreprocessor(
  966. Preprocessor &PP, const PreprocessorOptions &InitOpts,
  967. const PCHContainerReader &PCHContainerRdr,
  968. const FrontendOptions &FEOpts) {
  969. const LangOptions &LangOpts = PP.getLangOpts();
  970. std::string PredefineBuffer;
  971. PredefineBuffer.reserve(4080);
  972. llvm::raw_string_ostream Predefines(PredefineBuffer);
  973. MacroBuilder Builder(Predefines);
  974. // Emit line markers for various builtin sections of the file. We don't do
  975. // this in asm preprocessor mode, because "# 4" is not a line marker directive
  976. // in this mode.
  977. if (!PP.getLangOpts().AsmPreprocessor)
  978. Builder.append("# 1 \"<built-in>\" 3");
  979. // Install things like __POWERPC__, __GNUC__, etc into the macro table.
  980. if (InitOpts.UsePredefines) {
  981. // FIXME: This will create multiple definitions for most of the predefined
  982. // macros. This is not the right way to handle this.
  983. if ((LangOpts.CUDA || LangOpts.OpenMPIsDevice) && PP.getAuxTargetInfo())
  984. InitializePredefinedMacros(*PP.getAuxTargetInfo(), LangOpts, FEOpts,
  985. Builder);
  986. InitializePredefinedMacros(PP.getTargetInfo(), LangOpts, FEOpts, Builder);
  987. // Install definitions to make Objective-C++ ARC work well with various
  988. // C++ Standard Library implementations.
  989. if (LangOpts.ObjC && LangOpts.CPlusPlus &&
  990. (LangOpts.ObjCAutoRefCount || LangOpts.ObjCWeak)) {
  991. switch (InitOpts.ObjCXXARCStandardLibrary) {
  992. case ARCXX_nolib:
  993. case ARCXX_libcxx:
  994. break;
  995. case ARCXX_libstdcxx:
  996. AddObjCXXARCLibstdcxxDefines(LangOpts, Builder);
  997. break;
  998. }
  999. }
  1000. }
  1001. // Even with predefines off, some macros are still predefined.
  1002. // These should all be defined in the preprocessor according to the
  1003. // current language configuration.
  1004. InitializeStandardPredefinedMacros(PP.getTargetInfo(), PP.getLangOpts(),
  1005. FEOpts, Builder);
  1006. // Add on the predefines from the driver. Wrap in a #line directive to report
  1007. // that they come from the command line.
  1008. if (!PP.getLangOpts().AsmPreprocessor)
  1009. Builder.append("# 1 \"<command line>\" 1");
  1010. // Process #define's and #undef's in the order they are given.
  1011. for (unsigned i = 0, e = InitOpts.Macros.size(); i != e; ++i) {
  1012. if (InitOpts.Macros[i].second) // isUndef
  1013. Builder.undefineMacro(InitOpts.Macros[i].first);
  1014. else
  1015. DefineBuiltinMacro(Builder, InitOpts.Macros[i].first,
  1016. PP.getDiagnostics());
  1017. }
  1018. // Exit the command line and go back to <built-in> (2 is LC_LEAVE).
  1019. if (!PP.getLangOpts().AsmPreprocessor)
  1020. Builder.append("# 1 \"<built-in>\" 2");
  1021. // If -imacros are specified, include them now. These are processed before
  1022. // any -include directives.
  1023. for (unsigned i = 0, e = InitOpts.MacroIncludes.size(); i != e; ++i)
  1024. AddImplicitIncludeMacros(Builder, InitOpts.MacroIncludes[i]);
  1025. // Process -include-pch/-include-pth directives.
  1026. if (!InitOpts.ImplicitPCHInclude.empty())
  1027. AddImplicitIncludePCH(Builder, PP, PCHContainerRdr,
  1028. InitOpts.ImplicitPCHInclude);
  1029. // Process -include directives.
  1030. for (unsigned i = 0, e = InitOpts.Includes.size(); i != e; ++i) {
  1031. const std::string &Path = InitOpts.Includes[i];
  1032. AddImplicitInclude(Builder, Path);
  1033. }
  1034. // Instruct the preprocessor to skip the preamble.
  1035. PP.setSkipMainFilePreamble(InitOpts.PrecompiledPreambleBytes.first,
  1036. InitOpts.PrecompiledPreambleBytes.second);
  1037. // Copy PredefinedBuffer into the Preprocessor.
  1038. PP.setPredefines(Predefines.str());
  1039. }