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