blob: 4c6aa4e45ac199103a39d60e53f8515e19c51cc2 [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 *
37Preprocessor::getMacroDirectiveHistory(const IdentifierInfo *II) const {
Alexander Kornienko1d26c022012-09-25 17:18:14 +000038 assert(II->hadMacroDefinition() && "Identifier has not been not a macro!");
Joao Matosc0d4c1b2012-08-31 21:34:27 +000039
40 macro_iterator Pos = Macros.find(II);
Joao Matosc0d4c1b2012-08-31 21:34:27 +000041 assert(Pos != Macros.end() && "Identifier macro info is missing!");
Joao Matosc0d4c1b2012-08-31 21:34:27 +000042 return Pos->second;
43}
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
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +000049 MacroDirective *&StoredMD = Macros[II];
50 MD->setPrevious(StoredMD);
51 StoredMD = MD;
Ben Langmuirc28ce3a2014-09-30 20:00:18 +000052 // Setup the identifier as having associated macro history.
53 II->setHasMacroDefinition(true);
54 if (!MD->isDefined())
55 II->setHasMacroDefinition(false);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000056 bool isImportedMacro = isa<DefMacroDirective>(MD) &&
57 cast<DefMacroDirective>(MD)->isImported();
58 if (II->isFromAST() && !isImportedMacro)
Joao Matosc0d4c1b2012-08-31 21:34:27 +000059 II->setChangedSinceDeserialization();
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000060}
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +000061
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000062void Preprocessor::setLoadedMacroDirective(IdentifierInfo *II,
63 MacroDirective *MD) {
64 assert(II && MD);
65 MacroDirective *&StoredMD = Macros[II];
66 assert(!StoredMD &&
67 "the macro history was modified before initializing it from a pch");
68 StoredMD = MD;
69 // Setup the identifier as having associated macro history.
70 II->setHasMacroDefinition(true);
71 if (!MD->isDefined())
72 II->setHasMacroDefinition(false);
Joao Matosc0d4c1b2012-08-31 21:34:27 +000073}
74
Richard Smithe56c8bc2015-04-22 00:26:11 +000075ModuleMacro *Preprocessor::addModuleMacro(unsigned ModuleID, IdentifierInfo *II,
76 MacroInfo *Macro,
77 ArrayRef<ModuleMacro *> Overrides,
78 bool &New) {
79 llvm::FoldingSetNodeID ID;
80 ModuleMacro::Profile(ID, ModuleID, II);
81
82 void *InsertPos;
83 if (auto *MM = ModuleMacros.FindNodeOrInsertPos(ID, InsertPos)) {
84 New = false;
85 return MM;
86 }
87
88 auto *MM = ModuleMacro::create(*this, ModuleID, II, Macro, Overrides);
89 ModuleMacros.InsertNode(MM, InsertPos);
90
91 // Each overridden macro is now overridden by one more macro.
92 bool HidAny = false;
93 for (auto *O : Overrides) {
94 HidAny |= (O->NumOverriddenBy == 0);
95 ++O->NumOverriddenBy;
96 }
97
98 // If we were the first overrider for any macro, it's no longer a leaf.
99 auto &LeafMacros = LeafModuleMacros[II];
100 if (HidAny) {
101 LeafMacros.erase(std::remove_if(LeafMacros.begin(), LeafMacros.end(),
102 [](ModuleMacro *MM) {
103 return MM->NumOverriddenBy != 0;
104 }),
105 LeafMacros.end());
106 }
107
108 // The new macro is always a leaf macro.
109 LeafMacros.push_back(MM);
110
111 New = true;
112 return MM;
113}
114
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000115/// RegisterBuiltinMacro - Register the specified identifier in the identifier
116/// table and mark it as a builtin macro to be expanded.
117static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
118 // Get the identifier.
119 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
120
121 // Mark it as being a macro that is builtin.
122 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
123 MI->setIsBuiltinMacro();
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000124 PP.appendDefMacroDirective(Id, MI);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000125 return Id;
126}
127
128
129/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
130/// identifier table.
131void Preprocessor::RegisterBuiltinMacros() {
132 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
133 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
134 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
135 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
136 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
137 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
138
Aaron Ballmana0344c52014-11-14 13:44:02 +0000139 // C++ Standing Document Extensions.
140 Ident__has_cpp_attribute = RegisterBuiltinMacro(*this, "__has_cpp_attribute");
141
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000142 // GCC Extensions.
143 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
144 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
145 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
146
Richard Smithae385082014-03-15 00:06:08 +0000147 // Microsoft Extensions.
148 if (LangOpts.MicrosoftExt) {
149 Ident__identifier = RegisterBuiltinMacro(*this, "__identifier");
150 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
151 } else {
Craig Topperd2d442c2014-05-17 23:10:59 +0000152 Ident__identifier = nullptr;
153 Ident__pragma = nullptr;
Richard Smithae385082014-03-15 00:06:08 +0000154 }
155
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000156 // Clang Extensions.
157 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
158 Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension");
159 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
160 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
Aaron Ballman3c0f9b42014-12-05 15:05:29 +0000161 Ident__has_declspec = RegisterBuiltinMacro(*this, "__has_declspec_attribute");
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000162 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
163 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
164 Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning");
Yunzhong Gaoef309f42014-04-11 20:55:19 +0000165 Ident__is_identifier = RegisterBuiltinMacro(*this, "__is_identifier");
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000166
Douglas Gregorc83de302012-09-25 15:44:52 +0000167 // Modules.
168 if (LangOpts.Modules) {
169 Ident__building_module = RegisterBuiltinMacro(*this, "__building_module");
170
171 // __MODULE__
172 if (!LangOpts.CurrentModule.empty())
173 Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__");
174 else
Craig Topperd2d442c2014-05-17 23:10:59 +0000175 Ident__MODULE__ = nullptr;
Douglas Gregorc83de302012-09-25 15:44:52 +0000176 } else {
Craig Topperd2d442c2014-05-17 23:10:59 +0000177 Ident__building_module = nullptr;
178 Ident__MODULE__ = nullptr;
Douglas Gregorc83de302012-09-25 15:44:52 +0000179 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000180}
181
182/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
183/// in its expansion, currently expands to that token literally.
184static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
185 const IdentifierInfo *MacroIdent,
186 Preprocessor &PP) {
187 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
188
189 // If the token isn't an identifier, it's always literally expanded.
Craig Topperd2d442c2014-05-17 23:10:59 +0000190 if (!II) return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000191
192 // If the information about this identifier is out of date, update it from
193 // the external source.
194 if (II->isOutOfDate())
195 PP.getExternalSource()->updateOutOfDateIdentifier(*II);
196
197 // If the identifier is a macro, and if that macro is enabled, it may be
198 // expanded so it's not a trivial expansion.
199 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
200 // Fast expanding "#define X X" is ok, because X would be disabled.
201 II != MacroIdent)
202 return false;
203
204 // If this is an object-like macro invocation, it is safe to trivially expand
205 // it.
206 if (MI->isObjectLike()) return true;
207
208 // If this is a function-like macro invocation, it's safe to trivially expand
209 // as long as the identifier is not a macro argument.
210 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
211 I != E; ++I)
212 if (*I == II)
213 return false; // Identifier is a macro argument.
214
215 return true;
216}
217
218
219/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
220/// lexed is a '('. If so, consume the token and return true, if not, this
221/// method should have no observable side-effect on the lexed tokens.
222bool Preprocessor::isNextPPTokenLParen() {
223 // Do some quick tests for rejection cases.
224 unsigned Val;
225 if (CurLexer)
226 Val = CurLexer->isNextPPTokenLParen();
227 else if (CurPTHLexer)
228 Val = CurPTHLexer->isNextPPTokenLParen();
229 else
230 Val = CurTokenLexer->isNextTokenLParen();
231
232 if (Val == 2) {
233 // We have run off the end. If it's a source file we don't
234 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
235 // macro stack.
236 if (CurPPLexer)
237 return false;
238 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
239 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
240 if (Entry.TheLexer)
241 Val = Entry.TheLexer->isNextPPTokenLParen();
242 else if (Entry.ThePTHLexer)
243 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
244 else
245 Val = Entry.TheTokenLexer->isNextTokenLParen();
246
247 if (Val != 2)
248 break;
249
250 // Ran off the end of a source file?
251 if (Entry.ThePPLexer)
252 return false;
253 }
254 }
255
256 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
257 // have found something that isn't a '(' or we found the end of the
258 // translation unit. In either case, return false.
259 return Val == 1;
260}
261
262/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
263/// expanded as a macro, handle it and return the next token as 'Identifier'.
264bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000265 MacroDirective *MD) {
Argyrios Kyrtzidis09796b92013-03-27 01:25:19 +0000266 MacroDirective::DefInfo Def = MD->getDefinition();
267 assert(Def.isValid());
268 MacroInfo *MI = Def.getMacroInfo();
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000269
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000270 // If this is a macro expansion in the "#if !defined(x)" line for the file,
271 // then the macro could expand to different things in other contexts, we need
272 // to disable the optimization in this case.
273 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
274
275 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
276 if (MI->isBuiltinMacro()) {
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000277 if (Callbacks) Callbacks->MacroExpands(Identifier, MD,
Craig Topperd2d442c2014-05-17 23:10:59 +0000278 Identifier.getLocation(),
279 /*Args=*/nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000280 ExpandBuiltinMacro(Identifier);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000281 return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000282 }
283
284 /// Args - If this is a function-like macro expansion, this contains,
285 /// for each macro argument, the list of tokens that were provided to the
286 /// invocation.
Craig Topperd2d442c2014-05-17 23:10:59 +0000287 MacroArgs *Args = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000288
289 // Remember where the end of the expansion occurred. For an object-like
290 // macro, this is the identifier. For a function-like macro, this is the ')'.
291 SourceLocation ExpansionEnd = Identifier.getLocation();
292
293 // If this is a function-like macro, read the arguments.
294 if (MI->isFunctionLike()) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000295 // Remember that we are now parsing the arguments to a macro invocation.
296 // Preprocessor directives used inside macro arguments are not portable, and
297 // this enables the warning.
298 InMacroArgs = true;
299 Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd);
300
301 // Finished parsing args.
302 InMacroArgs = false;
303
304 // If there was an error parsing the arguments, bail out.
Craig Topperd2d442c2014-05-17 23:10:59 +0000305 if (!Args) return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000306
307 ++NumFnMacroExpanded;
308 } else {
309 ++NumMacroExpanded;
310 }
311
312 // Notice that this macro has been used.
313 markMacroAsUsed(MI);
314
315 // Remember where the token is expanded.
316 SourceLocation ExpandLoc = Identifier.getLocation();
317 SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
318
319 if (Callbacks) {
320 if (InMacroArgs) {
321 // We can have macro expansion inside a conditional directive while
322 // reading the function macro arguments. To ensure, in that case, that
323 // MacroExpands callbacks still happen in source order, queue this
324 // callback to have it happen after the function macro callback.
325 DelayedMacroExpandsCallbacks.push_back(
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000326 MacroExpandsInfo(Identifier, MD, ExpansionRange));
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000327 } else {
Argyrios Kyrtzidis37e48ff2013-05-03 22:31:32 +0000328 Callbacks->MacroExpands(Identifier, MD, ExpansionRange, Args);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000329 if (!DelayedMacroExpandsCallbacks.empty()) {
330 for (unsigned i=0, e = DelayedMacroExpandsCallbacks.size(); i!=e; ++i) {
331 MacroExpandsInfo &Info = DelayedMacroExpandsCallbacks[i];
Argyrios Kyrtzidis37e48ff2013-05-03 22:31:32 +0000332 // FIXME: We lose macro args info with delayed callback.
Craig Topperd2d442c2014-05-17 23:10:59 +0000333 Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range,
334 /*Args=*/nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000335 }
336 DelayedMacroExpandsCallbacks.clear();
337 }
338 }
339 }
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000340
341 // If the macro definition is ambiguous, complain.
Argyrios Kyrtzidis09796b92013-03-27 01:25:19 +0000342 if (Def.getDirective()->isAmbiguous()) {
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000343 Diag(Identifier, diag::warn_pp_ambiguous_macro)
344 << Identifier.getIdentifierInfo();
345 Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)
346 << Identifier.getIdentifierInfo();
Argyrios Kyrtzidis09796b92013-03-27 01:25:19 +0000347 for (MacroDirective::DefInfo PrevDef = Def.getPreviousDefinition();
348 PrevDef && !PrevDef.isUndefined();
349 PrevDef = PrevDef.getPreviousDefinition()) {
Richard Smith49f906a2014-03-01 00:08:04 +0000350 Diag(PrevDef.getMacroInfo()->getDefinitionLoc(),
351 diag::note_pp_ambiguous_macro_other)
352 << Identifier.getIdentifierInfo();
353 if (!PrevDef.getDirective()->isAmbiguous())
354 break;
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000355 }
356 }
357
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000358 // If we started lexing a macro, enter the macro expansion body.
359
360 // If this macro expands to no tokens, don't bother to push it onto the
361 // expansion stack, only to take it right back off.
362 if (MI->getNumTokens() == 0) {
363 // No need for arg info.
364 if (Args) Args->destroy(*this);
365
Eli Friedman0834a4b2013-09-19 00:41:32 +0000366 // Propagate whitespace info as if we had pushed, then popped,
367 // a macro context.
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000368 Identifier.setFlag(Token::LeadingEmptyMacro);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000369 PropagateLineStartLeadingSpaceInfo(Identifier);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000370 ++NumFastMacroExpanded;
371 return false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000372 } else if (MI->getNumTokens() == 1 &&
373 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
374 *this)) {
375 // Otherwise, if this macro expands into a single trivially-expanded
376 // token: expand it now. This handles common cases like
377 // "#define VAL 42".
378
379 // No need for arg info.
380 if (Args) Args->destroy(*this);
381
382 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
383 // identifier to the expanded token.
384 bool isAtStartOfLine = Identifier.isAtStartOfLine();
385 bool hasLeadingSpace = Identifier.hasLeadingSpace();
386
387 // Replace the result token.
388 Identifier = MI->getReplacementToken(0);
389
390 // Restore the StartOfLine/LeadingSpace markers.
391 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
392 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
393
394 // Update the tokens location to include both its expansion and physical
395 // locations.
396 SourceLocation Loc =
397 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
398 ExpansionEnd,Identifier.getLength());
399 Identifier.setLocation(Loc);
400
401 // If this is a disabled macro or #define X X, we must mark the result as
402 // unexpandable.
403 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
404 if (MacroInfo *NewMI = getMacroInfo(NewII))
405 if (!NewMI->isEnabled() || NewMI == MI) {
406 Identifier.setFlag(Token::DisableExpand);
Douglas Gregor1a347f72013-01-30 23:10:17 +0000407 // Don't warn for "#define X X" like "#define bool bool" from
408 // stdbool.h.
409 if (NewMI != MI || MI->isFunctionLike())
410 Diag(Identifier, diag::pp_disabled_macro_expansion);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000411 }
412 }
413
414 // Since this is not an identifier token, it can't be macro expanded, so
415 // we're done.
416 ++NumFastMacroExpanded;
Eli Friedman0834a4b2013-09-19 00:41:32 +0000417 return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000418 }
419
420 // Start expanding the macro.
421 EnterMacro(Identifier, ExpansionEnd, MI, Args);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000422 return false;
423}
424
Richard Trieu79b45382013-07-23 18:01:49 +0000425enum Bracket {
426 Brace,
427 Paren
428};
429
430/// CheckMatchedBrackets - Returns true if the braces and parentheses in the
431/// token vector are properly nested.
432static bool CheckMatchedBrackets(const SmallVectorImpl<Token> &Tokens) {
433 SmallVector<Bracket, 8> Brackets;
434 for (SmallVectorImpl<Token>::const_iterator I = Tokens.begin(),
435 E = Tokens.end();
436 I != E; ++I) {
437 if (I->is(tok::l_paren)) {
438 Brackets.push_back(Paren);
439 } else if (I->is(tok::r_paren)) {
440 if (Brackets.empty() || Brackets.back() == Brace)
441 return false;
442 Brackets.pop_back();
443 } else if (I->is(tok::l_brace)) {
444 Brackets.push_back(Brace);
445 } else if (I->is(tok::r_brace)) {
446 if (Brackets.empty() || Brackets.back() == Paren)
447 return false;
448 Brackets.pop_back();
449 }
450 }
451 if (!Brackets.empty())
452 return false;
453 return true;
454}
455
456/// GenerateNewArgTokens - Returns true if OldTokens can be converted to a new
457/// vector of tokens in NewTokens. The new number of arguments will be placed
458/// in NumArgs and the ranges which need to surrounded in parentheses will be
459/// in ParenHints.
460/// Returns false if the token stream cannot be changed. If this is because
461/// of an initializer list starting a macro argument, the range of those
462/// initializer lists will be place in InitLists.
463static bool GenerateNewArgTokens(Preprocessor &PP,
464 SmallVectorImpl<Token> &OldTokens,
465 SmallVectorImpl<Token> &NewTokens,
466 unsigned &NumArgs,
467 SmallVectorImpl<SourceRange> &ParenHints,
468 SmallVectorImpl<SourceRange> &InitLists) {
469 if (!CheckMatchedBrackets(OldTokens))
470 return false;
471
472 // Once it is known that the brackets are matched, only a simple count of the
473 // braces is needed.
474 unsigned Braces = 0;
475
476 // First token of a new macro argument.
477 SmallVectorImpl<Token>::iterator ArgStartIterator = OldTokens.begin();
478
479 // First closing brace in a new macro argument. Used to generate
480 // SourceRanges for InitLists.
481 SmallVectorImpl<Token>::iterator ClosingBrace = OldTokens.end();
482 NumArgs = 0;
483 Token TempToken;
484 // Set to true when a macro separator token is found inside a braced list.
485 // If true, the fixed argument spans multiple old arguments and ParenHints
486 // will be updated.
487 bool FoundSeparatorToken = false;
488 for (SmallVectorImpl<Token>::iterator I = OldTokens.begin(),
489 E = OldTokens.end();
490 I != E; ++I) {
491 if (I->is(tok::l_brace)) {
492 ++Braces;
493 } else if (I->is(tok::r_brace)) {
494 --Braces;
495 if (Braces == 0 && ClosingBrace == E && FoundSeparatorToken)
496 ClosingBrace = I;
497 } else if (I->is(tok::eof)) {
498 // EOF token is used to separate macro arguments
499 if (Braces != 0) {
500 // Assume comma separator is actually braced list separator and change
501 // it back to a comma.
502 FoundSeparatorToken = true;
503 I->setKind(tok::comma);
504 I->setLength(1);
505 } else { // Braces == 0
506 // Separator token still separates arguments.
507 ++NumArgs;
508
509 // If the argument starts with a brace, it can't be fixed with
510 // parentheses. A different diagnostic will be given.
511 if (FoundSeparatorToken && ArgStartIterator->is(tok::l_brace)) {
512 InitLists.push_back(
513 SourceRange(ArgStartIterator->getLocation(),
514 PP.getLocForEndOfToken(ClosingBrace->getLocation())));
515 ClosingBrace = E;
516 }
517
518 // Add left paren
519 if (FoundSeparatorToken) {
520 TempToken.startToken();
521 TempToken.setKind(tok::l_paren);
522 TempToken.setLocation(ArgStartIterator->getLocation());
523 TempToken.setLength(0);
524 NewTokens.push_back(TempToken);
525 }
526
527 // Copy over argument tokens
528 NewTokens.insert(NewTokens.end(), ArgStartIterator, I);
529
530 // Add right paren and store the paren locations in ParenHints
531 if (FoundSeparatorToken) {
532 SourceLocation Loc = PP.getLocForEndOfToken((I - 1)->getLocation());
533 TempToken.startToken();
534 TempToken.setKind(tok::r_paren);
535 TempToken.setLocation(Loc);
536 TempToken.setLength(0);
537 NewTokens.push_back(TempToken);
538 ParenHints.push_back(SourceRange(ArgStartIterator->getLocation(),
539 Loc));
540 }
541
542 // Copy separator token
543 NewTokens.push_back(*I);
544
545 // Reset values
546 ArgStartIterator = I + 1;
547 FoundSeparatorToken = false;
548 }
549 }
550 }
551
552 return !ParenHints.empty() && InitLists.empty();
553}
554
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000555/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
556/// token is the '(' of the macro, this method is invoked to read all of the
557/// actual arguments specified for the macro invocation. This returns null on
558/// error.
559MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
560 MacroInfo *MI,
561 SourceLocation &MacroEnd) {
562 // The number of fixed arguments to parse.
563 unsigned NumFixedArgsLeft = MI->getNumArgs();
564 bool isVariadic = MI->isVariadic();
565
566 // Outer loop, while there are more arguments, keep reading them.
567 Token Tok;
568
569 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
570 // an argument value in a macro could expand to ',' or '(' or ')'.
571 LexUnexpandedToken(Tok);
572 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
573
574 // ArgTokens - Build up a list of tokens that make up each argument. Each
575 // argument is separated by an EOF token. Use a SmallVector so we can avoid
576 // heap allocations in the common case.
577 SmallVector<Token, 64> ArgTokens;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000578 bool ContainsCodeCompletionTok = false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000579
Richard Trieu79b45382013-07-23 18:01:49 +0000580 SourceLocation TooManyArgsLoc;
581
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000582 unsigned NumActuals = 0;
583 while (Tok.isNot(tok::r_paren)) {
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000584 if (ContainsCodeCompletionTok && (Tok.is(tok::eof) || Tok.is(tok::eod)))
585 break;
586
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000587 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
588 "only expect argument separators here");
589
590 unsigned ArgTokenStart = ArgTokens.size();
591 SourceLocation ArgStartLoc = Tok.getLocation();
592
593 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
594 // that we already consumed the first one.
595 unsigned NumParens = 0;
596
597 while (1) {
598 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
599 // an argument value in a macro could expand to ',' or '(' or ')'.
600 LexUnexpandedToken(Tok);
601
602 if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n"
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000603 if (!ContainsCodeCompletionTok) {
604 Diag(MacroName, diag::err_unterm_macro_invoc);
605 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
606 << MacroName.getIdentifierInfo();
607 // Do not lose the EOF/EOD. Return it to the client.
608 MacroName = Tok;
Craig Topperd2d442c2014-05-17 23:10:59 +0000609 return nullptr;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000610 } else {
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000611 // Do not lose the EOF/EOD.
612 Token *Toks = new Token[1];
613 Toks[0] = Tok;
614 EnterTokenStream(Toks, 1, true, true);
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000615 break;
616 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000617 } else if (Tok.is(tok::r_paren)) {
618 // If we found the ) token, the macro arg list is done.
619 if (NumParens-- == 0) {
620 MacroEnd = Tok.getLocation();
621 break;
622 }
623 } else if (Tok.is(tok::l_paren)) {
624 ++NumParens;
Reid Kleckner596b85c2013-06-26 17:16:08 +0000625 } else if (Tok.is(tok::comma) && NumParens == 0 &&
626 !(Tok.getFlags() & Token::IgnoredComma)) {
627 // In Microsoft-compatibility mode, single commas from nested macro
628 // expansions should not be considered as argument separators. We test
629 // for this with the IgnoredComma token flag above.
630
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000631 // Comma ends this argument if there are more fixed arguments expected.
632 // However, if this is a variadic macro, and this is part of the
633 // variadic part, then the comma is just an argument token.
634 if (!isVariadic) break;
635 if (NumFixedArgsLeft > 1)
636 break;
637 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
638 // If this is a comment token in the argument list and we're just in
639 // -C mode (not -CC mode), discard the comment.
640 continue;
David Majnemerd8dee1f2015-03-18 07:53:20 +0000641 } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo() != nullptr) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000642 // Reading macro arguments can cause macros that we are currently
643 // expanding from to be popped off the expansion stack. Doing so causes
644 // them to be reenabled for expansion. Here we record whether any
645 // identifiers we lex as macro arguments correspond to disabled macros.
646 // If so, we mark the token as noexpand. This is a subtle aspect of
647 // C99 6.10.3.4p2.
648 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
649 if (!MI->isEnabled())
650 Tok.setFlag(Token::DisableExpand);
651 } else if (Tok.is(tok::code_completion)) {
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000652 ContainsCodeCompletionTok = true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000653 if (CodeComplete)
654 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
655 MI, NumActuals);
656 // Don't mark that we reached the code-completion point because the
657 // parser is going to handle the token and there will be another
658 // code-completion callback.
659 }
660
661 ArgTokens.push_back(Tok);
662 }
663
664 // If this was an empty argument list foo(), don't add this as an empty
665 // argument.
666 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
667 break;
668
669 // If this is not a variadic macro, and too many args were specified, emit
670 // an error.
Richard Trieu79b45382013-07-23 18:01:49 +0000671 if (!isVariadic && NumFixedArgsLeft == 0 && TooManyArgsLoc.isInvalid()) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000672 if (ArgTokens.size() != ArgTokenStart)
Richard Trieu79b45382013-07-23 18:01:49 +0000673 TooManyArgsLoc = ArgTokens[ArgTokenStart].getLocation();
674 else
675 TooManyArgsLoc = ArgStartLoc;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000676 }
677
Richard Trieu79b45382013-07-23 18:01:49 +0000678 // Empty arguments are standard in C99 and C++0x, and are supported as an
679 // extension in other modes.
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000680 if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99)
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000681 Diag(Tok, LangOpts.CPlusPlus11 ?
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000682 diag::warn_cxx98_compat_empty_fnmacro_arg :
683 diag::ext_empty_fnmacro_arg);
684
685 // Add a marker EOF token to the end of the token list for this argument.
686 Token EOFTok;
687 EOFTok.startToken();
688 EOFTok.setKind(tok::eof);
689 EOFTok.setLocation(Tok.getLocation());
690 EOFTok.setLength(0);
691 ArgTokens.push_back(EOFTok);
692 ++NumActuals;
Richard Trieu79b45382013-07-23 18:01:49 +0000693 if (!ContainsCodeCompletionTok && NumFixedArgsLeft != 0)
Argyrios Kyrtzidisfb703802013-02-22 22:28:58 +0000694 --NumFixedArgsLeft;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000695 }
696
697 // Okay, we either found the r_paren. Check to see if we parsed too few
698 // arguments.
699 unsigned MinArgsExpected = MI->getNumArgs();
700
Richard Trieu79b45382013-07-23 18:01:49 +0000701 // If this is not a variadic macro, and too many args were specified, emit
702 // an error.
703 if (!isVariadic && NumActuals > MinArgsExpected &&
704 !ContainsCodeCompletionTok) {
705 // Emit the diagnostic at the macro name in case there is a missing ).
706 // Emitting it at the , could be far away from the macro name.
707 Diag(TooManyArgsLoc, diag::err_too_many_args_in_macro_invoc);
708 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
709 << MacroName.getIdentifierInfo();
710
711 // Commas from braced initializer lists will be treated as argument
712 // separators inside macros. Attempt to correct for this with parentheses.
713 // TODO: See if this can be generalized to angle brackets for templates
714 // inside macro arguments.
715
Bob Wilson57217352013-07-27 21:59:57 +0000716 SmallVector<Token, 4> FixedArgTokens;
Richard Trieu79b45382013-07-23 18:01:49 +0000717 unsigned FixedNumArgs = 0;
718 SmallVector<SourceRange, 4> ParenHints, InitLists;
719 if (!GenerateNewArgTokens(*this, ArgTokens, FixedArgTokens, FixedNumArgs,
720 ParenHints, InitLists)) {
721 if (!InitLists.empty()) {
722 DiagnosticBuilder DB =
723 Diag(MacroName,
724 diag::note_init_list_at_beginning_of_macro_argument);
Alexander Kornienkod3b4e082014-05-22 19:56:11 +0000725 for (const SourceRange &Range : InitLists)
726 DB << Range;
Richard Trieu79b45382013-07-23 18:01:49 +0000727 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000728 return nullptr;
Richard Trieu79b45382013-07-23 18:01:49 +0000729 }
730 if (FixedNumArgs != MinArgsExpected)
Craig Topperd2d442c2014-05-17 23:10:59 +0000731 return nullptr;
Richard Trieu79b45382013-07-23 18:01:49 +0000732
733 DiagnosticBuilder DB = Diag(MacroName, diag::note_suggest_parens_for_macro);
Alexander Kornienkod3b4e082014-05-22 19:56:11 +0000734 for (const SourceRange &ParenLocation : ParenHints) {
735 DB << FixItHint::CreateInsertion(ParenLocation.getBegin(), "(");
736 DB << FixItHint::CreateInsertion(ParenLocation.getEnd(), ")");
Richard Trieu79b45382013-07-23 18:01:49 +0000737 }
738 ArgTokens.swap(FixedArgTokens);
739 NumActuals = FixedNumArgs;
740 }
741
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000742 // See MacroArgs instance var for description of this.
743 bool isVarargsElided = false;
744
Argyrios Kyrtzidisd4635d42012-12-21 01:51:12 +0000745 if (ContainsCodeCompletionTok) {
746 // Recover from not-fully-formed macro invocation during code-completion.
747 Token EOFTok;
748 EOFTok.startToken();
749 EOFTok.setKind(tok::eof);
750 EOFTok.setLocation(Tok.getLocation());
751 EOFTok.setLength(0);
752 for (; NumActuals < MinArgsExpected; ++NumActuals)
753 ArgTokens.push_back(EOFTok);
754 }
755
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000756 if (NumActuals < MinArgsExpected) {
757 // There are several cases where too few arguments is ok, handle them now.
758 if (NumActuals == 0 && MinArgsExpected == 1) {
759 // #define A(X) or #define A(...) ---> A()
760
761 // If there is exactly one argument, and that argument is missing,
762 // then we have an empty "()" argument empty list. This is fine, even if
763 // the macro expects one argument (the argument is just empty).
764 isVarargsElided = MI->isVariadic();
765 } else if (MI->isVariadic() &&
766 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
767 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
768 // Varargs where the named vararg parameter is missing: OK as extension.
769 // #define A(x, ...)
770 // A("blah")
Eli Friedman14d3c792012-11-14 02:18:46 +0000771 //
772 // If the macro contains the comma pasting extension, the diagnostic
773 // is suppressed; we know we'll get another diagnostic later.
774 if (!MI->hasCommaPasting()) {
775 Diag(Tok, diag::ext_missing_varargs_arg);
776 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
777 << MacroName.getIdentifierInfo();
778 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000779
780 // Remember this occurred, allowing us to elide the comma when used for
781 // cases like:
782 // #define A(x, foo...) blah(a, ## foo)
783 // #define B(x, ...) blah(a, ## __VA_ARGS__)
784 // #define C(...) blah(a, ## __VA_ARGS__)
785 // A(x) B(x) C()
786 isVarargsElided = true;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000787 } else if (!ContainsCodeCompletionTok) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000788 // Otherwise, emit the error.
789 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Argyrios Kyrtzidis164fdb62012-12-14 18:53:47 +0000790 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
791 << MacroName.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000792 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000793 }
794
795 // Add a marker EOF token to the end of the token list for this argument.
796 SourceLocation EndLoc = Tok.getLocation();
797 Tok.startToken();
798 Tok.setKind(tok::eof);
799 Tok.setLocation(EndLoc);
800 Tok.setLength(0);
801 ArgTokens.push_back(Tok);
802
803 // If we expect two arguments, add both as empty.
804 if (NumActuals == 0 && MinArgsExpected == 2)
805 ArgTokens.push_back(Tok);
806
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000807 } else if (NumActuals > MinArgsExpected && !MI->isVariadic() &&
808 !ContainsCodeCompletionTok) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000809 // Emit the diagnostic at the macro name in case there is a missing ).
810 // Emitting it at the , could be far away from the macro name.
811 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Argyrios Kyrtzidis164fdb62012-12-14 18:53:47 +0000812 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
813 << MacroName.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000814 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000815 }
816
817 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
818}
819
820/// \brief Keeps macro expanded tokens for TokenLexers.
821//
822/// Works like a stack; a TokenLexer adds the macro expanded tokens that is
823/// going to lex in the cache and when it finishes the tokens are removed
824/// from the end of the cache.
825Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
826 ArrayRef<Token> tokens) {
827 assert(tokLexer);
828 if (tokens.empty())
Craig Topperd2d442c2014-05-17 23:10:59 +0000829 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000830
831 size_t newIndex = MacroExpandedTokens.size();
832 bool cacheNeedsToGrow = tokens.size() >
833 MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
834 MacroExpandedTokens.append(tokens.begin(), tokens.end());
835
836 if (cacheNeedsToGrow) {
837 // Go through all the TokenLexers whose 'Tokens' pointer points in the
838 // buffer and update the pointers to the (potential) new buffer array.
839 for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) {
840 TokenLexer *prevLexer;
841 size_t tokIndex;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000842 std::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i];
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000843 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
844 }
845 }
846
847 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
848 return MacroExpandedTokens.data() + newIndex;
849}
850
851void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
852 assert(!MacroExpandingLexersStack.empty());
853 size_t tokIndex = MacroExpandingLexersStack.back().second;
854 assert(tokIndex < MacroExpandedTokens.size());
855 // Pop the cached macro expanded tokens from the end.
856 MacroExpandedTokens.resize(tokIndex);
857 MacroExpandingLexersStack.pop_back();
858}
859
860/// ComputeDATE_TIME - Compute the current time, enter it into the specified
861/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
862/// the identifier tokens inserted.
863static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
864 Preprocessor &PP) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000865 time_t TT = time(nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000866 struct tm *TM = localtime(&TT);
867
868 static const char * const Months[] = {
869 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
870 };
871
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000872 {
873 SmallString<32> TmpBuffer;
874 llvm::raw_svector_ostream TmpStream(TmpBuffer);
875 TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
876 TM->tm_mday, TM->tm_year + 1900);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000877 Token TmpTok;
878 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000879 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000880 DATELoc = TmpTok.getLocation();
881 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000882
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000883 {
884 SmallString<32> TmpBuffer;
885 llvm::raw_svector_ostream TmpStream(TmpBuffer);
886 TmpStream << llvm::format("\"%02d:%02d:%02d\"",
887 TM->tm_hour, TM->tm_min, TM->tm_sec);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000888 Token TmpTok;
889 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000890 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000891 TIMELoc = TmpTok.getLocation();
892 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000893}
894
895
896/// HasFeature - Return true if we recognize and implement the feature
897/// specified by the identifier as a standard language feature.
898static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
899 const LangOptions &LangOpts = PP.getLangOpts();
900 StringRef Feature = II->getName();
901
902 // Normalize the feature name, __foo__ becomes foo.
903 if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4)
904 Feature = Feature.substr(2, Feature.size() - 4);
905
906 return llvm::StringSwitch<bool>(Feature)
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000907 .Case("address_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Address))
908 .Case("attribute_analyzer_noreturn", true)
909 .Case("attribute_availability", true)
910 .Case("attribute_availability_with_message", true)
Bob Wilsonb111ec92015-03-02 19:01:14 +0000911 .Case("attribute_availability_app_extension", true)
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000912 .Case("attribute_cf_returns_not_retained", true)
913 .Case("attribute_cf_returns_retained", true)
914 .Case("attribute_deprecated_with_message", true)
915 .Case("attribute_ext_vector_type", true)
916 .Case("attribute_ns_returns_not_retained", true)
917 .Case("attribute_ns_returns_retained", true)
918 .Case("attribute_ns_consumes_self", true)
919 .Case("attribute_ns_consumed", true)
920 .Case("attribute_cf_consumed", true)
921 .Case("attribute_objc_ivar_unused", true)
922 .Case("attribute_objc_method_family", true)
923 .Case("attribute_overloadable", true)
924 .Case("attribute_unavailable_with_message", true)
925 .Case("attribute_unused_on_fields", true)
926 .Case("blocks", LangOpts.Blocks)
927 .Case("c_thread_safety_attributes", true)
928 .Case("cxx_exceptions", LangOpts.CXXExceptions)
929 .Case("cxx_rtti", LangOpts.RTTI)
930 .Case("enumerator_attributes", true)
931 .Case("memory_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Memory))
932 .Case("thread_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Thread))
933 .Case("dataflow_sanitizer", LangOpts.Sanitize.has(SanitizerKind::DataFlow))
934 // Objective-C features
935 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
936 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
937 .Case("objc_arc_weak", LangOpts.ObjCARCWeak)
938 .Case("objc_default_synthesize_properties", LangOpts.ObjC2)
939 .Case("objc_fixed_enum", LangOpts.ObjC2)
940 .Case("objc_instancetype", LangOpts.ObjC2)
941 .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules)
942 .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile())
943 .Case("objc_property_explicit_atomic",
944 true) // Does clang support explicit "atomic" keyword?
945 .Case("objc_protocol_qualifier_mangling", true)
946 .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport())
947 .Case("ownership_holds", true)
948 .Case("ownership_returns", true)
949 .Case("ownership_takes", true)
950 .Case("objc_bool", true)
951 .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile())
952 .Case("objc_array_literals", LangOpts.ObjC2)
953 .Case("objc_dictionary_literals", LangOpts.ObjC2)
954 .Case("objc_boxed_expressions", LangOpts.ObjC2)
955 .Case("arc_cf_code_audited", true)
John McCall28592582015-02-01 22:34:06 +0000956 .Case("objc_bridge_id", true)
957 .Case("objc_bridge_id_on_typedefs", true)
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000958 // C11 features
959 .Case("c_alignas", LangOpts.C11)
Nico Weber736a9932014-12-03 01:25:49 +0000960 .Case("c_alignof", LangOpts.C11)
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000961 .Case("c_atomic", LangOpts.C11)
962 .Case("c_generic_selections", LangOpts.C11)
963 .Case("c_static_assert", LangOpts.C11)
964 .Case("c_thread_local",
965 LangOpts.C11 && PP.getTargetInfo().isTLSSupported())
966 // C++11 features
967 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus11)
968 .Case("cxx_alias_templates", LangOpts.CPlusPlus11)
969 .Case("cxx_alignas", LangOpts.CPlusPlus11)
Nico Weber736a9932014-12-03 01:25:49 +0000970 .Case("cxx_alignof", LangOpts.CPlusPlus11)
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000971 .Case("cxx_atomic", LangOpts.CPlusPlus11)
972 .Case("cxx_attributes", LangOpts.CPlusPlus11)
973 .Case("cxx_auto_type", LangOpts.CPlusPlus11)
974 .Case("cxx_constexpr", LangOpts.CPlusPlus11)
975 .Case("cxx_decltype", LangOpts.CPlusPlus11)
976 .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus11)
977 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus11)
978 .Case("cxx_defaulted_functions", LangOpts.CPlusPlus11)
979 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus11)
980 .Case("cxx_deleted_functions", LangOpts.CPlusPlus11)
981 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus11)
982 .Case("cxx_generalized_initializers", LangOpts.CPlusPlus11)
983 .Case("cxx_implicit_moves", LangOpts.CPlusPlus11)
984 .Case("cxx_inheriting_constructors", LangOpts.CPlusPlus11)
985 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus11)
986 .Case("cxx_lambdas", LangOpts.CPlusPlus11)
987 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus11)
988 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus11)
989 .Case("cxx_noexcept", LangOpts.CPlusPlus11)
990 .Case("cxx_nullptr", LangOpts.CPlusPlus11)
991 .Case("cxx_override_control", LangOpts.CPlusPlus11)
992 .Case("cxx_range_for", LangOpts.CPlusPlus11)
993 .Case("cxx_raw_string_literals", LangOpts.CPlusPlus11)
994 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus11)
995 .Case("cxx_rvalue_references", LangOpts.CPlusPlus11)
996 .Case("cxx_strong_enums", LangOpts.CPlusPlus11)
997 .Case("cxx_static_assert", LangOpts.CPlusPlus11)
998 .Case("cxx_thread_local",
999 LangOpts.CPlusPlus11 && PP.getTargetInfo().isTLSSupported())
1000 .Case("cxx_trailing_return", LangOpts.CPlusPlus11)
1001 .Case("cxx_unicode_literals", LangOpts.CPlusPlus11)
1002 .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus11)
1003 .Case("cxx_user_literals", LangOpts.CPlusPlus11)
1004 .Case("cxx_variadic_templates", LangOpts.CPlusPlus11)
1005 // C++1y features
1006 .Case("cxx_aggregate_nsdmi", LangOpts.CPlusPlus14)
1007 .Case("cxx_binary_literals", LangOpts.CPlusPlus14)
1008 .Case("cxx_contextual_conversions", LangOpts.CPlusPlus14)
1009 .Case("cxx_decltype_auto", LangOpts.CPlusPlus14)
1010 .Case("cxx_generic_lambdas", LangOpts.CPlusPlus14)
1011 .Case("cxx_init_captures", LangOpts.CPlusPlus14)
1012 .Case("cxx_relaxed_constexpr", LangOpts.CPlusPlus14)
1013 .Case("cxx_return_type_deduction", LangOpts.CPlusPlus14)
1014 .Case("cxx_variable_templates", LangOpts.CPlusPlus14)
1015 // C++ TSes
1016 //.Case("cxx_runtime_arrays", LangOpts.CPlusPlusTSArrays)
1017 //.Case("cxx_concepts", LangOpts.CPlusPlusTSConcepts)
1018 // FIXME: Should this be __has_feature or __has_extension?
1019 //.Case("raw_invocation_type", LangOpts.CPlusPlus)
1020 // Type traits
1021 .Case("has_nothrow_assign", LangOpts.CPlusPlus)
1022 .Case("has_nothrow_copy", LangOpts.CPlusPlus)
1023 .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
1024 .Case("has_trivial_assign", LangOpts.CPlusPlus)
1025 .Case("has_trivial_copy", LangOpts.CPlusPlus)
1026 .Case("has_trivial_constructor", LangOpts.CPlusPlus)
1027 .Case("has_trivial_destructor", LangOpts.CPlusPlus)
1028 .Case("has_virtual_destructor", LangOpts.CPlusPlus)
1029 .Case("is_abstract", LangOpts.CPlusPlus)
1030 .Case("is_base_of", LangOpts.CPlusPlus)
1031 .Case("is_class", LangOpts.CPlusPlus)
1032 .Case("is_constructible", LangOpts.CPlusPlus)
1033 .Case("is_convertible_to", LangOpts.CPlusPlus)
1034 .Case("is_empty", LangOpts.CPlusPlus)
1035 .Case("is_enum", LangOpts.CPlusPlus)
1036 .Case("is_final", LangOpts.CPlusPlus)
1037 .Case("is_literal", LangOpts.CPlusPlus)
1038 .Case("is_standard_layout", LangOpts.CPlusPlus)
1039 .Case("is_pod", LangOpts.CPlusPlus)
1040 .Case("is_polymorphic", LangOpts.CPlusPlus)
1041 .Case("is_sealed", LangOpts.MicrosoftExt)
1042 .Case("is_trivial", LangOpts.CPlusPlus)
1043 .Case("is_trivially_assignable", LangOpts.CPlusPlus)
1044 .Case("is_trivially_constructible", LangOpts.CPlusPlus)
1045 .Case("is_trivially_copyable", LangOpts.CPlusPlus)
1046 .Case("is_union", LangOpts.CPlusPlus)
1047 .Case("modules", LangOpts.Modules)
1048 .Case("tls", PP.getTargetInfo().isTLSSupported())
1049 .Case("underlying_type", LangOpts.CPlusPlus)
1050 .Default(false);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001051}
1052
1053/// HasExtension - Return true if we recognize and implement the feature
1054/// specified by the identifier, either as an extension or a standard language
1055/// feature.
1056static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) {
1057 if (HasFeature(PP, II))
1058 return true;
1059
1060 // If the use of an extension results in an error diagnostic, extensions are
1061 // effectively unavailable, so just return false here.
Alp Tokerac4e8e52014-06-22 21:58:33 +00001062 if (PP.getDiagnostics().getExtensionHandlingBehavior() >=
1063 diag::Severity::Error)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001064 return false;
1065
1066 const LangOptions &LangOpts = PP.getLangOpts();
1067 StringRef Extension = II->getName();
1068
1069 // Normalize the extension name, __foo__ becomes foo.
1070 if (Extension.startswith("__") && Extension.endswith("__") &&
1071 Extension.size() >= 4)
1072 Extension = Extension.substr(2, Extension.size() - 4);
1073
1074 // Because we inherit the feature list from HasFeature, this string switch
1075 // must be less restrictive than HasFeature's.
1076 return llvm::StringSwitch<bool>(Extension)
1077 // C11 features supported by other languages as extensions.
1078 .Case("c_alignas", true)
Nico Weber736a9932014-12-03 01:25:49 +00001079 .Case("c_alignof", true)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001080 .Case("c_atomic", true)
1081 .Case("c_generic_selections", true)
1082 .Case("c_static_assert", true)
Ed Schouten401aeba2013-09-14 16:17:20 +00001083 .Case("c_thread_local", PP.getTargetInfo().isTLSSupported())
Richard Smith0a715422013-05-07 19:32:56 +00001084 // C++11 features supported by other languages as extensions.
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001085 .Case("cxx_atomic", LangOpts.CPlusPlus)
1086 .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
1087 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
1088 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
1089 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus)
1090 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
1091 .Case("cxx_override_control", LangOpts.CPlusPlus)
1092 .Case("cxx_range_for", LangOpts.CPlusPlus)
1093 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
1094 .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
Richard Smith0a715422013-05-07 19:32:56 +00001095 // C++1y features supported by other languages as extensions.
1096 .Case("cxx_binary_literals", true)
Richard Smithb438e622013-09-28 04:37:56 +00001097 .Case("cxx_init_captures", LangOpts.CPlusPlus11)
Alp Tokera8bb9c92014-01-15 04:11:24 +00001098 .Case("cxx_variable_templates", LangOpts.CPlusPlus)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001099 .Default(false);
1100}
1101
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001102/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
1103/// or '__has_include_next("path")' expression.
1104/// Returns true if successful.
1105static bool EvaluateHasIncludeCommon(Token &Tok,
1106 IdentifierInfo *II, Preprocessor &PP,
Richard Smith25d50752014-10-20 00:15:49 +00001107 const DirectoryLookup *LookupFrom,
1108 const FileEntry *LookupFromFile) {
Richard Trieuda031982012-10-22 20:28:48 +00001109 // Save the location of the current token. If a '(' is later found, use
Aaron Ballman5cb24112013-01-15 21:59:46 +00001110 // that location. If not, use the end of this location instead.
Richard Trieuda031982012-10-22 20:28:48 +00001111 SourceLocation LParenLoc = Tok.getLocation();
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001112
Aaron Ballman6ce00002013-01-16 19:32:21 +00001113 // These expressions are only allowed within a preprocessor directive.
1114 if (!PP.isParsingIfOrElifDirective()) {
1115 PP.Diag(LParenLoc, diag::err_pp_directive_required) << II->getName();
Benjamin Kramer0a126ad2015-03-29 19:05:27 +00001116 // Return a valid identifier token.
1117 assert(Tok.is(tok::identifier));
1118 Tok.setIdentifierInfo(II);
Aaron Ballman6ce00002013-01-16 19:32:21 +00001119 return false;
1120 }
1121
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001122 // Get '('.
1123 PP.LexNonComment(Tok);
1124
1125 // Ensure we have a '('.
1126 if (Tok.isNot(tok::l_paren)) {
Richard Trieuda031982012-10-22 20:28:48 +00001127 // No '(', use end of last token.
1128 LParenLoc = PP.getLocForEndOfToken(LParenLoc);
Alp Toker751d6352013-12-30 01:59:29 +00001129 PP.Diag(LParenLoc, diag::err_pp_expected_after) << II << tok::l_paren;
Richard Trieuda031982012-10-22 20:28:48 +00001130 // If the next token looks like a filename or the start of one,
1131 // assume it is and process it as such.
1132 if (!Tok.is(tok::angle_string_literal) && !Tok.is(tok::string_literal) &&
1133 !Tok.is(tok::less))
1134 return false;
1135 } else {
1136 // Save '(' location for possible missing ')' message.
1137 LParenLoc = Tok.getLocation();
1138
Eli Friedmanec94b612013-01-09 02:20:00 +00001139 if (PP.getCurrentLexer()) {
1140 // Get the file name.
1141 PP.getCurrentLexer()->LexIncludeFilename(Tok);
1142 } else {
1143 // We're in a macro, so we can't use LexIncludeFilename; just
1144 // grab the next token.
1145 PP.Lex(Tok);
1146 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001147 }
1148
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001149 // Reserve a buffer to get the spelling.
1150 SmallString<128> FilenameBuffer;
1151 StringRef Filename;
1152 SourceLocation EndLoc;
1153
1154 switch (Tok.getKind()) {
1155 case tok::eod:
1156 // If the token kind is EOD, the error has already been diagnosed.
1157 return false;
1158
1159 case tok::angle_string_literal:
1160 case tok::string_literal: {
1161 bool Invalid = false;
1162 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
1163 if (Invalid)
1164 return false;
1165 break;
1166 }
1167
1168 case tok::less:
1169 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1170 // case, glue the tokens together into FilenameBuffer and interpret those.
1171 FilenameBuffer.push_back('<');
Richard Trieuda031982012-10-22 20:28:48 +00001172 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc)) {
1173 // Let the caller know a <eod> was found by changing the Token kind.
1174 Tok.setKind(tok::eod);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001175 return false; // Found <eod> but no ">"? Diagnostic already emitted.
Richard Trieuda031982012-10-22 20:28:48 +00001176 }
Yaron Keren92e1b622015-03-18 10:17:07 +00001177 Filename = FilenameBuffer;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001178 break;
1179 default:
1180 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
1181 return false;
1182 }
1183
Richard Trieuda031982012-10-22 20:28:48 +00001184 SourceLocation FilenameLoc = Tok.getLocation();
1185
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001186 // Get ')'.
1187 PP.LexNonComment(Tok);
1188
1189 // Ensure we have a trailing ).
1190 if (Tok.isNot(tok::r_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001191 PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after)
1192 << II << tok::r_paren;
Alp Tokerec543272013-12-24 09:48:30 +00001193 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001194 return false;
1195 }
1196
1197 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
1198 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1199 // error.
1200 if (Filename.empty())
1201 return false;
1202
1203 // Search include directories.
1204 const DirectoryLookup *CurDir;
1205 const FileEntry *File =
Richard Smith25d50752014-10-20 00:15:49 +00001206 PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, LookupFromFile,
1207 CurDir, nullptr, nullptr, nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001208
1209 // Get the result value. A result of true means the file exists.
Craig Topperd2d442c2014-05-17 23:10:59 +00001210 return File != nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001211}
1212
1213/// EvaluateHasInclude - Process a '__has_include("path")' expression.
1214/// Returns true if successful.
1215static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
1216 Preprocessor &PP) {
Richard Smith25d50752014-10-20 00:15:49 +00001217 return EvaluateHasIncludeCommon(Tok, II, PP, nullptr, nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001218}
1219
1220/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
1221/// Returns true if successful.
1222static bool EvaluateHasIncludeNext(Token &Tok,
1223 IdentifierInfo *II, Preprocessor &PP) {
1224 // __has_include_next is like __has_include, except that we start
1225 // searching after the current found directory. If we can't do this,
1226 // issue a diagnostic.
Yaron Kerenbc5986f2015-02-19 11:21:11 +00001227 // FIXME: Factor out duplication with
Richard Smith25d50752014-10-20 00:15:49 +00001228 // Preprocessor::HandleIncludeNextDirective.
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001229 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
Richard Smith25d50752014-10-20 00:15:49 +00001230 const FileEntry *LookupFromFile = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001231 if (PP.isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001232 Lookup = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001233 PP.Diag(Tok, diag::pp_include_next_in_primary);
Richard Smith25d50752014-10-20 00:15:49 +00001234 } else if (PP.getCurrentSubmodule()) {
1235 // Start looking up in the directory *after* the one in which the current
1236 // file would be found, if any.
1237 assert(PP.getCurrentLexer() && "#include_next directive in macro?");
1238 LookupFromFile = PP.getCurrentLexer()->getFileEntry();
1239 Lookup = nullptr;
Craig Topperd2d442c2014-05-17 23:10:59 +00001240 } else if (!Lookup) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001241 PP.Diag(Tok, diag::pp_include_next_absolute_path);
1242 } else {
1243 // Start looking up in the next directory.
1244 ++Lookup;
1245 }
1246
Richard Smith25d50752014-10-20 00:15:49 +00001247 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup, LookupFromFile);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001248}
1249
Douglas Gregorc83de302012-09-25 15:44:52 +00001250/// \brief Process __building_module(identifier) expression.
1251/// \returns true if we are building the named module, false otherwise.
1252static bool EvaluateBuildingModule(Token &Tok,
1253 IdentifierInfo *II, Preprocessor &PP) {
1254 // Get '('.
1255 PP.LexNonComment(Tok);
1256
1257 // Ensure we have a '('.
1258 if (Tok.isNot(tok::l_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001259 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1260 << tok::l_paren;
Douglas Gregorc83de302012-09-25 15:44:52 +00001261 return false;
1262 }
1263
1264 // Save '(' location for possible missing ')' message.
1265 SourceLocation LParenLoc = Tok.getLocation();
1266
1267 // Get the module name.
1268 PP.LexNonComment(Tok);
1269
1270 // Ensure that we have an identifier.
1271 if (Tok.isNot(tok::identifier)) {
1272 PP.Diag(Tok.getLocation(), diag::err_expected_id_building_module);
1273 return false;
1274 }
1275
1276 bool Result
1277 = Tok.getIdentifierInfo()->getName() == PP.getLangOpts().CurrentModule;
1278
1279 // Get ')'.
1280 PP.LexNonComment(Tok);
1281
1282 // Ensure we have a trailing ).
1283 if (Tok.isNot(tok::r_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001284 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1285 << tok::r_paren;
Alp Tokerec543272013-12-24 09:48:30 +00001286 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
Douglas Gregorc83de302012-09-25 15:44:52 +00001287 return false;
1288 }
1289
1290 return Result;
1291}
1292
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001293/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1294/// as a builtin macro, handle it and return the next token as 'Tok'.
1295void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
1296 // Figure out which token this is.
1297 IdentifierInfo *II = Tok.getIdentifierInfo();
1298 assert(II && "Can't be a macro without id info!");
1299
1300 // If this is an _Pragma or Microsoft __pragma directive, expand it,
1301 // invoke the pragma handler, then lex the token after it.
1302 if (II == Ident_Pragma)
1303 return Handle_Pragma(Tok);
1304 else if (II == Ident__pragma) // in non-MS mode this is null
1305 return HandleMicrosoft__pragma(Tok);
1306
1307 ++NumBuiltinMacroExpanded;
1308
1309 SmallString<128> TmpBuffer;
1310 llvm::raw_svector_ostream OS(TmpBuffer);
1311
1312 // Set up the return result.
Craig Topperd2d442c2014-05-17 23:10:59 +00001313 Tok.setIdentifierInfo(nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001314 Tok.clearFlag(Token::NeedsCleaning);
1315
1316 if (II == Ident__LINE__) {
1317 // C99 6.10.8: "__LINE__: The presumed line number (within the current
1318 // source file) of the current source line (an integer constant)". This can
1319 // be affected by #line.
1320 SourceLocation Loc = Tok.getLocation();
1321
1322 // Advance to the location of the first _, this might not be the first byte
1323 // of the token if it starts with an escaped newline.
1324 Loc = AdvanceToTokenCharacter(Loc, 0);
1325
1326 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
1327 // a macro expansion. This doesn't matter for object-like macros, but
1328 // can matter for a function-like macro that expands to contain __LINE__.
1329 // Skip down through expansion points until we find a file loc for the
1330 // end of the expansion history.
1331 Loc = SourceMgr.getExpansionRange(Loc).second;
1332 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
1333
1334 // __LINE__ expands to a simple numeric value.
1335 OS << (PLoc.isValid()? PLoc.getLine() : 1);
1336 Tok.setKind(tok::numeric_constant);
1337 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
1338 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
1339 // character string literal)". This can be affected by #line.
1340 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1341
1342 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
1343 // #include stack instead of the current file.
1344 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
1345 SourceLocation NextLoc = PLoc.getIncludeLoc();
1346 while (NextLoc.isValid()) {
1347 PLoc = SourceMgr.getPresumedLoc(NextLoc);
1348 if (PLoc.isInvalid())
1349 break;
1350
1351 NextLoc = PLoc.getIncludeLoc();
1352 }
1353 }
1354
1355 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
1356 SmallString<128> FN;
1357 if (PLoc.isValid()) {
1358 FN += PLoc.getFilename();
1359 Lexer::Stringify(FN);
Yaron Keren09fb7c62015-03-10 07:33:23 +00001360 OS << '"' << FN << '"';
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001361 }
1362 Tok.setKind(tok::string_literal);
1363 } else if (II == Ident__DATE__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001364 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001365 if (!DATELoc.isValid())
1366 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1367 Tok.setKind(tok::string_literal);
1368 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1369 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
1370 Tok.getLocation(),
1371 Tok.getLength()));
1372 return;
1373 } else if (II == Ident__TIME__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001374 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001375 if (!TIMELoc.isValid())
1376 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1377 Tok.setKind(tok::string_literal);
1378 Tok.setLength(strlen("\"hh:mm:ss\""));
1379 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
1380 Tok.getLocation(),
1381 Tok.getLength()));
1382 return;
1383 } else if (II == Ident__INCLUDE_LEVEL__) {
1384 // Compute the presumed include depth of this token. This can be affected
1385 // by GNU line markers.
1386 unsigned Depth = 0;
1387
1388 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1389 if (PLoc.isValid()) {
1390 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1391 for (; PLoc.isValid(); ++Depth)
1392 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1393 }
1394
1395 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1396 OS << Depth;
1397 Tok.setKind(tok::numeric_constant);
1398 } else if (II == Ident__TIMESTAMP__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001399 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001400 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1401 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1402
1403 // Get the file that we are lexing out of. If we're currently lexing from
1404 // a macro, dig into the include stack.
Craig Topperd2d442c2014-05-17 23:10:59 +00001405 const FileEntry *CurFile = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001406 PreprocessorLexer *TheLexer = getCurrentFileLexer();
1407
1408 if (TheLexer)
1409 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
1410
1411 const char *Result;
1412 if (CurFile) {
1413 time_t TT = CurFile->getModificationTime();
1414 struct tm *TM = localtime(&TT);
1415 Result = asctime(TM);
1416 } else {
1417 Result = "??? ??? ?? ??:??:?? ????\n";
1418 }
1419 // Surround the string with " and strip the trailing newline.
Alp Toker4f43e552014-06-10 06:08:51 +00001420 OS << '"' << StringRef(Result).drop_back() << '"';
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001421 Tok.setKind(tok::string_literal);
1422 } else if (II == Ident__COUNTER__) {
1423 // __COUNTER__ expands to a simple numeric value.
1424 OS << CounterValue++;
1425 Tok.setKind(tok::numeric_constant);
1426 } else if (II == Ident__has_feature ||
1427 II == Ident__has_extension ||
1428 II == Ident__has_builtin ||
Yunzhong Gaoef309f42014-04-11 20:55:19 +00001429 II == Ident__is_identifier ||
Aaron Ballmana0344c52014-11-14 13:44:02 +00001430 II == Ident__has_attribute ||
Aaron Ballman3c0f9b42014-12-05 15:05:29 +00001431 II == Ident__has_declspec ||
Aaron Ballmana0344c52014-11-14 13:44:02 +00001432 II == Ident__has_cpp_attribute) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001433 // The argument to these builtins should be a parenthesized identifier.
1434 SourceLocation StartLoc = Tok.getLocation();
1435
1436 bool IsValid = false;
Craig Topperd2d442c2014-05-17 23:10:59 +00001437 IdentifierInfo *FeatureII = nullptr;
Aaron Ballmana0344c52014-11-14 13:44:02 +00001438 IdentifierInfo *ScopeII = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001439
1440 // Read the '('.
Andy Gibbsd41d0942012-11-17 19:18:27 +00001441 LexUnexpandedToken(Tok);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001442 if (Tok.is(tok::l_paren)) {
1443 // Read the identifier
Andy Gibbsd41d0942012-11-17 19:18:27 +00001444 LexUnexpandedToken(Tok);
Richard Smithbaf29122013-07-09 00:57:56 +00001445 if ((FeatureII = Tok.getIdentifierInfo())) {
Aaron Ballmana0344c52014-11-14 13:44:02 +00001446 // If we're checking __has_cpp_attribute, it is possible to receive a
1447 // scope token. Read the "::", if it's available.
Andy Gibbsd41d0942012-11-17 19:18:27 +00001448 LexUnexpandedToken(Tok);
Aaron Ballmana0344c52014-11-14 13:44:02 +00001449 bool IsScopeValid = true;
1450 if (II == Ident__has_cpp_attribute && Tok.is(tok::coloncolon)) {
1451 LexUnexpandedToken(Tok);
1452 // The first thing we read was not the feature, it was the scope.
1453 ScopeII = FeatureII;
Aaron Ballman918474c2014-11-14 14:40:49 +00001454 if ((FeatureII = Tok.getIdentifierInfo()))
Aaron Ballmana0344c52014-11-14 13:44:02 +00001455 LexUnexpandedToken(Tok);
1456 else
1457 IsScopeValid = false;
1458 }
1459 // Read the closing paren.
1460 if (IsScopeValid && Tok.is(tok::r_paren))
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001461 IsValid = true;
1462 }
David Majnemerd6163622014-12-15 09:03:58 +00001463 // Eat tokens until ')'.
1464 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) &&
1465 Tok.isNot(tok::eof))
1466 LexUnexpandedToken(Tok);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001467 }
1468
Aaron Ballmana0344c52014-11-14 13:44:02 +00001469 int Value = 0;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001470 if (!IsValid)
1471 Diag(StartLoc, diag::err_feature_check_malformed);
Yunzhong Gaoef309f42014-04-11 20:55:19 +00001472 else if (II == Ident__is_identifier)
1473 Value = FeatureII->getTokenID() == tok::identifier;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001474 else if (II == Ident__has_builtin) {
1475 // Check for a builtin is trivial.
1476 Value = FeatureII->getBuiltinID() != 0;
1477 } else if (II == Ident__has_attribute)
Aaron Ballmana6f759e2014-12-05 15:24:55 +00001478 Value = hasAttribute(AttrSyntax::GNU, nullptr, FeatureII,
Aaron Ballman2fbf9942014-03-31 13:14:44 +00001479 getTargetInfo().getTriple(), getLangOpts());
Aaron Ballmana0344c52014-11-14 13:44:02 +00001480 else if (II == Ident__has_cpp_attribute)
1481 Value = hasAttribute(AttrSyntax::CXX, ScopeII, FeatureII,
1482 getTargetInfo().getTriple(), getLangOpts());
Aaron Ballman3c0f9b42014-12-05 15:05:29 +00001483 else if (II == Ident__has_declspec)
1484 Value = hasAttribute(AttrSyntax::Declspec, nullptr, FeatureII,
1485 getTargetInfo().getTriple(), getLangOpts());
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001486 else if (II == Ident__has_extension)
1487 Value = HasExtension(*this, FeatureII);
1488 else {
1489 assert(II == Ident__has_feature && "Must be feature check");
1490 Value = HasFeature(*this, FeatureII);
1491 }
1492
David Majnemerd6163622014-12-15 09:03:58 +00001493 if (!IsValid)
1494 return;
Aaron Ballmana0344c52014-11-14 13:44:02 +00001495 OS << Value;
David Majnemerd6163622014-12-15 09:03:58 +00001496 Tok.setKind(tok::numeric_constant);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001497 } else if (II == Ident__has_include ||
1498 II == Ident__has_include_next) {
1499 // The argument to these two builtins should be a parenthesized
1500 // file name string literal using angle brackets (<>) or
1501 // double-quotes ("").
1502 bool Value;
1503 if (II == Ident__has_include)
1504 Value = EvaluateHasInclude(Tok, II, *this);
1505 else
1506 Value = EvaluateHasIncludeNext(Tok, II, *this);
Benjamin Kramer18ff02d2015-03-29 15:33:29 +00001507
1508 if (Tok.isNot(tok::r_paren))
1509 return;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001510 OS << (int)Value;
Benjamin Kramer18ff02d2015-03-29 15:33:29 +00001511 Tok.setKind(tok::numeric_constant);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001512 } else if (II == Ident__has_warning) {
1513 // The argument should be a parenthesized string literal.
1514 // The argument to these builtins should be a parenthesized identifier.
1515 SourceLocation StartLoc = Tok.getLocation();
1516 bool IsValid = false;
1517 bool Value = false;
1518 // Read the '('.
Andy Gibbs58905d22012-11-17 19:15:38 +00001519 LexUnexpandedToken(Tok);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001520 do {
Andy Gibbs58905d22012-11-17 19:15:38 +00001521 if (Tok.isNot(tok::l_paren)) {
1522 Diag(StartLoc, diag::err_warning_check_malformed);
1523 break;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001524 }
Andy Gibbs58905d22012-11-17 19:15:38 +00001525
1526 LexUnexpandedToken(Tok);
1527 std::string WarningName;
1528 SourceLocation StrStartLoc = Tok.getLocation();
Andy Gibbsa8df57a2012-11-17 19:16:52 +00001529 if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",
1530 /*MacroExpansion=*/false)) {
Andy Gibbs58905d22012-11-17 19:15:38 +00001531 // Eat tokens until ')'.
Andy Gibbsb5b30c42012-11-17 22:17:28 +00001532 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) &&
1533 Tok.isNot(tok::eof))
Andy Gibbs58905d22012-11-17 19:15:38 +00001534 LexUnexpandedToken(Tok);
1535 break;
1536 }
1537
1538 // Is the end a ')'?
1539 if (!(IsValid = Tok.is(tok::r_paren))) {
1540 Diag(StartLoc, diag::err_warning_check_malformed);
1541 break;
1542 }
1543
Richard Smith3be1cb22014-08-07 00:24:21 +00001544 // FIXME: Should we accept "-R..." flags here, or should that be handled
1545 // by a separate __has_remark?
Andy Gibbs58905d22012-11-17 19:15:38 +00001546 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1547 WarningName[1] != 'W') {
1548 Diag(StrStartLoc, diag::warn_has_warning_invalid_option);
1549 break;
1550 }
1551
1552 // Finally, check if the warning flags maps to a diagnostic group.
1553 // We construct a SmallVector here to talk to getDiagnosticIDs().
1554 // Although we don't use the result, this isn't a hot path, and not
1555 // worth special casing.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001556 SmallVector<diag::kind, 10> Diags;
Andy Gibbs58905d22012-11-17 19:15:38 +00001557 Value = !getDiagnostics().getDiagnosticIDs()->
Richard Smith3be1cb22014-08-07 00:24:21 +00001558 getDiagnosticsInGroup(diag::Flavor::WarningOrError,
1559 WarningName.substr(2), Diags);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001560 } while (false);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001561
David Majnemerd6163622014-12-15 09:03:58 +00001562 if (!IsValid)
1563 return;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001564 OS << (int)Value;
David Majnemerd6163622014-12-15 09:03:58 +00001565 Tok.setKind(tok::numeric_constant);
Douglas Gregorc83de302012-09-25 15:44:52 +00001566 } else if (II == Ident__building_module) {
1567 // The argument to this builtin should be an identifier. The
1568 // builtin evaluates to 1 when that identifier names the module we are
1569 // currently building.
1570 OS << (int)EvaluateBuildingModule(Tok, II, *this);
1571 Tok.setKind(tok::numeric_constant);
1572 } else if (II == Ident__MODULE__) {
1573 // The current module as an identifier.
1574 OS << getLangOpts().CurrentModule;
1575 IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);
1576 Tok.setIdentifierInfo(ModuleII);
1577 Tok.setKind(ModuleII->getTokenID());
Richard Smithae385082014-03-15 00:06:08 +00001578 } else if (II == Ident__identifier) {
1579 SourceLocation Loc = Tok.getLocation();
1580
1581 // We're expecting '__identifier' '(' identifier ')'. Try to recover
1582 // if the parens are missing.
1583 LexNonComment(Tok);
1584 if (Tok.isNot(tok::l_paren)) {
1585 // No '(', use end of last token.
1586 Diag(getLocForEndOfToken(Loc), diag::err_pp_expected_after)
1587 << II << tok::l_paren;
1588 // If the next token isn't valid as our argument, we can't recover.
1589 if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1590 Tok.setKind(tok::identifier);
1591 return;
1592 }
1593
1594 SourceLocation LParenLoc = Tok.getLocation();
1595 LexNonComment(Tok);
1596
1597 if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1598 Tok.setKind(tok::identifier);
1599 else {
1600 Diag(Tok.getLocation(), diag::err_pp_identifier_arg_not_identifier)
1601 << Tok.getKind();
1602 // Don't walk past anything that's not a real token.
1603 if (Tok.is(tok::eof) || Tok.is(tok::eod) || Tok.isAnnotation())
1604 return;
1605 }
1606
1607 // Discard the ')', preserving 'Tok' as our result.
1608 Token RParen;
1609 LexNonComment(RParen);
1610 if (RParen.isNot(tok::r_paren)) {
1611 Diag(getLocForEndOfToken(Tok.getLocation()), diag::err_pp_expected_after)
1612 << Tok.getKind() << tok::r_paren;
1613 Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1614 }
1615 return;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001616 } else {
1617 llvm_unreachable("Unknown identifier!");
1618 }
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00001619 CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation());
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001620}
1621
1622void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
1623 // If the 'used' status changed, and the macro requires 'unused' warning,
1624 // remove its SourceLocation from the warn-for-unused-macro locations.
1625 if (MI->isWarnIfUnused() && !MI->isUsed())
1626 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1627 MI->setIsUsed(true);
1628}