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