PPMacroExpansion.cpp 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884
  1. //===--- PPMacroExpansion.cpp - Top level Macro Expansion -----------------===//
  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 top level handling of macro expansion for the
  10. // preprocessor.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Basic/Attributes.h"
  14. #include "clang/Basic/Builtins.h"
  15. #include "clang/Basic/FileManager.h"
  16. #include "clang/Basic/IdentifierTable.h"
  17. #include "clang/Basic/LLVM.h"
  18. #include "clang/Basic/LangOptions.h"
  19. #include "clang/Basic/ObjCRuntime.h"
  20. #include "clang/Basic/SourceLocation.h"
  21. #include "clang/Basic/TargetInfo.h"
  22. #include "clang/Lex/CodeCompletionHandler.h"
  23. #include "clang/Lex/DirectoryLookup.h"
  24. #include "clang/Lex/ExternalPreprocessorSource.h"
  25. #include "clang/Lex/HeaderSearch.h"
  26. #include "clang/Lex/LexDiagnostic.h"
  27. #include "clang/Lex/LiteralSupport.h"
  28. #include "clang/Lex/MacroArgs.h"
  29. #include "clang/Lex/MacroInfo.h"
  30. #include "clang/Lex/Preprocessor.h"
  31. #include "clang/Lex/PreprocessorLexer.h"
  32. #include "clang/Lex/PreprocessorOptions.h"
  33. #include "clang/Lex/Token.h"
  34. #include "llvm/ADT/ArrayRef.h"
  35. #include "llvm/ADT/DenseMap.h"
  36. #include "llvm/ADT/DenseSet.h"
  37. #include "llvm/ADT/FoldingSet.h"
  38. #include "llvm/ADT/None.h"
  39. #include "llvm/ADT/Optional.h"
  40. #include "llvm/ADT/STLExtras.h"
  41. #include "llvm/ADT/SmallString.h"
  42. #include "llvm/ADT/SmallVector.h"
  43. #include "llvm/ADT/StringRef.h"
  44. #include "llvm/ADT/StringSwitch.h"
  45. #include "llvm/Support/Casting.h"
  46. #include "llvm/Support/ErrorHandling.h"
  47. #include "llvm/Support/Format.h"
  48. #include "llvm/Support/Path.h"
  49. #include "llvm/Support/raw_ostream.h"
  50. #include <algorithm>
  51. #include <cassert>
  52. #include <cstddef>
  53. #include <cstring>
  54. #include <ctime>
  55. #include <string>
  56. #include <tuple>
  57. #include <utility>
  58. using namespace clang;
  59. MacroDirective *
  60. Preprocessor::getLocalMacroDirectiveHistory(const IdentifierInfo *II) const {
  61. if (!II->hadMacroDefinition())
  62. return nullptr;
  63. auto Pos = CurSubmoduleState->Macros.find(II);
  64. return Pos == CurSubmoduleState->Macros.end() ? nullptr
  65. : Pos->second.getLatest();
  66. }
  67. void Preprocessor::appendMacroDirective(IdentifierInfo *II, MacroDirective *MD){
  68. assert(MD && "MacroDirective should be non-zero!");
  69. assert(!MD->getPrevious() && "Already attached to a MacroDirective history.");
  70. MacroState &StoredMD = CurSubmoduleState->Macros[II];
  71. auto *OldMD = StoredMD.getLatest();
  72. MD->setPrevious(OldMD);
  73. StoredMD.setLatest(MD);
  74. StoredMD.overrideActiveModuleMacros(*this, II);
  75. if (needModuleMacros()) {
  76. // Track that we created a new macro directive, so we know we should
  77. // consider building a ModuleMacro for it when we get to the end of
  78. // the module.
  79. PendingModuleMacroNames.push_back(II);
  80. }
  81. // Set up the identifier as having associated macro history.
  82. II->setHasMacroDefinition(true);
  83. if (!MD->isDefined() && LeafModuleMacros.find(II) == LeafModuleMacros.end())
  84. II->setHasMacroDefinition(false);
  85. if (II->isFromAST())
  86. II->setChangedSinceDeserialization();
  87. }
  88. void Preprocessor::setLoadedMacroDirective(IdentifierInfo *II,
  89. MacroDirective *ED,
  90. MacroDirective *MD) {
  91. // Normally, when a macro is defined, it goes through appendMacroDirective()
  92. // above, which chains a macro to previous defines, undefs, etc.
  93. // However, in a pch, the whole macro history up to the end of the pch is
  94. // stored, so ASTReader goes through this function instead.
  95. // However, built-in macros are already registered in the Preprocessor
  96. // ctor, and ASTWriter stops writing the macro chain at built-in macros,
  97. // so in that case the chain from the pch needs to be spliced to the existing
  98. // built-in.
  99. assert(II && MD);
  100. MacroState &StoredMD = CurSubmoduleState->Macros[II];
  101. if (auto *OldMD = StoredMD.getLatest()) {
  102. // shouldIgnoreMacro() in ASTWriter also stops at macros from the
  103. // predefines buffer in module builds. However, in module builds, modules
  104. // are loaded completely before predefines are processed, so StoredMD
  105. // will be nullptr for them when they're loaded. StoredMD should only be
  106. // non-nullptr for builtins read from a pch file.
  107. assert(OldMD->getMacroInfo()->isBuiltinMacro() &&
  108. "only built-ins should have an entry here");
  109. assert(!OldMD->getPrevious() && "builtin should only have a single entry");
  110. ED->setPrevious(OldMD);
  111. StoredMD.setLatest(MD);
  112. } else {
  113. StoredMD = MD;
  114. }
  115. // Setup the identifier as having associated macro history.
  116. II->setHasMacroDefinition(true);
  117. if (!MD->isDefined() && LeafModuleMacros.find(II) == LeafModuleMacros.end())
  118. II->setHasMacroDefinition(false);
  119. }
  120. ModuleMacro *Preprocessor::addModuleMacro(Module *Mod, IdentifierInfo *II,
  121. MacroInfo *Macro,
  122. ArrayRef<ModuleMacro *> Overrides,
  123. bool &New) {
  124. llvm::FoldingSetNodeID ID;
  125. ModuleMacro::Profile(ID, Mod, II);
  126. void *InsertPos;
  127. if (auto *MM = ModuleMacros.FindNodeOrInsertPos(ID, InsertPos)) {
  128. New = false;
  129. return MM;
  130. }
  131. auto *MM = ModuleMacro::create(*this, Mod, II, Macro, Overrides);
  132. ModuleMacros.InsertNode(MM, InsertPos);
  133. // Each overridden macro is now overridden by one more macro.
  134. bool HidAny = false;
  135. for (auto *O : Overrides) {
  136. HidAny |= (O->NumOverriddenBy == 0);
  137. ++O->NumOverriddenBy;
  138. }
  139. // If we were the first overrider for any macro, it's no longer a leaf.
  140. auto &LeafMacros = LeafModuleMacros[II];
  141. if (HidAny) {
  142. llvm::erase_if(LeafMacros,
  143. [](ModuleMacro *MM) { return MM->NumOverriddenBy != 0; });
  144. }
  145. // The new macro is always a leaf macro.
  146. LeafMacros.push_back(MM);
  147. // The identifier now has defined macros (that may or may not be visible).
  148. II->setHasMacroDefinition(true);
  149. New = true;
  150. return MM;
  151. }
  152. ModuleMacro *Preprocessor::getModuleMacro(Module *Mod,
  153. const IdentifierInfo *II) {
  154. llvm::FoldingSetNodeID ID;
  155. ModuleMacro::Profile(ID, Mod, II);
  156. void *InsertPos;
  157. return ModuleMacros.FindNodeOrInsertPos(ID, InsertPos);
  158. }
  159. void Preprocessor::updateModuleMacroInfo(const IdentifierInfo *II,
  160. ModuleMacroInfo &Info) {
  161. assert(Info.ActiveModuleMacrosGeneration !=
  162. CurSubmoduleState->VisibleModules.getGeneration() &&
  163. "don't need to update this macro name info");
  164. Info.ActiveModuleMacrosGeneration =
  165. CurSubmoduleState->VisibleModules.getGeneration();
  166. auto Leaf = LeafModuleMacros.find(II);
  167. if (Leaf == LeafModuleMacros.end()) {
  168. // No imported macros at all: nothing to do.
  169. return;
  170. }
  171. Info.ActiveModuleMacros.clear();
  172. // Every macro that's locally overridden is overridden by a visible macro.
  173. llvm::DenseMap<ModuleMacro *, int> NumHiddenOverrides;
  174. for (auto *O : Info.OverriddenMacros)
  175. NumHiddenOverrides[O] = -1;
  176. // Collect all macros that are not overridden by a visible macro.
  177. llvm::SmallVector<ModuleMacro *, 16> Worklist;
  178. for (auto *LeafMM : Leaf->second) {
  179. assert(LeafMM->getNumOverridingMacros() == 0 && "leaf macro overridden");
  180. if (NumHiddenOverrides.lookup(LeafMM) == 0)
  181. Worklist.push_back(LeafMM);
  182. }
  183. while (!Worklist.empty()) {
  184. auto *MM = Worklist.pop_back_val();
  185. if (CurSubmoduleState->VisibleModules.isVisible(MM->getOwningModule())) {
  186. // We only care about collecting definitions; undefinitions only act
  187. // to override other definitions.
  188. if (MM->getMacroInfo())
  189. Info.ActiveModuleMacros.push_back(MM);
  190. } else {
  191. for (auto *O : MM->overrides())
  192. if ((unsigned)++NumHiddenOverrides[O] == O->getNumOverridingMacros())
  193. Worklist.push_back(O);
  194. }
  195. }
  196. // Our reverse postorder walk found the macros in reverse order.
  197. std::reverse(Info.ActiveModuleMacros.begin(), Info.ActiveModuleMacros.end());
  198. // Determine whether the macro name is ambiguous.
  199. MacroInfo *MI = nullptr;
  200. bool IsSystemMacro = true;
  201. bool IsAmbiguous = false;
  202. if (auto *MD = Info.MD) {
  203. while (MD && isa<VisibilityMacroDirective>(MD))
  204. MD = MD->getPrevious();
  205. if (auto *DMD = dyn_cast_or_null<DefMacroDirective>(MD)) {
  206. MI = DMD->getInfo();
  207. IsSystemMacro &= SourceMgr.isInSystemHeader(DMD->getLocation());
  208. }
  209. }
  210. for (auto *Active : Info.ActiveModuleMacros) {
  211. auto *NewMI = Active->getMacroInfo();
  212. // Before marking the macro as ambiguous, check if this is a case where
  213. // both macros are in system headers. If so, we trust that the system
  214. // did not get it wrong. This also handles cases where Clang's own
  215. // headers have a different spelling of certain system macros:
  216. // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
  217. // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
  218. //
  219. // FIXME: Remove the defined-in-system-headers check. clang's limits.h
  220. // overrides the system limits.h's macros, so there's no conflict here.
  221. if (MI && NewMI != MI &&
  222. !MI->isIdenticalTo(*NewMI, *this, /*Syntactically=*/true))
  223. IsAmbiguous = true;
  224. IsSystemMacro &= Active->getOwningModule()->IsSystem ||
  225. SourceMgr.isInSystemHeader(NewMI->getDefinitionLoc());
  226. MI = NewMI;
  227. }
  228. Info.IsAmbiguous = IsAmbiguous && !IsSystemMacro;
  229. }
  230. void Preprocessor::dumpMacroInfo(const IdentifierInfo *II) {
  231. ArrayRef<ModuleMacro*> Leaf;
  232. auto LeafIt = LeafModuleMacros.find(II);
  233. if (LeafIt != LeafModuleMacros.end())
  234. Leaf = LeafIt->second;
  235. const MacroState *State = nullptr;
  236. auto Pos = CurSubmoduleState->Macros.find(II);
  237. if (Pos != CurSubmoduleState->Macros.end())
  238. State = &Pos->second;
  239. llvm::errs() << "MacroState " << State << " " << II->getNameStart();
  240. if (State && State->isAmbiguous(*this, II))
  241. llvm::errs() << " ambiguous";
  242. if (State && !State->getOverriddenMacros().empty()) {
  243. llvm::errs() << " overrides";
  244. for (auto *O : State->getOverriddenMacros())
  245. llvm::errs() << " " << O->getOwningModule()->getFullModuleName();
  246. }
  247. llvm::errs() << "\n";
  248. // Dump local macro directives.
  249. for (auto *MD = State ? State->getLatest() : nullptr; MD;
  250. MD = MD->getPrevious()) {
  251. llvm::errs() << " ";
  252. MD->dump();
  253. }
  254. // Dump module macros.
  255. llvm::DenseSet<ModuleMacro*> Active;
  256. for (auto *MM : State ? State->getActiveModuleMacros(*this, II) : None)
  257. Active.insert(MM);
  258. llvm::DenseSet<ModuleMacro*> Visited;
  259. llvm::SmallVector<ModuleMacro *, 16> Worklist(Leaf.begin(), Leaf.end());
  260. while (!Worklist.empty()) {
  261. auto *MM = Worklist.pop_back_val();
  262. llvm::errs() << " ModuleMacro " << MM << " "
  263. << MM->getOwningModule()->getFullModuleName();
  264. if (!MM->getMacroInfo())
  265. llvm::errs() << " undef";
  266. if (Active.count(MM))
  267. llvm::errs() << " active";
  268. else if (!CurSubmoduleState->VisibleModules.isVisible(
  269. MM->getOwningModule()))
  270. llvm::errs() << " hidden";
  271. else if (MM->getMacroInfo())
  272. llvm::errs() << " overridden";
  273. if (!MM->overrides().empty()) {
  274. llvm::errs() << " overrides";
  275. for (auto *O : MM->overrides()) {
  276. llvm::errs() << " " << O->getOwningModule()->getFullModuleName();
  277. if (Visited.insert(O).second)
  278. Worklist.push_back(O);
  279. }
  280. }
  281. llvm::errs() << "\n";
  282. if (auto *MI = MM->getMacroInfo()) {
  283. llvm::errs() << " ";
  284. MI->dump();
  285. llvm::errs() << "\n";
  286. }
  287. }
  288. }
  289. /// RegisterBuiltinMacro - Register the specified identifier in the identifier
  290. /// table and mark it as a builtin macro to be expanded.
  291. static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
  292. // Get the identifier.
  293. IdentifierInfo *Id = PP.getIdentifierInfo(Name);
  294. // Mark it as being a macro that is builtin.
  295. MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
  296. MI->setIsBuiltinMacro();
  297. PP.appendDefMacroDirective(Id, MI);
  298. return Id;
  299. }
  300. /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
  301. /// identifier table.
  302. void Preprocessor::RegisterBuiltinMacros() {
  303. Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
  304. Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
  305. Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
  306. Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
  307. Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
  308. Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
  309. // C++ Standing Document Extensions.
  310. if (getLangOpts().CPlusPlus)
  311. Ident__has_cpp_attribute =
  312. RegisterBuiltinMacro(*this, "__has_cpp_attribute");
  313. else
  314. Ident__has_cpp_attribute = nullptr;
  315. // GCC Extensions.
  316. Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
  317. Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
  318. Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
  319. // Microsoft Extensions.
  320. if (getLangOpts().MicrosoftExt) {
  321. Ident__identifier = RegisterBuiltinMacro(*this, "__identifier");
  322. Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
  323. } else {
  324. Ident__identifier = nullptr;
  325. Ident__pragma = nullptr;
  326. }
  327. // Clang Extensions.
  328. Ident__FILE_NAME__ = RegisterBuiltinMacro(*this, "__FILE_NAME__");
  329. Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
  330. Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension");
  331. Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
  332. Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
  333. if (!getLangOpts().CPlusPlus)
  334. Ident__has_c_attribute = RegisterBuiltinMacro(*this, "__has_c_attribute");
  335. else
  336. Ident__has_c_attribute = nullptr;
  337. Ident__has_declspec = RegisterBuiltinMacro(*this, "__has_declspec_attribute");
  338. Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
  339. Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
  340. Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning");
  341. Ident__is_identifier = RegisterBuiltinMacro(*this, "__is_identifier");
  342. Ident__is_target_arch = RegisterBuiltinMacro(*this, "__is_target_arch");
  343. Ident__is_target_vendor = RegisterBuiltinMacro(*this, "__is_target_vendor");
  344. Ident__is_target_os = RegisterBuiltinMacro(*this, "__is_target_os");
  345. Ident__is_target_environment =
  346. RegisterBuiltinMacro(*this, "__is_target_environment");
  347. // Modules.
  348. Ident__building_module = RegisterBuiltinMacro(*this, "__building_module");
  349. if (!getLangOpts().CurrentModule.empty())
  350. Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__");
  351. else
  352. Ident__MODULE__ = nullptr;
  353. }
  354. /// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
  355. /// in its expansion, currently expands to that token literally.
  356. static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
  357. const IdentifierInfo *MacroIdent,
  358. Preprocessor &PP) {
  359. IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
  360. // If the token isn't an identifier, it's always literally expanded.
  361. if (!II) return true;
  362. // If the information about this identifier is out of date, update it from
  363. // the external source.
  364. if (II->isOutOfDate())
  365. PP.getExternalSource()->updateOutOfDateIdentifier(*II);
  366. // If the identifier is a macro, and if that macro is enabled, it may be
  367. // expanded so it's not a trivial expansion.
  368. if (auto *ExpansionMI = PP.getMacroInfo(II))
  369. if (ExpansionMI->isEnabled() &&
  370. // Fast expanding "#define X X" is ok, because X would be disabled.
  371. II != MacroIdent)
  372. return false;
  373. // If this is an object-like macro invocation, it is safe to trivially expand
  374. // it.
  375. if (MI->isObjectLike()) return true;
  376. // If this is a function-like macro invocation, it's safe to trivially expand
  377. // as long as the identifier is not a macro argument.
  378. return !llvm::is_contained(MI->params(), II);
  379. }
  380. /// isNextPPTokenLParen - Determine whether the next preprocessor token to be
  381. /// lexed is a '('. If so, consume the token and return true, if not, this
  382. /// method should have no observable side-effect on the lexed tokens.
  383. bool Preprocessor::isNextPPTokenLParen() {
  384. // Do some quick tests for rejection cases.
  385. unsigned Val;
  386. if (CurLexer)
  387. Val = CurLexer->isNextPPTokenLParen();
  388. else
  389. Val = CurTokenLexer->isNextTokenLParen();
  390. if (Val == 2) {
  391. // We have run off the end. If it's a source file we don't
  392. // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
  393. // macro stack.
  394. if (CurPPLexer)
  395. return false;
  396. for (const IncludeStackInfo &Entry : llvm::reverse(IncludeMacroStack)) {
  397. if (Entry.TheLexer)
  398. Val = Entry.TheLexer->isNextPPTokenLParen();
  399. else
  400. Val = Entry.TheTokenLexer->isNextTokenLParen();
  401. if (Val != 2)
  402. break;
  403. // Ran off the end of a source file?
  404. if (Entry.ThePPLexer)
  405. return false;
  406. }
  407. }
  408. // Okay, if we know that the token is a '(', lex it and return. Otherwise we
  409. // have found something that isn't a '(' or we found the end of the
  410. // translation unit. In either case, return false.
  411. return Val == 1;
  412. }
  413. /// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
  414. /// expanded as a macro, handle it and return the next token as 'Identifier'.
  415. bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
  416. const MacroDefinition &M) {
  417. emitMacroExpansionWarnings(Identifier);
  418. MacroInfo *MI = M.getMacroInfo();
  419. // If this is a macro expansion in the "#if !defined(x)" line for the file,
  420. // then the macro could expand to different things in other contexts, we need
  421. // to disable the optimization in this case.
  422. if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
  423. // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
  424. if (MI->isBuiltinMacro()) {
  425. if (Callbacks)
  426. Callbacks->MacroExpands(Identifier, M, Identifier.getLocation(),
  427. /*Args=*/nullptr);
  428. ExpandBuiltinMacro(Identifier);
  429. return true;
  430. }
  431. /// Args - If this is a function-like macro expansion, this contains,
  432. /// for each macro argument, the list of tokens that were provided to the
  433. /// invocation.
  434. MacroArgs *Args = nullptr;
  435. // Remember where the end of the expansion occurred. For an object-like
  436. // macro, this is the identifier. For a function-like macro, this is the ')'.
  437. SourceLocation ExpansionEnd = Identifier.getLocation();
  438. // If this is a function-like macro, read the arguments.
  439. if (MI->isFunctionLike()) {
  440. // Remember that we are now parsing the arguments to a macro invocation.
  441. // Preprocessor directives used inside macro arguments are not portable, and
  442. // this enables the warning.
  443. InMacroArgs = true;
  444. ArgMacro = &Identifier;
  445. Args = ReadMacroCallArgumentList(Identifier, MI, ExpansionEnd);
  446. // Finished parsing args.
  447. InMacroArgs = false;
  448. ArgMacro = nullptr;
  449. // If there was an error parsing the arguments, bail out.
  450. if (!Args) return true;
  451. ++NumFnMacroExpanded;
  452. } else {
  453. ++NumMacroExpanded;
  454. }
  455. // Notice that this macro has been used.
  456. markMacroAsUsed(MI);
  457. // Remember where the token is expanded.
  458. SourceLocation ExpandLoc = Identifier.getLocation();
  459. SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
  460. if (Callbacks) {
  461. if (InMacroArgs) {
  462. // We can have macro expansion inside a conditional directive while
  463. // reading the function macro arguments. To ensure, in that case, that
  464. // MacroExpands callbacks still happen in source order, queue this
  465. // callback to have it happen after the function macro callback.
  466. DelayedMacroExpandsCallbacks.push_back(
  467. MacroExpandsInfo(Identifier, M, ExpansionRange));
  468. } else {
  469. Callbacks->MacroExpands(Identifier, M, ExpansionRange, Args);
  470. if (!DelayedMacroExpandsCallbacks.empty()) {
  471. for (const MacroExpandsInfo &Info : DelayedMacroExpandsCallbacks) {
  472. // FIXME: We lose macro args info with delayed callback.
  473. Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range,
  474. /*Args=*/nullptr);
  475. }
  476. DelayedMacroExpandsCallbacks.clear();
  477. }
  478. }
  479. }
  480. // If the macro definition is ambiguous, complain.
  481. if (M.isAmbiguous()) {
  482. Diag(Identifier, diag::warn_pp_ambiguous_macro)
  483. << Identifier.getIdentifierInfo();
  484. Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)
  485. << Identifier.getIdentifierInfo();
  486. M.forAllDefinitions([&](const MacroInfo *OtherMI) {
  487. if (OtherMI != MI)
  488. Diag(OtherMI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_other)
  489. << Identifier.getIdentifierInfo();
  490. });
  491. }
  492. // If we started lexing a macro, enter the macro expansion body.
  493. // If this macro expands to no tokens, don't bother to push it onto the
  494. // expansion stack, only to take it right back off.
  495. if (MI->getNumTokens() == 0) {
  496. // No need for arg info.
  497. if (Args) Args->destroy(*this);
  498. // Propagate whitespace info as if we had pushed, then popped,
  499. // a macro context.
  500. Identifier.setFlag(Token::LeadingEmptyMacro);
  501. PropagateLineStartLeadingSpaceInfo(Identifier);
  502. ++NumFastMacroExpanded;
  503. return false;
  504. } else if (MI->getNumTokens() == 1 &&
  505. isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
  506. *this)) {
  507. // Otherwise, if this macro expands into a single trivially-expanded
  508. // token: expand it now. This handles common cases like
  509. // "#define VAL 42".
  510. // No need for arg info.
  511. if (Args) Args->destroy(*this);
  512. // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
  513. // identifier to the expanded token.
  514. bool isAtStartOfLine = Identifier.isAtStartOfLine();
  515. bool hasLeadingSpace = Identifier.hasLeadingSpace();
  516. // Replace the result token.
  517. Identifier = MI->getReplacementToken(0);
  518. // Restore the StartOfLine/LeadingSpace markers.
  519. Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
  520. Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
  521. // Update the tokens location to include both its expansion and physical
  522. // locations.
  523. SourceLocation Loc =
  524. SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
  525. ExpansionEnd,Identifier.getLength());
  526. Identifier.setLocation(Loc);
  527. // If this is a disabled macro or #define X X, we must mark the result as
  528. // unexpandable.
  529. if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
  530. if (MacroInfo *NewMI = getMacroInfo(NewII))
  531. if (!NewMI->isEnabled() || NewMI == MI) {
  532. Identifier.setFlag(Token::DisableExpand);
  533. // Don't warn for "#define X X" like "#define bool bool" from
  534. // stdbool.h.
  535. if (NewMI != MI || MI->isFunctionLike())
  536. Diag(Identifier, diag::pp_disabled_macro_expansion);
  537. }
  538. }
  539. // Since this is not an identifier token, it can't be macro expanded, so
  540. // we're done.
  541. ++NumFastMacroExpanded;
  542. return true;
  543. }
  544. // Start expanding the macro.
  545. EnterMacro(Identifier, ExpansionEnd, MI, Args);
  546. return false;
  547. }
  548. enum Bracket {
  549. Brace,
  550. Paren
  551. };
  552. /// CheckMatchedBrackets - Returns true if the braces and parentheses in the
  553. /// token vector are properly nested.
  554. static bool CheckMatchedBrackets(const SmallVectorImpl<Token> &Tokens) {
  555. SmallVector<Bracket, 8> Brackets;
  556. for (SmallVectorImpl<Token>::const_iterator I = Tokens.begin(),
  557. E = Tokens.end();
  558. I != E; ++I) {
  559. if (I->is(tok::l_paren)) {
  560. Brackets.push_back(Paren);
  561. } else if (I->is(tok::r_paren)) {
  562. if (Brackets.empty() || Brackets.back() == Brace)
  563. return false;
  564. Brackets.pop_back();
  565. } else if (I->is(tok::l_brace)) {
  566. Brackets.push_back(Brace);
  567. } else if (I->is(tok::r_brace)) {
  568. if (Brackets.empty() || Brackets.back() == Paren)
  569. return false;
  570. Brackets.pop_back();
  571. }
  572. }
  573. return Brackets.empty();
  574. }
  575. /// GenerateNewArgTokens - Returns true if OldTokens can be converted to a new
  576. /// vector of tokens in NewTokens. The new number of arguments will be placed
  577. /// in NumArgs and the ranges which need to surrounded in parentheses will be
  578. /// in ParenHints.
  579. /// Returns false if the token stream cannot be changed. If this is because
  580. /// of an initializer list starting a macro argument, the range of those
  581. /// initializer lists will be place in InitLists.
  582. static bool GenerateNewArgTokens(Preprocessor &PP,
  583. SmallVectorImpl<Token> &OldTokens,
  584. SmallVectorImpl<Token> &NewTokens,
  585. unsigned &NumArgs,
  586. SmallVectorImpl<SourceRange> &ParenHints,
  587. SmallVectorImpl<SourceRange> &InitLists) {
  588. if (!CheckMatchedBrackets(OldTokens))
  589. return false;
  590. // Once it is known that the brackets are matched, only a simple count of the
  591. // braces is needed.
  592. unsigned Braces = 0;
  593. // First token of a new macro argument.
  594. SmallVectorImpl<Token>::iterator ArgStartIterator = OldTokens.begin();
  595. // First closing brace in a new macro argument. Used to generate
  596. // SourceRanges for InitLists.
  597. SmallVectorImpl<Token>::iterator ClosingBrace = OldTokens.end();
  598. NumArgs = 0;
  599. Token TempToken;
  600. // Set to true when a macro separator token is found inside a braced list.
  601. // If true, the fixed argument spans multiple old arguments and ParenHints
  602. // will be updated.
  603. bool FoundSeparatorToken = false;
  604. for (SmallVectorImpl<Token>::iterator I = OldTokens.begin(),
  605. E = OldTokens.end();
  606. I != E; ++I) {
  607. if (I->is(tok::l_brace)) {
  608. ++Braces;
  609. } else if (I->is(tok::r_brace)) {
  610. --Braces;
  611. if (Braces == 0 && ClosingBrace == E && FoundSeparatorToken)
  612. ClosingBrace = I;
  613. } else if (I->is(tok::eof)) {
  614. // EOF token is used to separate macro arguments
  615. if (Braces != 0) {
  616. // Assume comma separator is actually braced list separator and change
  617. // it back to a comma.
  618. FoundSeparatorToken = true;
  619. I->setKind(tok::comma);
  620. I->setLength(1);
  621. } else { // Braces == 0
  622. // Separator token still separates arguments.
  623. ++NumArgs;
  624. // If the argument starts with a brace, it can't be fixed with
  625. // parentheses. A different diagnostic will be given.
  626. if (FoundSeparatorToken && ArgStartIterator->is(tok::l_brace)) {
  627. InitLists.push_back(
  628. SourceRange(ArgStartIterator->getLocation(),
  629. PP.getLocForEndOfToken(ClosingBrace->getLocation())));
  630. ClosingBrace = E;
  631. }
  632. // Add left paren
  633. if (FoundSeparatorToken) {
  634. TempToken.startToken();
  635. TempToken.setKind(tok::l_paren);
  636. TempToken.setLocation(ArgStartIterator->getLocation());
  637. TempToken.setLength(0);
  638. NewTokens.push_back(TempToken);
  639. }
  640. // Copy over argument tokens
  641. NewTokens.insert(NewTokens.end(), ArgStartIterator, I);
  642. // Add right paren and store the paren locations in ParenHints
  643. if (FoundSeparatorToken) {
  644. SourceLocation Loc = PP.getLocForEndOfToken((I - 1)->getLocation());
  645. TempToken.startToken();
  646. TempToken.setKind(tok::r_paren);
  647. TempToken.setLocation(Loc);
  648. TempToken.setLength(0);
  649. NewTokens.push_back(TempToken);
  650. ParenHints.push_back(SourceRange(ArgStartIterator->getLocation(),
  651. Loc));
  652. }
  653. // Copy separator token
  654. NewTokens.push_back(*I);
  655. // Reset values
  656. ArgStartIterator = I + 1;
  657. FoundSeparatorToken = false;
  658. }
  659. }
  660. }
  661. return !ParenHints.empty() && InitLists.empty();
  662. }
  663. /// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
  664. /// token is the '(' of the macro, this method is invoked to read all of the
  665. /// actual arguments specified for the macro invocation. This returns null on
  666. /// error.
  667. MacroArgs *Preprocessor::ReadMacroCallArgumentList(Token &MacroName,
  668. MacroInfo *MI,
  669. SourceLocation &MacroEnd) {
  670. // The number of fixed arguments to parse.
  671. unsigned NumFixedArgsLeft = MI->getNumParams();
  672. bool isVariadic = MI->isVariadic();
  673. // Outer loop, while there are more arguments, keep reading them.
  674. Token Tok;
  675. // Read arguments as unexpanded tokens. This avoids issues, e.g., where
  676. // an argument value in a macro could expand to ',' or '(' or ')'.
  677. LexUnexpandedToken(Tok);
  678. assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
  679. // ArgTokens - Build up a list of tokens that make up each argument. Each
  680. // argument is separated by an EOF token. Use a SmallVector so we can avoid
  681. // heap allocations in the common case.
  682. SmallVector<Token, 64> ArgTokens;
  683. bool ContainsCodeCompletionTok = false;
  684. bool FoundElidedComma = false;
  685. SourceLocation TooManyArgsLoc;
  686. unsigned NumActuals = 0;
  687. while (Tok.isNot(tok::r_paren)) {
  688. if (ContainsCodeCompletionTok && Tok.isOneOf(tok::eof, tok::eod))
  689. break;
  690. assert(Tok.isOneOf(tok::l_paren, tok::comma) &&
  691. "only expect argument separators here");
  692. size_t ArgTokenStart = ArgTokens.size();
  693. SourceLocation ArgStartLoc = Tok.getLocation();
  694. // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
  695. // that we already consumed the first one.
  696. unsigned NumParens = 0;
  697. while (true) {
  698. // Read arguments as unexpanded tokens. This avoids issues, e.g., where
  699. // an argument value in a macro could expand to ',' or '(' or ')'.
  700. LexUnexpandedToken(Tok);
  701. if (Tok.isOneOf(tok::eof, tok::eod)) { // "#if f(<eof>" & "#if f(\n"
  702. if (!ContainsCodeCompletionTok) {
  703. Diag(MacroName, diag::err_unterm_macro_invoc);
  704. Diag(MI->getDefinitionLoc(), diag::note_macro_here)
  705. << MacroName.getIdentifierInfo();
  706. // Do not lose the EOF/EOD. Return it to the client.
  707. MacroName = Tok;
  708. return nullptr;
  709. }
  710. // Do not lose the EOF/EOD.
  711. auto Toks = std::make_unique<Token[]>(1);
  712. Toks[0] = Tok;
  713. EnterTokenStream(std::move(Toks), 1, true, /*IsReinject*/ false);
  714. break;
  715. } else if (Tok.is(tok::r_paren)) {
  716. // If we found the ) token, the macro arg list is done.
  717. if (NumParens-- == 0) {
  718. MacroEnd = Tok.getLocation();
  719. if (!ArgTokens.empty() &&
  720. ArgTokens.back().commaAfterElided()) {
  721. FoundElidedComma = true;
  722. }
  723. break;
  724. }
  725. } else if (Tok.is(tok::l_paren)) {
  726. ++NumParens;
  727. } else if (Tok.is(tok::comma)) {
  728. // In Microsoft-compatibility mode, single commas from nested macro
  729. // expansions should not be considered as argument separators. We test
  730. // for this with the IgnoredComma token flag.
  731. if (Tok.getFlags() & Token::IgnoredComma) {
  732. // However, in MSVC's preprocessor, subsequent expansions do treat
  733. // these commas as argument separators. This leads to a common
  734. // workaround used in macros that need to work in both MSVC and
  735. // compliant preprocessors. Therefore, the IgnoredComma flag can only
  736. // apply once to any given token.
  737. Tok.clearFlag(Token::IgnoredComma);
  738. } else if (NumParens == 0) {
  739. // Comma ends this argument if there are more fixed arguments
  740. // expected. However, if this is a variadic macro, and this is part of
  741. // the variadic part, then the comma is just an argument token.
  742. if (!isVariadic)
  743. break;
  744. if (NumFixedArgsLeft > 1)
  745. break;
  746. }
  747. } else if (Tok.is(tok::comment) && !KeepMacroComments) {
  748. // If this is a comment token in the argument list and we're just in
  749. // -C mode (not -CC mode), discard the comment.
  750. continue;
  751. } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo() != nullptr) {
  752. // Reading macro arguments can cause macros that we are currently
  753. // expanding from to be popped off the expansion stack. Doing so causes
  754. // them to be reenabled for expansion. Here we record whether any
  755. // identifiers we lex as macro arguments correspond to disabled macros.
  756. // If so, we mark the token as noexpand. This is a subtle aspect of
  757. // C99 6.10.3.4p2.
  758. if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
  759. if (!MI->isEnabled())
  760. Tok.setFlag(Token::DisableExpand);
  761. } else if (Tok.is(tok::code_completion)) {
  762. ContainsCodeCompletionTok = true;
  763. if (CodeComplete)
  764. CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
  765. MI, NumActuals);
  766. // Don't mark that we reached the code-completion point because the
  767. // parser is going to handle the token and there will be another
  768. // code-completion callback.
  769. }
  770. ArgTokens.push_back(Tok);
  771. }
  772. // If this was an empty argument list foo(), don't add this as an empty
  773. // argument.
  774. if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
  775. break;
  776. // If this is not a variadic macro, and too many args were specified, emit
  777. // an error.
  778. if (!isVariadic && NumFixedArgsLeft == 0 && TooManyArgsLoc.isInvalid()) {
  779. if (ArgTokens.size() != ArgTokenStart)
  780. TooManyArgsLoc = ArgTokens[ArgTokenStart].getLocation();
  781. else
  782. TooManyArgsLoc = ArgStartLoc;
  783. }
  784. // Empty arguments are standard in C99 and C++0x, and are supported as an
  785. // extension in other modes.
  786. if (ArgTokens.size() == ArgTokenStart && !getLangOpts().C99)
  787. Diag(Tok, getLangOpts().CPlusPlus11
  788. ? diag::warn_cxx98_compat_empty_fnmacro_arg
  789. : diag::ext_empty_fnmacro_arg);
  790. // Add a marker EOF token to the end of the token list for this argument.
  791. Token EOFTok;
  792. EOFTok.startToken();
  793. EOFTok.setKind(tok::eof);
  794. EOFTok.setLocation(Tok.getLocation());
  795. EOFTok.setLength(0);
  796. ArgTokens.push_back(EOFTok);
  797. ++NumActuals;
  798. if (!ContainsCodeCompletionTok && NumFixedArgsLeft != 0)
  799. --NumFixedArgsLeft;
  800. }
  801. // Okay, we either found the r_paren. Check to see if we parsed too few
  802. // arguments.
  803. unsigned MinArgsExpected = MI->getNumParams();
  804. // If this is not a variadic macro, and too many args were specified, emit
  805. // an error.
  806. if (!isVariadic && NumActuals > MinArgsExpected &&
  807. !ContainsCodeCompletionTok) {
  808. // Emit the diagnostic at the macro name in case there is a missing ).
  809. // Emitting it at the , could be far away from the macro name.
  810. Diag(TooManyArgsLoc, diag::err_too_many_args_in_macro_invoc);
  811. Diag(MI->getDefinitionLoc(), diag::note_macro_here)
  812. << MacroName.getIdentifierInfo();
  813. // Commas from braced initializer lists will be treated as argument
  814. // separators inside macros. Attempt to correct for this with parentheses.
  815. // TODO: See if this can be generalized to angle brackets for templates
  816. // inside macro arguments.
  817. SmallVector<Token, 4> FixedArgTokens;
  818. unsigned FixedNumArgs = 0;
  819. SmallVector<SourceRange, 4> ParenHints, InitLists;
  820. if (!GenerateNewArgTokens(*this, ArgTokens, FixedArgTokens, FixedNumArgs,
  821. ParenHints, InitLists)) {
  822. if (!InitLists.empty()) {
  823. DiagnosticBuilder DB =
  824. Diag(MacroName,
  825. diag::note_init_list_at_beginning_of_macro_argument);
  826. for (SourceRange Range : InitLists)
  827. DB << Range;
  828. }
  829. return nullptr;
  830. }
  831. if (FixedNumArgs != MinArgsExpected)
  832. return nullptr;
  833. DiagnosticBuilder DB = Diag(MacroName, diag::note_suggest_parens_for_macro);
  834. for (SourceRange ParenLocation : ParenHints) {
  835. DB << FixItHint::CreateInsertion(ParenLocation.getBegin(), "(");
  836. DB << FixItHint::CreateInsertion(ParenLocation.getEnd(), ")");
  837. }
  838. ArgTokens.swap(FixedArgTokens);
  839. NumActuals = FixedNumArgs;
  840. }
  841. // See MacroArgs instance var for description of this.
  842. bool isVarargsElided = false;
  843. if (ContainsCodeCompletionTok) {
  844. // Recover from not-fully-formed macro invocation during code-completion.
  845. Token EOFTok;
  846. EOFTok.startToken();
  847. EOFTok.setKind(tok::eof);
  848. EOFTok.setLocation(Tok.getLocation());
  849. EOFTok.setLength(0);
  850. for (; NumActuals < MinArgsExpected; ++NumActuals)
  851. ArgTokens.push_back(EOFTok);
  852. }
  853. if (NumActuals < MinArgsExpected) {
  854. // There are several cases where too few arguments is ok, handle them now.
  855. if (NumActuals == 0 && MinArgsExpected == 1) {
  856. // #define A(X) or #define A(...) ---> A()
  857. // If there is exactly one argument, and that argument is missing,
  858. // then we have an empty "()" argument empty list. This is fine, even if
  859. // the macro expects one argument (the argument is just empty).
  860. isVarargsElided = MI->isVariadic();
  861. } else if ((FoundElidedComma || MI->isVariadic()) &&
  862. (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
  863. (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
  864. // Varargs where the named vararg parameter is missing: OK as extension.
  865. // #define A(x, ...)
  866. // A("blah")
  867. //
  868. // If the macro contains the comma pasting extension, the diagnostic
  869. // is suppressed; we know we'll get another diagnostic later.
  870. if (!MI->hasCommaPasting()) {
  871. // C++20 allows this construct, but standards before C++20 and all C
  872. // standards do not allow the construct (we allow it as an extension).
  873. Diag(Tok, getLangOpts().CPlusPlus20
  874. ? diag::warn_cxx17_compat_missing_varargs_arg
  875. : diag::ext_missing_varargs_arg);
  876. Diag(MI->getDefinitionLoc(), diag::note_macro_here)
  877. << MacroName.getIdentifierInfo();
  878. }
  879. // Remember this occurred, allowing us to elide the comma when used for
  880. // cases like:
  881. // #define A(x, foo...) blah(a, ## foo)
  882. // #define B(x, ...) blah(a, ## __VA_ARGS__)
  883. // #define C(...) blah(a, ## __VA_ARGS__)
  884. // A(x) B(x) C()
  885. isVarargsElided = true;
  886. } else if (!ContainsCodeCompletionTok) {
  887. // Otherwise, emit the error.
  888. Diag(Tok, diag::err_too_few_args_in_macro_invoc);
  889. Diag(MI->getDefinitionLoc(), diag::note_macro_here)
  890. << MacroName.getIdentifierInfo();
  891. return nullptr;
  892. }
  893. // Add a marker EOF token to the end of the token list for this argument.
  894. SourceLocation EndLoc = Tok.getLocation();
  895. Tok.startToken();
  896. Tok.setKind(tok::eof);
  897. Tok.setLocation(EndLoc);
  898. Tok.setLength(0);
  899. ArgTokens.push_back(Tok);
  900. // If we expect two arguments, add both as empty.
  901. if (NumActuals == 0 && MinArgsExpected == 2)
  902. ArgTokens.push_back(Tok);
  903. } else if (NumActuals > MinArgsExpected && !MI->isVariadic() &&
  904. !ContainsCodeCompletionTok) {
  905. // Emit the diagnostic at the macro name in case there is a missing ).
  906. // Emitting it at the , could be far away from the macro name.
  907. Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
  908. Diag(MI->getDefinitionLoc(), diag::note_macro_here)
  909. << MacroName.getIdentifierInfo();
  910. return nullptr;
  911. }
  912. return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
  913. }
  914. /// Keeps macro expanded tokens for TokenLexers.
  915. //
  916. /// Works like a stack; a TokenLexer adds the macro expanded tokens that is
  917. /// going to lex in the cache and when it finishes the tokens are removed
  918. /// from the end of the cache.
  919. Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
  920. ArrayRef<Token> tokens) {
  921. assert(tokLexer);
  922. if (tokens.empty())
  923. return nullptr;
  924. size_t newIndex = MacroExpandedTokens.size();
  925. bool cacheNeedsToGrow = tokens.size() >
  926. MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
  927. MacroExpandedTokens.append(tokens.begin(), tokens.end());
  928. if (cacheNeedsToGrow) {
  929. // Go through all the TokenLexers whose 'Tokens' pointer points in the
  930. // buffer and update the pointers to the (potential) new buffer array.
  931. for (const auto &Lexer : MacroExpandingLexersStack) {
  932. TokenLexer *prevLexer;
  933. size_t tokIndex;
  934. std::tie(prevLexer, tokIndex) = Lexer;
  935. prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
  936. }
  937. }
  938. MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
  939. return MacroExpandedTokens.data() + newIndex;
  940. }
  941. void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
  942. assert(!MacroExpandingLexersStack.empty());
  943. size_t tokIndex = MacroExpandingLexersStack.back().second;
  944. assert(tokIndex < MacroExpandedTokens.size());
  945. // Pop the cached macro expanded tokens from the end.
  946. MacroExpandedTokens.resize(tokIndex);
  947. MacroExpandingLexersStack.pop_back();
  948. }
  949. /// ComputeDATE_TIME - Compute the current time, enter it into the specified
  950. /// scratch buffer, then return DATELoc/TIMELoc locations with the position of
  951. /// the identifier tokens inserted.
  952. static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
  953. Preprocessor &PP) {
  954. time_t TT = time(nullptr);
  955. struct tm *TM = localtime(&TT);
  956. static const char * const Months[] = {
  957. "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
  958. };
  959. {
  960. SmallString<32> TmpBuffer;
  961. llvm::raw_svector_ostream TmpStream(TmpBuffer);
  962. TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
  963. TM->tm_mday, TM->tm_year + 1900);
  964. Token TmpTok;
  965. TmpTok.startToken();
  966. PP.CreateString(TmpStream.str(), TmpTok);
  967. DATELoc = TmpTok.getLocation();
  968. }
  969. {
  970. SmallString<32> TmpBuffer;
  971. llvm::raw_svector_ostream TmpStream(TmpBuffer);
  972. TmpStream << llvm::format("\"%02d:%02d:%02d\"",
  973. TM->tm_hour, TM->tm_min, TM->tm_sec);
  974. Token TmpTok;
  975. TmpTok.startToken();
  976. PP.CreateString(TmpStream.str(), TmpTok);
  977. TIMELoc = TmpTok.getLocation();
  978. }
  979. }
  980. /// HasFeature - Return true if we recognize and implement the feature
  981. /// specified by the identifier as a standard language feature.
  982. static bool HasFeature(const Preprocessor &PP, StringRef Feature) {
  983. const LangOptions &LangOpts = PP.getLangOpts();
  984. // Normalize the feature name, __foo__ becomes foo.
  985. if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4)
  986. Feature = Feature.substr(2, Feature.size() - 4);
  987. #define FEATURE(Name, Predicate) .Case(#Name, Predicate)
  988. return llvm::StringSwitch<bool>(Feature)
  989. #include "clang/Basic/Features.def"
  990. .Default(false);
  991. #undef FEATURE
  992. }
  993. /// HasExtension - Return true if we recognize and implement the feature
  994. /// specified by the identifier, either as an extension or a standard language
  995. /// feature.
  996. static bool HasExtension(const Preprocessor &PP, StringRef Extension) {
  997. if (HasFeature(PP, Extension))
  998. return true;
  999. // If the use of an extension results in an error diagnostic, extensions are
  1000. // effectively unavailable, so just return false here.
  1001. if (PP.getDiagnostics().getExtensionHandlingBehavior() >=
  1002. diag::Severity::Error)
  1003. return false;
  1004. const LangOptions &LangOpts = PP.getLangOpts();
  1005. // Normalize the extension name, __foo__ becomes foo.
  1006. if (Extension.startswith("__") && Extension.endswith("__") &&
  1007. Extension.size() >= 4)
  1008. Extension = Extension.substr(2, Extension.size() - 4);
  1009. // Because we inherit the feature list from HasFeature, this string switch
  1010. // must be less restrictive than HasFeature's.
  1011. #define EXTENSION(Name, Predicate) .Case(#Name, Predicate)
  1012. return llvm::StringSwitch<bool>(Extension)
  1013. #include "clang/Basic/Features.def"
  1014. .Default(false);
  1015. #undef EXTENSION
  1016. }
  1017. /// EvaluateHasIncludeCommon - Process a '__has_include("path")'
  1018. /// or '__has_include_next("path")' expression.
  1019. /// Returns true if successful.
  1020. static bool EvaluateHasIncludeCommon(Token &Tok,
  1021. IdentifierInfo *II, Preprocessor &PP,
  1022. const DirectoryLookup *LookupFrom,
  1023. const FileEntry *LookupFromFile) {
  1024. // Save the location of the current token. If a '(' is later found, use
  1025. // that location. If not, use the end of this location instead.
  1026. SourceLocation LParenLoc = Tok.getLocation();
  1027. // These expressions are only allowed within a preprocessor directive.
  1028. if (!PP.isParsingIfOrElifDirective()) {
  1029. PP.Diag(LParenLoc, diag::err_pp_directive_required) << II;
  1030. // Return a valid identifier token.
  1031. assert(Tok.is(tok::identifier));
  1032. Tok.setIdentifierInfo(II);
  1033. return false;
  1034. }
  1035. // Get '('. If we don't have a '(', try to form a header-name token.
  1036. do {
  1037. if (PP.LexHeaderName(Tok))
  1038. return false;
  1039. } while (Tok.getKind() == tok::comment);
  1040. // Ensure we have a '('.
  1041. if (Tok.isNot(tok::l_paren)) {
  1042. // No '(', use end of last token.
  1043. LParenLoc = PP.getLocForEndOfToken(LParenLoc);
  1044. PP.Diag(LParenLoc, diag::err_pp_expected_after) << II << tok::l_paren;
  1045. // If the next token looks like a filename or the start of one,
  1046. // assume it is and process it as such.
  1047. if (Tok.isNot(tok::header_name))
  1048. return false;
  1049. } else {
  1050. // Save '(' location for possible missing ')' message.
  1051. LParenLoc = Tok.getLocation();
  1052. if (PP.LexHeaderName(Tok))
  1053. return false;
  1054. }
  1055. if (Tok.isNot(tok::header_name)) {
  1056. PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
  1057. return false;
  1058. }
  1059. // Reserve a buffer to get the spelling.
  1060. SmallString<128> FilenameBuffer;
  1061. bool Invalid = false;
  1062. StringRef Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
  1063. if (Invalid)
  1064. return false;
  1065. SourceLocation FilenameLoc = Tok.getLocation();
  1066. // Get ')'.
  1067. PP.LexNonComment(Tok);
  1068. // Ensure we have a trailing ).
  1069. if (Tok.isNot(tok::r_paren)) {
  1070. PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after)
  1071. << II << tok::r_paren;
  1072. PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
  1073. return false;
  1074. }
  1075. bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
  1076. // If GetIncludeFilenameSpelling set the start ptr to null, there was an
  1077. // error.
  1078. if (Filename.empty())
  1079. return false;
  1080. // Search include directories.
  1081. Optional<FileEntryRef> File =
  1082. PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, LookupFromFile,
  1083. nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);
  1084. if (PPCallbacks *Callbacks = PP.getPPCallbacks()) {
  1085. SrcMgr::CharacteristicKind FileType = SrcMgr::C_User;
  1086. if (File)
  1087. FileType =
  1088. PP.getHeaderSearchInfo().getFileDirFlavor(&File->getFileEntry());
  1089. Callbacks->HasInclude(FilenameLoc, Filename, isAngled, File, FileType);
  1090. }
  1091. // Get the result value. A result of true means the file exists.
  1092. return File.hasValue();
  1093. }
  1094. /// EvaluateHasInclude - Process a '__has_include("path")' expression.
  1095. /// Returns true if successful.
  1096. static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
  1097. Preprocessor &PP) {
  1098. return EvaluateHasIncludeCommon(Tok, II, PP, nullptr, nullptr);
  1099. }
  1100. /// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
  1101. /// Returns true if successful.
  1102. static bool EvaluateHasIncludeNext(Token &Tok,
  1103. IdentifierInfo *II, Preprocessor &PP) {
  1104. // __has_include_next is like __has_include, except that we start
  1105. // searching after the current found directory. If we can't do this,
  1106. // issue a diagnostic.
  1107. // FIXME: Factor out duplication with
  1108. // Preprocessor::HandleIncludeNextDirective.
  1109. const DirectoryLookup *Lookup = PP.GetCurDirLookup();
  1110. const FileEntry *LookupFromFile = nullptr;
  1111. if (PP.isInPrimaryFile() && PP.getLangOpts().IsHeaderFile) {
  1112. // If the main file is a header, then it's either for PCH/AST generation,
  1113. // or libclang opened it. Either way, handle it as a normal include below
  1114. // and do not complain about __has_include_next.
  1115. } else if (PP.isInPrimaryFile()) {
  1116. Lookup = nullptr;
  1117. PP.Diag(Tok, diag::pp_include_next_in_primary);
  1118. } else if (PP.getCurrentLexerSubmodule()) {
  1119. // Start looking up in the directory *after* the one in which the current
  1120. // file would be found, if any.
  1121. assert(PP.getCurrentLexer() && "#include_next directive in macro?");
  1122. LookupFromFile = PP.getCurrentLexer()->getFileEntry();
  1123. Lookup = nullptr;
  1124. } else if (!Lookup) {
  1125. PP.Diag(Tok, diag::pp_include_next_absolute_path);
  1126. } else {
  1127. // Start looking up in the next directory.
  1128. ++Lookup;
  1129. }
  1130. return EvaluateHasIncludeCommon(Tok, II, PP, Lookup, LookupFromFile);
  1131. }
  1132. /// Process single-argument builtin feature-like macros that return
  1133. /// integer values.
  1134. static void EvaluateFeatureLikeBuiltinMacro(llvm::raw_svector_ostream& OS,
  1135. Token &Tok, IdentifierInfo *II,
  1136. Preprocessor &PP, bool ExpandArgs,
  1137. llvm::function_ref<
  1138. int(Token &Tok,
  1139. bool &HasLexedNextTok)> Op) {
  1140. // Parse the initial '('.
  1141. PP.LexUnexpandedToken(Tok);
  1142. if (Tok.isNot(tok::l_paren)) {
  1143. PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
  1144. << tok::l_paren;
  1145. // Provide a dummy '0' value on output stream to elide further errors.
  1146. if (!Tok.isOneOf(tok::eof, tok::eod)) {
  1147. OS << 0;
  1148. Tok.setKind(tok::numeric_constant);
  1149. }
  1150. return;
  1151. }
  1152. unsigned ParenDepth = 1;
  1153. SourceLocation LParenLoc = Tok.getLocation();
  1154. llvm::Optional<int> Result;
  1155. Token ResultTok;
  1156. bool SuppressDiagnostic = false;
  1157. while (true) {
  1158. // Parse next token.
  1159. if (ExpandArgs)
  1160. PP.Lex(Tok);
  1161. else
  1162. PP.LexUnexpandedToken(Tok);
  1163. already_lexed:
  1164. switch (Tok.getKind()) {
  1165. case tok::eof:
  1166. case tok::eod:
  1167. // Don't provide even a dummy value if the eod or eof marker is
  1168. // reached. Simply provide a diagnostic.
  1169. PP.Diag(Tok.getLocation(), diag::err_unterm_macro_invoc);
  1170. return;
  1171. case tok::comma:
  1172. if (!SuppressDiagnostic) {
  1173. PP.Diag(Tok.getLocation(), diag::err_too_many_args_in_macro_invoc);
  1174. SuppressDiagnostic = true;
  1175. }
  1176. continue;
  1177. case tok::l_paren:
  1178. ++ParenDepth;
  1179. if (Result.hasValue())
  1180. break;
  1181. if (!SuppressDiagnostic) {
  1182. PP.Diag(Tok.getLocation(), diag::err_pp_nested_paren) << II;
  1183. SuppressDiagnostic = true;
  1184. }
  1185. continue;
  1186. case tok::r_paren:
  1187. if (--ParenDepth > 0)
  1188. continue;
  1189. // The last ')' has been reached; return the value if one found or
  1190. // a diagnostic and a dummy value.
  1191. if (Result.hasValue()) {
  1192. OS << Result.getValue();
  1193. // For strict conformance to __has_cpp_attribute rules, use 'L'
  1194. // suffix for dated literals.
  1195. if (Result.getValue() > 1)
  1196. OS << 'L';
  1197. } else {
  1198. OS << 0;
  1199. if (!SuppressDiagnostic)
  1200. PP.Diag(Tok.getLocation(), diag::err_too_few_args_in_macro_invoc);
  1201. }
  1202. Tok.setKind(tok::numeric_constant);
  1203. return;
  1204. default: {
  1205. // Parse the macro argument, if one not found so far.
  1206. if (Result.hasValue())
  1207. break;
  1208. bool HasLexedNextToken = false;
  1209. Result = Op(Tok, HasLexedNextToken);
  1210. ResultTok = Tok;
  1211. if (HasLexedNextToken)
  1212. goto already_lexed;
  1213. continue;
  1214. }
  1215. }
  1216. // Diagnose missing ')'.
  1217. if (!SuppressDiagnostic) {
  1218. if (auto Diag = PP.Diag(Tok.getLocation(), diag::err_pp_expected_after)) {
  1219. if (IdentifierInfo *LastII = ResultTok.getIdentifierInfo())
  1220. Diag << LastII;
  1221. else
  1222. Diag << ResultTok.getKind();
  1223. Diag << tok::r_paren << ResultTok.getLocation();
  1224. }
  1225. PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
  1226. SuppressDiagnostic = true;
  1227. }
  1228. }
  1229. }
  1230. /// Helper function to return the IdentifierInfo structure of a Token
  1231. /// or generate a diagnostic if none available.
  1232. static IdentifierInfo *ExpectFeatureIdentifierInfo(Token &Tok,
  1233. Preprocessor &PP,
  1234. signed DiagID) {
  1235. IdentifierInfo *II;
  1236. if (!Tok.isAnnotation() && (II = Tok.getIdentifierInfo()))
  1237. return II;
  1238. PP.Diag(Tok.getLocation(), DiagID);
  1239. return nullptr;
  1240. }
  1241. /// Implements the __is_target_arch builtin macro.
  1242. static bool isTargetArch(const TargetInfo &TI, const IdentifierInfo *II) {
  1243. std::string ArchName = II->getName().lower() + "--";
  1244. llvm::Triple Arch(ArchName);
  1245. const llvm::Triple &TT = TI.getTriple();
  1246. if (TT.isThumb()) {
  1247. // arm matches thumb or thumbv7. armv7 matches thumbv7.
  1248. if ((Arch.getSubArch() == llvm::Triple::NoSubArch ||
  1249. Arch.getSubArch() == TT.getSubArch()) &&
  1250. ((TT.getArch() == llvm::Triple::thumb &&
  1251. Arch.getArch() == llvm::Triple::arm) ||
  1252. (TT.getArch() == llvm::Triple::thumbeb &&
  1253. Arch.getArch() == llvm::Triple::armeb)))
  1254. return true;
  1255. }
  1256. // Check the parsed arch when it has no sub arch to allow Clang to
  1257. // match thumb to thumbv7 but to prohibit matching thumbv6 to thumbv7.
  1258. return (Arch.getSubArch() == llvm::Triple::NoSubArch ||
  1259. Arch.getSubArch() == TT.getSubArch()) &&
  1260. Arch.getArch() == TT.getArch();
  1261. }
  1262. /// Implements the __is_target_vendor builtin macro.
  1263. static bool isTargetVendor(const TargetInfo &TI, const IdentifierInfo *II) {
  1264. StringRef VendorName = TI.getTriple().getVendorName();
  1265. if (VendorName.empty())
  1266. VendorName = "unknown";
  1267. return VendorName.equals_insensitive(II->getName());
  1268. }
  1269. /// Implements the __is_target_os builtin macro.
  1270. static bool isTargetOS(const TargetInfo &TI, const IdentifierInfo *II) {
  1271. std::string OSName =
  1272. (llvm::Twine("unknown-unknown-") + II->getName().lower()).str();
  1273. llvm::Triple OS(OSName);
  1274. if (OS.getOS() == llvm::Triple::Darwin) {
  1275. // Darwin matches macos, ios, etc.
  1276. return TI.getTriple().isOSDarwin();
  1277. }
  1278. return TI.getTriple().getOS() == OS.getOS();
  1279. }
  1280. /// Implements the __is_target_environment builtin macro.
  1281. static bool isTargetEnvironment(const TargetInfo &TI,
  1282. const IdentifierInfo *II) {
  1283. std::string EnvName = (llvm::Twine("---") + II->getName().lower()).str();
  1284. llvm::Triple Env(EnvName);
  1285. return TI.getTriple().getEnvironment() == Env.getEnvironment();
  1286. }
  1287. /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
  1288. /// as a builtin macro, handle it and return the next token as 'Tok'.
  1289. void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
  1290. // Figure out which token this is.
  1291. IdentifierInfo *II = Tok.getIdentifierInfo();
  1292. assert(II && "Can't be a macro without id info!");
  1293. // If this is an _Pragma or Microsoft __pragma directive, expand it,
  1294. // invoke the pragma handler, then lex the token after it.
  1295. if (II == Ident_Pragma)
  1296. return Handle_Pragma(Tok);
  1297. else if (II == Ident__pragma) // in non-MS mode this is null
  1298. return HandleMicrosoft__pragma(Tok);
  1299. ++NumBuiltinMacroExpanded;
  1300. SmallString<128> TmpBuffer;
  1301. llvm::raw_svector_ostream OS(TmpBuffer);
  1302. // Set up the return result.
  1303. Tok.setIdentifierInfo(nullptr);
  1304. Tok.clearFlag(Token::NeedsCleaning);
  1305. bool IsAtStartOfLine = Tok.isAtStartOfLine();
  1306. bool HasLeadingSpace = Tok.hasLeadingSpace();
  1307. if (II == Ident__LINE__) {
  1308. // C99 6.10.8: "__LINE__: The presumed line number (within the current
  1309. // source file) of the current source line (an integer constant)". This can
  1310. // be affected by #line.
  1311. SourceLocation Loc = Tok.getLocation();
  1312. // Advance to the location of the first _, this might not be the first byte
  1313. // of the token if it starts with an escaped newline.
  1314. Loc = AdvanceToTokenCharacter(Loc, 0);
  1315. // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
  1316. // a macro expansion. This doesn't matter for object-like macros, but
  1317. // can matter for a function-like macro that expands to contain __LINE__.
  1318. // Skip down through expansion points until we find a file loc for the
  1319. // end of the expansion history.
  1320. Loc = SourceMgr.getExpansionRange(Loc).getEnd();
  1321. PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
  1322. // __LINE__ expands to a simple numeric value.
  1323. OS << (PLoc.isValid()? PLoc.getLine() : 1);
  1324. Tok.setKind(tok::numeric_constant);
  1325. } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__ ||
  1326. II == Ident__FILE_NAME__) {
  1327. // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
  1328. // character string literal)". This can be affected by #line.
  1329. PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
  1330. // __BASE_FILE__ is a GNU extension that returns the top of the presumed
  1331. // #include stack instead of the current file.
  1332. if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
  1333. SourceLocation NextLoc = PLoc.getIncludeLoc();
  1334. while (NextLoc.isValid()) {
  1335. PLoc = SourceMgr.getPresumedLoc(NextLoc);
  1336. if (PLoc.isInvalid())
  1337. break;
  1338. NextLoc = PLoc.getIncludeLoc();
  1339. }
  1340. }
  1341. // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
  1342. SmallString<256> FN;
  1343. if (PLoc.isValid()) {
  1344. // __FILE_NAME__ is a Clang-specific extension that expands to the
  1345. // the last part of __FILE__.
  1346. if (II == Ident__FILE_NAME__) {
  1347. // Try to get the last path component, failing that return the original
  1348. // presumed location.
  1349. StringRef PLFileName = llvm::sys::path::filename(PLoc.getFilename());
  1350. if (PLFileName != "")
  1351. FN += PLFileName;
  1352. else
  1353. FN += PLoc.getFilename();
  1354. } else {
  1355. FN += PLoc.getFilename();
  1356. }
  1357. getLangOpts().remapPathPrefix(FN);
  1358. Lexer::Stringify(FN);
  1359. OS << '"' << FN << '"';
  1360. }
  1361. Tok.setKind(tok::string_literal);
  1362. } else if (II == Ident__DATE__) {
  1363. Diag(Tok.getLocation(), diag::warn_pp_date_time);
  1364. if (!DATELoc.isValid())
  1365. ComputeDATE_TIME(DATELoc, TIMELoc, *this);
  1366. Tok.setKind(tok::string_literal);
  1367. Tok.setLength(strlen("\"Mmm dd yyyy\""));
  1368. Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
  1369. Tok.getLocation(),
  1370. Tok.getLength()));
  1371. return;
  1372. } else if (II == Ident__TIME__) {
  1373. Diag(Tok.getLocation(), diag::warn_pp_date_time);
  1374. if (!TIMELoc.isValid())
  1375. ComputeDATE_TIME(DATELoc, TIMELoc, *this);
  1376. Tok.setKind(tok::string_literal);
  1377. Tok.setLength(strlen("\"hh:mm:ss\""));
  1378. Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
  1379. Tok.getLocation(),
  1380. Tok.getLength()));
  1381. return;
  1382. } else if (II == Ident__INCLUDE_LEVEL__) {
  1383. // Compute the presumed include depth of this token. This can be affected
  1384. // by GNU line markers.
  1385. unsigned Depth = 0;
  1386. PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
  1387. if (PLoc.isValid()) {
  1388. PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
  1389. for (; PLoc.isValid(); ++Depth)
  1390. PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
  1391. }
  1392. // __INCLUDE_LEVEL__ expands to a simple numeric value.
  1393. OS << Depth;
  1394. Tok.setKind(tok::numeric_constant);
  1395. } else if (II == Ident__TIMESTAMP__) {
  1396. Diag(Tok.getLocation(), diag::warn_pp_date_time);
  1397. // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
  1398. // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
  1399. // Get the file that we are lexing out of. If we're currently lexing from
  1400. // a macro, dig into the include stack.
  1401. const FileEntry *CurFile = nullptr;
  1402. PreprocessorLexer *TheLexer = getCurrentFileLexer();
  1403. if (TheLexer)
  1404. CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
  1405. const char *Result;
  1406. if (CurFile) {
  1407. time_t TT = CurFile->getModificationTime();
  1408. struct tm *TM = localtime(&TT);
  1409. Result = asctime(TM);
  1410. } else {
  1411. Result = "??? ??? ?? ??:??:?? ????\n";
  1412. }
  1413. // Surround the string with " and strip the trailing newline.
  1414. OS << '"' << StringRef(Result).drop_back() << '"';
  1415. Tok.setKind(tok::string_literal);
  1416. } else if (II == Ident__COUNTER__) {
  1417. // __COUNTER__ expands to a simple numeric value.
  1418. OS << CounterValue++;
  1419. Tok.setKind(tok::numeric_constant);
  1420. } else if (II == Ident__has_feature) {
  1421. EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
  1422. [this](Token &Tok, bool &HasLexedNextToken) -> int {
  1423. IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
  1424. diag::err_feature_check_malformed);
  1425. return II && HasFeature(*this, II->getName());
  1426. });
  1427. } else if (II == Ident__has_extension) {
  1428. EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
  1429. [this](Token &Tok, bool &HasLexedNextToken) -> int {
  1430. IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
  1431. diag::err_feature_check_malformed);
  1432. return II && HasExtension(*this, II->getName());
  1433. });
  1434. } else if (II == Ident__has_builtin) {
  1435. EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
  1436. [this](Token &Tok, bool &HasLexedNextToken) -> int {
  1437. IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
  1438. diag::err_feature_check_malformed);
  1439. if (!II)
  1440. return false;
  1441. else if (II->getBuiltinID() != 0) {
  1442. switch (II->getBuiltinID()) {
  1443. case Builtin::BI__builtin_operator_new:
  1444. case Builtin::BI__builtin_operator_delete:
  1445. // denotes date of behavior change to support calling arbitrary
  1446. // usual allocation and deallocation functions. Required by libc++
  1447. return 201802;
  1448. default:
  1449. return true;
  1450. }
  1451. return true;
  1452. } else if (II->getTokenID() != tok::identifier ||
  1453. II->hasRevertedTokenIDToIdentifier()) {
  1454. // Treat all keywords that introduce a custom syntax of the form
  1455. //
  1456. // '__some_keyword' '(' [...] ')'
  1457. //
  1458. // as being "builtin functions", even if the syntax isn't a valid
  1459. // function call (for example, because the builtin takes a type
  1460. // argument).
  1461. if (II->getName().startswith("__builtin_") ||
  1462. II->getName().startswith("__is_") ||
  1463. II->getName().startswith("__has_"))
  1464. return true;
  1465. return llvm::StringSwitch<bool>(II->getName())
  1466. .Case("__array_rank", true)
  1467. .Case("__array_extent", true)
  1468. .Case("__reference_binds_to_temporary", true)
  1469. .Case("__underlying_type", true)
  1470. .Default(false);
  1471. } else {
  1472. return llvm::StringSwitch<bool>(II->getName())
  1473. // Report builtin templates as being builtins.
  1474. .Case("__make_integer_seq", getLangOpts().CPlusPlus)
  1475. .Case("__type_pack_element", getLangOpts().CPlusPlus)
  1476. // Likewise for some builtin preprocessor macros.
  1477. // FIXME: This is inconsistent; we usually suggest detecting
  1478. // builtin macros via #ifdef. Don't add more cases here.
  1479. .Case("__is_target_arch", true)
  1480. .Case("__is_target_vendor", true)
  1481. .Case("__is_target_os", true)
  1482. .Case("__is_target_environment", true)
  1483. .Default(false);
  1484. }
  1485. });
  1486. } else if (II == Ident__is_identifier) {
  1487. EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
  1488. [](Token &Tok, bool &HasLexedNextToken) -> int {
  1489. return Tok.is(tok::identifier);
  1490. });
  1491. } else if (II == Ident__has_attribute) {
  1492. EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, true,
  1493. [this](Token &Tok, bool &HasLexedNextToken) -> int {
  1494. IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
  1495. diag::err_feature_check_malformed);
  1496. return II ? hasAttribute(AttrSyntax::GNU, nullptr, II,
  1497. getTargetInfo(), getLangOpts()) : 0;
  1498. });
  1499. } else if (II == Ident__has_declspec) {
  1500. EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, true,
  1501. [this](Token &Tok, bool &HasLexedNextToken) -> int {
  1502. IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
  1503. diag::err_feature_check_malformed);
  1504. if (II) {
  1505. const LangOptions &LangOpts = getLangOpts();
  1506. return LangOpts.DeclSpecKeyword &&
  1507. hasAttribute(AttrSyntax::Declspec, nullptr, II,
  1508. getTargetInfo(), LangOpts);
  1509. }
  1510. return false;
  1511. });
  1512. } else if (II == Ident__has_cpp_attribute ||
  1513. II == Ident__has_c_attribute) {
  1514. bool IsCXX = II == Ident__has_cpp_attribute;
  1515. EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, true,
  1516. [&](Token &Tok, bool &HasLexedNextToken) -> int {
  1517. IdentifierInfo *ScopeII = nullptr;
  1518. IdentifierInfo *II = ExpectFeatureIdentifierInfo(
  1519. Tok, *this, diag::err_feature_check_malformed);
  1520. if (!II)
  1521. return false;
  1522. // It is possible to receive a scope token. Read the "::", if it is
  1523. // available, and the subsequent identifier.
  1524. LexUnexpandedToken(Tok);
  1525. if (Tok.isNot(tok::coloncolon))
  1526. HasLexedNextToken = true;
  1527. else {
  1528. ScopeII = II;
  1529. // Lex an expanded token for the attribute name.
  1530. Lex(Tok);
  1531. II = ExpectFeatureIdentifierInfo(Tok, *this,
  1532. diag::err_feature_check_malformed);
  1533. }
  1534. AttrSyntax Syntax = IsCXX ? AttrSyntax::CXX : AttrSyntax::C;
  1535. return II ? hasAttribute(Syntax, ScopeII, II, getTargetInfo(),
  1536. getLangOpts())
  1537. : 0;
  1538. });
  1539. } else if (II == Ident__has_include ||
  1540. II == Ident__has_include_next) {
  1541. // The argument to these two builtins should be a parenthesized
  1542. // file name string literal using angle brackets (<>) or
  1543. // double-quotes ("").
  1544. bool Value;
  1545. if (II == Ident__has_include)
  1546. Value = EvaluateHasInclude(Tok, II, *this);
  1547. else
  1548. Value = EvaluateHasIncludeNext(Tok, II, *this);
  1549. if (Tok.isNot(tok::r_paren))
  1550. return;
  1551. OS << (int)Value;
  1552. Tok.setKind(tok::numeric_constant);
  1553. } else if (II == Ident__has_warning) {
  1554. // The argument should be a parenthesized string literal.
  1555. EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
  1556. [this](Token &Tok, bool &HasLexedNextToken) -> int {
  1557. std::string WarningName;
  1558. SourceLocation StrStartLoc = Tok.getLocation();
  1559. HasLexedNextToken = Tok.is(tok::string_literal);
  1560. if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",
  1561. /*AllowMacroExpansion=*/false))
  1562. return false;
  1563. // FIXME: Should we accept "-R..." flags here, or should that be
  1564. // handled by a separate __has_remark?
  1565. if (WarningName.size() < 3 || WarningName[0] != '-' ||
  1566. WarningName[1] != 'W') {
  1567. Diag(StrStartLoc, diag::warn_has_warning_invalid_option);
  1568. return false;
  1569. }
  1570. // Finally, check if the warning flags maps to a diagnostic group.
  1571. // We construct a SmallVector here to talk to getDiagnosticIDs().
  1572. // Although we don't use the result, this isn't a hot path, and not
  1573. // worth special casing.
  1574. SmallVector<diag::kind, 10> Diags;
  1575. return !getDiagnostics().getDiagnosticIDs()->
  1576. getDiagnosticsInGroup(diag::Flavor::WarningOrError,
  1577. WarningName.substr(2), Diags);
  1578. });
  1579. } else if (II == Ident__building_module) {
  1580. // The argument to this builtin should be an identifier. The
  1581. // builtin evaluates to 1 when that identifier names the module we are
  1582. // currently building.
  1583. EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
  1584. [this](Token &Tok, bool &HasLexedNextToken) -> int {
  1585. IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
  1586. diag::err_expected_id_building_module);
  1587. return getLangOpts().isCompilingModule() && II &&
  1588. (II->getName() == getLangOpts().CurrentModule);
  1589. });
  1590. } else if (II == Ident__MODULE__) {
  1591. // The current module as an identifier.
  1592. OS << getLangOpts().CurrentModule;
  1593. IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);
  1594. Tok.setIdentifierInfo(ModuleII);
  1595. Tok.setKind(ModuleII->getTokenID());
  1596. } else if (II == Ident__identifier) {
  1597. SourceLocation Loc = Tok.getLocation();
  1598. // We're expecting '__identifier' '(' identifier ')'. Try to recover
  1599. // if the parens are missing.
  1600. LexNonComment(Tok);
  1601. if (Tok.isNot(tok::l_paren)) {
  1602. // No '(', use end of last token.
  1603. Diag(getLocForEndOfToken(Loc), diag::err_pp_expected_after)
  1604. << II << tok::l_paren;
  1605. // If the next token isn't valid as our argument, we can't recover.
  1606. if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
  1607. Tok.setKind(tok::identifier);
  1608. return;
  1609. }
  1610. SourceLocation LParenLoc = Tok.getLocation();
  1611. LexNonComment(Tok);
  1612. if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
  1613. Tok.setKind(tok::identifier);
  1614. else if (Tok.is(tok::string_literal) && !Tok.hasUDSuffix()) {
  1615. StringLiteralParser Literal(Tok, *this);
  1616. if (Literal.hadError)
  1617. return;
  1618. Tok.setIdentifierInfo(getIdentifierInfo(Literal.GetString()));
  1619. Tok.setKind(tok::identifier);
  1620. } else {
  1621. Diag(Tok.getLocation(), diag::err_pp_identifier_arg_not_identifier)
  1622. << Tok.getKind();
  1623. // Don't walk past anything that's not a real token.
  1624. if (Tok.isOneOf(tok::eof, tok::eod) || Tok.isAnnotation())
  1625. return;
  1626. }
  1627. // Discard the ')', preserving 'Tok' as our result.
  1628. Token RParen;
  1629. LexNonComment(RParen);
  1630. if (RParen.isNot(tok::r_paren)) {
  1631. Diag(getLocForEndOfToken(Tok.getLocation()), diag::err_pp_expected_after)
  1632. << Tok.getKind() << tok::r_paren;
  1633. Diag(LParenLoc, diag::note_matching) << tok::l_paren;
  1634. }
  1635. return;
  1636. } else if (II == Ident__is_target_arch) {
  1637. EvaluateFeatureLikeBuiltinMacro(
  1638. OS, Tok, II, *this, false,
  1639. [this](Token &Tok, bool &HasLexedNextToken) -> int {
  1640. IdentifierInfo *II = ExpectFeatureIdentifierInfo(
  1641. Tok, *this, diag::err_feature_check_malformed);
  1642. return II && isTargetArch(getTargetInfo(), II);
  1643. });
  1644. } else if (II == Ident__is_target_vendor) {
  1645. EvaluateFeatureLikeBuiltinMacro(
  1646. OS, Tok, II, *this, false,
  1647. [this](Token &Tok, bool &HasLexedNextToken) -> int {
  1648. IdentifierInfo *II = ExpectFeatureIdentifierInfo(
  1649. Tok, *this, diag::err_feature_check_malformed);
  1650. return II && isTargetVendor(getTargetInfo(), II);
  1651. });
  1652. } else if (II == Ident__is_target_os) {
  1653. EvaluateFeatureLikeBuiltinMacro(
  1654. OS, Tok, II, *this, false,
  1655. [this](Token &Tok, bool &HasLexedNextToken) -> int {
  1656. IdentifierInfo *II = ExpectFeatureIdentifierInfo(
  1657. Tok, *this, diag::err_feature_check_malformed);
  1658. return II && isTargetOS(getTargetInfo(), II);
  1659. });
  1660. } else if (II == Ident__is_target_environment) {
  1661. EvaluateFeatureLikeBuiltinMacro(
  1662. OS, Tok, II, *this, false,
  1663. [this](Token &Tok, bool &HasLexedNextToken) -> int {
  1664. IdentifierInfo *II = ExpectFeatureIdentifierInfo(
  1665. Tok, *this, diag::err_feature_check_malformed);
  1666. return II && isTargetEnvironment(getTargetInfo(), II);
  1667. });
  1668. } else {
  1669. llvm_unreachable("Unknown identifier!");
  1670. }
  1671. CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation());
  1672. Tok.setFlagValue(Token::StartOfLine, IsAtStartOfLine);
  1673. Tok.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
  1674. }
  1675. void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
  1676. // If the 'used' status changed, and the macro requires 'unused' warning,
  1677. // remove its SourceLocation from the warn-for-unused-macro locations.
  1678. if (MI->isWarnIfUnused() && !MI->isUsed())
  1679. WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
  1680. MI->setIsUsed(true);
  1681. }