blob: 11b4a0b3d8c3cd2bc61dd993cb8f3b0d59618871 [file] [log] [blame]
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001//===--- MacroExpansion.cpp - Top level Macro Expansion -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
James Dennett32740042013-12-02 17:39:27 +000010// This file implements the top level handling of macro expansion for the
Joao Matosc0d4c1b2012-08-31 21:34:27 +000011// preprocessor.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Preprocessor.h"
Aaron Ballman2fbf9942014-03-31 13:14:44 +000016#include "clang/Basic/Attributes.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000017#include "clang/Basic/FileManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Basic/SourceManager.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000019#include "clang/Basic/TargetInfo.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000020#include "clang/Lex/CodeCompletionHandler.h"
21#include "clang/Lex/ExternalPreprocessorSource.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Lex/LexDiagnostic.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000023#include "clang/Lex/MacroArgs.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Lex/MacroInfo.h"
25#include "llvm/ADT/STLExtras.h"
Andy Gibbs58905d22012-11-17 19:15:38 +000026#include "llvm/ADT/SmallString.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000027#include "llvm/ADT/StringSwitch.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000028#include "llvm/Config/llvm-config.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000029#include "llvm/Support/ErrorHandling.h"
Dmitri Gribenkoae07f722012-09-24 20:56:28 +000030#include "llvm/Support/Format.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "llvm/Support/raw_ostream.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000032#include <cstdio>
33#include <ctime>
34using namespace clang;
35
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +000036MacroDirective *
Richard Smith20e883e2015-04-29 23:20:19 +000037Preprocessor::getLocalMacroDirectiveHistory(const IdentifierInfo *II) const {
38 if (!II->hadMacroDefinition())
39 return nullptr;
Richard Smith04765ae2015-05-21 01:20:10 +000040 auto Pos = CurSubmoduleState->Macros.find(II);
41 return Pos == CurSubmoduleState->Macros.end() ? nullptr
42 : Pos->second.getLatest();
Joao Matosc0d4c1b2012-08-31 21:34:27 +000043}
44
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000045void Preprocessor::appendMacroDirective(IdentifierInfo *II, MacroDirective *MD){
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000046 assert(MD && "MacroDirective should be non-zero!");
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000047 assert(!MD->getPrevious() && "Already attached to a MacroDirective history.");
Douglas Gregor5a4649b2012-10-11 00:46:49 +000048
Richard Smith04765ae2015-05-21 01:20:10 +000049 MacroState &StoredMD = CurSubmoduleState->Macros[II];
Richard Smithb8b2ed62015-04-23 18:18:26 +000050 auto *OldMD = StoredMD.getLatest();
51 MD->setPrevious(OldMD);
52 StoredMD.setLatest(MD);
Richard Smith753e0072015-04-27 23:21:38 +000053 StoredMD.overrideActiveModuleMacros(*this, II);
Richard Smithb8b2ed62015-04-23 18:18:26 +000054
55 // Set up the identifier as having associated macro history.
Ben Langmuirc28ce3a2014-09-30 20:00:18 +000056 II->setHasMacroDefinition(true);
Richard Smith20e883e2015-04-29 23:20:19 +000057 if (!MD->isDefined() && LeafModuleMacros.find(II) == LeafModuleMacros.end())
Ben Langmuirc28ce3a2014-09-30 20:00:18 +000058 II->setHasMacroDefinition(false);
Richard Smith3981b172015-04-30 02:16:23 +000059 if (II->isFromAST())
Joao Matosc0d4c1b2012-08-31 21:34:27 +000060 II->setChangedSinceDeserialization();
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000061}
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +000062
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000063void Preprocessor::setLoadedMacroDirective(IdentifierInfo *II,
64 MacroDirective *MD) {
65 assert(II && MD);
Richard Smith04765ae2015-05-21 01:20:10 +000066 MacroState &StoredMD = CurSubmoduleState->Macros[II];
Richard Smithb8b2ed62015-04-23 18:18:26 +000067 assert(!StoredMD.getLatest() &&
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000068 "the macro history was modified before initializing it from a pch");
69 StoredMD = MD;
70 // Setup the identifier as having associated macro history.
71 II->setHasMacroDefinition(true);
Richard Smith20e883e2015-04-29 23:20:19 +000072 if (!MD->isDefined() && LeafModuleMacros.find(II) == LeafModuleMacros.end())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000073 II->setHasMacroDefinition(false);
Joao Matosc0d4c1b2012-08-31 21:34:27 +000074}
75
Richard Smithb8b2ed62015-04-23 18:18:26 +000076ModuleMacro *Preprocessor::addModuleMacro(Module *Mod, IdentifierInfo *II,
Richard Smithe56c8bc2015-04-22 00:26:11 +000077 MacroInfo *Macro,
78 ArrayRef<ModuleMacro *> Overrides,
79 bool &New) {
80 llvm::FoldingSetNodeID ID;
Richard Smithb8b2ed62015-04-23 18:18:26 +000081 ModuleMacro::Profile(ID, Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +000082
83 void *InsertPos;
84 if (auto *MM = ModuleMacros.FindNodeOrInsertPos(ID, InsertPos)) {
85 New = false;
86 return MM;
87 }
88
Richard Smithb8b2ed62015-04-23 18:18:26 +000089 auto *MM = ModuleMacro::create(*this, Mod, II, Macro, Overrides);
Richard Smithe56c8bc2015-04-22 00:26:11 +000090 ModuleMacros.InsertNode(MM, InsertPos);
91
92 // Each overridden macro is now overridden by one more macro.
93 bool HidAny = false;
94 for (auto *O : Overrides) {
95 HidAny |= (O->NumOverriddenBy == 0);
96 ++O->NumOverriddenBy;
97 }
98
99 // If we were the first overrider for any macro, it's no longer a leaf.
100 auto &LeafMacros = LeafModuleMacros[II];
101 if (HidAny) {
102 LeafMacros.erase(std::remove_if(LeafMacros.begin(), LeafMacros.end(),
103 [](ModuleMacro *MM) {
104 return MM->NumOverriddenBy != 0;
105 }),
106 LeafMacros.end());
107 }
108
109 // The new macro is always a leaf macro.
110 LeafMacros.push_back(MM);
Richard Smith20e883e2015-04-29 23:20:19 +0000111 // The identifier now has defined macros (that may or may not be visible).
112 II->setHasMacroDefinition(true);
Richard Smithe56c8bc2015-04-22 00:26:11 +0000113
114 New = true;
115 return MM;
116}
117
Richard Smithb8b2ed62015-04-23 18:18:26 +0000118ModuleMacro *Preprocessor::getModuleMacro(Module *Mod, IdentifierInfo *II) {
Richard Smith5dbef922015-04-22 02:09:43 +0000119 llvm::FoldingSetNodeID ID;
Richard Smithb8b2ed62015-04-23 18:18:26 +0000120 ModuleMacro::Profile(ID, Mod, II);
Richard Smith5dbef922015-04-22 02:09:43 +0000121
122 void *InsertPos;
123 return ModuleMacros.FindNodeOrInsertPos(ID, InsertPos);
124}
125
Richard Smith20e883e2015-04-29 23:20:19 +0000126void Preprocessor::updateModuleMacroInfo(const IdentifierInfo *II,
Richard Smith753e0072015-04-27 23:21:38 +0000127 ModuleMacroInfo &Info) {
Richard Smith04765ae2015-05-21 01:20:10 +0000128 assert(Info.ActiveModuleMacrosGeneration !=
129 CurSubmoduleState->VisibleModules.getGeneration() &&
Richard Smith753e0072015-04-27 23:21:38 +0000130 "don't need to update this macro name info");
Richard Smith04765ae2015-05-21 01:20:10 +0000131 Info.ActiveModuleMacrosGeneration =
132 CurSubmoduleState->VisibleModules.getGeneration();
Richard Smith753e0072015-04-27 23:21:38 +0000133
134 auto Leaf = LeafModuleMacros.find(II);
135 if (Leaf == LeafModuleMacros.end()) {
136 // No imported macros at all: nothing to do.
137 return;
138 }
139
140 Info.ActiveModuleMacros.clear();
141
142 // Every macro that's locally overridden is overridden by a visible macro.
143 llvm::DenseMap<ModuleMacro *, int> NumHiddenOverrides;
144 for (auto *O : Info.OverriddenMacros)
145 NumHiddenOverrides[O] = -1;
146
147 // Collect all macros that are not overridden by a visible macro.
Richard Smith938d7012015-09-16 00:55:50 +0000148 llvm::SmallVector<ModuleMacro *, 16> Worklist;
149 for (auto *LeafMM : Leaf->second) {
150 assert(LeafMM->getNumOverridingMacros() == 0 && "leaf macro overridden");
151 if (NumHiddenOverrides.lookup(LeafMM) == 0)
152 Worklist.push_back(LeafMM);
153 }
Richard Smith753e0072015-04-27 23:21:38 +0000154 while (!Worklist.empty()) {
155 auto *MM = Worklist.pop_back_val();
Richard Smith04765ae2015-05-21 01:20:10 +0000156 if (CurSubmoduleState->VisibleModules.isVisible(MM->getOwningModule())) {
Richard Smith753e0072015-04-27 23:21:38 +0000157 // We only care about collecting definitions; undefinitions only act
158 // to override other definitions.
159 if (MM->getMacroInfo())
160 Info.ActiveModuleMacros.push_back(MM);
161 } else {
162 for (auto *O : MM->overrides())
163 if ((unsigned)++NumHiddenOverrides[O] == O->getNumOverridingMacros())
164 Worklist.push_back(O);
165 }
166 }
Richard Smith20e883e2015-04-29 23:20:19 +0000167 // Our reverse postorder walk found the macros in reverse order.
168 std::reverse(Info.ActiveModuleMacros.begin(), Info.ActiveModuleMacros.end());
Richard Smith753e0072015-04-27 23:21:38 +0000169
170 // Determine whether the macro name is ambiguous.
Richard Smith753e0072015-04-27 23:21:38 +0000171 MacroInfo *MI = nullptr;
Richard Smith20e883e2015-04-29 23:20:19 +0000172 bool IsSystemMacro = true;
173 bool IsAmbiguous = false;
174 if (auto *MD = Info.MD) {
175 while (MD && isa<VisibilityMacroDirective>(MD))
176 MD = MD->getPrevious();
177 if (auto *DMD = dyn_cast_or_null<DefMacroDirective>(MD)) {
178 MI = DMD->getInfo();
179 IsSystemMacro &= SourceMgr.isInSystemHeader(DMD->getLocation());
180 }
Richard Smith753e0072015-04-27 23:21:38 +0000181 }
182 for (auto *Active : Info.ActiveModuleMacros) {
183 auto *NewMI = Active->getMacroInfo();
184
185 // Before marking the macro as ambiguous, check if this is a case where
186 // both macros are in system headers. If so, we trust that the system
187 // did not get it wrong. This also handles cases where Clang's own
188 // headers have a different spelling of certain system macros:
189 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
190 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
191 //
192 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
193 // overrides the system limits.h's macros, so there's no conflict here.
Richard Smith20e883e2015-04-29 23:20:19 +0000194 if (MI && NewMI != MI &&
195 !MI->isIdenticalTo(*NewMI, *this, /*Syntactically=*/true))
196 IsAmbiguous = true;
197 IsSystemMacro &= Active->getOwningModule()->IsSystem ||
198 SourceMgr.isInSystemHeader(NewMI->getDefinitionLoc());
199 MI = NewMI;
Richard Smith753e0072015-04-27 23:21:38 +0000200 }
Richard Smith20e883e2015-04-29 23:20:19 +0000201 Info.IsAmbiguous = IsAmbiguous && !IsSystemMacro;
Richard Smith753e0072015-04-27 23:21:38 +0000202}
203
Richard Smith3ffa61d2015-04-30 23:10:40 +0000204void Preprocessor::dumpMacroInfo(const IdentifierInfo *II) {
205 ArrayRef<ModuleMacro*> Leaf;
206 auto LeafIt = LeafModuleMacros.find(II);
207 if (LeafIt != LeafModuleMacros.end())
208 Leaf = LeafIt->second;
209 const MacroState *State = nullptr;
Richard Smith04765ae2015-05-21 01:20:10 +0000210 auto Pos = CurSubmoduleState->Macros.find(II);
211 if (Pos != CurSubmoduleState->Macros.end())
Richard Smith3ffa61d2015-04-30 23:10:40 +0000212 State = &Pos->second;
213
214 llvm::errs() << "MacroState " << State << " " << II->getNameStart();
215 if (State && State->isAmbiguous(*this, II))
216 llvm::errs() << " ambiguous";
Richard Smithd0014bf2015-04-30 23:42:10 +0000217 if (State && !State->getOverriddenMacros().empty()) {
Richard Smith3ffa61d2015-04-30 23:10:40 +0000218 llvm::errs() << " overrides";
219 for (auto *O : State->getOverriddenMacros())
220 llvm::errs() << " " << O->getOwningModule()->getFullModuleName();
221 }
222 llvm::errs() << "\n";
223
224 // Dump local macro directives.
225 for (auto *MD = State ? State->getLatest() : nullptr; MD;
226 MD = MD->getPrevious()) {
227 llvm::errs() << " ";
228 MD->dump();
229 }
230
231 // Dump module macros.
232 llvm::DenseSet<ModuleMacro*> Active;
233 for (auto *MM : State ? State->getActiveModuleMacros(*this, II) : None)
234 Active.insert(MM);
235 llvm::DenseSet<ModuleMacro*> Visited;
236 llvm::SmallVector<ModuleMacro *, 16> Worklist(Leaf.begin(), Leaf.end());
237 while (!Worklist.empty()) {
238 auto *MM = Worklist.pop_back_val();
239 llvm::errs() << " ModuleMacro " << MM << " "
240 << MM->getOwningModule()->getFullModuleName();
241 if (!MM->getMacroInfo())
242 llvm::errs() << " undef";
243
244 if (Active.count(MM))
245 llvm::errs() << " active";
Richard Smith04765ae2015-05-21 01:20:10 +0000246 else if (!CurSubmoduleState->VisibleModules.isVisible(
247 MM->getOwningModule()))
Richard Smith3ffa61d2015-04-30 23:10:40 +0000248 llvm::errs() << " hidden";
Richard Smith42413142015-05-15 20:05:43 +0000249 else if (MM->getMacroInfo())
Richard Smith3ffa61d2015-04-30 23:10:40 +0000250 llvm::errs() << " overridden";
251
252 if (!MM->overrides().empty()) {
253 llvm::errs() << " overrides";
254 for (auto *O : MM->overrides()) {
255 llvm::errs() << " " << O->getOwningModule()->getFullModuleName();
256 if (Visited.insert(O).second)
257 Worklist.push_back(O);
258 }
259 }
260 llvm::errs() << "\n";
261 if (auto *MI = MM->getMacroInfo()) {
262 llvm::errs() << " ";
263 MI->dump();
264 llvm::errs() << "\n";
265 }
266 }
267}
268
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000269/// RegisterBuiltinMacro - Register the specified identifier in the identifier
270/// table and mark it as a builtin macro to be expanded.
271static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
272 // Get the identifier.
273 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
274
275 // Mark it as being a macro that is builtin.
276 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
277 MI->setIsBuiltinMacro();
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000278 PP.appendDefMacroDirective(Id, MI);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000279 return Id;
280}
281
282
283/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
284/// identifier table.
285void Preprocessor::RegisterBuiltinMacros() {
286 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
287 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
288 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
289 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
290 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
291 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
292
Aaron Ballmana0344c52014-11-14 13:44:02 +0000293 // C++ Standing Document Extensions.
Aaron Ballman416b1272015-05-11 14:09:50 +0000294 if (LangOpts.CPlusPlus)
295 Ident__has_cpp_attribute =
296 RegisterBuiltinMacro(*this, "__has_cpp_attribute");
297 else
298 Ident__has_cpp_attribute = nullptr;
Aaron Ballmana0344c52014-11-14 13:44:02 +0000299
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000300 // GCC Extensions.
301 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
302 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
303 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
304
Richard Smithae385082014-03-15 00:06:08 +0000305 // Microsoft Extensions.
306 if (LangOpts.MicrosoftExt) {
307 Ident__identifier = RegisterBuiltinMacro(*this, "__identifier");
308 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
309 } else {
Craig Topperd2d442c2014-05-17 23:10:59 +0000310 Ident__identifier = nullptr;
311 Ident__pragma = nullptr;
Richard Smithae385082014-03-15 00:06:08 +0000312 }
313
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000314 // Clang Extensions.
315 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
316 Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension");
317 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
318 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
Aaron Ballman3c0f9b42014-12-05 15:05:29 +0000319 Ident__has_declspec = RegisterBuiltinMacro(*this, "__has_declspec_attribute");
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000320 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
321 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
322 Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning");
Yunzhong Gaoef309f42014-04-11 20:55:19 +0000323 Ident__is_identifier = RegisterBuiltinMacro(*this, "__is_identifier");
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000324
Douglas Gregorc83de302012-09-25 15:44:52 +0000325 // Modules.
326 if (LangOpts.Modules) {
327 Ident__building_module = RegisterBuiltinMacro(*this, "__building_module");
328
329 // __MODULE__
330 if (!LangOpts.CurrentModule.empty())
331 Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__");
332 else
Craig Topperd2d442c2014-05-17 23:10:59 +0000333 Ident__MODULE__ = nullptr;
Douglas Gregorc83de302012-09-25 15:44:52 +0000334 } else {
Craig Topperd2d442c2014-05-17 23:10:59 +0000335 Ident__building_module = nullptr;
336 Ident__MODULE__ = nullptr;
Douglas Gregorc83de302012-09-25 15:44:52 +0000337 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000338}
339
340/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
341/// in its expansion, currently expands to that token literally.
342static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
343 const IdentifierInfo *MacroIdent,
344 Preprocessor &PP) {
345 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
346
347 // If the token isn't an identifier, it's always literally expanded.
Craig Topperd2d442c2014-05-17 23:10:59 +0000348 if (!II) return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000349
350 // If the information about this identifier is out of date, update it from
351 // the external source.
352 if (II->isOutOfDate())
353 PP.getExternalSource()->updateOutOfDateIdentifier(*II);
354
355 // If the identifier is a macro, and if that macro is enabled, it may be
356 // expanded so it's not a trivial expansion.
Richard Smith20e883e2015-04-29 23:20:19 +0000357 if (auto *ExpansionMI = PP.getMacroInfo(II))
Richard Smith3d5925b2015-04-29 23:26:13 +0000358 if (ExpansionMI->isEnabled() &&
Richard Smith20e883e2015-04-29 23:20:19 +0000359 // Fast expanding "#define X X" is ok, because X would be disabled.
360 II != MacroIdent)
361 return false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000362
363 // If this is an object-like macro invocation, it is safe to trivially expand
364 // it.
365 if (MI->isObjectLike()) return true;
366
367 // If this is a function-like macro invocation, it's safe to trivially expand
368 // as long as the identifier is not a macro argument.
Daniel Marjamakie4770da2015-05-29 09:15:24 +0000369 return std::find(MI->arg_begin(), MI->arg_end(), II) == MI->arg_end();
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000370
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000371}
372
373
374/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
375/// lexed is a '('. If so, consume the token and return true, if not, this
376/// method should have no observable side-effect on the lexed tokens.
377bool Preprocessor::isNextPPTokenLParen() {
378 // Do some quick tests for rejection cases.
379 unsigned Val;
380 if (CurLexer)
381 Val = CurLexer->isNextPPTokenLParen();
382 else if (CurPTHLexer)
383 Val = CurPTHLexer->isNextPPTokenLParen();
384 else
385 Val = CurTokenLexer->isNextTokenLParen();
386
387 if (Val == 2) {
388 // We have run off the end. If it's a source file we don't
389 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
390 // macro stack.
391 if (CurPPLexer)
392 return false;
393 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
394 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
395 if (Entry.TheLexer)
396 Val = Entry.TheLexer->isNextPPTokenLParen();
397 else if (Entry.ThePTHLexer)
398 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
399 else
400 Val = Entry.TheTokenLexer->isNextTokenLParen();
401
402 if (Val != 2)
403 break;
404
405 // Ran off the end of a source file?
406 if (Entry.ThePPLexer)
407 return false;
408 }
409 }
410
411 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
412 // have found something that isn't a '(' or we found the end of the
413 // translation unit. In either case, return false.
414 return Val == 1;
415}
416
417/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
418/// expanded as a macro, handle it and return the next token as 'Identifier'.
419bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Richard Smith20e883e2015-04-29 23:20:19 +0000420 const MacroDefinition &M) {
421 MacroInfo *MI = M.getMacroInfo();
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000422
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000423 // If this is a macro expansion in the "#if !defined(x)" line for the file,
424 // then the macro could expand to different things in other contexts, we need
425 // to disable the optimization in this case.
426 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
427
428 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
429 if (MI->isBuiltinMacro()) {
Richard Smith36bd40d2015-05-04 03:15:40 +0000430 if (Callbacks)
431 Callbacks->MacroExpands(Identifier, M, Identifier.getLocation(),
432 /*Args=*/nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000433 ExpandBuiltinMacro(Identifier);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000434 return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000435 }
436
437 /// Args - If this is a function-like macro expansion, this contains,
438 /// for each macro argument, the list of tokens that were provided to the
439 /// invocation.
Craig Topperd2d442c2014-05-17 23:10:59 +0000440 MacroArgs *Args = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000441
442 // Remember where the end of the expansion occurred. For an object-like
443 // macro, this is the identifier. For a function-like macro, this is the ')'.
444 SourceLocation ExpansionEnd = Identifier.getLocation();
445
446 // If this is a function-like macro, read the arguments.
447 if (MI->isFunctionLike()) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000448 // Remember that we are now parsing the arguments to a macro invocation.
449 // Preprocessor directives used inside macro arguments are not portable, and
450 // this enables the warning.
451 InMacroArgs = true;
452 Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd);
453
454 // Finished parsing args.
455 InMacroArgs = false;
456
457 // If there was an error parsing the arguments, bail out.
Craig Topperd2d442c2014-05-17 23:10:59 +0000458 if (!Args) return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000459
460 ++NumFnMacroExpanded;
461 } else {
462 ++NumMacroExpanded;
463 }
464
465 // Notice that this macro has been used.
466 markMacroAsUsed(MI);
467
468 // Remember where the token is expanded.
469 SourceLocation ExpandLoc = Identifier.getLocation();
470 SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
471
472 if (Callbacks) {
473 if (InMacroArgs) {
474 // We can have macro expansion inside a conditional directive while
475 // reading the function macro arguments. To ensure, in that case, that
476 // MacroExpands callbacks still happen in source order, queue this
477 // callback to have it happen after the function macro callback.
478 DelayedMacroExpandsCallbacks.push_back(
Richard Smith36bd40d2015-05-04 03:15:40 +0000479 MacroExpandsInfo(Identifier, M, ExpansionRange));
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000480 } else {
Richard Smith36bd40d2015-05-04 03:15:40 +0000481 Callbacks->MacroExpands(Identifier, M, ExpansionRange, Args);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000482 if (!DelayedMacroExpandsCallbacks.empty()) {
483 for (unsigned i=0, e = DelayedMacroExpandsCallbacks.size(); i!=e; ++i) {
484 MacroExpandsInfo &Info = DelayedMacroExpandsCallbacks[i];
Argyrios Kyrtzidis37e48ff2013-05-03 22:31:32 +0000485 // FIXME: We lose macro args info with delayed callback.
Craig Topperd2d442c2014-05-17 23:10:59 +0000486 Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range,
487 /*Args=*/nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000488 }
489 DelayedMacroExpandsCallbacks.clear();
490 }
491 }
492 }
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000493
494 // If the macro definition is ambiguous, complain.
Richard Smith20e883e2015-04-29 23:20:19 +0000495 if (M.isAmbiguous()) {
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000496 Diag(Identifier, diag::warn_pp_ambiguous_macro)
497 << Identifier.getIdentifierInfo();
498 Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)
499 << Identifier.getIdentifierInfo();
Richard Smith20e883e2015-04-29 23:20:19 +0000500 M.forAllDefinitions([&](const MacroInfo *OtherMI) {
501 if (OtherMI != MI)
502 Diag(OtherMI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_other)
503 << Identifier.getIdentifierInfo();
504 });
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000505 }
506
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000507 // If we started lexing a macro, enter the macro expansion body.
508
509 // If this macro expands to no tokens, don't bother to push it onto the
510 // expansion stack, only to take it right back off.
511 if (MI->getNumTokens() == 0) {
512 // No need for arg info.
513 if (Args) Args->destroy(*this);
514
Eli Friedman0834a4b2013-09-19 00:41:32 +0000515 // Propagate whitespace info as if we had pushed, then popped,
516 // a macro context.
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000517 Identifier.setFlag(Token::LeadingEmptyMacro);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000518 PropagateLineStartLeadingSpaceInfo(Identifier);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000519 ++NumFastMacroExpanded;
520 return false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000521 } else if (MI->getNumTokens() == 1 &&
522 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
523 *this)) {
524 // Otherwise, if this macro expands into a single trivially-expanded
525 // token: expand it now. This handles common cases like
526 // "#define VAL 42".
527
528 // No need for arg info.
529 if (Args) Args->destroy(*this);
530
531 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
532 // identifier to the expanded token.
533 bool isAtStartOfLine = Identifier.isAtStartOfLine();
534 bool hasLeadingSpace = Identifier.hasLeadingSpace();
535
536 // Replace the result token.
537 Identifier = MI->getReplacementToken(0);
538
539 // Restore the StartOfLine/LeadingSpace markers.
540 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
541 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
542
543 // Update the tokens location to include both its expansion and physical
544 // locations.
545 SourceLocation Loc =
546 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
547 ExpansionEnd,Identifier.getLength());
548 Identifier.setLocation(Loc);
549
550 // If this is a disabled macro or #define X X, we must mark the result as
551 // unexpandable.
552 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
553 if (MacroInfo *NewMI = getMacroInfo(NewII))
554 if (!NewMI->isEnabled() || NewMI == MI) {
555 Identifier.setFlag(Token::DisableExpand);
Douglas Gregor1a347f72013-01-30 23:10:17 +0000556 // Don't warn for "#define X X" like "#define bool bool" from
557 // stdbool.h.
558 if (NewMI != MI || MI->isFunctionLike())
559 Diag(Identifier, diag::pp_disabled_macro_expansion);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000560 }
561 }
562
563 // Since this is not an identifier token, it can't be macro expanded, so
564 // we're done.
565 ++NumFastMacroExpanded;
Eli Friedman0834a4b2013-09-19 00:41:32 +0000566 return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000567 }
568
569 // Start expanding the macro.
570 EnterMacro(Identifier, ExpansionEnd, MI, Args);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000571 return false;
572}
573
Richard Trieu79b45382013-07-23 18:01:49 +0000574enum Bracket {
575 Brace,
576 Paren
577};
578
579/// CheckMatchedBrackets - Returns true if the braces and parentheses in the
580/// token vector are properly nested.
581static bool CheckMatchedBrackets(const SmallVectorImpl<Token> &Tokens) {
582 SmallVector<Bracket, 8> Brackets;
583 for (SmallVectorImpl<Token>::const_iterator I = Tokens.begin(),
584 E = Tokens.end();
585 I != E; ++I) {
586 if (I->is(tok::l_paren)) {
587 Brackets.push_back(Paren);
588 } else if (I->is(tok::r_paren)) {
589 if (Brackets.empty() || Brackets.back() == Brace)
590 return false;
591 Brackets.pop_back();
592 } else if (I->is(tok::l_brace)) {
593 Brackets.push_back(Brace);
594 } else if (I->is(tok::r_brace)) {
595 if (Brackets.empty() || Brackets.back() == Paren)
596 return false;
597 Brackets.pop_back();
598 }
599 }
Alexander Kornienkoa26c4952015-12-28 15:30:42 +0000600 return Brackets.empty();
Richard Trieu79b45382013-07-23 18:01:49 +0000601}
602
603/// GenerateNewArgTokens - Returns true if OldTokens can be converted to a new
604/// vector of tokens in NewTokens. The new number of arguments will be placed
605/// in NumArgs and the ranges which need to surrounded in parentheses will be
606/// in ParenHints.
607/// Returns false if the token stream cannot be changed. If this is because
608/// of an initializer list starting a macro argument, the range of those
609/// initializer lists will be place in InitLists.
610static bool GenerateNewArgTokens(Preprocessor &PP,
611 SmallVectorImpl<Token> &OldTokens,
612 SmallVectorImpl<Token> &NewTokens,
613 unsigned &NumArgs,
614 SmallVectorImpl<SourceRange> &ParenHints,
615 SmallVectorImpl<SourceRange> &InitLists) {
616 if (!CheckMatchedBrackets(OldTokens))
617 return false;
618
619 // Once it is known that the brackets are matched, only a simple count of the
620 // braces is needed.
621 unsigned Braces = 0;
622
623 // First token of a new macro argument.
624 SmallVectorImpl<Token>::iterator ArgStartIterator = OldTokens.begin();
625
626 // First closing brace in a new macro argument. Used to generate
627 // SourceRanges for InitLists.
628 SmallVectorImpl<Token>::iterator ClosingBrace = OldTokens.end();
629 NumArgs = 0;
630 Token TempToken;
631 // Set to true when a macro separator token is found inside a braced list.
632 // If true, the fixed argument spans multiple old arguments and ParenHints
633 // will be updated.
634 bool FoundSeparatorToken = false;
635 for (SmallVectorImpl<Token>::iterator I = OldTokens.begin(),
636 E = OldTokens.end();
637 I != E; ++I) {
638 if (I->is(tok::l_brace)) {
639 ++Braces;
640 } else if (I->is(tok::r_brace)) {
641 --Braces;
642 if (Braces == 0 && ClosingBrace == E && FoundSeparatorToken)
643 ClosingBrace = I;
644 } else if (I->is(tok::eof)) {
645 // EOF token is used to separate macro arguments
646 if (Braces != 0) {
647 // Assume comma separator is actually braced list separator and change
648 // it back to a comma.
649 FoundSeparatorToken = true;
650 I->setKind(tok::comma);
651 I->setLength(1);
652 } else { // Braces == 0
653 // Separator token still separates arguments.
654 ++NumArgs;
655
656 // If the argument starts with a brace, it can't be fixed with
657 // parentheses. A different diagnostic will be given.
658 if (FoundSeparatorToken && ArgStartIterator->is(tok::l_brace)) {
659 InitLists.push_back(
660 SourceRange(ArgStartIterator->getLocation(),
661 PP.getLocForEndOfToken(ClosingBrace->getLocation())));
662 ClosingBrace = E;
663 }
664
665 // Add left paren
666 if (FoundSeparatorToken) {
667 TempToken.startToken();
668 TempToken.setKind(tok::l_paren);
669 TempToken.setLocation(ArgStartIterator->getLocation());
670 TempToken.setLength(0);
671 NewTokens.push_back(TempToken);
672 }
673
674 // Copy over argument tokens
675 NewTokens.insert(NewTokens.end(), ArgStartIterator, I);
676
677 // Add right paren and store the paren locations in ParenHints
678 if (FoundSeparatorToken) {
679 SourceLocation Loc = PP.getLocForEndOfToken((I - 1)->getLocation());
680 TempToken.startToken();
681 TempToken.setKind(tok::r_paren);
682 TempToken.setLocation(Loc);
683 TempToken.setLength(0);
684 NewTokens.push_back(TempToken);
685 ParenHints.push_back(SourceRange(ArgStartIterator->getLocation(),
686 Loc));
687 }
688
689 // Copy separator token
690 NewTokens.push_back(*I);
691
692 // Reset values
693 ArgStartIterator = I + 1;
694 FoundSeparatorToken = false;
695 }
696 }
697 }
698
699 return !ParenHints.empty() && InitLists.empty();
700}
701
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000702/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
703/// token is the '(' of the macro, this method is invoked to read all of the
704/// actual arguments specified for the macro invocation. This returns null on
705/// error.
706MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
707 MacroInfo *MI,
708 SourceLocation &MacroEnd) {
709 // The number of fixed arguments to parse.
710 unsigned NumFixedArgsLeft = MI->getNumArgs();
711 bool isVariadic = MI->isVariadic();
712
713 // Outer loop, while there are more arguments, keep reading them.
714 Token Tok;
715
716 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
717 // an argument value in a macro could expand to ',' or '(' or ')'.
718 LexUnexpandedToken(Tok);
719 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
720
721 // ArgTokens - Build up a list of tokens that make up each argument. Each
722 // argument is separated by an EOF token. Use a SmallVector so we can avoid
723 // heap allocations in the common case.
724 SmallVector<Token, 64> ArgTokens;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000725 bool ContainsCodeCompletionTok = false;
Ehsan Akhgari34461a62016-01-22 19:26:44 +0000726 bool FoundElidedComma = false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000727
Richard Trieu79b45382013-07-23 18:01:49 +0000728 SourceLocation TooManyArgsLoc;
729
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000730 unsigned NumActuals = 0;
731 while (Tok.isNot(tok::r_paren)) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000732 if (ContainsCodeCompletionTok && Tok.isOneOf(tok::eof, tok::eod))
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000733 break;
734
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000735 assert(Tok.isOneOf(tok::l_paren, tok::comma) &&
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000736 "only expect argument separators here");
737
738 unsigned ArgTokenStart = ArgTokens.size();
739 SourceLocation ArgStartLoc = Tok.getLocation();
740
741 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
742 // that we already consumed the first one.
743 unsigned NumParens = 0;
744
745 while (1) {
746 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
747 // an argument value in a macro could expand to ',' or '(' or ')'.
748 LexUnexpandedToken(Tok);
749
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000750 if (Tok.isOneOf(tok::eof, tok::eod)) { // "#if f(<eof>" & "#if f(\n"
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000751 if (!ContainsCodeCompletionTok) {
752 Diag(MacroName, diag::err_unterm_macro_invoc);
753 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
754 << MacroName.getIdentifierInfo();
755 // Do not lose the EOF/EOD. Return it to the client.
756 MacroName = Tok;
Craig Topperd2d442c2014-05-17 23:10:59 +0000757 return nullptr;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000758 } else {
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000759 // Do not lose the EOF/EOD.
760 Token *Toks = new Token[1];
761 Toks[0] = Tok;
762 EnterTokenStream(Toks, 1, true, true);
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000763 break;
764 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000765 } else if (Tok.is(tok::r_paren)) {
766 // If we found the ) token, the macro arg list is done.
767 if (NumParens-- == 0) {
768 MacroEnd = Tok.getLocation();
Ehsan Akhgari34461a62016-01-22 19:26:44 +0000769 if (!ArgTokens.empty() &&
770 ArgTokens.back().commaAfterElided()) {
771 FoundElidedComma = true;
772 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000773 break;
774 }
775 } else if (Tok.is(tok::l_paren)) {
776 ++NumParens;
Reid Kleckner596b85c2013-06-26 17:16:08 +0000777 } else if (Tok.is(tok::comma) && NumParens == 0 &&
778 !(Tok.getFlags() & Token::IgnoredComma)) {
779 // In Microsoft-compatibility mode, single commas from nested macro
780 // expansions should not be considered as argument separators. We test
781 // for this with the IgnoredComma token flag above.
782
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000783 // Comma ends this argument if there are more fixed arguments expected.
784 // However, if this is a variadic macro, and this is part of the
785 // variadic part, then the comma is just an argument token.
786 if (!isVariadic) break;
787 if (NumFixedArgsLeft > 1)
788 break;
789 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
790 // If this is a comment token in the argument list and we're just in
791 // -C mode (not -CC mode), discard the comment.
792 continue;
David Majnemerd8dee1f2015-03-18 07:53:20 +0000793 } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo() != nullptr) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000794 // Reading macro arguments can cause macros that we are currently
795 // expanding from to be popped off the expansion stack. Doing so causes
796 // them to be reenabled for expansion. Here we record whether any
797 // identifiers we lex as macro arguments correspond to disabled macros.
798 // If so, we mark the token as noexpand. This is a subtle aspect of
799 // C99 6.10.3.4p2.
800 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
801 if (!MI->isEnabled())
802 Tok.setFlag(Token::DisableExpand);
803 } else if (Tok.is(tok::code_completion)) {
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000804 ContainsCodeCompletionTok = true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000805 if (CodeComplete)
806 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
807 MI, NumActuals);
808 // Don't mark that we reached the code-completion point because the
809 // parser is going to handle the token and there will be another
810 // code-completion callback.
811 }
812
813 ArgTokens.push_back(Tok);
814 }
815
816 // If this was an empty argument list foo(), don't add this as an empty
817 // argument.
818 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
819 break;
820
821 // If this is not a variadic macro, and too many args were specified, emit
822 // an error.
Richard Trieu79b45382013-07-23 18:01:49 +0000823 if (!isVariadic && NumFixedArgsLeft == 0 && TooManyArgsLoc.isInvalid()) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000824 if (ArgTokens.size() != ArgTokenStart)
Richard Trieu79b45382013-07-23 18:01:49 +0000825 TooManyArgsLoc = ArgTokens[ArgTokenStart].getLocation();
826 else
827 TooManyArgsLoc = ArgStartLoc;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000828 }
829
Richard Trieu79b45382013-07-23 18:01:49 +0000830 // Empty arguments are standard in C99 and C++0x, and are supported as an
831 // extension in other modes.
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000832 if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99)
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000833 Diag(Tok, LangOpts.CPlusPlus11 ?
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000834 diag::warn_cxx98_compat_empty_fnmacro_arg :
835 diag::ext_empty_fnmacro_arg);
836
837 // Add a marker EOF token to the end of the token list for this argument.
838 Token EOFTok;
839 EOFTok.startToken();
840 EOFTok.setKind(tok::eof);
841 EOFTok.setLocation(Tok.getLocation());
842 EOFTok.setLength(0);
843 ArgTokens.push_back(EOFTok);
844 ++NumActuals;
Richard Trieu79b45382013-07-23 18:01:49 +0000845 if (!ContainsCodeCompletionTok && NumFixedArgsLeft != 0)
Argyrios Kyrtzidisfb703802013-02-22 22:28:58 +0000846 --NumFixedArgsLeft;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000847 }
848
849 // Okay, we either found the r_paren. Check to see if we parsed too few
850 // arguments.
851 unsigned MinArgsExpected = MI->getNumArgs();
852
Richard Trieu79b45382013-07-23 18:01:49 +0000853 // If this is not a variadic macro, and too many args were specified, emit
854 // an error.
855 if (!isVariadic && NumActuals > MinArgsExpected &&
856 !ContainsCodeCompletionTok) {
857 // Emit the diagnostic at the macro name in case there is a missing ).
858 // Emitting it at the , could be far away from the macro name.
859 Diag(TooManyArgsLoc, diag::err_too_many_args_in_macro_invoc);
860 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
861 << MacroName.getIdentifierInfo();
862
863 // Commas from braced initializer lists will be treated as argument
864 // separators inside macros. Attempt to correct for this with parentheses.
865 // TODO: See if this can be generalized to angle brackets for templates
866 // inside macro arguments.
867
Bob Wilson57217352013-07-27 21:59:57 +0000868 SmallVector<Token, 4> FixedArgTokens;
Richard Trieu79b45382013-07-23 18:01:49 +0000869 unsigned FixedNumArgs = 0;
870 SmallVector<SourceRange, 4> ParenHints, InitLists;
871 if (!GenerateNewArgTokens(*this, ArgTokens, FixedArgTokens, FixedNumArgs,
872 ParenHints, InitLists)) {
873 if (!InitLists.empty()) {
874 DiagnosticBuilder DB =
875 Diag(MacroName,
876 diag::note_init_list_at_beginning_of_macro_argument);
Craig Toppere335f252015-10-04 04:53:55 +0000877 for (SourceRange Range : InitLists)
Alexander Kornienkod3b4e082014-05-22 19:56:11 +0000878 DB << Range;
Richard Trieu79b45382013-07-23 18:01:49 +0000879 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000880 return nullptr;
Richard Trieu79b45382013-07-23 18:01:49 +0000881 }
882 if (FixedNumArgs != MinArgsExpected)
Craig Topperd2d442c2014-05-17 23:10:59 +0000883 return nullptr;
Richard Trieu79b45382013-07-23 18:01:49 +0000884
885 DiagnosticBuilder DB = Diag(MacroName, diag::note_suggest_parens_for_macro);
Craig Toppere335f252015-10-04 04:53:55 +0000886 for (SourceRange ParenLocation : ParenHints) {
Alexander Kornienkod3b4e082014-05-22 19:56:11 +0000887 DB << FixItHint::CreateInsertion(ParenLocation.getBegin(), "(");
888 DB << FixItHint::CreateInsertion(ParenLocation.getEnd(), ")");
Richard Trieu79b45382013-07-23 18:01:49 +0000889 }
890 ArgTokens.swap(FixedArgTokens);
891 NumActuals = FixedNumArgs;
892 }
893
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000894 // See MacroArgs instance var for description of this.
895 bool isVarargsElided = false;
896
Argyrios Kyrtzidisd4635d42012-12-21 01:51:12 +0000897 if (ContainsCodeCompletionTok) {
898 // Recover from not-fully-formed macro invocation during code-completion.
899 Token EOFTok;
900 EOFTok.startToken();
901 EOFTok.setKind(tok::eof);
902 EOFTok.setLocation(Tok.getLocation());
903 EOFTok.setLength(0);
904 for (; NumActuals < MinArgsExpected; ++NumActuals)
905 ArgTokens.push_back(EOFTok);
906 }
907
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000908 if (NumActuals < MinArgsExpected) {
909 // There are several cases where too few arguments is ok, handle them now.
910 if (NumActuals == 0 && MinArgsExpected == 1) {
911 // #define A(X) or #define A(...) ---> A()
912
913 // If there is exactly one argument, and that argument is missing,
914 // then we have an empty "()" argument empty list. This is fine, even if
915 // the macro expects one argument (the argument is just empty).
916 isVarargsElided = MI->isVariadic();
Ehsan Akhgari34461a62016-01-22 19:26:44 +0000917 } else if ((FoundElidedComma || MI->isVariadic()) &&
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000918 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
919 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
920 // Varargs where the named vararg parameter is missing: OK as extension.
921 // #define A(x, ...)
922 // A("blah")
Eli Friedman14d3c792012-11-14 02:18:46 +0000923 //
924 // If the macro contains the comma pasting extension, the diagnostic
925 // is suppressed; we know we'll get another diagnostic later.
926 if (!MI->hasCommaPasting()) {
927 Diag(Tok, diag::ext_missing_varargs_arg);
928 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
929 << MacroName.getIdentifierInfo();
930 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000931
932 // Remember this occurred, allowing us to elide the comma when used for
933 // cases like:
934 // #define A(x, foo...) blah(a, ## foo)
935 // #define B(x, ...) blah(a, ## __VA_ARGS__)
936 // #define C(...) blah(a, ## __VA_ARGS__)
937 // A(x) B(x) C()
938 isVarargsElided = true;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000939 } else if (!ContainsCodeCompletionTok) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000940 // Otherwise, emit the error.
941 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Argyrios Kyrtzidis164fdb62012-12-14 18:53:47 +0000942 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
943 << MacroName.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000944 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000945 }
946
947 // Add a marker EOF token to the end of the token list for this argument.
948 SourceLocation EndLoc = Tok.getLocation();
949 Tok.startToken();
950 Tok.setKind(tok::eof);
951 Tok.setLocation(EndLoc);
952 Tok.setLength(0);
953 ArgTokens.push_back(Tok);
954
955 // If we expect two arguments, add both as empty.
956 if (NumActuals == 0 && MinArgsExpected == 2)
957 ArgTokens.push_back(Tok);
958
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000959 } else if (NumActuals > MinArgsExpected && !MI->isVariadic() &&
960 !ContainsCodeCompletionTok) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000961 // Emit the diagnostic at the macro name in case there is a missing ).
962 // Emitting it at the , could be far away from the macro name.
963 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Argyrios Kyrtzidis164fdb62012-12-14 18:53:47 +0000964 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
965 << MacroName.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000966 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000967 }
968
969 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
970}
971
972/// \brief Keeps macro expanded tokens for TokenLexers.
973//
974/// Works like a stack; a TokenLexer adds the macro expanded tokens that is
975/// going to lex in the cache and when it finishes the tokens are removed
976/// from the end of the cache.
977Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
978 ArrayRef<Token> tokens) {
979 assert(tokLexer);
980 if (tokens.empty())
Craig Topperd2d442c2014-05-17 23:10:59 +0000981 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000982
983 size_t newIndex = MacroExpandedTokens.size();
984 bool cacheNeedsToGrow = tokens.size() >
985 MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
986 MacroExpandedTokens.append(tokens.begin(), tokens.end());
987
988 if (cacheNeedsToGrow) {
989 // Go through all the TokenLexers whose 'Tokens' pointer points in the
990 // buffer and update the pointers to the (potential) new buffer array.
991 for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) {
992 TokenLexer *prevLexer;
993 size_t tokIndex;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000994 std::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i];
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000995 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
996 }
997 }
998
999 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
1000 return MacroExpandedTokens.data() + newIndex;
1001}
1002
1003void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
1004 assert(!MacroExpandingLexersStack.empty());
1005 size_t tokIndex = MacroExpandingLexersStack.back().second;
1006 assert(tokIndex < MacroExpandedTokens.size());
1007 // Pop the cached macro expanded tokens from the end.
1008 MacroExpandedTokens.resize(tokIndex);
1009 MacroExpandingLexersStack.pop_back();
1010}
1011
1012/// ComputeDATE_TIME - Compute the current time, enter it into the specified
1013/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
1014/// the identifier tokens inserted.
1015static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
1016 Preprocessor &PP) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001017 time_t TT = time(nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001018 struct tm *TM = localtime(&TT);
1019
1020 static const char * const Months[] = {
1021 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
1022 };
1023
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001024 {
1025 SmallString<32> TmpBuffer;
1026 llvm::raw_svector_ostream TmpStream(TmpBuffer);
1027 TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
1028 TM->tm_mday, TM->tm_year + 1900);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001029 Token TmpTok;
1030 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00001031 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001032 DATELoc = TmpTok.getLocation();
1033 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001034
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001035 {
1036 SmallString<32> TmpBuffer;
1037 llvm::raw_svector_ostream TmpStream(TmpBuffer);
1038 TmpStream << llvm::format("\"%02d:%02d:%02d\"",
1039 TM->tm_hour, TM->tm_min, TM->tm_sec);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001040 Token TmpTok;
1041 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00001042 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001043 TIMELoc = TmpTok.getLocation();
1044 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001045}
1046
1047
1048/// HasFeature - Return true if we recognize and implement the feature
1049/// specified by the identifier as a standard language feature.
1050static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
1051 const LangOptions &LangOpts = PP.getLangOpts();
1052 StringRef Feature = II->getName();
1053
1054 // Normalize the feature name, __foo__ becomes foo.
1055 if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4)
1056 Feature = Feature.substr(2, Feature.size() - 4);
1057
1058 return llvm::StringSwitch<bool>(Feature)
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001059 .Case("address_sanitizer",
1060 LangOpts.Sanitize.hasOneOf(SanitizerKind::Address |
1061 SanitizerKind::KernelAddress))
Douglas Gregor4c27d102015-06-29 18:11:42 +00001062 .Case("assume_nonnull", true)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001063 .Case("attribute_analyzer_noreturn", true)
1064 .Case("attribute_availability", true)
1065 .Case("attribute_availability_with_message", true)
Bob Wilsonb111ec92015-03-02 19:01:14 +00001066 .Case("attribute_availability_app_extension", true)
Jordan Rose7e5de9c2015-07-16 22:30:10 +00001067 .Case("attribute_availability_with_version_underscores", true)
Tim Northover7a73cc72015-10-30 16:30:49 +00001068 .Case("attribute_availability_tvos", true)
1069 .Case("attribute_availability_watchos", true)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001070 .Case("attribute_cf_returns_not_retained", true)
1071 .Case("attribute_cf_returns_retained", true)
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00001072 .Case("attribute_cf_returns_on_parameters", true)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001073 .Case("attribute_deprecated_with_message", true)
1074 .Case("attribute_ext_vector_type", true)
1075 .Case("attribute_ns_returns_not_retained", true)
1076 .Case("attribute_ns_returns_retained", true)
1077 .Case("attribute_ns_consumes_self", true)
1078 .Case("attribute_ns_consumed", true)
1079 .Case("attribute_cf_consumed", true)
1080 .Case("attribute_objc_ivar_unused", true)
1081 .Case("attribute_objc_method_family", true)
1082 .Case("attribute_overloadable", true)
1083 .Case("attribute_unavailable_with_message", true)
1084 .Case("attribute_unused_on_fields", true)
1085 .Case("blocks", LangOpts.Blocks)
1086 .Case("c_thread_safety_attributes", true)
1087 .Case("cxx_exceptions", LangOpts.CXXExceptions)
Reid Kleckner6cf4a6b2015-08-13 17:56:49 +00001088 .Case("cxx_rtti", LangOpts.RTTI && LangOpts.RTTIData)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001089 .Case("enumerator_attributes", true)
Douglas Gregor4c27d102015-06-29 18:11:42 +00001090 .Case("nullability", true)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001091 .Case("memory_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Memory))
1092 .Case("thread_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Thread))
1093 .Case("dataflow_sanitizer", LangOpts.Sanitize.has(SanitizerKind::DataFlow))
1094 // Objective-C features
1095 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
1096 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
John McCall460ce582015-10-22 18:38:17 +00001097 .Case("objc_arc_weak", LangOpts.ObjCWeak)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001098 .Case("objc_default_synthesize_properties", LangOpts.ObjC2)
1099 .Case("objc_fixed_enum", LangOpts.ObjC2)
1100 .Case("objc_instancetype", LangOpts.ObjC2)
Douglas Gregorab209d82015-07-07 03:58:42 +00001101 .Case("objc_kindof", LangOpts.ObjC2)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001102 .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules)
1103 .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile())
1104 .Case("objc_property_explicit_atomic",
1105 true) // Does clang support explicit "atomic" keyword?
1106 .Case("objc_protocol_qualifier_mangling", true)
1107 .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport())
1108 .Case("ownership_holds", true)
1109 .Case("ownership_returns", true)
1110 .Case("ownership_takes", true)
1111 .Case("objc_bool", true)
1112 .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile())
1113 .Case("objc_array_literals", LangOpts.ObjC2)
1114 .Case("objc_dictionary_literals", LangOpts.ObjC2)
1115 .Case("objc_boxed_expressions", LangOpts.ObjC2)
Alex Denisovfde64952015-06-26 05:28:36 +00001116 .Case("objc_boxed_nsvalue_expressions", LangOpts.ObjC2)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001117 .Case("arc_cf_code_audited", true)
John McCall28592582015-02-01 22:34:06 +00001118 .Case("objc_bridge_id", true)
1119 .Case("objc_bridge_id_on_typedefs", true)
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001120 .Case("objc_generics", LangOpts.ObjC2)
Douglas Gregor1ac1b632015-07-07 03:58:54 +00001121 .Case("objc_generics_variance", LangOpts.ObjC2)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001122 // C11 features
1123 .Case("c_alignas", LangOpts.C11)
Nico Weber736a9932014-12-03 01:25:49 +00001124 .Case("c_alignof", LangOpts.C11)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001125 .Case("c_atomic", LangOpts.C11)
1126 .Case("c_generic_selections", LangOpts.C11)
1127 .Case("c_static_assert", LangOpts.C11)
1128 .Case("c_thread_local",
1129 LangOpts.C11 && PP.getTargetInfo().isTLSSupported())
1130 // C++11 features
1131 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus11)
1132 .Case("cxx_alias_templates", LangOpts.CPlusPlus11)
1133 .Case("cxx_alignas", LangOpts.CPlusPlus11)
Nico Weber736a9932014-12-03 01:25:49 +00001134 .Case("cxx_alignof", LangOpts.CPlusPlus11)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001135 .Case("cxx_atomic", LangOpts.CPlusPlus11)
1136 .Case("cxx_attributes", LangOpts.CPlusPlus11)
1137 .Case("cxx_auto_type", LangOpts.CPlusPlus11)
1138 .Case("cxx_constexpr", LangOpts.CPlusPlus11)
1139 .Case("cxx_decltype", LangOpts.CPlusPlus11)
1140 .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus11)
1141 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus11)
1142 .Case("cxx_defaulted_functions", LangOpts.CPlusPlus11)
1143 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus11)
1144 .Case("cxx_deleted_functions", LangOpts.CPlusPlus11)
1145 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus11)
1146 .Case("cxx_generalized_initializers", LangOpts.CPlusPlus11)
1147 .Case("cxx_implicit_moves", LangOpts.CPlusPlus11)
1148 .Case("cxx_inheriting_constructors", LangOpts.CPlusPlus11)
1149 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus11)
1150 .Case("cxx_lambdas", LangOpts.CPlusPlus11)
1151 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus11)
1152 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus11)
1153 .Case("cxx_noexcept", LangOpts.CPlusPlus11)
1154 .Case("cxx_nullptr", LangOpts.CPlusPlus11)
1155 .Case("cxx_override_control", LangOpts.CPlusPlus11)
1156 .Case("cxx_range_for", LangOpts.CPlusPlus11)
1157 .Case("cxx_raw_string_literals", LangOpts.CPlusPlus11)
1158 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus11)
1159 .Case("cxx_rvalue_references", LangOpts.CPlusPlus11)
1160 .Case("cxx_strong_enums", LangOpts.CPlusPlus11)
1161 .Case("cxx_static_assert", LangOpts.CPlusPlus11)
1162 .Case("cxx_thread_local",
1163 LangOpts.CPlusPlus11 && PP.getTargetInfo().isTLSSupported())
1164 .Case("cxx_trailing_return", LangOpts.CPlusPlus11)
1165 .Case("cxx_unicode_literals", LangOpts.CPlusPlus11)
1166 .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus11)
1167 .Case("cxx_user_literals", LangOpts.CPlusPlus11)
1168 .Case("cxx_variadic_templates", LangOpts.CPlusPlus11)
1169 // C++1y features
1170 .Case("cxx_aggregate_nsdmi", LangOpts.CPlusPlus14)
1171 .Case("cxx_binary_literals", LangOpts.CPlusPlus14)
1172 .Case("cxx_contextual_conversions", LangOpts.CPlusPlus14)
1173 .Case("cxx_decltype_auto", LangOpts.CPlusPlus14)
1174 .Case("cxx_generic_lambdas", LangOpts.CPlusPlus14)
1175 .Case("cxx_init_captures", LangOpts.CPlusPlus14)
1176 .Case("cxx_relaxed_constexpr", LangOpts.CPlusPlus14)
1177 .Case("cxx_return_type_deduction", LangOpts.CPlusPlus14)
1178 .Case("cxx_variable_templates", LangOpts.CPlusPlus14)
1179 // C++ TSes
1180 //.Case("cxx_runtime_arrays", LangOpts.CPlusPlusTSArrays)
1181 //.Case("cxx_concepts", LangOpts.CPlusPlusTSConcepts)
1182 // FIXME: Should this be __has_feature or __has_extension?
1183 //.Case("raw_invocation_type", LangOpts.CPlusPlus)
1184 // Type traits
1185 .Case("has_nothrow_assign", LangOpts.CPlusPlus)
1186 .Case("has_nothrow_copy", LangOpts.CPlusPlus)
1187 .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
1188 .Case("has_trivial_assign", LangOpts.CPlusPlus)
1189 .Case("has_trivial_copy", LangOpts.CPlusPlus)
1190 .Case("has_trivial_constructor", LangOpts.CPlusPlus)
1191 .Case("has_trivial_destructor", LangOpts.CPlusPlus)
1192 .Case("has_virtual_destructor", LangOpts.CPlusPlus)
1193 .Case("is_abstract", LangOpts.CPlusPlus)
1194 .Case("is_base_of", LangOpts.CPlusPlus)
1195 .Case("is_class", LangOpts.CPlusPlus)
1196 .Case("is_constructible", LangOpts.CPlusPlus)
1197 .Case("is_convertible_to", LangOpts.CPlusPlus)
1198 .Case("is_empty", LangOpts.CPlusPlus)
1199 .Case("is_enum", LangOpts.CPlusPlus)
1200 .Case("is_final", LangOpts.CPlusPlus)
1201 .Case("is_literal", LangOpts.CPlusPlus)
1202 .Case("is_standard_layout", LangOpts.CPlusPlus)
1203 .Case("is_pod", LangOpts.CPlusPlus)
1204 .Case("is_polymorphic", LangOpts.CPlusPlus)
1205 .Case("is_sealed", LangOpts.MicrosoftExt)
1206 .Case("is_trivial", LangOpts.CPlusPlus)
1207 .Case("is_trivially_assignable", LangOpts.CPlusPlus)
1208 .Case("is_trivially_constructible", LangOpts.CPlusPlus)
1209 .Case("is_trivially_copyable", LangOpts.CPlusPlus)
1210 .Case("is_union", LangOpts.CPlusPlus)
1211 .Case("modules", LangOpts.Modules)
Peter Collingbournec4122c12015-06-15 21:08:13 +00001212 .Case("safe_stack", LangOpts.Sanitize.has(SanitizerKind::SafeStack))
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001213 .Case("tls", PP.getTargetInfo().isTLSSupported())
1214 .Case("underlying_type", LangOpts.CPlusPlus)
1215 .Default(false);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001216}
1217
1218/// HasExtension - Return true if we recognize and implement the feature
1219/// specified by the identifier, either as an extension or a standard language
1220/// feature.
1221static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) {
1222 if (HasFeature(PP, II))
1223 return true;
1224
1225 // If the use of an extension results in an error diagnostic, extensions are
1226 // effectively unavailable, so just return false here.
Alp Tokerac4e8e52014-06-22 21:58:33 +00001227 if (PP.getDiagnostics().getExtensionHandlingBehavior() >=
1228 diag::Severity::Error)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001229 return false;
1230
1231 const LangOptions &LangOpts = PP.getLangOpts();
1232 StringRef Extension = II->getName();
1233
1234 // Normalize the extension name, __foo__ becomes foo.
1235 if (Extension.startswith("__") && Extension.endswith("__") &&
1236 Extension.size() >= 4)
1237 Extension = Extension.substr(2, Extension.size() - 4);
1238
1239 // Because we inherit the feature list from HasFeature, this string switch
1240 // must be less restrictive than HasFeature's.
1241 return llvm::StringSwitch<bool>(Extension)
1242 // C11 features supported by other languages as extensions.
1243 .Case("c_alignas", true)
Nico Weber736a9932014-12-03 01:25:49 +00001244 .Case("c_alignof", true)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001245 .Case("c_atomic", true)
1246 .Case("c_generic_selections", true)
1247 .Case("c_static_assert", true)
Ed Schouten401aeba2013-09-14 16:17:20 +00001248 .Case("c_thread_local", PP.getTargetInfo().isTLSSupported())
Richard Smith0a715422013-05-07 19:32:56 +00001249 // C++11 features supported by other languages as extensions.
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001250 .Case("cxx_atomic", LangOpts.CPlusPlus)
1251 .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
1252 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
1253 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
1254 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus)
1255 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
1256 .Case("cxx_override_control", LangOpts.CPlusPlus)
1257 .Case("cxx_range_for", LangOpts.CPlusPlus)
1258 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
1259 .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
Eric Fiselier7aa0d4a2015-05-12 22:37:23 +00001260 .Case("cxx_variadic_templates", LangOpts.CPlusPlus)
Richard Smith0a715422013-05-07 19:32:56 +00001261 // C++1y features supported by other languages as extensions.
1262 .Case("cxx_binary_literals", true)
Richard Smithb438e622013-09-28 04:37:56 +00001263 .Case("cxx_init_captures", LangOpts.CPlusPlus11)
Alp Tokera8bb9c92014-01-15 04:11:24 +00001264 .Case("cxx_variable_templates", LangOpts.CPlusPlus)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001265 .Default(false);
1266}
1267
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001268/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
1269/// or '__has_include_next("path")' expression.
1270/// Returns true if successful.
1271static bool EvaluateHasIncludeCommon(Token &Tok,
1272 IdentifierInfo *II, Preprocessor &PP,
Richard Smith25d50752014-10-20 00:15:49 +00001273 const DirectoryLookup *LookupFrom,
1274 const FileEntry *LookupFromFile) {
Richard Trieuda031982012-10-22 20:28:48 +00001275 // Save the location of the current token. If a '(' is later found, use
Aaron Ballman5cb24112013-01-15 21:59:46 +00001276 // that location. If not, use the end of this location instead.
Richard Trieuda031982012-10-22 20:28:48 +00001277 SourceLocation LParenLoc = Tok.getLocation();
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001278
Aaron Ballman6ce00002013-01-16 19:32:21 +00001279 // These expressions are only allowed within a preprocessor directive.
1280 if (!PP.isParsingIfOrElifDirective()) {
1281 PP.Diag(LParenLoc, diag::err_pp_directive_required) << II->getName();
Benjamin Kramer0a126ad2015-03-29 19:05:27 +00001282 // Return a valid identifier token.
1283 assert(Tok.is(tok::identifier));
1284 Tok.setIdentifierInfo(II);
Aaron Ballman6ce00002013-01-16 19:32:21 +00001285 return false;
1286 }
1287
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001288 // Get '('.
1289 PP.LexNonComment(Tok);
1290
1291 // Ensure we have a '('.
1292 if (Tok.isNot(tok::l_paren)) {
Richard Trieuda031982012-10-22 20:28:48 +00001293 // No '(', use end of last token.
1294 LParenLoc = PP.getLocForEndOfToken(LParenLoc);
Alp Toker751d6352013-12-30 01:59:29 +00001295 PP.Diag(LParenLoc, diag::err_pp_expected_after) << II << tok::l_paren;
Richard Trieuda031982012-10-22 20:28:48 +00001296 // If the next token looks like a filename or the start of one,
1297 // assume it is and process it as such.
1298 if (!Tok.is(tok::angle_string_literal) && !Tok.is(tok::string_literal) &&
1299 !Tok.is(tok::less))
1300 return false;
1301 } else {
1302 // Save '(' location for possible missing ')' message.
1303 LParenLoc = Tok.getLocation();
1304
Eli Friedmanec94b612013-01-09 02:20:00 +00001305 if (PP.getCurrentLexer()) {
1306 // Get the file name.
1307 PP.getCurrentLexer()->LexIncludeFilename(Tok);
1308 } else {
1309 // We're in a macro, so we can't use LexIncludeFilename; just
1310 // grab the next token.
1311 PP.Lex(Tok);
1312 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001313 }
1314
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001315 // Reserve a buffer to get the spelling.
1316 SmallString<128> FilenameBuffer;
1317 StringRef Filename;
1318 SourceLocation EndLoc;
1319
1320 switch (Tok.getKind()) {
1321 case tok::eod:
1322 // If the token kind is EOD, the error has already been diagnosed.
1323 return false;
1324
1325 case tok::angle_string_literal:
1326 case tok::string_literal: {
1327 bool Invalid = false;
1328 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
1329 if (Invalid)
1330 return false;
1331 break;
1332 }
1333
1334 case tok::less:
1335 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1336 // case, glue the tokens together into FilenameBuffer and interpret those.
1337 FilenameBuffer.push_back('<');
Richard Trieuda031982012-10-22 20:28:48 +00001338 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc)) {
1339 // Let the caller know a <eod> was found by changing the Token kind.
1340 Tok.setKind(tok::eod);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001341 return false; // Found <eod> but no ">"? Diagnostic already emitted.
Richard Trieuda031982012-10-22 20:28:48 +00001342 }
Yaron Keren92e1b622015-03-18 10:17:07 +00001343 Filename = FilenameBuffer;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001344 break;
1345 default:
1346 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
1347 return false;
1348 }
1349
Richard Trieuda031982012-10-22 20:28:48 +00001350 SourceLocation FilenameLoc = Tok.getLocation();
1351
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001352 // Get ')'.
1353 PP.LexNonComment(Tok);
1354
1355 // Ensure we have a trailing ).
1356 if (Tok.isNot(tok::r_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001357 PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after)
1358 << II << tok::r_paren;
Alp Tokerec543272013-12-24 09:48:30 +00001359 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001360 return false;
1361 }
1362
1363 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
1364 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1365 // error.
1366 if (Filename.empty())
1367 return false;
1368
1369 // Search include directories.
1370 const DirectoryLookup *CurDir;
1371 const FileEntry *File =
Richard Smith25d50752014-10-20 00:15:49 +00001372 PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, LookupFromFile,
1373 CurDir, nullptr, nullptr, nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001374
1375 // Get the result value. A result of true means the file exists.
Craig Topperd2d442c2014-05-17 23:10:59 +00001376 return File != nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001377}
1378
1379/// EvaluateHasInclude - Process a '__has_include("path")' expression.
1380/// Returns true if successful.
1381static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
1382 Preprocessor &PP) {
Richard Smith25d50752014-10-20 00:15:49 +00001383 return EvaluateHasIncludeCommon(Tok, II, PP, nullptr, nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001384}
1385
1386/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
1387/// Returns true if successful.
1388static bool EvaluateHasIncludeNext(Token &Tok,
1389 IdentifierInfo *II, Preprocessor &PP) {
1390 // __has_include_next is like __has_include, except that we start
1391 // searching after the current found directory. If we can't do this,
1392 // issue a diagnostic.
Yaron Kerenbc5986f2015-02-19 11:21:11 +00001393 // FIXME: Factor out duplication with
Richard Smith25d50752014-10-20 00:15:49 +00001394 // Preprocessor::HandleIncludeNextDirective.
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001395 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
Richard Smith25d50752014-10-20 00:15:49 +00001396 const FileEntry *LookupFromFile = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001397 if (PP.isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001398 Lookup = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001399 PP.Diag(Tok, diag::pp_include_next_in_primary);
Richard Smith25d50752014-10-20 00:15:49 +00001400 } else if (PP.getCurrentSubmodule()) {
1401 // Start looking up in the directory *after* the one in which the current
1402 // file would be found, if any.
1403 assert(PP.getCurrentLexer() && "#include_next directive in macro?");
1404 LookupFromFile = PP.getCurrentLexer()->getFileEntry();
1405 Lookup = nullptr;
Craig Topperd2d442c2014-05-17 23:10:59 +00001406 } else if (!Lookup) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001407 PP.Diag(Tok, diag::pp_include_next_absolute_path);
1408 } else {
1409 // Start looking up in the next directory.
1410 ++Lookup;
1411 }
1412
Richard Smith25d50752014-10-20 00:15:49 +00001413 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup, LookupFromFile);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001414}
1415
Douglas Gregorc83de302012-09-25 15:44:52 +00001416/// \brief Process __building_module(identifier) expression.
1417/// \returns true if we are building the named module, false otherwise.
1418static bool EvaluateBuildingModule(Token &Tok,
1419 IdentifierInfo *II, Preprocessor &PP) {
1420 // Get '('.
1421 PP.LexNonComment(Tok);
1422
1423 // Ensure we have a '('.
1424 if (Tok.isNot(tok::l_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001425 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1426 << tok::l_paren;
Douglas Gregorc83de302012-09-25 15:44:52 +00001427 return false;
1428 }
1429
1430 // Save '(' location for possible missing ')' message.
1431 SourceLocation LParenLoc = Tok.getLocation();
1432
1433 // Get the module name.
1434 PP.LexNonComment(Tok);
1435
1436 // Ensure that we have an identifier.
1437 if (Tok.isNot(tok::identifier)) {
1438 PP.Diag(Tok.getLocation(), diag::err_expected_id_building_module);
1439 return false;
1440 }
1441
1442 bool Result
1443 = Tok.getIdentifierInfo()->getName() == PP.getLangOpts().CurrentModule;
1444
1445 // Get ')'.
1446 PP.LexNonComment(Tok);
1447
1448 // Ensure we have a trailing ).
1449 if (Tok.isNot(tok::r_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001450 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1451 << tok::r_paren;
Alp Tokerec543272013-12-24 09:48:30 +00001452 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
Douglas Gregorc83de302012-09-25 15:44:52 +00001453 return false;
1454 }
1455
1456 return Result;
1457}
1458
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001459/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1460/// as a builtin macro, handle it and return the next token as 'Tok'.
1461void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
1462 // Figure out which token this is.
1463 IdentifierInfo *II = Tok.getIdentifierInfo();
1464 assert(II && "Can't be a macro without id info!");
1465
1466 // If this is an _Pragma or Microsoft __pragma directive, expand it,
1467 // invoke the pragma handler, then lex the token after it.
1468 if (II == Ident_Pragma)
1469 return Handle_Pragma(Tok);
1470 else if (II == Ident__pragma) // in non-MS mode this is null
1471 return HandleMicrosoft__pragma(Tok);
1472
1473 ++NumBuiltinMacroExpanded;
1474
1475 SmallString<128> TmpBuffer;
1476 llvm::raw_svector_ostream OS(TmpBuffer);
1477
1478 // Set up the return result.
Craig Topperd2d442c2014-05-17 23:10:59 +00001479 Tok.setIdentifierInfo(nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001480 Tok.clearFlag(Token::NeedsCleaning);
1481
1482 if (II == Ident__LINE__) {
1483 // C99 6.10.8: "__LINE__: The presumed line number (within the current
1484 // source file) of the current source line (an integer constant)". This can
1485 // be affected by #line.
1486 SourceLocation Loc = Tok.getLocation();
1487
1488 // Advance to the location of the first _, this might not be the first byte
1489 // of the token if it starts with an escaped newline.
1490 Loc = AdvanceToTokenCharacter(Loc, 0);
1491
1492 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
1493 // a macro expansion. This doesn't matter for object-like macros, but
1494 // can matter for a function-like macro that expands to contain __LINE__.
1495 // Skip down through expansion points until we find a file loc for the
1496 // end of the expansion history.
1497 Loc = SourceMgr.getExpansionRange(Loc).second;
1498 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
1499
1500 // __LINE__ expands to a simple numeric value.
1501 OS << (PLoc.isValid()? PLoc.getLine() : 1);
1502 Tok.setKind(tok::numeric_constant);
1503 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
1504 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
1505 // character string literal)". This can be affected by #line.
1506 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1507
1508 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
1509 // #include stack instead of the current file.
1510 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
1511 SourceLocation NextLoc = PLoc.getIncludeLoc();
1512 while (NextLoc.isValid()) {
1513 PLoc = SourceMgr.getPresumedLoc(NextLoc);
1514 if (PLoc.isInvalid())
1515 break;
1516
1517 NextLoc = PLoc.getIncludeLoc();
1518 }
1519 }
1520
1521 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
1522 SmallString<128> FN;
1523 if (PLoc.isValid()) {
1524 FN += PLoc.getFilename();
1525 Lexer::Stringify(FN);
Yaron Keren09fb7c62015-03-10 07:33:23 +00001526 OS << '"' << FN << '"';
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001527 }
1528 Tok.setKind(tok::string_literal);
1529 } else if (II == Ident__DATE__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001530 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001531 if (!DATELoc.isValid())
1532 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1533 Tok.setKind(tok::string_literal);
1534 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1535 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
1536 Tok.getLocation(),
1537 Tok.getLength()));
1538 return;
1539 } else if (II == Ident__TIME__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001540 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001541 if (!TIMELoc.isValid())
1542 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1543 Tok.setKind(tok::string_literal);
1544 Tok.setLength(strlen("\"hh:mm:ss\""));
1545 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
1546 Tok.getLocation(),
1547 Tok.getLength()));
1548 return;
1549 } else if (II == Ident__INCLUDE_LEVEL__) {
1550 // Compute the presumed include depth of this token. This can be affected
1551 // by GNU line markers.
1552 unsigned Depth = 0;
1553
1554 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1555 if (PLoc.isValid()) {
1556 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1557 for (; PLoc.isValid(); ++Depth)
1558 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1559 }
1560
1561 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1562 OS << Depth;
1563 Tok.setKind(tok::numeric_constant);
1564 } else if (II == Ident__TIMESTAMP__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001565 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001566 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1567 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1568
1569 // Get the file that we are lexing out of. If we're currently lexing from
1570 // a macro, dig into the include stack.
Craig Topperd2d442c2014-05-17 23:10:59 +00001571 const FileEntry *CurFile = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001572 PreprocessorLexer *TheLexer = getCurrentFileLexer();
1573
1574 if (TheLexer)
1575 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
1576
1577 const char *Result;
1578 if (CurFile) {
1579 time_t TT = CurFile->getModificationTime();
1580 struct tm *TM = localtime(&TT);
1581 Result = asctime(TM);
1582 } else {
1583 Result = "??? ??? ?? ??:??:?? ????\n";
1584 }
1585 // Surround the string with " and strip the trailing newline.
Alp Toker4f43e552014-06-10 06:08:51 +00001586 OS << '"' << StringRef(Result).drop_back() << '"';
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001587 Tok.setKind(tok::string_literal);
1588 } else if (II == Ident__COUNTER__) {
1589 // __COUNTER__ expands to a simple numeric value.
1590 OS << CounterValue++;
1591 Tok.setKind(tok::numeric_constant);
1592 } else if (II == Ident__has_feature ||
1593 II == Ident__has_extension ||
1594 II == Ident__has_builtin ||
Yunzhong Gaoef309f42014-04-11 20:55:19 +00001595 II == Ident__is_identifier ||
Aaron Ballmana0344c52014-11-14 13:44:02 +00001596 II == Ident__has_attribute ||
Aaron Ballman3c0f9b42014-12-05 15:05:29 +00001597 II == Ident__has_declspec ||
Aaron Ballmana0344c52014-11-14 13:44:02 +00001598 II == Ident__has_cpp_attribute) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001599 // The argument to these builtins should be a parenthesized identifier.
1600 SourceLocation StartLoc = Tok.getLocation();
1601
1602 bool IsValid = false;
Craig Topperd2d442c2014-05-17 23:10:59 +00001603 IdentifierInfo *FeatureII = nullptr;
Aaron Ballmana0344c52014-11-14 13:44:02 +00001604 IdentifierInfo *ScopeII = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001605
1606 // Read the '('.
Andy Gibbsd41d0942012-11-17 19:18:27 +00001607 LexUnexpandedToken(Tok);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001608 if (Tok.is(tok::l_paren)) {
1609 // Read the identifier
Andy Gibbsd41d0942012-11-17 19:18:27 +00001610 LexUnexpandedToken(Tok);
Richard Smithbaf29122013-07-09 00:57:56 +00001611 if ((FeatureII = Tok.getIdentifierInfo())) {
Aaron Ballmana0344c52014-11-14 13:44:02 +00001612 // If we're checking __has_cpp_attribute, it is possible to receive a
1613 // scope token. Read the "::", if it's available.
Andy Gibbsd41d0942012-11-17 19:18:27 +00001614 LexUnexpandedToken(Tok);
Aaron Ballmana0344c52014-11-14 13:44:02 +00001615 bool IsScopeValid = true;
1616 if (II == Ident__has_cpp_attribute && Tok.is(tok::coloncolon)) {
1617 LexUnexpandedToken(Tok);
1618 // The first thing we read was not the feature, it was the scope.
1619 ScopeII = FeatureII;
Aaron Ballman918474c2014-11-14 14:40:49 +00001620 if ((FeatureII = Tok.getIdentifierInfo()))
Aaron Ballmana0344c52014-11-14 13:44:02 +00001621 LexUnexpandedToken(Tok);
1622 else
1623 IsScopeValid = false;
1624 }
1625 // Read the closing paren.
1626 if (IsScopeValid && Tok.is(tok::r_paren))
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001627 IsValid = true;
1628 }
David Majnemerd6163622014-12-15 09:03:58 +00001629 // Eat tokens until ')'.
1630 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) &&
1631 Tok.isNot(tok::eof))
1632 LexUnexpandedToken(Tok);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001633 }
1634
Aaron Ballmana0344c52014-11-14 13:44:02 +00001635 int Value = 0;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001636 if (!IsValid)
1637 Diag(StartLoc, diag::err_feature_check_malformed);
Yunzhong Gaoef309f42014-04-11 20:55:19 +00001638 else if (II == Ident__is_identifier)
1639 Value = FeatureII->getTokenID() == tok::identifier;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001640 else if (II == Ident__has_builtin) {
1641 // Check for a builtin is trivial.
David Majnemer5088cdf2015-11-05 01:01:47 +00001642 if (FeatureII->getBuiltinID() != 0) {
1643 Value = true;
1644 } else {
David Majnemer5088cdf2015-11-05 01:01:47 +00001645 StringRef Feature = FeatureII->getName();
1646 Value = llvm::StringSwitch<bool>(Feature)
David Majnemer18e96252015-11-05 01:10:42 +00001647 .Case("__make_integer_seq", getLangOpts().CPlusPlus)
David Majnemer5088cdf2015-11-05 01:01:47 +00001648 .Default(false);
1649 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001650 } else if (II == Ident__has_attribute)
Aaron Ballmana6f759e2014-12-05 15:24:55 +00001651 Value = hasAttribute(AttrSyntax::GNU, nullptr, FeatureII,
Bob Wilson7c730832015-07-20 22:57:31 +00001652 getTargetInfo(), getLangOpts());
Aaron Ballmana0344c52014-11-14 13:44:02 +00001653 else if (II == Ident__has_cpp_attribute)
1654 Value = hasAttribute(AttrSyntax::CXX, ScopeII, FeatureII,
Bob Wilson7c730832015-07-20 22:57:31 +00001655 getTargetInfo(), getLangOpts());
Aaron Ballman3c0f9b42014-12-05 15:05:29 +00001656 else if (II == Ident__has_declspec)
1657 Value = hasAttribute(AttrSyntax::Declspec, nullptr, FeatureII,
Bob Wilson7c730832015-07-20 22:57:31 +00001658 getTargetInfo(), getLangOpts());
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001659 else if (II == Ident__has_extension)
1660 Value = HasExtension(*this, FeatureII);
1661 else {
1662 assert(II == Ident__has_feature && "Must be feature check");
1663 Value = HasFeature(*this, FeatureII);
1664 }
1665
David Majnemerd6163622014-12-15 09:03:58 +00001666 if (!IsValid)
1667 return;
Aaron Ballmana0344c52014-11-14 13:44:02 +00001668 OS << Value;
David Majnemerd6163622014-12-15 09:03:58 +00001669 Tok.setKind(tok::numeric_constant);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001670 } else if (II == Ident__has_include ||
1671 II == Ident__has_include_next) {
1672 // The argument to these two builtins should be a parenthesized
1673 // file name string literal using angle brackets (<>) or
1674 // double-quotes ("").
1675 bool Value;
1676 if (II == Ident__has_include)
1677 Value = EvaluateHasInclude(Tok, II, *this);
1678 else
1679 Value = EvaluateHasIncludeNext(Tok, II, *this);
Benjamin Kramer18ff02d2015-03-29 15:33:29 +00001680
1681 if (Tok.isNot(tok::r_paren))
1682 return;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001683 OS << (int)Value;
Benjamin Kramer18ff02d2015-03-29 15:33:29 +00001684 Tok.setKind(tok::numeric_constant);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001685 } else if (II == Ident__has_warning) {
1686 // The argument should be a parenthesized string literal.
1687 // The argument to these builtins should be a parenthesized identifier.
1688 SourceLocation StartLoc = Tok.getLocation();
1689 bool IsValid = false;
1690 bool Value = false;
1691 // Read the '('.
Andy Gibbs58905d22012-11-17 19:15:38 +00001692 LexUnexpandedToken(Tok);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001693 do {
Andy Gibbs58905d22012-11-17 19:15:38 +00001694 if (Tok.isNot(tok::l_paren)) {
1695 Diag(StartLoc, diag::err_warning_check_malformed);
1696 break;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001697 }
Andy Gibbs58905d22012-11-17 19:15:38 +00001698
1699 LexUnexpandedToken(Tok);
1700 std::string WarningName;
1701 SourceLocation StrStartLoc = Tok.getLocation();
Andy Gibbsa8df57a2012-11-17 19:16:52 +00001702 if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",
1703 /*MacroExpansion=*/false)) {
Andy Gibbs58905d22012-11-17 19:15:38 +00001704 // Eat tokens until ')'.
Andy Gibbsb5b30c42012-11-17 22:17:28 +00001705 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) &&
1706 Tok.isNot(tok::eof))
Andy Gibbs58905d22012-11-17 19:15:38 +00001707 LexUnexpandedToken(Tok);
1708 break;
1709 }
1710
1711 // Is the end a ')'?
1712 if (!(IsValid = Tok.is(tok::r_paren))) {
1713 Diag(StartLoc, diag::err_warning_check_malformed);
1714 break;
1715 }
1716
Richard Smith3be1cb22014-08-07 00:24:21 +00001717 // FIXME: Should we accept "-R..." flags here, or should that be handled
1718 // by a separate __has_remark?
Andy Gibbs58905d22012-11-17 19:15:38 +00001719 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1720 WarningName[1] != 'W') {
1721 Diag(StrStartLoc, diag::warn_has_warning_invalid_option);
1722 break;
1723 }
1724
1725 // Finally, check if the warning flags maps to a diagnostic group.
1726 // We construct a SmallVector here to talk to getDiagnosticIDs().
1727 // Although we don't use the result, this isn't a hot path, and not
1728 // worth special casing.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001729 SmallVector<diag::kind, 10> Diags;
Andy Gibbs58905d22012-11-17 19:15:38 +00001730 Value = !getDiagnostics().getDiagnosticIDs()->
Richard Smith3be1cb22014-08-07 00:24:21 +00001731 getDiagnosticsInGroup(diag::Flavor::WarningOrError,
1732 WarningName.substr(2), Diags);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001733 } while (false);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001734
David Majnemerd6163622014-12-15 09:03:58 +00001735 if (!IsValid)
1736 return;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001737 OS << (int)Value;
David Majnemerd6163622014-12-15 09:03:58 +00001738 Tok.setKind(tok::numeric_constant);
Douglas Gregorc83de302012-09-25 15:44:52 +00001739 } else if (II == Ident__building_module) {
1740 // The argument to this builtin should be an identifier. The
1741 // builtin evaluates to 1 when that identifier names the module we are
1742 // currently building.
1743 OS << (int)EvaluateBuildingModule(Tok, II, *this);
1744 Tok.setKind(tok::numeric_constant);
1745 } else if (II == Ident__MODULE__) {
1746 // The current module as an identifier.
1747 OS << getLangOpts().CurrentModule;
1748 IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);
1749 Tok.setIdentifierInfo(ModuleII);
1750 Tok.setKind(ModuleII->getTokenID());
Richard Smithae385082014-03-15 00:06:08 +00001751 } else if (II == Ident__identifier) {
1752 SourceLocation Loc = Tok.getLocation();
1753
1754 // We're expecting '__identifier' '(' identifier ')'. Try to recover
1755 // if the parens are missing.
1756 LexNonComment(Tok);
1757 if (Tok.isNot(tok::l_paren)) {
1758 // No '(', use end of last token.
1759 Diag(getLocForEndOfToken(Loc), diag::err_pp_expected_after)
1760 << II << tok::l_paren;
1761 // If the next token isn't valid as our argument, we can't recover.
1762 if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1763 Tok.setKind(tok::identifier);
1764 return;
1765 }
1766
1767 SourceLocation LParenLoc = Tok.getLocation();
1768 LexNonComment(Tok);
1769
1770 if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1771 Tok.setKind(tok::identifier);
1772 else {
1773 Diag(Tok.getLocation(), diag::err_pp_identifier_arg_not_identifier)
1774 << Tok.getKind();
1775 // Don't walk past anything that's not a real token.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001776 if (Tok.isOneOf(tok::eof, tok::eod) || Tok.isAnnotation())
Richard Smithae385082014-03-15 00:06:08 +00001777 return;
1778 }
1779
1780 // Discard the ')', preserving 'Tok' as our result.
1781 Token RParen;
1782 LexNonComment(RParen);
1783 if (RParen.isNot(tok::r_paren)) {
1784 Diag(getLocForEndOfToken(Tok.getLocation()), diag::err_pp_expected_after)
1785 << Tok.getKind() << tok::r_paren;
1786 Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1787 }
1788 return;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001789 } else {
1790 llvm_unreachable("Unknown identifier!");
1791 }
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00001792 CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation());
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001793}
1794
1795void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
1796 // If the 'used' status changed, and the macro requires 'unused' warning,
1797 // remove its SourceLocation from the warn-for-unused-macro locations.
1798 if (MI->isWarnIfUnused() && !MI->isUsed())
1799 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1800 MI->setIsUsed(true);
1801}