blob: 4278faef708602f03b54fd3cb5f88b71f755ae7b [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);
678 for (SmallVector<SourceRange, 4>::iterator
679 Range = InitLists.begin(), RangeEnd = InitLists.end();
680 Range != RangeEnd; ++Range) {
681 if (DB.hasMaxRanges())
682 break;
683 DB << *Range;
684 }
685 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000686 return nullptr;
Richard Trieu79b45382013-07-23 18:01:49 +0000687 }
688 if (FixedNumArgs != MinArgsExpected)
Craig Topperd2d442c2014-05-17 23:10:59 +0000689 return nullptr;
Richard Trieu79b45382013-07-23 18:01:49 +0000690
691 DiagnosticBuilder DB = Diag(MacroName, diag::note_suggest_parens_for_macro);
692 for (SmallVector<SourceRange, 4>::iterator
693 ParenLocation = ParenHints.begin(), ParenEnd = ParenHints.end();
694 ParenLocation != ParenEnd; ++ParenLocation) {
695 if (DB.hasMaxFixItHints())
696 break;
697 DB << FixItHint::CreateInsertion(ParenLocation->getBegin(), "(");
698 if (DB.hasMaxFixItHints())
699 break;
700 DB << FixItHint::CreateInsertion(ParenLocation->getEnd(), ")");
701 }
702 ArgTokens.swap(FixedArgTokens);
703 NumActuals = FixedNumArgs;
704 }
705
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000706 // See MacroArgs instance var for description of this.
707 bool isVarargsElided = false;
708
Argyrios Kyrtzidisd4635d42012-12-21 01:51:12 +0000709 if (ContainsCodeCompletionTok) {
710 // Recover from not-fully-formed macro invocation during code-completion.
711 Token EOFTok;
712 EOFTok.startToken();
713 EOFTok.setKind(tok::eof);
714 EOFTok.setLocation(Tok.getLocation());
715 EOFTok.setLength(0);
716 for (; NumActuals < MinArgsExpected; ++NumActuals)
717 ArgTokens.push_back(EOFTok);
718 }
719
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000720 if (NumActuals < MinArgsExpected) {
721 // There are several cases where too few arguments is ok, handle them now.
722 if (NumActuals == 0 && MinArgsExpected == 1) {
723 // #define A(X) or #define A(...) ---> A()
724
725 // If there is exactly one argument, and that argument is missing,
726 // then we have an empty "()" argument empty list. This is fine, even if
727 // the macro expects one argument (the argument is just empty).
728 isVarargsElided = MI->isVariadic();
729 } else if (MI->isVariadic() &&
730 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
731 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
732 // Varargs where the named vararg parameter is missing: OK as extension.
733 // #define A(x, ...)
734 // A("blah")
Eli Friedman14d3c792012-11-14 02:18:46 +0000735 //
736 // If the macro contains the comma pasting extension, the diagnostic
737 // is suppressed; we know we'll get another diagnostic later.
738 if (!MI->hasCommaPasting()) {
739 Diag(Tok, diag::ext_missing_varargs_arg);
740 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
741 << MacroName.getIdentifierInfo();
742 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000743
744 // Remember this occurred, allowing us to elide the comma when used for
745 // cases like:
746 // #define A(x, foo...) blah(a, ## foo)
747 // #define B(x, ...) blah(a, ## __VA_ARGS__)
748 // #define C(...) blah(a, ## __VA_ARGS__)
749 // A(x) B(x) C()
750 isVarargsElided = true;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000751 } else if (!ContainsCodeCompletionTok) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000752 // Otherwise, emit the error.
753 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Argyrios Kyrtzidis164fdb62012-12-14 18:53:47 +0000754 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
755 << MacroName.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000756 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000757 }
758
759 // Add a marker EOF token to the end of the token list for this argument.
760 SourceLocation EndLoc = Tok.getLocation();
761 Tok.startToken();
762 Tok.setKind(tok::eof);
763 Tok.setLocation(EndLoc);
764 Tok.setLength(0);
765 ArgTokens.push_back(Tok);
766
767 // If we expect two arguments, add both as empty.
768 if (NumActuals == 0 && MinArgsExpected == 2)
769 ArgTokens.push_back(Tok);
770
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000771 } else if (NumActuals > MinArgsExpected && !MI->isVariadic() &&
772 !ContainsCodeCompletionTok) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000773 // Emit the diagnostic at the macro name in case there is a missing ).
774 // Emitting it at the , could be far away from the macro name.
775 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Argyrios Kyrtzidis164fdb62012-12-14 18:53:47 +0000776 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
777 << MacroName.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000778 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000779 }
780
781 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
782}
783
784/// \brief Keeps macro expanded tokens for TokenLexers.
785//
786/// Works like a stack; a TokenLexer adds the macro expanded tokens that is
787/// going to lex in the cache and when it finishes the tokens are removed
788/// from the end of the cache.
789Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
790 ArrayRef<Token> tokens) {
791 assert(tokLexer);
792 if (tokens.empty())
Craig Topperd2d442c2014-05-17 23:10:59 +0000793 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000794
795 size_t newIndex = MacroExpandedTokens.size();
796 bool cacheNeedsToGrow = tokens.size() >
797 MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
798 MacroExpandedTokens.append(tokens.begin(), tokens.end());
799
800 if (cacheNeedsToGrow) {
801 // Go through all the TokenLexers whose 'Tokens' pointer points in the
802 // buffer and update the pointers to the (potential) new buffer array.
803 for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) {
804 TokenLexer *prevLexer;
805 size_t tokIndex;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000806 std::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i];
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000807 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
808 }
809 }
810
811 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
812 return MacroExpandedTokens.data() + newIndex;
813}
814
815void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
816 assert(!MacroExpandingLexersStack.empty());
817 size_t tokIndex = MacroExpandingLexersStack.back().second;
818 assert(tokIndex < MacroExpandedTokens.size());
819 // Pop the cached macro expanded tokens from the end.
820 MacroExpandedTokens.resize(tokIndex);
821 MacroExpandingLexersStack.pop_back();
822}
823
824/// ComputeDATE_TIME - Compute the current time, enter it into the specified
825/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
826/// the identifier tokens inserted.
827static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
828 Preprocessor &PP) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000829 time_t TT = time(nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000830 struct tm *TM = localtime(&TT);
831
832 static const char * const Months[] = {
833 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
834 };
835
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000836 {
837 SmallString<32> TmpBuffer;
838 llvm::raw_svector_ostream TmpStream(TmpBuffer);
839 TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
840 TM->tm_mday, TM->tm_year + 1900);
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 DATELoc = TmpTok.getLocation();
845 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000846
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000847 {
848 SmallString<32> TmpBuffer;
849 llvm::raw_svector_ostream TmpStream(TmpBuffer);
850 TmpStream << llvm::format("\"%02d:%02d:%02d\"",
851 TM->tm_hour, TM->tm_min, TM->tm_sec);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000852 Token TmpTok;
853 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000854 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000855 TIMELoc = TmpTok.getLocation();
856 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000857}
858
859
860/// HasFeature - Return true if we recognize and implement the feature
861/// specified by the identifier as a standard language feature.
862static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
863 const LangOptions &LangOpts = PP.getLangOpts();
864 StringRef Feature = II->getName();
865
866 // Normalize the feature name, __foo__ becomes foo.
867 if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4)
868 Feature = Feature.substr(2, Feature.size() - 4);
869
870 return llvm::StringSwitch<bool>(Feature)
Will Dietzf54319c2013-01-18 11:30:38 +0000871 .Case("address_sanitizer", LangOpts.Sanitize.Address)
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000872 .Case("attribute_analyzer_noreturn", true)
873 .Case("attribute_availability", true)
874 .Case("attribute_availability_with_message", true)
875 .Case("attribute_cf_returns_not_retained", true)
876 .Case("attribute_cf_returns_retained", true)
877 .Case("attribute_deprecated_with_message", true)
878 .Case("attribute_ext_vector_type", true)
879 .Case("attribute_ns_returns_not_retained", true)
880 .Case("attribute_ns_returns_retained", true)
881 .Case("attribute_ns_consumes_self", true)
882 .Case("attribute_ns_consumed", true)
883 .Case("attribute_cf_consumed", true)
884 .Case("attribute_objc_ivar_unused", true)
885 .Case("attribute_objc_method_family", true)
886 .Case("attribute_overloadable", true)
887 .Case("attribute_unavailable_with_message", true)
888 .Case("attribute_unused_on_fields", true)
889 .Case("blocks", LangOpts.Blocks)
David Blaikie021221d2013-07-29 18:24:03 +0000890 .Case("c_thread_safety_attributes", true)
Justin Bogner4e3a01f2014-04-16 02:56:48 +0000891 .Case("cxx_exceptions", LangOpts.CXXExceptions)
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000892 .Case("cxx_rtti", LangOpts.RTTI)
893 .Case("enumerator_attributes", true)
Will Dietzf54319c2013-01-18 11:30:38 +0000894 .Case("memory_sanitizer", LangOpts.Sanitize.Memory)
895 .Case("thread_sanitizer", LangOpts.Sanitize.Thread)
Peter Collingbournec3772752013-08-07 22:47:34 +0000896 .Case("dataflow_sanitizer", LangOpts.Sanitize.DataFlow)
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000897 // Objective-C features
898 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
899 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
900 .Case("objc_arc_weak", LangOpts.ObjCARCWeak)
901 .Case("objc_default_synthesize_properties", LangOpts.ObjC2)
902 .Case("objc_fixed_enum", LangOpts.ObjC2)
903 .Case("objc_instancetype", LangOpts.ObjC2)
904 .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules)
905 .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile())
Ted Kremenekdae8f9f2013-01-04 19:04:44 +0000906 .Case("objc_property_explicit_atomic", true) // Does clang support explicit "atomic" keyword?
Ted Kremenekb0cba4c2013-10-14 23:48:27 +0000907 .Case("objc_protocol_qualifier_mangling", true)
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000908 .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport())
909 .Case("ownership_holds", true)
910 .Case("ownership_returns", true)
911 .Case("ownership_takes", true)
912 .Case("objc_bool", true)
913 .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile())
914 .Case("objc_array_literals", LangOpts.ObjC2)
915 .Case("objc_dictionary_literals", LangOpts.ObjC2)
916 .Case("objc_boxed_expressions", LangOpts.ObjC2)
917 .Case("arc_cf_code_audited", true)
918 // C11 features
919 .Case("c_alignas", LangOpts.C11)
920 .Case("c_atomic", LangOpts.C11)
921 .Case("c_generic_selections", LangOpts.C11)
922 .Case("c_static_assert", LangOpts.C11)
Richard Smith6d540142014-05-09 21:08:59 +0000923 .Case("c_thread_local",
Douglas Gregora7130bf2013-05-02 05:28:32 +0000924 LangOpts.C11 && PP.getTargetInfo().isTLSSupported())
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000925 // C++11 features
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000926 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus11)
927 .Case("cxx_alias_templates", LangOpts.CPlusPlus11)
928 .Case("cxx_alignas", LangOpts.CPlusPlus11)
929 .Case("cxx_atomic", LangOpts.CPlusPlus11)
930 .Case("cxx_attributes", LangOpts.CPlusPlus11)
931 .Case("cxx_auto_type", LangOpts.CPlusPlus11)
932 .Case("cxx_constexpr", LangOpts.CPlusPlus11)
933 .Case("cxx_decltype", LangOpts.CPlusPlus11)
934 .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus11)
935 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus11)
936 .Case("cxx_defaulted_functions", LangOpts.CPlusPlus11)
937 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus11)
938 .Case("cxx_deleted_functions", LangOpts.CPlusPlus11)
939 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus11)
940 .Case("cxx_generalized_initializers", LangOpts.CPlusPlus11)
941 .Case("cxx_implicit_moves", LangOpts.CPlusPlus11)
Richard Smith25b555a2013-04-19 17:00:31 +0000942 .Case("cxx_inheriting_constructors", LangOpts.CPlusPlus11)
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000943 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus11)
944 .Case("cxx_lambdas", LangOpts.CPlusPlus11)
945 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus11)
946 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus11)
947 .Case("cxx_noexcept", LangOpts.CPlusPlus11)
948 .Case("cxx_nullptr", LangOpts.CPlusPlus11)
949 .Case("cxx_override_control", LangOpts.CPlusPlus11)
950 .Case("cxx_range_for", LangOpts.CPlusPlus11)
951 .Case("cxx_raw_string_literals", LangOpts.CPlusPlus11)
952 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus11)
953 .Case("cxx_rvalue_references", LangOpts.CPlusPlus11)
954 .Case("cxx_strong_enums", LangOpts.CPlusPlus11)
955 .Case("cxx_static_assert", LangOpts.CPlusPlus11)
Richard Smithb438e622013-09-28 04:37:56 +0000956 .Case("cxx_thread_local",
Douglas Gregora7130bf2013-05-02 05:28:32 +0000957 LangOpts.CPlusPlus11 && PP.getTargetInfo().isTLSSupported())
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000958 .Case("cxx_trailing_return", LangOpts.CPlusPlus11)
959 .Case("cxx_unicode_literals", LangOpts.CPlusPlus11)
960 .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus11)
961 .Case("cxx_user_literals", LangOpts.CPlusPlus11)
962 .Case("cxx_variadic_templates", LangOpts.CPlusPlus11)
Richard Smith0a715422013-05-07 19:32:56 +0000963 // C++1y features
Richard Smith4fb09722013-07-24 17:51:13 +0000964 .Case("cxx_aggregate_nsdmi", LangOpts.CPlusPlus1y)
Richard Smith0a715422013-05-07 19:32:56 +0000965 .Case("cxx_binary_literals", LangOpts.CPlusPlus1y)
Richard Smithc0f7b812013-07-24 17:41:31 +0000966 .Case("cxx_contextual_conversions", LangOpts.CPlusPlus1y)
Richard Smith6d540142014-05-09 21:08:59 +0000967 .Case("cxx_decltype_auto", LangOpts.CPlusPlus1y)
968 .Case("cxx_generic_lambdas", LangOpts.CPlusPlus1y)
Richard Smithb438e622013-09-28 04:37:56 +0000969 .Case("cxx_init_captures", LangOpts.CPlusPlus1y)
Richard Smithc0f7b812013-07-24 17:41:31 +0000970 .Case("cxx_relaxed_constexpr", LangOpts.CPlusPlus1y)
Richard Smith9155be12013-05-12 03:09:35 +0000971 .Case("cxx_return_type_deduction", LangOpts.CPlusPlus1y)
Richard Smithdca0c7a2013-09-27 20:19:41 +0000972 .Case("cxx_variable_templates", LangOpts.CPlusPlus1y)
Richard Smith6d540142014-05-09 21:08:59 +0000973 // C++ TSes
974 //.Case("cxx_runtime_arrays", LangOpts.CPlusPlusTSArrays)
975 //.Case("cxx_concepts", LangOpts.CPlusPlusTSConcepts)
976 // FIXME: Should this be __has_feature or __has_extension?
977 //.Case("raw_invocation_type", LangOpts.CPlusPlus)
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000978 // Type traits
979 .Case("has_nothrow_assign", LangOpts.CPlusPlus)
980 .Case("has_nothrow_copy", LangOpts.CPlusPlus)
981 .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
982 .Case("has_trivial_assign", LangOpts.CPlusPlus)
983 .Case("has_trivial_copy", LangOpts.CPlusPlus)
984 .Case("has_trivial_constructor", LangOpts.CPlusPlus)
985 .Case("has_trivial_destructor", LangOpts.CPlusPlus)
986 .Case("has_virtual_destructor", LangOpts.CPlusPlus)
987 .Case("is_abstract", LangOpts.CPlusPlus)
988 .Case("is_base_of", LangOpts.CPlusPlus)
989 .Case("is_class", LangOpts.CPlusPlus)
Marshall Clowd28acc02014-03-18 14:13:10 +0000990 .Case("is_constructible", LangOpts.CPlusPlus)
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000991 .Case("is_convertible_to", LangOpts.CPlusPlus)
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000992 .Case("is_empty", LangOpts.CPlusPlus)
993 .Case("is_enum", LangOpts.CPlusPlus)
994 .Case("is_final", LangOpts.CPlusPlus)
995 .Case("is_literal", LangOpts.CPlusPlus)
996 .Case("is_standard_layout", LangOpts.CPlusPlus)
997 .Case("is_pod", LangOpts.CPlusPlus)
998 .Case("is_polymorphic", LangOpts.CPlusPlus)
David Majnemera5433082013-10-18 00:33:31 +0000999 .Case("is_sealed", LangOpts.MicrosoftExt)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001000 .Case("is_trivial", LangOpts.CPlusPlus)
1001 .Case("is_trivially_assignable", LangOpts.CPlusPlus)
1002 .Case("is_trivially_constructible", LangOpts.CPlusPlus)
1003 .Case("is_trivially_copyable", LangOpts.CPlusPlus)
1004 .Case("is_union", LangOpts.CPlusPlus)
1005 .Case("modules", LangOpts.Modules)
1006 .Case("tls", PP.getTargetInfo().isTLSSupported())
1007 .Case("underlying_type", LangOpts.CPlusPlus)
1008 .Default(false);
1009}
1010
1011/// HasExtension - Return true if we recognize and implement the feature
1012/// specified by the identifier, either as an extension or a standard language
1013/// feature.
1014static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) {
1015 if (HasFeature(PP, II))
1016 return true;
1017
1018 // If the use of an extension results in an error diagnostic, extensions are
1019 // effectively unavailable, so just return false here.
1020 if (PP.getDiagnostics().getExtensionHandlingBehavior() ==
1021 DiagnosticsEngine::Ext_Error)
1022 return false;
1023
1024 const LangOptions &LangOpts = PP.getLangOpts();
1025 StringRef Extension = II->getName();
1026
1027 // Normalize the extension name, __foo__ becomes foo.
1028 if (Extension.startswith("__") && Extension.endswith("__") &&
1029 Extension.size() >= 4)
1030 Extension = Extension.substr(2, Extension.size() - 4);
1031
1032 // Because we inherit the feature list from HasFeature, this string switch
1033 // must be less restrictive than HasFeature's.
1034 return llvm::StringSwitch<bool>(Extension)
1035 // C11 features supported by other languages as extensions.
1036 .Case("c_alignas", true)
1037 .Case("c_atomic", true)
1038 .Case("c_generic_selections", true)
1039 .Case("c_static_assert", true)
Ed Schouten401aeba2013-09-14 16:17:20 +00001040 .Case("c_thread_local", PP.getTargetInfo().isTLSSupported())
Richard Smith0a715422013-05-07 19:32:56 +00001041 // C++11 features supported by other languages as extensions.
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001042 .Case("cxx_atomic", LangOpts.CPlusPlus)
1043 .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
1044 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
1045 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
1046 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus)
1047 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
1048 .Case("cxx_override_control", LangOpts.CPlusPlus)
1049 .Case("cxx_range_for", LangOpts.CPlusPlus)
1050 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
1051 .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
Richard Smith0a715422013-05-07 19:32:56 +00001052 // C++1y features supported by other languages as extensions.
1053 .Case("cxx_binary_literals", true)
Richard Smithb438e622013-09-28 04:37:56 +00001054 .Case("cxx_init_captures", LangOpts.CPlusPlus11)
Alp Tokera8bb9c92014-01-15 04:11:24 +00001055 .Case("cxx_variable_templates", LangOpts.CPlusPlus)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001056 .Default(false);
1057}
1058
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001059/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
1060/// or '__has_include_next("path")' expression.
1061/// Returns true if successful.
1062static bool EvaluateHasIncludeCommon(Token &Tok,
1063 IdentifierInfo *II, Preprocessor &PP,
1064 const DirectoryLookup *LookupFrom) {
Richard Trieuda031982012-10-22 20:28:48 +00001065 // Save the location of the current token. If a '(' is later found, use
Aaron Ballman5cb24112013-01-15 21:59:46 +00001066 // that location. If not, use the end of this location instead.
Richard Trieuda031982012-10-22 20:28:48 +00001067 SourceLocation LParenLoc = Tok.getLocation();
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001068
Aaron Ballman6ce00002013-01-16 19:32:21 +00001069 // These expressions are only allowed within a preprocessor directive.
1070 if (!PP.isParsingIfOrElifDirective()) {
1071 PP.Diag(LParenLoc, diag::err_pp_directive_required) << II->getName();
1072 return false;
1073 }
1074
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001075 // Get '('.
1076 PP.LexNonComment(Tok);
1077
1078 // Ensure we have a '('.
1079 if (Tok.isNot(tok::l_paren)) {
Richard Trieuda031982012-10-22 20:28:48 +00001080 // No '(', use end of last token.
1081 LParenLoc = PP.getLocForEndOfToken(LParenLoc);
Alp Toker751d6352013-12-30 01:59:29 +00001082 PP.Diag(LParenLoc, diag::err_pp_expected_after) << II << tok::l_paren;
Richard Trieuda031982012-10-22 20:28:48 +00001083 // If the next token looks like a filename or the start of one,
1084 // assume it is and process it as such.
1085 if (!Tok.is(tok::angle_string_literal) && !Tok.is(tok::string_literal) &&
1086 !Tok.is(tok::less))
1087 return false;
1088 } else {
1089 // Save '(' location for possible missing ')' message.
1090 LParenLoc = Tok.getLocation();
1091
Eli Friedmanec94b612013-01-09 02:20:00 +00001092 if (PP.getCurrentLexer()) {
1093 // Get the file name.
1094 PP.getCurrentLexer()->LexIncludeFilename(Tok);
1095 } else {
1096 // We're in a macro, so we can't use LexIncludeFilename; just
1097 // grab the next token.
1098 PP.Lex(Tok);
1099 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001100 }
1101
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001102 // Reserve a buffer to get the spelling.
1103 SmallString<128> FilenameBuffer;
1104 StringRef Filename;
1105 SourceLocation EndLoc;
1106
1107 switch (Tok.getKind()) {
1108 case tok::eod:
1109 // If the token kind is EOD, the error has already been diagnosed.
1110 return false;
1111
1112 case tok::angle_string_literal:
1113 case tok::string_literal: {
1114 bool Invalid = false;
1115 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
1116 if (Invalid)
1117 return false;
1118 break;
1119 }
1120
1121 case tok::less:
1122 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1123 // case, glue the tokens together into FilenameBuffer and interpret those.
1124 FilenameBuffer.push_back('<');
Richard Trieuda031982012-10-22 20:28:48 +00001125 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc)) {
1126 // Let the caller know a <eod> was found by changing the Token kind.
1127 Tok.setKind(tok::eod);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001128 return false; // Found <eod> but no ">"? Diagnostic already emitted.
Richard Trieuda031982012-10-22 20:28:48 +00001129 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001130 Filename = FilenameBuffer.str();
1131 break;
1132 default:
1133 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
1134 return false;
1135 }
1136
Richard Trieuda031982012-10-22 20:28:48 +00001137 SourceLocation FilenameLoc = Tok.getLocation();
1138
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001139 // Get ')'.
1140 PP.LexNonComment(Tok);
1141
1142 // Ensure we have a trailing ).
1143 if (Tok.isNot(tok::r_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001144 PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after)
1145 << II << tok::r_paren;
Alp Tokerec543272013-12-24 09:48:30 +00001146 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001147 return false;
1148 }
1149
1150 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
1151 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1152 // error.
1153 if (Filename.empty())
1154 return false;
1155
1156 // Search include directories.
1157 const DirectoryLookup *CurDir;
1158 const FileEntry *File =
Craig Topperd2d442c2014-05-17 23:10:59 +00001159 PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, CurDir,
1160 nullptr, nullptr, nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001161
1162 // Get the result value. A result of true means the file exists.
Craig Topperd2d442c2014-05-17 23:10:59 +00001163 return File != nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001164}
1165
1166/// EvaluateHasInclude - Process a '__has_include("path")' expression.
1167/// Returns true if successful.
1168static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
1169 Preprocessor &PP) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001170 return EvaluateHasIncludeCommon(Tok, II, PP, nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001171}
1172
1173/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
1174/// Returns true if successful.
1175static bool EvaluateHasIncludeNext(Token &Tok,
1176 IdentifierInfo *II, Preprocessor &PP) {
1177 // __has_include_next is like __has_include, except that we start
1178 // searching after the current found directory. If we can't do this,
1179 // issue a diagnostic.
1180 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
1181 if (PP.isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001182 Lookup = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001183 PP.Diag(Tok, diag::pp_include_next_in_primary);
Craig Topperd2d442c2014-05-17 23:10:59 +00001184 } else if (!Lookup) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001185 PP.Diag(Tok, diag::pp_include_next_absolute_path);
1186 } else {
1187 // Start looking up in the next directory.
1188 ++Lookup;
1189 }
1190
1191 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup);
1192}
1193
Douglas Gregorc83de302012-09-25 15:44:52 +00001194/// \brief Process __building_module(identifier) expression.
1195/// \returns true if we are building the named module, false otherwise.
1196static bool EvaluateBuildingModule(Token &Tok,
1197 IdentifierInfo *II, Preprocessor &PP) {
1198 // Get '('.
1199 PP.LexNonComment(Tok);
1200
1201 // Ensure we have a '('.
1202 if (Tok.isNot(tok::l_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001203 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1204 << tok::l_paren;
Douglas Gregorc83de302012-09-25 15:44:52 +00001205 return false;
1206 }
1207
1208 // Save '(' location for possible missing ')' message.
1209 SourceLocation LParenLoc = Tok.getLocation();
1210
1211 // Get the module name.
1212 PP.LexNonComment(Tok);
1213
1214 // Ensure that we have an identifier.
1215 if (Tok.isNot(tok::identifier)) {
1216 PP.Diag(Tok.getLocation(), diag::err_expected_id_building_module);
1217 return false;
1218 }
1219
1220 bool Result
1221 = Tok.getIdentifierInfo()->getName() == PP.getLangOpts().CurrentModule;
1222
1223 // Get ')'.
1224 PP.LexNonComment(Tok);
1225
1226 // Ensure we have a trailing ).
1227 if (Tok.isNot(tok::r_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001228 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1229 << tok::r_paren;
Alp Tokerec543272013-12-24 09:48:30 +00001230 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
Douglas Gregorc83de302012-09-25 15:44:52 +00001231 return false;
1232 }
1233
1234 return Result;
1235}
1236
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001237/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1238/// as a builtin macro, handle it and return the next token as 'Tok'.
1239void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
1240 // Figure out which token this is.
1241 IdentifierInfo *II = Tok.getIdentifierInfo();
1242 assert(II && "Can't be a macro without id info!");
1243
1244 // If this is an _Pragma or Microsoft __pragma directive, expand it,
1245 // invoke the pragma handler, then lex the token after it.
1246 if (II == Ident_Pragma)
1247 return Handle_Pragma(Tok);
1248 else if (II == Ident__pragma) // in non-MS mode this is null
1249 return HandleMicrosoft__pragma(Tok);
1250
1251 ++NumBuiltinMacroExpanded;
1252
1253 SmallString<128> TmpBuffer;
1254 llvm::raw_svector_ostream OS(TmpBuffer);
1255
1256 // Set up the return result.
Craig Topperd2d442c2014-05-17 23:10:59 +00001257 Tok.setIdentifierInfo(nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001258 Tok.clearFlag(Token::NeedsCleaning);
1259
1260 if (II == Ident__LINE__) {
1261 // C99 6.10.8: "__LINE__: The presumed line number (within the current
1262 // source file) of the current source line (an integer constant)". This can
1263 // be affected by #line.
1264 SourceLocation Loc = Tok.getLocation();
1265
1266 // Advance to the location of the first _, this might not be the first byte
1267 // of the token if it starts with an escaped newline.
1268 Loc = AdvanceToTokenCharacter(Loc, 0);
1269
1270 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
1271 // a macro expansion. This doesn't matter for object-like macros, but
1272 // can matter for a function-like macro that expands to contain __LINE__.
1273 // Skip down through expansion points until we find a file loc for the
1274 // end of the expansion history.
1275 Loc = SourceMgr.getExpansionRange(Loc).second;
1276 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
1277
1278 // __LINE__ expands to a simple numeric value.
1279 OS << (PLoc.isValid()? PLoc.getLine() : 1);
1280 Tok.setKind(tok::numeric_constant);
1281 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
1282 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
1283 // character string literal)". This can be affected by #line.
1284 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1285
1286 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
1287 // #include stack instead of the current file.
1288 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
1289 SourceLocation NextLoc = PLoc.getIncludeLoc();
1290 while (NextLoc.isValid()) {
1291 PLoc = SourceMgr.getPresumedLoc(NextLoc);
1292 if (PLoc.isInvalid())
1293 break;
1294
1295 NextLoc = PLoc.getIncludeLoc();
1296 }
1297 }
1298
1299 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
1300 SmallString<128> FN;
1301 if (PLoc.isValid()) {
1302 FN += PLoc.getFilename();
1303 Lexer::Stringify(FN);
1304 OS << '"' << FN.str() << '"';
1305 }
1306 Tok.setKind(tok::string_literal);
1307 } else if (II == Ident__DATE__) {
1308 if (!DATELoc.isValid())
1309 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1310 Tok.setKind(tok::string_literal);
1311 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1312 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
1313 Tok.getLocation(),
1314 Tok.getLength()));
1315 return;
1316 } else if (II == Ident__TIME__) {
1317 if (!TIMELoc.isValid())
1318 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1319 Tok.setKind(tok::string_literal);
1320 Tok.setLength(strlen("\"hh:mm:ss\""));
1321 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
1322 Tok.getLocation(),
1323 Tok.getLength()));
1324 return;
1325 } else if (II == Ident__INCLUDE_LEVEL__) {
1326 // Compute the presumed include depth of this token. This can be affected
1327 // by GNU line markers.
1328 unsigned Depth = 0;
1329
1330 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1331 if (PLoc.isValid()) {
1332 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1333 for (; PLoc.isValid(); ++Depth)
1334 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1335 }
1336
1337 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1338 OS << Depth;
1339 Tok.setKind(tok::numeric_constant);
1340 } else if (II == Ident__TIMESTAMP__) {
1341 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1342 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1343
1344 // Get the file that we are lexing out of. If we're currently lexing from
1345 // a macro, dig into the include stack.
Craig Topperd2d442c2014-05-17 23:10:59 +00001346 const FileEntry *CurFile = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001347 PreprocessorLexer *TheLexer = getCurrentFileLexer();
1348
1349 if (TheLexer)
1350 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
1351
1352 const char *Result;
1353 if (CurFile) {
1354 time_t TT = CurFile->getModificationTime();
1355 struct tm *TM = localtime(&TT);
1356 Result = asctime(TM);
1357 } else {
1358 Result = "??? ??? ?? ??:??:?? ????\n";
1359 }
1360 // Surround the string with " and strip the trailing newline.
1361 OS << '"' << StringRef(Result, strlen(Result)-1) << '"';
1362 Tok.setKind(tok::string_literal);
1363 } else if (II == Ident__COUNTER__) {
1364 // __COUNTER__ expands to a simple numeric value.
1365 OS << CounterValue++;
1366 Tok.setKind(tok::numeric_constant);
1367 } else if (II == Ident__has_feature ||
1368 II == Ident__has_extension ||
1369 II == Ident__has_builtin ||
Yunzhong Gaoef309f42014-04-11 20:55:19 +00001370 II == Ident__is_identifier ||
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001371 II == Ident__has_attribute) {
1372 // The argument to these builtins should be a parenthesized identifier.
1373 SourceLocation StartLoc = Tok.getLocation();
1374
1375 bool IsValid = false;
Craig Topperd2d442c2014-05-17 23:10:59 +00001376 IdentifierInfo *FeatureII = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001377
1378 // Read the '('.
Andy Gibbsd41d0942012-11-17 19:18:27 +00001379 LexUnexpandedToken(Tok);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001380 if (Tok.is(tok::l_paren)) {
1381 // Read the identifier
Andy Gibbsd41d0942012-11-17 19:18:27 +00001382 LexUnexpandedToken(Tok);
Richard Smithbaf29122013-07-09 00:57:56 +00001383 if ((FeatureII = Tok.getIdentifierInfo())) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001384 // Read the ')'.
Andy Gibbsd41d0942012-11-17 19:18:27 +00001385 LexUnexpandedToken(Tok);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001386 if (Tok.is(tok::r_paren))
1387 IsValid = true;
1388 }
1389 }
1390
1391 bool Value = false;
1392 if (!IsValid)
1393 Diag(StartLoc, diag::err_feature_check_malformed);
Yunzhong Gaoef309f42014-04-11 20:55:19 +00001394 else if (II == Ident__is_identifier)
1395 Value = FeatureII->getTokenID() == tok::identifier;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001396 else if (II == Ident__has_builtin) {
1397 // Check for a builtin is trivial.
1398 Value = FeatureII->getBuiltinID() != 0;
1399 } else if (II == Ident__has_attribute)
Aaron Ballman759c71d2014-03-31 15:26:40 +00001400 Value = hasAttribute(AttrSyntax::Generic, nullptr, FeatureII,
Aaron Ballman2fbf9942014-03-31 13:14:44 +00001401 getTargetInfo().getTriple(), getLangOpts());
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001402 else if (II == Ident__has_extension)
1403 Value = HasExtension(*this, FeatureII);
1404 else {
1405 assert(II == Ident__has_feature && "Must be feature check");
1406 Value = HasFeature(*this, FeatureII);
1407 }
1408
1409 OS << (int)Value;
1410 if (IsValid)
1411 Tok.setKind(tok::numeric_constant);
1412 } else if (II == Ident__has_include ||
1413 II == Ident__has_include_next) {
1414 // The argument to these two builtins should be a parenthesized
1415 // file name string literal using angle brackets (<>) or
1416 // double-quotes ("").
1417 bool Value;
1418 if (II == Ident__has_include)
1419 Value = EvaluateHasInclude(Tok, II, *this);
1420 else
1421 Value = EvaluateHasIncludeNext(Tok, II, *this);
1422 OS << (int)Value;
Richard Trieuda031982012-10-22 20:28:48 +00001423 if (Tok.is(tok::r_paren))
1424 Tok.setKind(tok::numeric_constant);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001425 } else if (II == Ident__has_warning) {
1426 // The argument should be a parenthesized string literal.
1427 // The argument to these builtins should be a parenthesized identifier.
1428 SourceLocation StartLoc = Tok.getLocation();
1429 bool IsValid = false;
1430 bool Value = false;
1431 // Read the '('.
Andy Gibbs58905d22012-11-17 19:15:38 +00001432 LexUnexpandedToken(Tok);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001433 do {
Andy Gibbs58905d22012-11-17 19:15:38 +00001434 if (Tok.isNot(tok::l_paren)) {
1435 Diag(StartLoc, diag::err_warning_check_malformed);
1436 break;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001437 }
Andy Gibbs58905d22012-11-17 19:15:38 +00001438
1439 LexUnexpandedToken(Tok);
1440 std::string WarningName;
1441 SourceLocation StrStartLoc = Tok.getLocation();
Andy Gibbsa8df57a2012-11-17 19:16:52 +00001442 if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",
1443 /*MacroExpansion=*/false)) {
Andy Gibbs58905d22012-11-17 19:15:38 +00001444 // Eat tokens until ')'.
Andy Gibbsb5b30c42012-11-17 22:17:28 +00001445 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) &&
1446 Tok.isNot(tok::eof))
Andy Gibbs58905d22012-11-17 19:15:38 +00001447 LexUnexpandedToken(Tok);
1448 break;
1449 }
1450
1451 // Is the end a ')'?
1452 if (!(IsValid = Tok.is(tok::r_paren))) {
1453 Diag(StartLoc, diag::err_warning_check_malformed);
1454 break;
1455 }
1456
1457 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1458 WarningName[1] != 'W') {
1459 Diag(StrStartLoc, diag::warn_has_warning_invalid_option);
1460 break;
1461 }
1462
1463 // Finally, check if the warning flags maps to a diagnostic group.
1464 // We construct a SmallVector here to talk to getDiagnosticIDs().
1465 // Although we don't use the result, this isn't a hot path, and not
1466 // worth special casing.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001467 SmallVector<diag::kind, 10> Diags;
Andy Gibbs58905d22012-11-17 19:15:38 +00001468 Value = !getDiagnostics().getDiagnosticIDs()->
1469 getDiagnosticsInGroup(WarningName.substr(2), Diags);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001470 } while (false);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001471
1472 OS << (int)Value;
Andy Gibbsf591982b2012-11-17 19:14:53 +00001473 if (IsValid)
1474 Tok.setKind(tok::numeric_constant);
Douglas Gregorc83de302012-09-25 15:44:52 +00001475 } else if (II == Ident__building_module) {
1476 // The argument to this builtin should be an identifier. The
1477 // builtin evaluates to 1 when that identifier names the module we are
1478 // currently building.
1479 OS << (int)EvaluateBuildingModule(Tok, II, *this);
1480 Tok.setKind(tok::numeric_constant);
1481 } else if (II == Ident__MODULE__) {
1482 // The current module as an identifier.
1483 OS << getLangOpts().CurrentModule;
1484 IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);
1485 Tok.setIdentifierInfo(ModuleII);
1486 Tok.setKind(ModuleII->getTokenID());
Richard Smithae385082014-03-15 00:06:08 +00001487 } else if (II == Ident__identifier) {
1488 SourceLocation Loc = Tok.getLocation();
1489
1490 // We're expecting '__identifier' '(' identifier ')'. Try to recover
1491 // if the parens are missing.
1492 LexNonComment(Tok);
1493 if (Tok.isNot(tok::l_paren)) {
1494 // No '(', use end of last token.
1495 Diag(getLocForEndOfToken(Loc), diag::err_pp_expected_after)
1496 << II << tok::l_paren;
1497 // If the next token isn't valid as our argument, we can't recover.
1498 if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1499 Tok.setKind(tok::identifier);
1500 return;
1501 }
1502
1503 SourceLocation LParenLoc = Tok.getLocation();
1504 LexNonComment(Tok);
1505
1506 if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1507 Tok.setKind(tok::identifier);
1508 else {
1509 Diag(Tok.getLocation(), diag::err_pp_identifier_arg_not_identifier)
1510 << Tok.getKind();
1511 // Don't walk past anything that's not a real token.
1512 if (Tok.is(tok::eof) || Tok.is(tok::eod) || Tok.isAnnotation())
1513 return;
1514 }
1515
1516 // Discard the ')', preserving 'Tok' as our result.
1517 Token RParen;
1518 LexNonComment(RParen);
1519 if (RParen.isNot(tok::r_paren)) {
1520 Diag(getLocForEndOfToken(Tok.getLocation()), diag::err_pp_expected_after)
1521 << Tok.getKind() << tok::r_paren;
1522 Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1523 }
1524 return;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001525 } else {
1526 llvm_unreachable("Unknown identifier!");
1527 }
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00001528 CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation());
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001529}
1530
1531void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
1532 // If the 'used' status changed, and the macro requires 'unused' warning,
1533 // remove its SourceLocation from the warn-for-unused-macro locations.
1534 if (MI->isWarnIfUnused() && !MI->isUsed())
1535 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1536 MI->setIsUsed(true);
1537}