PPMacroExpansion.cpp 69 KB

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