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