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