blob: 57bc9468049e9f3426a1ab97b5ab0360fa33640a [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;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000052 II->setHasMacroDefinition(MD->isDefined());
53 bool isImportedMacro = isa<DefMacroDirective>(MD) &&
54 cast<DefMacroDirective>(MD)->isImported();
55 if (II->isFromAST() && !isImportedMacro)
Joao Matosc0d4c1b2012-08-31 21:34:27 +000056 II->setChangedSinceDeserialization();
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000057}
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +000058
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000059void Preprocessor::setLoadedMacroDirective(IdentifierInfo *II,
60 MacroDirective *MD) {
61 assert(II && MD);
62 MacroDirective *&StoredMD = Macros[II];
63 assert(!StoredMD &&
64 "the macro history was modified before initializing it from a pch");
65 StoredMD = MD;
66 // Setup the identifier as having associated macro history.
67 II->setHasMacroDefinition(true);
68 if (!MD->isDefined())
69 II->setHasMacroDefinition(false);
Joao Matosc0d4c1b2012-08-31 21:34:27 +000070}
71
Joao Matosc0d4c1b2012-08-31 21:34:27 +000072/// RegisterBuiltinMacro - Register the specified identifier in the identifier
73/// table and mark it as a builtin macro to be expanded.
74static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
75 // Get the identifier.
76 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
77
78 // Mark it as being a macro that is builtin.
79 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
80 MI->setIsBuiltinMacro();
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000081 PP.appendDefMacroDirective(Id, MI);
Joao Matosc0d4c1b2012-08-31 21:34:27 +000082 return Id;
83}
84
85
86/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
87/// identifier table.
88void Preprocessor::RegisterBuiltinMacros() {
89 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
90 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
91 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
92 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
93 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
94 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
95
96 // GCC Extensions.
97 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
98 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
99 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
100
Richard Smithae385082014-03-15 00:06:08 +0000101 // Microsoft Extensions.
102 if (LangOpts.MicrosoftExt) {
103 Ident__identifier = RegisterBuiltinMacro(*this, "__identifier");
104 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
105 } else {
Craig Topperd2d442c2014-05-17 23:10:59 +0000106 Ident__identifier = nullptr;
107 Ident__pragma = nullptr;
Richard Smithae385082014-03-15 00:06:08 +0000108 }
109
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000110 // Clang Extensions.
111 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
112 Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension");
113 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
114 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
115 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
116 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
117 Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning");
Yunzhong Gaoef309f42014-04-11 20:55:19 +0000118 Ident__is_identifier = RegisterBuiltinMacro(*this, "__is_identifier");
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000119
Douglas Gregorc83de302012-09-25 15:44:52 +0000120 // Modules.
121 if (LangOpts.Modules) {
122 Ident__building_module = RegisterBuiltinMacro(*this, "__building_module");
123
124 // __MODULE__
125 if (!LangOpts.CurrentModule.empty())
126 Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__");
127 else
Craig Topperd2d442c2014-05-17 23:10:59 +0000128 Ident__MODULE__ = nullptr;
Douglas Gregorc83de302012-09-25 15:44:52 +0000129 } else {
Craig Topperd2d442c2014-05-17 23:10:59 +0000130 Ident__building_module = nullptr;
131 Ident__MODULE__ = nullptr;
Douglas Gregorc83de302012-09-25 15:44:52 +0000132 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000133}
134
135/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
136/// in its expansion, currently expands to that token literally.
137static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
138 const IdentifierInfo *MacroIdent,
139 Preprocessor &PP) {
140 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
141
142 // If the token isn't an identifier, it's always literally expanded.
Craig Topperd2d442c2014-05-17 23:10:59 +0000143 if (!II) return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000144
145 // If the information about this identifier is out of date, update it from
146 // the external source.
147 if (II->isOutOfDate())
148 PP.getExternalSource()->updateOutOfDateIdentifier(*II);
149
150 // If the identifier is a macro, and if that macro is enabled, it may be
151 // expanded so it's not a trivial expansion.
152 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
153 // Fast expanding "#define X X" is ok, because X would be disabled.
154 II != MacroIdent)
155 return false;
156
157 // If this is an object-like macro invocation, it is safe to trivially expand
158 // it.
159 if (MI->isObjectLike()) return true;
160
161 // If this is a function-like macro invocation, it's safe to trivially expand
162 // as long as the identifier is not a macro argument.
163 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
164 I != E; ++I)
165 if (*I == II)
166 return false; // Identifier is a macro argument.
167
168 return true;
169}
170
171
172/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
173/// lexed is a '('. If so, consume the token and return true, if not, this
174/// method should have no observable side-effect on the lexed tokens.
175bool Preprocessor::isNextPPTokenLParen() {
176 // Do some quick tests for rejection cases.
177 unsigned Val;
178 if (CurLexer)
179 Val = CurLexer->isNextPPTokenLParen();
180 else if (CurPTHLexer)
181 Val = CurPTHLexer->isNextPPTokenLParen();
182 else
183 Val = CurTokenLexer->isNextTokenLParen();
184
185 if (Val == 2) {
186 // We have run off the end. If it's a source file we don't
187 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
188 // macro stack.
189 if (CurPPLexer)
190 return false;
191 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
192 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
193 if (Entry.TheLexer)
194 Val = Entry.TheLexer->isNextPPTokenLParen();
195 else if (Entry.ThePTHLexer)
196 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
197 else
198 Val = Entry.TheTokenLexer->isNextTokenLParen();
199
200 if (Val != 2)
201 break;
202
203 // Ran off the end of a source file?
204 if (Entry.ThePPLexer)
205 return false;
206 }
207 }
208
209 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
210 // have found something that isn't a '(' or we found the end of the
211 // translation unit. In either case, return false.
212 return Val == 1;
213}
214
215/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
216/// expanded as a macro, handle it and return the next token as 'Identifier'.
217bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000218 MacroDirective *MD) {
Argyrios Kyrtzidis09796b92013-03-27 01:25:19 +0000219 MacroDirective::DefInfo Def = MD->getDefinition();
220 assert(Def.isValid());
221 MacroInfo *MI = Def.getMacroInfo();
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000222
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000223 // If this is a macro expansion in the "#if !defined(x)" line for the file,
224 // then the macro could expand to different things in other contexts, we need
225 // to disable the optimization in this case.
226 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
227
228 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
229 if (MI->isBuiltinMacro()) {
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000230 if (Callbacks) Callbacks->MacroExpands(Identifier, MD,
Craig Topperd2d442c2014-05-17 23:10:59 +0000231 Identifier.getLocation(),
232 /*Args=*/nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000233 ExpandBuiltinMacro(Identifier);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000234 return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000235 }
236
237 /// Args - If this is a function-like macro expansion, this contains,
238 /// for each macro argument, the list of tokens that were provided to the
239 /// invocation.
Craig Topperd2d442c2014-05-17 23:10:59 +0000240 MacroArgs *Args = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000241
242 // Remember where the end of the expansion occurred. For an object-like
243 // macro, this is the identifier. For a function-like macro, this is the ')'.
244 SourceLocation ExpansionEnd = Identifier.getLocation();
245
246 // If this is a function-like macro, read the arguments.
247 if (MI->isFunctionLike()) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000248 // Remember that we are now parsing the arguments to a macro invocation.
249 // Preprocessor directives used inside macro arguments are not portable, and
250 // this enables the warning.
251 InMacroArgs = true;
252 Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd);
253
254 // Finished parsing args.
255 InMacroArgs = false;
256
257 // If there was an error parsing the arguments, bail out.
Craig Topperd2d442c2014-05-17 23:10:59 +0000258 if (!Args) return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000259
260 ++NumFnMacroExpanded;
261 } else {
262 ++NumMacroExpanded;
263 }
264
265 // Notice that this macro has been used.
266 markMacroAsUsed(MI);
267
268 // Remember where the token is expanded.
269 SourceLocation ExpandLoc = Identifier.getLocation();
270 SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
271
272 if (Callbacks) {
273 if (InMacroArgs) {
274 // We can have macro expansion inside a conditional directive while
275 // reading the function macro arguments. To ensure, in that case, that
276 // MacroExpands callbacks still happen in source order, queue this
277 // callback to have it happen after the function macro callback.
278 DelayedMacroExpandsCallbacks.push_back(
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000279 MacroExpandsInfo(Identifier, MD, ExpansionRange));
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000280 } else {
Argyrios Kyrtzidis37e48ff2013-05-03 22:31:32 +0000281 Callbacks->MacroExpands(Identifier, MD, ExpansionRange, Args);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000282 if (!DelayedMacroExpandsCallbacks.empty()) {
283 for (unsigned i=0, e = DelayedMacroExpandsCallbacks.size(); i!=e; ++i) {
284 MacroExpandsInfo &Info = DelayedMacroExpandsCallbacks[i];
Argyrios Kyrtzidis37e48ff2013-05-03 22:31:32 +0000285 // FIXME: We lose macro args info with delayed callback.
Craig Topperd2d442c2014-05-17 23:10:59 +0000286 Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range,
287 /*Args=*/nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000288 }
289 DelayedMacroExpandsCallbacks.clear();
290 }
291 }
292 }
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000293
294 // If the macro definition is ambiguous, complain.
Argyrios Kyrtzidis09796b92013-03-27 01:25:19 +0000295 if (Def.getDirective()->isAmbiguous()) {
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000296 Diag(Identifier, diag::warn_pp_ambiguous_macro)
297 << Identifier.getIdentifierInfo();
298 Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)
299 << Identifier.getIdentifierInfo();
Argyrios Kyrtzidis09796b92013-03-27 01:25:19 +0000300 for (MacroDirective::DefInfo PrevDef = Def.getPreviousDefinition();
301 PrevDef && !PrevDef.isUndefined();
302 PrevDef = PrevDef.getPreviousDefinition()) {
Richard Smith49f906a2014-03-01 00:08:04 +0000303 Diag(PrevDef.getMacroInfo()->getDefinitionLoc(),
304 diag::note_pp_ambiguous_macro_other)
305 << Identifier.getIdentifierInfo();
306 if (!PrevDef.getDirective()->isAmbiguous())
307 break;
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000308 }
309 }
310
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000311 // If we started lexing a macro, enter the macro expansion body.
312
313 // If this macro expands to no tokens, don't bother to push it onto the
314 // expansion stack, only to take it right back off.
315 if (MI->getNumTokens() == 0) {
316 // No need for arg info.
317 if (Args) Args->destroy(*this);
318
Eli Friedman0834a4b2013-09-19 00:41:32 +0000319 // Propagate whitespace info as if we had pushed, then popped,
320 // a macro context.
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000321 Identifier.setFlag(Token::LeadingEmptyMacro);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000322 PropagateLineStartLeadingSpaceInfo(Identifier);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000323 ++NumFastMacroExpanded;
324 return false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000325 } else if (MI->getNumTokens() == 1 &&
326 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
327 *this)) {
328 // Otherwise, if this macro expands into a single trivially-expanded
329 // token: expand it now. This handles common cases like
330 // "#define VAL 42".
331
332 // No need for arg info.
333 if (Args) Args->destroy(*this);
334
335 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
336 // identifier to the expanded token.
337 bool isAtStartOfLine = Identifier.isAtStartOfLine();
338 bool hasLeadingSpace = Identifier.hasLeadingSpace();
339
340 // Replace the result token.
341 Identifier = MI->getReplacementToken(0);
342
343 // Restore the StartOfLine/LeadingSpace markers.
344 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
345 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
346
347 // Update the tokens location to include both its expansion and physical
348 // locations.
349 SourceLocation Loc =
350 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
351 ExpansionEnd,Identifier.getLength());
352 Identifier.setLocation(Loc);
353
354 // If this is a disabled macro or #define X X, we must mark the result as
355 // unexpandable.
356 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
357 if (MacroInfo *NewMI = getMacroInfo(NewII))
358 if (!NewMI->isEnabled() || NewMI == MI) {
359 Identifier.setFlag(Token::DisableExpand);
Douglas Gregor1a347f72013-01-30 23:10:17 +0000360 // Don't warn for "#define X X" like "#define bool bool" from
361 // stdbool.h.
362 if (NewMI != MI || MI->isFunctionLike())
363 Diag(Identifier, diag::pp_disabled_macro_expansion);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000364 }
365 }
366
367 // Since this is not an identifier token, it can't be macro expanded, so
368 // we're done.
369 ++NumFastMacroExpanded;
Eli Friedman0834a4b2013-09-19 00:41:32 +0000370 return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000371 }
372
373 // Start expanding the macro.
374 EnterMacro(Identifier, ExpansionEnd, MI, Args);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000375 return false;
376}
377
Richard Trieu79b45382013-07-23 18:01:49 +0000378enum Bracket {
379 Brace,
380 Paren
381};
382
383/// CheckMatchedBrackets - Returns true if the braces and parentheses in the
384/// token vector are properly nested.
385static bool CheckMatchedBrackets(const SmallVectorImpl<Token> &Tokens) {
386 SmallVector<Bracket, 8> Brackets;
387 for (SmallVectorImpl<Token>::const_iterator I = Tokens.begin(),
388 E = Tokens.end();
389 I != E; ++I) {
390 if (I->is(tok::l_paren)) {
391 Brackets.push_back(Paren);
392 } else if (I->is(tok::r_paren)) {
393 if (Brackets.empty() || Brackets.back() == Brace)
394 return false;
395 Brackets.pop_back();
396 } else if (I->is(tok::l_brace)) {
397 Brackets.push_back(Brace);
398 } else if (I->is(tok::r_brace)) {
399 if (Brackets.empty() || Brackets.back() == Paren)
400 return false;
401 Brackets.pop_back();
402 }
403 }
404 if (!Brackets.empty())
405 return false;
406 return true;
407}
408
409/// GenerateNewArgTokens - Returns true if OldTokens can be converted to a new
410/// vector of tokens in NewTokens. The new number of arguments will be placed
411/// in NumArgs and the ranges which need to surrounded in parentheses will be
412/// in ParenHints.
413/// Returns false if the token stream cannot be changed. If this is because
414/// of an initializer list starting a macro argument, the range of those
415/// initializer lists will be place in InitLists.
416static bool GenerateNewArgTokens(Preprocessor &PP,
417 SmallVectorImpl<Token> &OldTokens,
418 SmallVectorImpl<Token> &NewTokens,
419 unsigned &NumArgs,
420 SmallVectorImpl<SourceRange> &ParenHints,
421 SmallVectorImpl<SourceRange> &InitLists) {
422 if (!CheckMatchedBrackets(OldTokens))
423 return false;
424
425 // Once it is known that the brackets are matched, only a simple count of the
426 // braces is needed.
427 unsigned Braces = 0;
428
429 // First token of a new macro argument.
430 SmallVectorImpl<Token>::iterator ArgStartIterator = OldTokens.begin();
431
432 // First closing brace in a new macro argument. Used to generate
433 // SourceRanges for InitLists.
434 SmallVectorImpl<Token>::iterator ClosingBrace = OldTokens.end();
435 NumArgs = 0;
436 Token TempToken;
437 // Set to true when a macro separator token is found inside a braced list.
438 // If true, the fixed argument spans multiple old arguments and ParenHints
439 // will be updated.
440 bool FoundSeparatorToken = false;
441 for (SmallVectorImpl<Token>::iterator I = OldTokens.begin(),
442 E = OldTokens.end();
443 I != E; ++I) {
444 if (I->is(tok::l_brace)) {
445 ++Braces;
446 } else if (I->is(tok::r_brace)) {
447 --Braces;
448 if (Braces == 0 && ClosingBrace == E && FoundSeparatorToken)
449 ClosingBrace = I;
450 } else if (I->is(tok::eof)) {
451 // EOF token is used to separate macro arguments
452 if (Braces != 0) {
453 // Assume comma separator is actually braced list separator and change
454 // it back to a comma.
455 FoundSeparatorToken = true;
456 I->setKind(tok::comma);
457 I->setLength(1);
458 } else { // Braces == 0
459 // Separator token still separates arguments.
460 ++NumArgs;
461
462 // If the argument starts with a brace, it can't be fixed with
463 // parentheses. A different diagnostic will be given.
464 if (FoundSeparatorToken && ArgStartIterator->is(tok::l_brace)) {
465 InitLists.push_back(
466 SourceRange(ArgStartIterator->getLocation(),
467 PP.getLocForEndOfToken(ClosingBrace->getLocation())));
468 ClosingBrace = E;
469 }
470
471 // Add left paren
472 if (FoundSeparatorToken) {
473 TempToken.startToken();
474 TempToken.setKind(tok::l_paren);
475 TempToken.setLocation(ArgStartIterator->getLocation());
476 TempToken.setLength(0);
477 NewTokens.push_back(TempToken);
478 }
479
480 // Copy over argument tokens
481 NewTokens.insert(NewTokens.end(), ArgStartIterator, I);
482
483 // Add right paren and store the paren locations in ParenHints
484 if (FoundSeparatorToken) {
485 SourceLocation Loc = PP.getLocForEndOfToken((I - 1)->getLocation());
486 TempToken.startToken();
487 TempToken.setKind(tok::r_paren);
488 TempToken.setLocation(Loc);
489 TempToken.setLength(0);
490 NewTokens.push_back(TempToken);
491 ParenHints.push_back(SourceRange(ArgStartIterator->getLocation(),
492 Loc));
493 }
494
495 // Copy separator token
496 NewTokens.push_back(*I);
497
498 // Reset values
499 ArgStartIterator = I + 1;
500 FoundSeparatorToken = false;
501 }
502 }
503 }
504
505 return !ParenHints.empty() && InitLists.empty();
506}
507
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000508/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
509/// token is the '(' of the macro, this method is invoked to read all of the
510/// actual arguments specified for the macro invocation. This returns null on
511/// error.
512MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
513 MacroInfo *MI,
514 SourceLocation &MacroEnd) {
515 // The number of fixed arguments to parse.
516 unsigned NumFixedArgsLeft = MI->getNumArgs();
517 bool isVariadic = MI->isVariadic();
518
519 // Outer loop, while there are more arguments, keep reading them.
520 Token Tok;
521
522 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
523 // an argument value in a macro could expand to ',' or '(' or ')'.
524 LexUnexpandedToken(Tok);
525 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
526
527 // ArgTokens - Build up a list of tokens that make up each argument. Each
528 // argument is separated by an EOF token. Use a SmallVector so we can avoid
529 // heap allocations in the common case.
530 SmallVector<Token, 64> ArgTokens;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000531 bool ContainsCodeCompletionTok = false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000532
Richard Trieu79b45382013-07-23 18:01:49 +0000533 SourceLocation TooManyArgsLoc;
534
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000535 unsigned NumActuals = 0;
536 while (Tok.isNot(tok::r_paren)) {
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000537 if (ContainsCodeCompletionTok && (Tok.is(tok::eof) || Tok.is(tok::eod)))
538 break;
539
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000540 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
541 "only expect argument separators here");
542
543 unsigned ArgTokenStart = ArgTokens.size();
544 SourceLocation ArgStartLoc = Tok.getLocation();
545
546 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
547 // that we already consumed the first one.
548 unsigned NumParens = 0;
549
550 while (1) {
551 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
552 // an argument value in a macro could expand to ',' or '(' or ')'.
553 LexUnexpandedToken(Tok);
554
555 if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n"
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000556 if (!ContainsCodeCompletionTok) {
557 Diag(MacroName, diag::err_unterm_macro_invoc);
558 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
559 << MacroName.getIdentifierInfo();
560 // Do not lose the EOF/EOD. Return it to the client.
561 MacroName = Tok;
Craig Topperd2d442c2014-05-17 23:10:59 +0000562 return nullptr;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000563 } else {
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000564 // Do not lose the EOF/EOD.
565 Token *Toks = new Token[1];
566 Toks[0] = Tok;
567 EnterTokenStream(Toks, 1, true, true);
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000568 break;
569 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000570 } else if (Tok.is(tok::r_paren)) {
571 // If we found the ) token, the macro arg list is done.
572 if (NumParens-- == 0) {
573 MacroEnd = Tok.getLocation();
574 break;
575 }
576 } else if (Tok.is(tok::l_paren)) {
577 ++NumParens;
Reid Kleckner596b85c2013-06-26 17:16:08 +0000578 } else if (Tok.is(tok::comma) && NumParens == 0 &&
579 !(Tok.getFlags() & Token::IgnoredComma)) {
580 // In Microsoft-compatibility mode, single commas from nested macro
581 // expansions should not be considered as argument separators. We test
582 // for this with the IgnoredComma token flag above.
583
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000584 // Comma ends this argument if there are more fixed arguments expected.
585 // However, if this is a variadic macro, and this is part of the
586 // variadic part, then the comma is just an argument token.
587 if (!isVariadic) break;
588 if (NumFixedArgsLeft > 1)
589 break;
590 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
591 // If this is a comment token in the argument list and we're just in
592 // -C mode (not -CC mode), discard the comment.
593 continue;
Craig Topperd2d442c2014-05-17 23:10:59 +0000594 } else if (Tok.getIdentifierInfo() != nullptr) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000595 // Reading macro arguments can cause macros that we are currently
596 // expanding from to be popped off the expansion stack. Doing so causes
597 // them to be reenabled for expansion. Here we record whether any
598 // identifiers we lex as macro arguments correspond to disabled macros.
599 // If so, we mark the token as noexpand. This is a subtle aspect of
600 // C99 6.10.3.4p2.
601 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
602 if (!MI->isEnabled())
603 Tok.setFlag(Token::DisableExpand);
604 } else if (Tok.is(tok::code_completion)) {
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000605 ContainsCodeCompletionTok = true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000606 if (CodeComplete)
607 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
608 MI, NumActuals);
609 // Don't mark that we reached the code-completion point because the
610 // parser is going to handle the token and there will be another
611 // code-completion callback.
612 }
613
614 ArgTokens.push_back(Tok);
615 }
616
617 // If this was an empty argument list foo(), don't add this as an empty
618 // argument.
619 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
620 break;
621
622 // If this is not a variadic macro, and too many args were specified, emit
623 // an error.
Richard Trieu79b45382013-07-23 18:01:49 +0000624 if (!isVariadic && NumFixedArgsLeft == 0 && TooManyArgsLoc.isInvalid()) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000625 if (ArgTokens.size() != ArgTokenStart)
Richard Trieu79b45382013-07-23 18:01:49 +0000626 TooManyArgsLoc = ArgTokens[ArgTokenStart].getLocation();
627 else
628 TooManyArgsLoc = ArgStartLoc;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000629 }
630
Richard Trieu79b45382013-07-23 18:01:49 +0000631 // Empty arguments are standard in C99 and C++0x, and are supported as an
632 // extension in other modes.
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000633 if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99)
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000634 Diag(Tok, LangOpts.CPlusPlus11 ?
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000635 diag::warn_cxx98_compat_empty_fnmacro_arg :
636 diag::ext_empty_fnmacro_arg);
637
638 // Add a marker EOF token to the end of the token list for this argument.
639 Token EOFTok;
640 EOFTok.startToken();
641 EOFTok.setKind(tok::eof);
642 EOFTok.setLocation(Tok.getLocation());
643 EOFTok.setLength(0);
644 ArgTokens.push_back(EOFTok);
645 ++NumActuals;
Richard Trieu79b45382013-07-23 18:01:49 +0000646 if (!ContainsCodeCompletionTok && NumFixedArgsLeft != 0)
Argyrios Kyrtzidisfb703802013-02-22 22:28:58 +0000647 --NumFixedArgsLeft;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000648 }
649
650 // Okay, we either found the r_paren. Check to see if we parsed too few
651 // arguments.
652 unsigned MinArgsExpected = MI->getNumArgs();
653
Richard Trieu79b45382013-07-23 18:01:49 +0000654 // If this is not a variadic macro, and too many args were specified, emit
655 // an error.
656 if (!isVariadic && NumActuals > MinArgsExpected &&
657 !ContainsCodeCompletionTok) {
658 // Emit the diagnostic at the macro name in case there is a missing ).
659 // Emitting it at the , could be far away from the macro name.
660 Diag(TooManyArgsLoc, diag::err_too_many_args_in_macro_invoc);
661 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
662 << MacroName.getIdentifierInfo();
663
664 // Commas from braced initializer lists will be treated as argument
665 // separators inside macros. Attempt to correct for this with parentheses.
666 // TODO: See if this can be generalized to angle brackets for templates
667 // inside macro arguments.
668
Bob Wilson57217352013-07-27 21:59:57 +0000669 SmallVector<Token, 4> FixedArgTokens;
Richard Trieu79b45382013-07-23 18:01:49 +0000670 unsigned FixedNumArgs = 0;
671 SmallVector<SourceRange, 4> ParenHints, InitLists;
672 if (!GenerateNewArgTokens(*this, ArgTokens, FixedArgTokens, FixedNumArgs,
673 ParenHints, InitLists)) {
674 if (!InitLists.empty()) {
675 DiagnosticBuilder DB =
676 Diag(MacroName,
677 diag::note_init_list_at_beginning_of_macro_argument);
Alexander Kornienkod3b4e082014-05-22 19:56:11 +0000678 for (const SourceRange &Range : InitLists)
679 DB << Range;
Richard Trieu79b45382013-07-23 18:01:49 +0000680 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000681 return nullptr;
Richard Trieu79b45382013-07-23 18:01:49 +0000682 }
683 if (FixedNumArgs != MinArgsExpected)
Craig Topperd2d442c2014-05-17 23:10:59 +0000684 return nullptr;
Richard Trieu79b45382013-07-23 18:01:49 +0000685
686 DiagnosticBuilder DB = Diag(MacroName, diag::note_suggest_parens_for_macro);
Alexander Kornienkod3b4e082014-05-22 19:56:11 +0000687 for (const SourceRange &ParenLocation : ParenHints) {
688 DB << FixItHint::CreateInsertion(ParenLocation.getBegin(), "(");
689 DB << FixItHint::CreateInsertion(ParenLocation.getEnd(), ")");
Richard Trieu79b45382013-07-23 18:01:49 +0000690 }
691 ArgTokens.swap(FixedArgTokens);
692 NumActuals = FixedNumArgs;
693 }
694
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000695 // See MacroArgs instance var for description of this.
696 bool isVarargsElided = false;
697
Argyrios Kyrtzidisd4635d42012-12-21 01:51:12 +0000698 if (ContainsCodeCompletionTok) {
699 // Recover from not-fully-formed macro invocation during code-completion.
700 Token EOFTok;
701 EOFTok.startToken();
702 EOFTok.setKind(tok::eof);
703 EOFTok.setLocation(Tok.getLocation());
704 EOFTok.setLength(0);
705 for (; NumActuals < MinArgsExpected; ++NumActuals)
706 ArgTokens.push_back(EOFTok);
707 }
708
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000709 if (NumActuals < MinArgsExpected) {
710 // There are several cases where too few arguments is ok, handle them now.
711 if (NumActuals == 0 && MinArgsExpected == 1) {
712 // #define A(X) or #define A(...) ---> A()
713
714 // If there is exactly one argument, and that argument is missing,
715 // then we have an empty "()" argument empty list. This is fine, even if
716 // the macro expects one argument (the argument is just empty).
717 isVarargsElided = MI->isVariadic();
718 } else if (MI->isVariadic() &&
719 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
720 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
721 // Varargs where the named vararg parameter is missing: OK as extension.
722 // #define A(x, ...)
723 // A("blah")
Eli Friedman14d3c792012-11-14 02:18:46 +0000724 //
725 // If the macro contains the comma pasting extension, the diagnostic
726 // is suppressed; we know we'll get another diagnostic later.
727 if (!MI->hasCommaPasting()) {
728 Diag(Tok, diag::ext_missing_varargs_arg);
729 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
730 << MacroName.getIdentifierInfo();
731 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000732
733 // Remember this occurred, allowing us to elide the comma when used for
734 // cases like:
735 // #define A(x, foo...) blah(a, ## foo)
736 // #define B(x, ...) blah(a, ## __VA_ARGS__)
737 // #define C(...) blah(a, ## __VA_ARGS__)
738 // A(x) B(x) C()
739 isVarargsElided = true;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000740 } else if (!ContainsCodeCompletionTok) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000741 // Otherwise, emit the error.
742 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Argyrios Kyrtzidis164fdb62012-12-14 18:53:47 +0000743 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
744 << MacroName.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000745 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000746 }
747
748 // Add a marker EOF token to the end of the token list for this argument.
749 SourceLocation EndLoc = Tok.getLocation();
750 Tok.startToken();
751 Tok.setKind(tok::eof);
752 Tok.setLocation(EndLoc);
753 Tok.setLength(0);
754 ArgTokens.push_back(Tok);
755
756 // If we expect two arguments, add both as empty.
757 if (NumActuals == 0 && MinArgsExpected == 2)
758 ArgTokens.push_back(Tok);
759
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000760 } else if (NumActuals > MinArgsExpected && !MI->isVariadic() &&
761 !ContainsCodeCompletionTok) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000762 // Emit the diagnostic at the macro name in case there is a missing ).
763 // Emitting it at the , could be far away from the macro name.
764 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Argyrios Kyrtzidis164fdb62012-12-14 18:53:47 +0000765 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
766 << MacroName.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000767 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000768 }
769
770 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
771}
772
773/// \brief Keeps macro expanded tokens for TokenLexers.
774//
775/// Works like a stack; a TokenLexer adds the macro expanded tokens that is
776/// going to lex in the cache and when it finishes the tokens are removed
777/// from the end of the cache.
778Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
779 ArrayRef<Token> tokens) {
780 assert(tokLexer);
781 if (tokens.empty())
Craig Topperd2d442c2014-05-17 23:10:59 +0000782 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000783
784 size_t newIndex = MacroExpandedTokens.size();
785 bool cacheNeedsToGrow = tokens.size() >
786 MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
787 MacroExpandedTokens.append(tokens.begin(), tokens.end());
788
789 if (cacheNeedsToGrow) {
790 // Go through all the TokenLexers whose 'Tokens' pointer points in the
791 // buffer and update the pointers to the (potential) new buffer array.
792 for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) {
793 TokenLexer *prevLexer;
794 size_t tokIndex;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000795 std::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i];
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000796 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
797 }
798 }
799
800 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
801 return MacroExpandedTokens.data() + newIndex;
802}
803
804void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
805 assert(!MacroExpandingLexersStack.empty());
806 size_t tokIndex = MacroExpandingLexersStack.back().second;
807 assert(tokIndex < MacroExpandedTokens.size());
808 // Pop the cached macro expanded tokens from the end.
809 MacroExpandedTokens.resize(tokIndex);
810 MacroExpandingLexersStack.pop_back();
811}
812
813/// ComputeDATE_TIME - Compute the current time, enter it into the specified
814/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
815/// the identifier tokens inserted.
816static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
817 Preprocessor &PP) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000818 time_t TT = time(nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000819 struct tm *TM = localtime(&TT);
820
821 static const char * const Months[] = {
822 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
823 };
824
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000825 {
826 SmallString<32> TmpBuffer;
827 llvm::raw_svector_ostream TmpStream(TmpBuffer);
828 TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
829 TM->tm_mday, TM->tm_year + 1900);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000830 Token TmpTok;
831 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000832 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000833 DATELoc = TmpTok.getLocation();
834 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000835
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000836 {
837 SmallString<32> TmpBuffer;
838 llvm::raw_svector_ostream TmpStream(TmpBuffer);
839 TmpStream << llvm::format("\"%02d:%02d:%02d\"",
840 TM->tm_hour, TM->tm_min, TM->tm_sec);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000841 Token TmpTok;
842 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000843 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000844 TIMELoc = TmpTok.getLocation();
845 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000846}
847
848
849/// HasFeature - Return true if we recognize and implement the feature
850/// specified by the identifier as a standard language feature.
851static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
852 const LangOptions &LangOpts = PP.getLangOpts();
853 StringRef Feature = II->getName();
854
855 // Normalize the feature name, __foo__ becomes foo.
856 if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4)
857 Feature = Feature.substr(2, Feature.size() - 4);
858
859 return llvm::StringSwitch<bool>(Feature)
Will Dietzf54319c2013-01-18 11:30:38 +0000860 .Case("address_sanitizer", LangOpts.Sanitize.Address)
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000861 .Case("attribute_analyzer_noreturn", true)
862 .Case("attribute_availability", true)
863 .Case("attribute_availability_with_message", true)
864 .Case("attribute_cf_returns_not_retained", true)
865 .Case("attribute_cf_returns_retained", true)
866 .Case("attribute_deprecated_with_message", true)
867 .Case("attribute_ext_vector_type", true)
868 .Case("attribute_ns_returns_not_retained", true)
869 .Case("attribute_ns_returns_retained", true)
870 .Case("attribute_ns_consumes_self", true)
871 .Case("attribute_ns_consumed", true)
872 .Case("attribute_cf_consumed", true)
873 .Case("attribute_objc_ivar_unused", true)
874 .Case("attribute_objc_method_family", true)
875 .Case("attribute_overloadable", true)
876 .Case("attribute_unavailable_with_message", true)
877 .Case("attribute_unused_on_fields", true)
878 .Case("blocks", LangOpts.Blocks)
David Blaikie021221d2013-07-29 18:24:03 +0000879 .Case("c_thread_safety_attributes", true)
Justin Bogner4e3a01f2014-04-16 02:56:48 +0000880 .Case("cxx_exceptions", LangOpts.CXXExceptions)
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000881 .Case("cxx_rtti", LangOpts.RTTI)
882 .Case("enumerator_attributes", true)
Will Dietzf54319c2013-01-18 11:30:38 +0000883 .Case("memory_sanitizer", LangOpts.Sanitize.Memory)
884 .Case("thread_sanitizer", LangOpts.Sanitize.Thread)
Peter Collingbournec3772752013-08-07 22:47:34 +0000885 .Case("dataflow_sanitizer", LangOpts.Sanitize.DataFlow)
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000886 // Objective-C features
887 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
888 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
889 .Case("objc_arc_weak", LangOpts.ObjCARCWeak)
890 .Case("objc_default_synthesize_properties", LangOpts.ObjC2)
891 .Case("objc_fixed_enum", LangOpts.ObjC2)
892 .Case("objc_instancetype", LangOpts.ObjC2)
893 .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules)
894 .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile())
Ted Kremenekdae8f9f2013-01-04 19:04:44 +0000895 .Case("objc_property_explicit_atomic", true) // Does clang support explicit "atomic" keyword?
Ted Kremenekb0cba4c2013-10-14 23:48:27 +0000896 .Case("objc_protocol_qualifier_mangling", true)
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000897 .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport())
898 .Case("ownership_holds", true)
899 .Case("ownership_returns", true)
900 .Case("ownership_takes", true)
901 .Case("objc_bool", true)
902 .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile())
903 .Case("objc_array_literals", LangOpts.ObjC2)
904 .Case("objc_dictionary_literals", LangOpts.ObjC2)
905 .Case("objc_boxed_expressions", LangOpts.ObjC2)
906 .Case("arc_cf_code_audited", true)
907 // C11 features
908 .Case("c_alignas", LangOpts.C11)
909 .Case("c_atomic", LangOpts.C11)
910 .Case("c_generic_selections", LangOpts.C11)
911 .Case("c_static_assert", LangOpts.C11)
Richard Smith6d540142014-05-09 21:08:59 +0000912 .Case("c_thread_local",
Douglas Gregora7130bf2013-05-02 05:28:32 +0000913 LangOpts.C11 && PP.getTargetInfo().isTLSSupported())
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000914 // C++11 features
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000915 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus11)
916 .Case("cxx_alias_templates", LangOpts.CPlusPlus11)
917 .Case("cxx_alignas", LangOpts.CPlusPlus11)
918 .Case("cxx_atomic", LangOpts.CPlusPlus11)
919 .Case("cxx_attributes", LangOpts.CPlusPlus11)
920 .Case("cxx_auto_type", LangOpts.CPlusPlus11)
921 .Case("cxx_constexpr", LangOpts.CPlusPlus11)
922 .Case("cxx_decltype", LangOpts.CPlusPlus11)
923 .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus11)
924 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus11)
925 .Case("cxx_defaulted_functions", LangOpts.CPlusPlus11)
926 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus11)
927 .Case("cxx_deleted_functions", LangOpts.CPlusPlus11)
928 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus11)
929 .Case("cxx_generalized_initializers", LangOpts.CPlusPlus11)
930 .Case("cxx_implicit_moves", LangOpts.CPlusPlus11)
Richard Smith25b555a2013-04-19 17:00:31 +0000931 .Case("cxx_inheriting_constructors", LangOpts.CPlusPlus11)
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000932 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus11)
933 .Case("cxx_lambdas", LangOpts.CPlusPlus11)
934 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus11)
935 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus11)
936 .Case("cxx_noexcept", LangOpts.CPlusPlus11)
937 .Case("cxx_nullptr", LangOpts.CPlusPlus11)
938 .Case("cxx_override_control", LangOpts.CPlusPlus11)
939 .Case("cxx_range_for", LangOpts.CPlusPlus11)
940 .Case("cxx_raw_string_literals", LangOpts.CPlusPlus11)
941 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus11)
942 .Case("cxx_rvalue_references", LangOpts.CPlusPlus11)
943 .Case("cxx_strong_enums", LangOpts.CPlusPlus11)
944 .Case("cxx_static_assert", LangOpts.CPlusPlus11)
Richard Smithb438e622013-09-28 04:37:56 +0000945 .Case("cxx_thread_local",
Douglas Gregora7130bf2013-05-02 05:28:32 +0000946 LangOpts.CPlusPlus11 && PP.getTargetInfo().isTLSSupported())
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000947 .Case("cxx_trailing_return", LangOpts.CPlusPlus11)
948 .Case("cxx_unicode_literals", LangOpts.CPlusPlus11)
949 .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus11)
950 .Case("cxx_user_literals", LangOpts.CPlusPlus11)
951 .Case("cxx_variadic_templates", LangOpts.CPlusPlus11)
Richard Smith0a715422013-05-07 19:32:56 +0000952 // C++1y features
Richard Smith4fb09722013-07-24 17:51:13 +0000953 .Case("cxx_aggregate_nsdmi", LangOpts.CPlusPlus1y)
Richard Smith0a715422013-05-07 19:32:56 +0000954 .Case("cxx_binary_literals", LangOpts.CPlusPlus1y)
Richard Smithc0f7b812013-07-24 17:41:31 +0000955 .Case("cxx_contextual_conversions", LangOpts.CPlusPlus1y)
Richard Smith6d540142014-05-09 21:08:59 +0000956 .Case("cxx_decltype_auto", LangOpts.CPlusPlus1y)
957 .Case("cxx_generic_lambdas", LangOpts.CPlusPlus1y)
Richard Smithb438e622013-09-28 04:37:56 +0000958 .Case("cxx_init_captures", LangOpts.CPlusPlus1y)
Richard Smithc0f7b812013-07-24 17:41:31 +0000959 .Case("cxx_relaxed_constexpr", LangOpts.CPlusPlus1y)
Richard Smith9155be12013-05-12 03:09:35 +0000960 .Case("cxx_return_type_deduction", LangOpts.CPlusPlus1y)
Richard Smithdca0c7a2013-09-27 20:19:41 +0000961 .Case("cxx_variable_templates", LangOpts.CPlusPlus1y)
Richard Smith6d540142014-05-09 21:08:59 +0000962 // C++ TSes
963 //.Case("cxx_runtime_arrays", LangOpts.CPlusPlusTSArrays)
964 //.Case("cxx_concepts", LangOpts.CPlusPlusTSConcepts)
965 // FIXME: Should this be __has_feature or __has_extension?
966 //.Case("raw_invocation_type", LangOpts.CPlusPlus)
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000967 // Type traits
968 .Case("has_nothrow_assign", LangOpts.CPlusPlus)
969 .Case("has_nothrow_copy", LangOpts.CPlusPlus)
970 .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
971 .Case("has_trivial_assign", LangOpts.CPlusPlus)
972 .Case("has_trivial_copy", LangOpts.CPlusPlus)
973 .Case("has_trivial_constructor", LangOpts.CPlusPlus)
974 .Case("has_trivial_destructor", LangOpts.CPlusPlus)
975 .Case("has_virtual_destructor", LangOpts.CPlusPlus)
976 .Case("is_abstract", LangOpts.CPlusPlus)
977 .Case("is_base_of", LangOpts.CPlusPlus)
978 .Case("is_class", LangOpts.CPlusPlus)
Marshall Clowd28acc02014-03-18 14:13:10 +0000979 .Case("is_constructible", LangOpts.CPlusPlus)
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000980 .Case("is_convertible_to", LangOpts.CPlusPlus)
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000981 .Case("is_empty", LangOpts.CPlusPlus)
982 .Case("is_enum", LangOpts.CPlusPlus)
983 .Case("is_final", LangOpts.CPlusPlus)
984 .Case("is_literal", LangOpts.CPlusPlus)
985 .Case("is_standard_layout", LangOpts.CPlusPlus)
986 .Case("is_pod", LangOpts.CPlusPlus)
987 .Case("is_polymorphic", LangOpts.CPlusPlus)
David Majnemera5433082013-10-18 00:33:31 +0000988 .Case("is_sealed", LangOpts.MicrosoftExt)
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000989 .Case("is_trivial", LangOpts.CPlusPlus)
990 .Case("is_trivially_assignable", LangOpts.CPlusPlus)
991 .Case("is_trivially_constructible", LangOpts.CPlusPlus)
992 .Case("is_trivially_copyable", LangOpts.CPlusPlus)
993 .Case("is_union", LangOpts.CPlusPlus)
994 .Case("modules", LangOpts.Modules)
995 .Case("tls", PP.getTargetInfo().isTLSSupported())
996 .Case("underlying_type", LangOpts.CPlusPlus)
997 .Default(false);
998}
999
1000/// HasExtension - Return true if we recognize and implement the feature
1001/// specified by the identifier, either as an extension or a standard language
1002/// feature.
1003static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) {
1004 if (HasFeature(PP, II))
1005 return true;
1006
1007 // If the use of an extension results in an error diagnostic, extensions are
1008 // effectively unavailable, so just return false here.
1009 if (PP.getDiagnostics().getExtensionHandlingBehavior() ==
1010 DiagnosticsEngine::Ext_Error)
1011 return false;
1012
1013 const LangOptions &LangOpts = PP.getLangOpts();
1014 StringRef Extension = II->getName();
1015
1016 // Normalize the extension name, __foo__ becomes foo.
1017 if (Extension.startswith("__") && Extension.endswith("__") &&
1018 Extension.size() >= 4)
1019 Extension = Extension.substr(2, Extension.size() - 4);
1020
1021 // Because we inherit the feature list from HasFeature, this string switch
1022 // must be less restrictive than HasFeature's.
1023 return llvm::StringSwitch<bool>(Extension)
1024 // C11 features supported by other languages as extensions.
1025 .Case("c_alignas", true)
1026 .Case("c_atomic", true)
1027 .Case("c_generic_selections", true)
1028 .Case("c_static_assert", true)
Ed Schouten401aeba2013-09-14 16:17:20 +00001029 .Case("c_thread_local", PP.getTargetInfo().isTLSSupported())
Richard Smith0a715422013-05-07 19:32:56 +00001030 // C++11 features supported by other languages as extensions.
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001031 .Case("cxx_atomic", LangOpts.CPlusPlus)
1032 .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
1033 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
1034 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
1035 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus)
1036 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
1037 .Case("cxx_override_control", LangOpts.CPlusPlus)
1038 .Case("cxx_range_for", LangOpts.CPlusPlus)
1039 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
1040 .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
Richard Smith0a715422013-05-07 19:32:56 +00001041 // C++1y features supported by other languages as extensions.
1042 .Case("cxx_binary_literals", true)
Richard Smithb438e622013-09-28 04:37:56 +00001043 .Case("cxx_init_captures", LangOpts.CPlusPlus11)
Alp Tokera8bb9c92014-01-15 04:11:24 +00001044 .Case("cxx_variable_templates", LangOpts.CPlusPlus)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001045 .Default(false);
1046}
1047
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001048/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
1049/// or '__has_include_next("path")' expression.
1050/// Returns true if successful.
1051static bool EvaluateHasIncludeCommon(Token &Tok,
1052 IdentifierInfo *II, Preprocessor &PP,
1053 const DirectoryLookup *LookupFrom) {
Richard Trieuda031982012-10-22 20:28:48 +00001054 // Save the location of the current token. If a '(' is later found, use
Aaron Ballman5cb24112013-01-15 21:59:46 +00001055 // that location. If not, use the end of this location instead.
Richard Trieuda031982012-10-22 20:28:48 +00001056 SourceLocation LParenLoc = Tok.getLocation();
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001057
Aaron Ballman6ce00002013-01-16 19:32:21 +00001058 // These expressions are only allowed within a preprocessor directive.
1059 if (!PP.isParsingIfOrElifDirective()) {
1060 PP.Diag(LParenLoc, diag::err_pp_directive_required) << II->getName();
1061 return false;
1062 }
1063
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001064 // Get '('.
1065 PP.LexNonComment(Tok);
1066
1067 // Ensure we have a '('.
1068 if (Tok.isNot(tok::l_paren)) {
Richard Trieuda031982012-10-22 20:28:48 +00001069 // No '(', use end of last token.
1070 LParenLoc = PP.getLocForEndOfToken(LParenLoc);
Alp Toker751d6352013-12-30 01:59:29 +00001071 PP.Diag(LParenLoc, diag::err_pp_expected_after) << II << tok::l_paren;
Richard Trieuda031982012-10-22 20:28:48 +00001072 // If the next token looks like a filename or the start of one,
1073 // assume it is and process it as such.
1074 if (!Tok.is(tok::angle_string_literal) && !Tok.is(tok::string_literal) &&
1075 !Tok.is(tok::less))
1076 return false;
1077 } else {
1078 // Save '(' location for possible missing ')' message.
1079 LParenLoc = Tok.getLocation();
1080
Eli Friedmanec94b612013-01-09 02:20:00 +00001081 if (PP.getCurrentLexer()) {
1082 // Get the file name.
1083 PP.getCurrentLexer()->LexIncludeFilename(Tok);
1084 } else {
1085 // We're in a macro, so we can't use LexIncludeFilename; just
1086 // grab the next token.
1087 PP.Lex(Tok);
1088 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001089 }
1090
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001091 // Reserve a buffer to get the spelling.
1092 SmallString<128> FilenameBuffer;
1093 StringRef Filename;
1094 SourceLocation EndLoc;
1095
1096 switch (Tok.getKind()) {
1097 case tok::eod:
1098 // If the token kind is EOD, the error has already been diagnosed.
1099 return false;
1100
1101 case tok::angle_string_literal:
1102 case tok::string_literal: {
1103 bool Invalid = false;
1104 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
1105 if (Invalid)
1106 return false;
1107 break;
1108 }
1109
1110 case tok::less:
1111 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1112 // case, glue the tokens together into FilenameBuffer and interpret those.
1113 FilenameBuffer.push_back('<');
Richard Trieuda031982012-10-22 20:28:48 +00001114 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc)) {
1115 // Let the caller know a <eod> was found by changing the Token kind.
1116 Tok.setKind(tok::eod);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001117 return false; // Found <eod> but no ">"? Diagnostic already emitted.
Richard Trieuda031982012-10-22 20:28:48 +00001118 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001119 Filename = FilenameBuffer.str();
1120 break;
1121 default:
1122 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
1123 return false;
1124 }
1125
Richard Trieuda031982012-10-22 20:28:48 +00001126 SourceLocation FilenameLoc = Tok.getLocation();
1127
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001128 // Get ')'.
1129 PP.LexNonComment(Tok);
1130
1131 // Ensure we have a trailing ).
1132 if (Tok.isNot(tok::r_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001133 PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after)
1134 << II << tok::r_paren;
Alp Tokerec543272013-12-24 09:48:30 +00001135 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001136 return false;
1137 }
1138
1139 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
1140 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1141 // error.
1142 if (Filename.empty())
1143 return false;
1144
1145 // Search include directories.
1146 const DirectoryLookup *CurDir;
1147 const FileEntry *File =
Craig Topperd2d442c2014-05-17 23:10:59 +00001148 PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, CurDir,
1149 nullptr, nullptr, nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001150
1151 // Get the result value. A result of true means the file exists.
Craig Topperd2d442c2014-05-17 23:10:59 +00001152 return File != nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001153}
1154
1155/// EvaluateHasInclude - Process a '__has_include("path")' expression.
1156/// Returns true if successful.
1157static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
1158 Preprocessor &PP) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001159 return EvaluateHasIncludeCommon(Tok, II, PP, nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001160}
1161
1162/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
1163/// Returns true if successful.
1164static bool EvaluateHasIncludeNext(Token &Tok,
1165 IdentifierInfo *II, Preprocessor &PP) {
1166 // __has_include_next is like __has_include, except that we start
1167 // searching after the current found directory. If we can't do this,
1168 // issue a diagnostic.
1169 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
1170 if (PP.isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001171 Lookup = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001172 PP.Diag(Tok, diag::pp_include_next_in_primary);
Craig Topperd2d442c2014-05-17 23:10:59 +00001173 } else if (!Lookup) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001174 PP.Diag(Tok, diag::pp_include_next_absolute_path);
1175 } else {
1176 // Start looking up in the next directory.
1177 ++Lookup;
1178 }
1179
1180 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup);
1181}
1182
Douglas Gregorc83de302012-09-25 15:44:52 +00001183/// \brief Process __building_module(identifier) expression.
1184/// \returns true if we are building the named module, false otherwise.
1185static bool EvaluateBuildingModule(Token &Tok,
1186 IdentifierInfo *II, Preprocessor &PP) {
1187 // Get '('.
1188 PP.LexNonComment(Tok);
1189
1190 // Ensure we have a '('.
1191 if (Tok.isNot(tok::l_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001192 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1193 << tok::l_paren;
Douglas Gregorc83de302012-09-25 15:44:52 +00001194 return false;
1195 }
1196
1197 // Save '(' location for possible missing ')' message.
1198 SourceLocation LParenLoc = Tok.getLocation();
1199
1200 // Get the module name.
1201 PP.LexNonComment(Tok);
1202
1203 // Ensure that we have an identifier.
1204 if (Tok.isNot(tok::identifier)) {
1205 PP.Diag(Tok.getLocation(), diag::err_expected_id_building_module);
1206 return false;
1207 }
1208
1209 bool Result
1210 = Tok.getIdentifierInfo()->getName() == PP.getLangOpts().CurrentModule;
1211
1212 // Get ')'.
1213 PP.LexNonComment(Tok);
1214
1215 // Ensure we have a trailing ).
1216 if (Tok.isNot(tok::r_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001217 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1218 << tok::r_paren;
Alp Tokerec543272013-12-24 09:48:30 +00001219 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
Douglas Gregorc83de302012-09-25 15:44:52 +00001220 return false;
1221 }
1222
1223 return Result;
1224}
1225
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001226/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1227/// as a builtin macro, handle it and return the next token as 'Tok'.
1228void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
1229 // Figure out which token this is.
1230 IdentifierInfo *II = Tok.getIdentifierInfo();
1231 assert(II && "Can't be a macro without id info!");
1232
1233 // If this is an _Pragma or Microsoft __pragma directive, expand it,
1234 // invoke the pragma handler, then lex the token after it.
1235 if (II == Ident_Pragma)
1236 return Handle_Pragma(Tok);
1237 else if (II == Ident__pragma) // in non-MS mode this is null
1238 return HandleMicrosoft__pragma(Tok);
1239
1240 ++NumBuiltinMacroExpanded;
1241
1242 SmallString<128> TmpBuffer;
1243 llvm::raw_svector_ostream OS(TmpBuffer);
1244
1245 // Set up the return result.
Craig Topperd2d442c2014-05-17 23:10:59 +00001246 Tok.setIdentifierInfo(nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001247 Tok.clearFlag(Token::NeedsCleaning);
1248
1249 if (II == Ident__LINE__) {
1250 // C99 6.10.8: "__LINE__: The presumed line number (within the current
1251 // source file) of the current source line (an integer constant)". This can
1252 // be affected by #line.
1253 SourceLocation Loc = Tok.getLocation();
1254
1255 // Advance to the location of the first _, this might not be the first byte
1256 // of the token if it starts with an escaped newline.
1257 Loc = AdvanceToTokenCharacter(Loc, 0);
1258
1259 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
1260 // a macro expansion. This doesn't matter for object-like macros, but
1261 // can matter for a function-like macro that expands to contain __LINE__.
1262 // Skip down through expansion points until we find a file loc for the
1263 // end of the expansion history.
1264 Loc = SourceMgr.getExpansionRange(Loc).second;
1265 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
1266
1267 // __LINE__ expands to a simple numeric value.
1268 OS << (PLoc.isValid()? PLoc.getLine() : 1);
1269 Tok.setKind(tok::numeric_constant);
1270 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
1271 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
1272 // character string literal)". This can be affected by #line.
1273 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1274
1275 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
1276 // #include stack instead of the current file.
1277 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
1278 SourceLocation NextLoc = PLoc.getIncludeLoc();
1279 while (NextLoc.isValid()) {
1280 PLoc = SourceMgr.getPresumedLoc(NextLoc);
1281 if (PLoc.isInvalid())
1282 break;
1283
1284 NextLoc = PLoc.getIncludeLoc();
1285 }
1286 }
1287
1288 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
1289 SmallString<128> FN;
1290 if (PLoc.isValid()) {
1291 FN += PLoc.getFilename();
1292 Lexer::Stringify(FN);
1293 OS << '"' << FN.str() << '"';
1294 }
1295 Tok.setKind(tok::string_literal);
1296 } else if (II == Ident__DATE__) {
1297 if (!DATELoc.isValid())
1298 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1299 Tok.setKind(tok::string_literal);
1300 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1301 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
1302 Tok.getLocation(),
1303 Tok.getLength()));
1304 return;
1305 } else if (II == Ident__TIME__) {
1306 if (!TIMELoc.isValid())
1307 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1308 Tok.setKind(tok::string_literal);
1309 Tok.setLength(strlen("\"hh:mm:ss\""));
1310 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
1311 Tok.getLocation(),
1312 Tok.getLength()));
1313 return;
1314 } else if (II == Ident__INCLUDE_LEVEL__) {
1315 // Compute the presumed include depth of this token. This can be affected
1316 // by GNU line markers.
1317 unsigned Depth = 0;
1318
1319 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1320 if (PLoc.isValid()) {
1321 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1322 for (; PLoc.isValid(); ++Depth)
1323 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1324 }
1325
1326 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1327 OS << Depth;
1328 Tok.setKind(tok::numeric_constant);
1329 } else if (II == Ident__TIMESTAMP__) {
1330 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1331 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1332
1333 // Get the file that we are lexing out of. If we're currently lexing from
1334 // a macro, dig into the include stack.
Craig Topperd2d442c2014-05-17 23:10:59 +00001335 const FileEntry *CurFile = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001336 PreprocessorLexer *TheLexer = getCurrentFileLexer();
1337
1338 if (TheLexer)
1339 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
1340
1341 const char *Result;
1342 if (CurFile) {
1343 time_t TT = CurFile->getModificationTime();
1344 struct tm *TM = localtime(&TT);
1345 Result = asctime(TM);
1346 } else {
1347 Result = "??? ??? ?? ??:??:?? ????\n";
1348 }
1349 // Surround the string with " and strip the trailing newline.
1350 OS << '"' << StringRef(Result, strlen(Result)-1) << '"';
1351 Tok.setKind(tok::string_literal);
1352 } else if (II == Ident__COUNTER__) {
1353 // __COUNTER__ expands to a simple numeric value.
1354 OS << CounterValue++;
1355 Tok.setKind(tok::numeric_constant);
1356 } else if (II == Ident__has_feature ||
1357 II == Ident__has_extension ||
1358 II == Ident__has_builtin ||
Yunzhong Gaoef309f42014-04-11 20:55:19 +00001359 II == Ident__is_identifier ||
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001360 II == Ident__has_attribute) {
1361 // The argument to these builtins should be a parenthesized identifier.
1362 SourceLocation StartLoc = Tok.getLocation();
1363
1364 bool IsValid = false;
Craig Topperd2d442c2014-05-17 23:10:59 +00001365 IdentifierInfo *FeatureII = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001366
1367 // Read the '('.
Andy Gibbsd41d0942012-11-17 19:18:27 +00001368 LexUnexpandedToken(Tok);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001369 if (Tok.is(tok::l_paren)) {
1370 // Read the identifier
Andy Gibbsd41d0942012-11-17 19:18:27 +00001371 LexUnexpandedToken(Tok);
Richard Smithbaf29122013-07-09 00:57:56 +00001372 if ((FeatureII = Tok.getIdentifierInfo())) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001373 // Read the ')'.
Andy Gibbsd41d0942012-11-17 19:18:27 +00001374 LexUnexpandedToken(Tok);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001375 if (Tok.is(tok::r_paren))
1376 IsValid = true;
1377 }
1378 }
1379
1380 bool Value = false;
1381 if (!IsValid)
1382 Diag(StartLoc, diag::err_feature_check_malformed);
Yunzhong Gaoef309f42014-04-11 20:55:19 +00001383 else if (II == Ident__is_identifier)
1384 Value = FeatureII->getTokenID() == tok::identifier;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001385 else if (II == Ident__has_builtin) {
1386 // Check for a builtin is trivial.
1387 Value = FeatureII->getBuiltinID() != 0;
1388 } else if (II == Ident__has_attribute)
Aaron Ballman759c71d2014-03-31 15:26:40 +00001389 Value = hasAttribute(AttrSyntax::Generic, nullptr, FeatureII,
Aaron Ballman2fbf9942014-03-31 13:14:44 +00001390 getTargetInfo().getTriple(), getLangOpts());
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001391 else if (II == Ident__has_extension)
1392 Value = HasExtension(*this, FeatureII);
1393 else {
1394 assert(II == Ident__has_feature && "Must be feature check");
1395 Value = HasFeature(*this, FeatureII);
1396 }
1397
1398 OS << (int)Value;
1399 if (IsValid)
1400 Tok.setKind(tok::numeric_constant);
1401 } else if (II == Ident__has_include ||
1402 II == Ident__has_include_next) {
1403 // The argument to these two builtins should be a parenthesized
1404 // file name string literal using angle brackets (<>) or
1405 // double-quotes ("").
1406 bool Value;
1407 if (II == Ident__has_include)
1408 Value = EvaluateHasInclude(Tok, II, *this);
1409 else
1410 Value = EvaluateHasIncludeNext(Tok, II, *this);
1411 OS << (int)Value;
Richard Trieuda031982012-10-22 20:28:48 +00001412 if (Tok.is(tok::r_paren))
1413 Tok.setKind(tok::numeric_constant);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001414 } else if (II == Ident__has_warning) {
1415 // The argument should be a parenthesized string literal.
1416 // The argument to these builtins should be a parenthesized identifier.
1417 SourceLocation StartLoc = Tok.getLocation();
1418 bool IsValid = false;
1419 bool Value = false;
1420 // Read the '('.
Andy Gibbs58905d22012-11-17 19:15:38 +00001421 LexUnexpandedToken(Tok);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001422 do {
Andy Gibbs58905d22012-11-17 19:15:38 +00001423 if (Tok.isNot(tok::l_paren)) {
1424 Diag(StartLoc, diag::err_warning_check_malformed);
1425 break;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001426 }
Andy Gibbs58905d22012-11-17 19:15:38 +00001427
1428 LexUnexpandedToken(Tok);
1429 std::string WarningName;
1430 SourceLocation StrStartLoc = Tok.getLocation();
Andy Gibbsa8df57a2012-11-17 19:16:52 +00001431 if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",
1432 /*MacroExpansion=*/false)) {
Andy Gibbs58905d22012-11-17 19:15:38 +00001433 // Eat tokens until ')'.
Andy Gibbsb5b30c42012-11-17 22:17:28 +00001434 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) &&
1435 Tok.isNot(tok::eof))
Andy Gibbs58905d22012-11-17 19:15:38 +00001436 LexUnexpandedToken(Tok);
1437 break;
1438 }
1439
1440 // Is the end a ')'?
1441 if (!(IsValid = Tok.is(tok::r_paren))) {
1442 Diag(StartLoc, diag::err_warning_check_malformed);
1443 break;
1444 }
1445
1446 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1447 WarningName[1] != 'W') {
1448 Diag(StrStartLoc, diag::warn_has_warning_invalid_option);
1449 break;
1450 }
1451
1452 // Finally, check if the warning flags maps to a diagnostic group.
1453 // We construct a SmallVector here to talk to getDiagnosticIDs().
1454 // Although we don't use the result, this isn't a hot path, and not
1455 // worth special casing.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001456 SmallVector<diag::kind, 10> Diags;
Andy Gibbs58905d22012-11-17 19:15:38 +00001457 Value = !getDiagnostics().getDiagnosticIDs()->
1458 getDiagnosticsInGroup(WarningName.substr(2), Diags);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001459 } while (false);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001460
1461 OS << (int)Value;
Andy Gibbsf591982b2012-11-17 19:14:53 +00001462 if (IsValid)
1463 Tok.setKind(tok::numeric_constant);
Douglas Gregorc83de302012-09-25 15:44:52 +00001464 } else if (II == Ident__building_module) {
1465 // The argument to this builtin should be an identifier. The
1466 // builtin evaluates to 1 when that identifier names the module we are
1467 // currently building.
1468 OS << (int)EvaluateBuildingModule(Tok, II, *this);
1469 Tok.setKind(tok::numeric_constant);
1470 } else if (II == Ident__MODULE__) {
1471 // The current module as an identifier.
1472 OS << getLangOpts().CurrentModule;
1473 IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);
1474 Tok.setIdentifierInfo(ModuleII);
1475 Tok.setKind(ModuleII->getTokenID());
Richard Smithae385082014-03-15 00:06:08 +00001476 } else if (II == Ident__identifier) {
1477 SourceLocation Loc = Tok.getLocation();
1478
1479 // We're expecting '__identifier' '(' identifier ')'. Try to recover
1480 // if the parens are missing.
1481 LexNonComment(Tok);
1482 if (Tok.isNot(tok::l_paren)) {
1483 // No '(', use end of last token.
1484 Diag(getLocForEndOfToken(Loc), diag::err_pp_expected_after)
1485 << II << tok::l_paren;
1486 // If the next token isn't valid as our argument, we can't recover.
1487 if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1488 Tok.setKind(tok::identifier);
1489 return;
1490 }
1491
1492 SourceLocation LParenLoc = Tok.getLocation();
1493 LexNonComment(Tok);
1494
1495 if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1496 Tok.setKind(tok::identifier);
1497 else {
1498 Diag(Tok.getLocation(), diag::err_pp_identifier_arg_not_identifier)
1499 << Tok.getKind();
1500 // Don't walk past anything that's not a real token.
1501 if (Tok.is(tok::eof) || Tok.is(tok::eod) || Tok.isAnnotation())
1502 return;
1503 }
1504
1505 // Discard the ')', preserving 'Tok' as our result.
1506 Token RParen;
1507 LexNonComment(RParen);
1508 if (RParen.isNot(tok::r_paren)) {
1509 Diag(getLocForEndOfToken(Tok.getLocation()), diag::err_pp_expected_after)
1510 << Tok.getKind() << tok::r_paren;
1511 Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1512 }
1513 return;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001514 } else {
1515 llvm_unreachable("Unknown identifier!");
1516 }
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00001517 CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation());
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001518}
1519
1520void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
1521 // If the 'used' status changed, and the macro requires 'unused' warning,
1522 // remove its SourceLocation from the warn-for-unused-macro locations.
1523 if (MI->isWarnIfUnused() && !MI->isUsed())
1524 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1525 MI->setIsUsed(true);
1526}