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