blob: 78d4e14ccd6e541c807bfd24857f6194487cb1fb [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"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000016#include "clang/Basic/FileManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/Basic/SourceManager.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000018#include "clang/Basic/TargetInfo.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000019#include "clang/Lex/CodeCompletionHandler.h"
20#include "clang/Lex/ExternalPreprocessorSource.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Lex/LexDiagnostic.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000022#include "clang/Lex/MacroArgs.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/Lex/MacroInfo.h"
24#include "llvm/ADT/STLExtras.h"
Andy Gibbs58905d22012-11-17 19:15:38 +000025#include "llvm/ADT/SmallString.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000026#include "llvm/ADT/StringSwitch.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000027#include "llvm/Config/llvm-config.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000028#include "llvm/Support/ErrorHandling.h"
Dmitri Gribenkoae07f722012-09-24 20:56:28 +000029#include "llvm/Support/Format.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "llvm/Support/raw_ostream.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000031#include <cstdio>
32#include <ctime>
33using namespace clang;
34
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +000035MacroDirective *
36Preprocessor::getMacroDirectiveHistory(const IdentifierInfo *II) const {
Alexander Kornienko1d26c022012-09-25 17:18:14 +000037 assert(II->hadMacroDefinition() && "Identifier has not been not a macro!");
Joao Matosc0d4c1b2012-08-31 21:34:27 +000038
39 macro_iterator Pos = Macros.find(II);
Joao Matosc0d4c1b2012-08-31 21:34:27 +000040 assert(Pos != Macros.end() && "Identifier macro info is missing!");
Joao Matosc0d4c1b2012-08-31 21:34:27 +000041 return Pos->second;
42}
43
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000044void Preprocessor::appendMacroDirective(IdentifierInfo *II, MacroDirective *MD){
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000045 assert(MD && "MacroDirective should be non-zero!");
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000046 assert(!MD->getPrevious() && "Already attached to a MacroDirective history.");
Douglas Gregor5a4649b2012-10-11 00:46:49 +000047
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +000048 MacroDirective *&StoredMD = Macros[II];
49 MD->setPrevious(StoredMD);
50 StoredMD = MD;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000051 II->setHasMacroDefinition(MD->isDefined());
52 bool isImportedMacro = isa<DefMacroDirective>(MD) &&
53 cast<DefMacroDirective>(MD)->isImported();
54 if (II->isFromAST() && !isImportedMacro)
Joao Matosc0d4c1b2012-08-31 21:34:27 +000055 II->setChangedSinceDeserialization();
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000056}
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +000057
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000058void Preprocessor::setLoadedMacroDirective(IdentifierInfo *II,
59 MacroDirective *MD) {
60 assert(II && MD);
61 MacroDirective *&StoredMD = Macros[II];
62 assert(!StoredMD &&
63 "the macro history was modified before initializing it from a pch");
64 StoredMD = MD;
65 // Setup the identifier as having associated macro history.
66 II->setHasMacroDefinition(true);
67 if (!MD->isDefined())
68 II->setHasMacroDefinition(false);
Joao Matosc0d4c1b2012-08-31 21:34:27 +000069}
70
Joao Matosc0d4c1b2012-08-31 21:34:27 +000071/// RegisterBuiltinMacro - Register the specified identifier in the identifier
72/// table and mark it as a builtin macro to be expanded.
73static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
74 // Get the identifier.
75 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
76
77 // Mark it as being a macro that is builtin.
78 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
79 MI->setIsBuiltinMacro();
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000080 PP.appendDefMacroDirective(Id, MI);
Joao Matosc0d4c1b2012-08-31 21:34:27 +000081 return Id;
82}
83
84
85/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
86/// identifier table.
87void Preprocessor::RegisterBuiltinMacros() {
88 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
89 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
90 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
91 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
92 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
93 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
94
95 // GCC Extensions.
96 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
97 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
98 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
99
Richard Smithae385082014-03-15 00:06:08 +0000100 // Microsoft Extensions.
101 if (LangOpts.MicrosoftExt) {
102 Ident__identifier = RegisterBuiltinMacro(*this, "__identifier");
103 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
104 } else {
105 Ident__identifier = 0;
106 Ident__pragma = 0;
107 }
108
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000109 // Clang Extensions.
110 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
111 Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension");
112 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
113 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
114 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
115 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
116 Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning");
117
Douglas Gregorc83de302012-09-25 15:44:52 +0000118 // Modules.
119 if (LangOpts.Modules) {
120 Ident__building_module = RegisterBuiltinMacro(*this, "__building_module");
121
122 // __MODULE__
123 if (!LangOpts.CurrentModule.empty())
124 Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__");
125 else
126 Ident__MODULE__ = 0;
127 } else {
128 Ident__building_module = 0;
129 Ident__MODULE__ = 0;
130 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000131}
132
133/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
134/// in its expansion, currently expands to that token literally.
135static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
136 const IdentifierInfo *MacroIdent,
137 Preprocessor &PP) {
138 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
139
140 // If the token isn't an identifier, it's always literally expanded.
141 if (II == 0) return true;
142
143 // If the information about this identifier is out of date, update it from
144 // the external source.
145 if (II->isOutOfDate())
146 PP.getExternalSource()->updateOutOfDateIdentifier(*II);
147
148 // If the identifier is a macro, and if that macro is enabled, it may be
149 // expanded so it's not a trivial expansion.
150 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
151 // Fast expanding "#define X X" is ok, because X would be disabled.
152 II != MacroIdent)
153 return false;
154
155 // If this is an object-like macro invocation, it is safe to trivially expand
156 // it.
157 if (MI->isObjectLike()) return true;
158
159 // If this is a function-like macro invocation, it's safe to trivially expand
160 // as long as the identifier is not a macro argument.
161 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
162 I != E; ++I)
163 if (*I == II)
164 return false; // Identifier is a macro argument.
165
166 return true;
167}
168
169
170/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
171/// lexed is a '('. If so, consume the token and return true, if not, this
172/// method should have no observable side-effect on the lexed tokens.
173bool Preprocessor::isNextPPTokenLParen() {
174 // Do some quick tests for rejection cases.
175 unsigned Val;
176 if (CurLexer)
177 Val = CurLexer->isNextPPTokenLParen();
178 else if (CurPTHLexer)
179 Val = CurPTHLexer->isNextPPTokenLParen();
180 else
181 Val = CurTokenLexer->isNextTokenLParen();
182
183 if (Val == 2) {
184 // We have run off the end. If it's a source file we don't
185 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
186 // macro stack.
187 if (CurPPLexer)
188 return false;
189 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
190 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
191 if (Entry.TheLexer)
192 Val = Entry.TheLexer->isNextPPTokenLParen();
193 else if (Entry.ThePTHLexer)
194 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
195 else
196 Val = Entry.TheTokenLexer->isNextTokenLParen();
197
198 if (Val != 2)
199 break;
200
201 // Ran off the end of a source file?
202 if (Entry.ThePPLexer)
203 return false;
204 }
205 }
206
207 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
208 // have found something that isn't a '(' or we found the end of the
209 // translation unit. In either case, return false.
210 return Val == 1;
211}
212
213/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
214/// expanded as a macro, handle it and return the next token as 'Identifier'.
215bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000216 MacroDirective *MD) {
Argyrios Kyrtzidis09796b92013-03-27 01:25:19 +0000217 MacroDirective::DefInfo Def = MD->getDefinition();
218 assert(Def.isValid());
219 MacroInfo *MI = Def.getMacroInfo();
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000220
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000221 // If this is a macro expansion in the "#if !defined(x)" line for the file,
222 // then the macro could expand to different things in other contexts, we need
223 // to disable the optimization in this case.
224 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
225
226 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
227 if (MI->isBuiltinMacro()) {
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000228 if (Callbacks) Callbacks->MacroExpands(Identifier, MD,
Argyrios Kyrtzidis37e48ff2013-05-03 22:31:32 +0000229 Identifier.getLocation(),/*Args=*/0);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000230 ExpandBuiltinMacro(Identifier);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000231 return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000232 }
233
234 /// Args - If this is a function-like macro expansion, this contains,
235 /// for each macro argument, the list of tokens that were provided to the
236 /// invocation.
237 MacroArgs *Args = 0;
238
239 // Remember where the end of the expansion occurred. For an object-like
240 // macro, this is the identifier. For a function-like macro, this is the ')'.
241 SourceLocation ExpansionEnd = Identifier.getLocation();
242
243 // If this is a function-like macro, read the arguments.
244 if (MI->isFunctionLike()) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000245 // Remember that we are now parsing the arguments to a macro invocation.
246 // Preprocessor directives used inside macro arguments are not portable, and
247 // this enables the warning.
248 InMacroArgs = true;
249 Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd);
250
251 // Finished parsing args.
252 InMacroArgs = false;
253
254 // If there was an error parsing the arguments, bail out.
Eli Friedman0834a4b2013-09-19 00:41:32 +0000255 if (Args == 0) return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000256
257 ++NumFnMacroExpanded;
258 } else {
259 ++NumMacroExpanded;
260 }
261
262 // Notice that this macro has been used.
263 markMacroAsUsed(MI);
264
265 // Remember where the token is expanded.
266 SourceLocation ExpandLoc = Identifier.getLocation();
267 SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
268
269 if (Callbacks) {
270 if (InMacroArgs) {
271 // We can have macro expansion inside a conditional directive while
272 // reading the function macro arguments. To ensure, in that case, that
273 // MacroExpands callbacks still happen in source order, queue this
274 // callback to have it happen after the function macro callback.
275 DelayedMacroExpandsCallbacks.push_back(
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000276 MacroExpandsInfo(Identifier, MD, ExpansionRange));
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000277 } else {
Argyrios Kyrtzidis37e48ff2013-05-03 22:31:32 +0000278 Callbacks->MacroExpands(Identifier, MD, ExpansionRange, Args);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000279 if (!DelayedMacroExpandsCallbacks.empty()) {
280 for (unsigned i=0, e = DelayedMacroExpandsCallbacks.size(); i!=e; ++i) {
281 MacroExpandsInfo &Info = DelayedMacroExpandsCallbacks[i];
Argyrios Kyrtzidis37e48ff2013-05-03 22:31:32 +0000282 // FIXME: We lose macro args info with delayed callback.
283 Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range, /*Args=*/0);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000284 }
285 DelayedMacroExpandsCallbacks.clear();
286 }
287 }
288 }
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000289
290 // If the macro definition is ambiguous, complain.
Argyrios Kyrtzidis09796b92013-03-27 01:25:19 +0000291 if (Def.getDirective()->isAmbiguous()) {
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000292 Diag(Identifier, diag::warn_pp_ambiguous_macro)
293 << Identifier.getIdentifierInfo();
294 Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)
295 << Identifier.getIdentifierInfo();
Argyrios Kyrtzidis09796b92013-03-27 01:25:19 +0000296 for (MacroDirective::DefInfo PrevDef = Def.getPreviousDefinition();
297 PrevDef && !PrevDef.isUndefined();
298 PrevDef = PrevDef.getPreviousDefinition()) {
Richard Smith49f906a2014-03-01 00:08:04 +0000299 Diag(PrevDef.getMacroInfo()->getDefinitionLoc(),
300 diag::note_pp_ambiguous_macro_other)
301 << Identifier.getIdentifierInfo();
302 if (!PrevDef.getDirective()->isAmbiguous())
303 break;
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000304 }
305 }
306
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000307 // If we started lexing a macro, enter the macro expansion body.
308
309 // If this macro expands to no tokens, don't bother to push it onto the
310 // expansion stack, only to take it right back off.
311 if (MI->getNumTokens() == 0) {
312 // No need for arg info.
313 if (Args) Args->destroy(*this);
314
Eli Friedman0834a4b2013-09-19 00:41:32 +0000315 // Propagate whitespace info as if we had pushed, then popped,
316 // a macro context.
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000317 Identifier.setFlag(Token::LeadingEmptyMacro);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000318 PropagateLineStartLeadingSpaceInfo(Identifier);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000319 ++NumFastMacroExpanded;
320 return false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000321 } else if (MI->getNumTokens() == 1 &&
322 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
323 *this)) {
324 // Otherwise, if this macro expands into a single trivially-expanded
325 // token: expand it now. This handles common cases like
326 // "#define VAL 42".
327
328 // No need for arg info.
329 if (Args) Args->destroy(*this);
330
331 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
332 // identifier to the expanded token.
333 bool isAtStartOfLine = Identifier.isAtStartOfLine();
334 bool hasLeadingSpace = Identifier.hasLeadingSpace();
335
336 // Replace the result token.
337 Identifier = MI->getReplacementToken(0);
338
339 // Restore the StartOfLine/LeadingSpace markers.
340 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
341 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
342
343 // Update the tokens location to include both its expansion and physical
344 // locations.
345 SourceLocation Loc =
346 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
347 ExpansionEnd,Identifier.getLength());
348 Identifier.setLocation(Loc);
349
350 // If this is a disabled macro or #define X X, we must mark the result as
351 // unexpandable.
352 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
353 if (MacroInfo *NewMI = getMacroInfo(NewII))
354 if (!NewMI->isEnabled() || NewMI == MI) {
355 Identifier.setFlag(Token::DisableExpand);
Douglas Gregor1a347f72013-01-30 23:10:17 +0000356 // Don't warn for "#define X X" like "#define bool bool" from
357 // stdbool.h.
358 if (NewMI != MI || MI->isFunctionLike())
359 Diag(Identifier, diag::pp_disabled_macro_expansion);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000360 }
361 }
362
363 // Since this is not an identifier token, it can't be macro expanded, so
364 // we're done.
365 ++NumFastMacroExpanded;
Eli Friedman0834a4b2013-09-19 00:41:32 +0000366 return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000367 }
368
369 // Start expanding the macro.
370 EnterMacro(Identifier, ExpansionEnd, MI, Args);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000371 return false;
372}
373
Richard Trieu79b45382013-07-23 18:01:49 +0000374enum Bracket {
375 Brace,
376 Paren
377};
378
379/// CheckMatchedBrackets - Returns true if the braces and parentheses in the
380/// token vector are properly nested.
381static bool CheckMatchedBrackets(const SmallVectorImpl<Token> &Tokens) {
382 SmallVector<Bracket, 8> Brackets;
383 for (SmallVectorImpl<Token>::const_iterator I = Tokens.begin(),
384 E = Tokens.end();
385 I != E; ++I) {
386 if (I->is(tok::l_paren)) {
387 Brackets.push_back(Paren);
388 } else if (I->is(tok::r_paren)) {
389 if (Brackets.empty() || Brackets.back() == Brace)
390 return false;
391 Brackets.pop_back();
392 } else if (I->is(tok::l_brace)) {
393 Brackets.push_back(Brace);
394 } else if (I->is(tok::r_brace)) {
395 if (Brackets.empty() || Brackets.back() == Paren)
396 return false;
397 Brackets.pop_back();
398 }
399 }
400 if (!Brackets.empty())
401 return false;
402 return true;
403}
404
405/// GenerateNewArgTokens - Returns true if OldTokens can be converted to a new
406/// vector of tokens in NewTokens. The new number of arguments will be placed
407/// in NumArgs and the ranges which need to surrounded in parentheses will be
408/// in ParenHints.
409/// Returns false if the token stream cannot be changed. If this is because
410/// of an initializer list starting a macro argument, the range of those
411/// initializer lists will be place in InitLists.
412static bool GenerateNewArgTokens(Preprocessor &PP,
413 SmallVectorImpl<Token> &OldTokens,
414 SmallVectorImpl<Token> &NewTokens,
415 unsigned &NumArgs,
416 SmallVectorImpl<SourceRange> &ParenHints,
417 SmallVectorImpl<SourceRange> &InitLists) {
418 if (!CheckMatchedBrackets(OldTokens))
419 return false;
420
421 // Once it is known that the brackets are matched, only a simple count of the
422 // braces is needed.
423 unsigned Braces = 0;
424
425 // First token of a new macro argument.
426 SmallVectorImpl<Token>::iterator ArgStartIterator = OldTokens.begin();
427
428 // First closing brace in a new macro argument. Used to generate
429 // SourceRanges for InitLists.
430 SmallVectorImpl<Token>::iterator ClosingBrace = OldTokens.end();
431 NumArgs = 0;
432 Token TempToken;
433 // Set to true when a macro separator token is found inside a braced list.
434 // If true, the fixed argument spans multiple old arguments and ParenHints
435 // will be updated.
436 bool FoundSeparatorToken = false;
437 for (SmallVectorImpl<Token>::iterator I = OldTokens.begin(),
438 E = OldTokens.end();
439 I != E; ++I) {
440 if (I->is(tok::l_brace)) {
441 ++Braces;
442 } else if (I->is(tok::r_brace)) {
443 --Braces;
444 if (Braces == 0 && ClosingBrace == E && FoundSeparatorToken)
445 ClosingBrace = I;
446 } else if (I->is(tok::eof)) {
447 // EOF token is used to separate macro arguments
448 if (Braces != 0) {
449 // Assume comma separator is actually braced list separator and change
450 // it back to a comma.
451 FoundSeparatorToken = true;
452 I->setKind(tok::comma);
453 I->setLength(1);
454 } else { // Braces == 0
455 // Separator token still separates arguments.
456 ++NumArgs;
457
458 // If the argument starts with a brace, it can't be fixed with
459 // parentheses. A different diagnostic will be given.
460 if (FoundSeparatorToken && ArgStartIterator->is(tok::l_brace)) {
461 InitLists.push_back(
462 SourceRange(ArgStartIterator->getLocation(),
463 PP.getLocForEndOfToken(ClosingBrace->getLocation())));
464 ClosingBrace = E;
465 }
466
467 // Add left paren
468 if (FoundSeparatorToken) {
469 TempToken.startToken();
470 TempToken.setKind(tok::l_paren);
471 TempToken.setLocation(ArgStartIterator->getLocation());
472 TempToken.setLength(0);
473 NewTokens.push_back(TempToken);
474 }
475
476 // Copy over argument tokens
477 NewTokens.insert(NewTokens.end(), ArgStartIterator, I);
478
479 // Add right paren and store the paren locations in ParenHints
480 if (FoundSeparatorToken) {
481 SourceLocation Loc = PP.getLocForEndOfToken((I - 1)->getLocation());
482 TempToken.startToken();
483 TempToken.setKind(tok::r_paren);
484 TempToken.setLocation(Loc);
485 TempToken.setLength(0);
486 NewTokens.push_back(TempToken);
487 ParenHints.push_back(SourceRange(ArgStartIterator->getLocation(),
488 Loc));
489 }
490
491 // Copy separator token
492 NewTokens.push_back(*I);
493
494 // Reset values
495 ArgStartIterator = I + 1;
496 FoundSeparatorToken = false;
497 }
498 }
499 }
500
501 return !ParenHints.empty() && InitLists.empty();
502}
503
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000504/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
505/// token is the '(' of the macro, this method is invoked to read all of the
506/// actual arguments specified for the macro invocation. This returns null on
507/// error.
508MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
509 MacroInfo *MI,
510 SourceLocation &MacroEnd) {
511 // The number of fixed arguments to parse.
512 unsigned NumFixedArgsLeft = MI->getNumArgs();
513 bool isVariadic = MI->isVariadic();
514
515 // Outer loop, while there are more arguments, keep reading them.
516 Token Tok;
517
518 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
519 // an argument value in a macro could expand to ',' or '(' or ')'.
520 LexUnexpandedToken(Tok);
521 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
522
523 // ArgTokens - Build up a list of tokens that make up each argument. Each
524 // argument is separated by an EOF token. Use a SmallVector so we can avoid
525 // heap allocations in the common case.
526 SmallVector<Token, 64> ArgTokens;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000527 bool ContainsCodeCompletionTok = false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000528
Richard Trieu79b45382013-07-23 18:01:49 +0000529 SourceLocation TooManyArgsLoc;
530
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000531 unsigned NumActuals = 0;
532 while (Tok.isNot(tok::r_paren)) {
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000533 if (ContainsCodeCompletionTok && (Tok.is(tok::eof) || Tok.is(tok::eod)))
534 break;
535
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000536 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
537 "only expect argument separators here");
538
539 unsigned ArgTokenStart = ArgTokens.size();
540 SourceLocation ArgStartLoc = Tok.getLocation();
541
542 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
543 // that we already consumed the first one.
544 unsigned NumParens = 0;
545
546 while (1) {
547 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
548 // an argument value in a macro could expand to ',' or '(' or ')'.
549 LexUnexpandedToken(Tok);
550
551 if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n"
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000552 if (!ContainsCodeCompletionTok) {
553 Diag(MacroName, diag::err_unterm_macro_invoc);
554 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
555 << MacroName.getIdentifierInfo();
556 // Do not lose the EOF/EOD. Return it to the client.
557 MacroName = Tok;
558 return 0;
559 } else {
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000560 // Do not lose the EOF/EOD.
561 Token *Toks = new Token[1];
562 Toks[0] = Tok;
563 EnterTokenStream(Toks, 1, true, true);
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000564 break;
565 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000566 } else if (Tok.is(tok::r_paren)) {
567 // If we found the ) token, the macro arg list is done.
568 if (NumParens-- == 0) {
569 MacroEnd = Tok.getLocation();
570 break;
571 }
572 } else if (Tok.is(tok::l_paren)) {
573 ++NumParens;
Reid Kleckner596b85c2013-06-26 17:16:08 +0000574 } else if (Tok.is(tok::comma) && NumParens == 0 &&
575 !(Tok.getFlags() & Token::IgnoredComma)) {
576 // In Microsoft-compatibility mode, single commas from nested macro
577 // expansions should not be considered as argument separators. We test
578 // for this with the IgnoredComma token flag above.
579
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000580 // Comma ends this argument if there are more fixed arguments expected.
581 // However, if this is a variadic macro, and this is part of the
582 // variadic part, then the comma is just an argument token.
583 if (!isVariadic) break;
584 if (NumFixedArgsLeft > 1)
585 break;
586 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
587 // If this is a comment token in the argument list and we're just in
588 // -C mode (not -CC mode), discard the comment.
589 continue;
590 } else if (Tok.getIdentifierInfo() != 0) {
591 // Reading macro arguments can cause macros that we are currently
592 // expanding from to be popped off the expansion stack. Doing so causes
593 // them to be reenabled for expansion. Here we record whether any
594 // identifiers we lex as macro arguments correspond to disabled macros.
595 // If so, we mark the token as noexpand. This is a subtle aspect of
596 // C99 6.10.3.4p2.
597 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
598 if (!MI->isEnabled())
599 Tok.setFlag(Token::DisableExpand);
600 } else if (Tok.is(tok::code_completion)) {
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000601 ContainsCodeCompletionTok = true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000602 if (CodeComplete)
603 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
604 MI, NumActuals);
605 // Don't mark that we reached the code-completion point because the
606 // parser is going to handle the token and there will be another
607 // code-completion callback.
608 }
609
610 ArgTokens.push_back(Tok);
611 }
612
613 // If this was an empty argument list foo(), don't add this as an empty
614 // argument.
615 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
616 break;
617
618 // If this is not a variadic macro, and too many args were specified, emit
619 // an error.
Richard Trieu79b45382013-07-23 18:01:49 +0000620 if (!isVariadic && NumFixedArgsLeft == 0 && TooManyArgsLoc.isInvalid()) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000621 if (ArgTokens.size() != ArgTokenStart)
Richard Trieu79b45382013-07-23 18:01:49 +0000622 TooManyArgsLoc = ArgTokens[ArgTokenStart].getLocation();
623 else
624 TooManyArgsLoc = ArgStartLoc;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000625 }
626
Richard Trieu79b45382013-07-23 18:01:49 +0000627 // Empty arguments are standard in C99 and C++0x, and are supported as an
628 // extension in other modes.
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000629 if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99)
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000630 Diag(Tok, LangOpts.CPlusPlus11 ?
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000631 diag::warn_cxx98_compat_empty_fnmacro_arg :
632 diag::ext_empty_fnmacro_arg);
633
634 // Add a marker EOF token to the end of the token list for this argument.
635 Token EOFTok;
636 EOFTok.startToken();
637 EOFTok.setKind(tok::eof);
638 EOFTok.setLocation(Tok.getLocation());
639 EOFTok.setLength(0);
640 ArgTokens.push_back(EOFTok);
641 ++NumActuals;
Richard Trieu79b45382013-07-23 18:01:49 +0000642 if (!ContainsCodeCompletionTok && NumFixedArgsLeft != 0)
Argyrios Kyrtzidisfb703802013-02-22 22:28:58 +0000643 --NumFixedArgsLeft;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000644 }
645
646 // Okay, we either found the r_paren. Check to see if we parsed too few
647 // arguments.
648 unsigned MinArgsExpected = MI->getNumArgs();
649
Richard Trieu79b45382013-07-23 18:01:49 +0000650 // If this is not a variadic macro, and too many args were specified, emit
651 // an error.
652 if (!isVariadic && NumActuals > MinArgsExpected &&
653 !ContainsCodeCompletionTok) {
654 // Emit the diagnostic at the macro name in case there is a missing ).
655 // Emitting it at the , could be far away from the macro name.
656 Diag(TooManyArgsLoc, diag::err_too_many_args_in_macro_invoc);
657 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
658 << MacroName.getIdentifierInfo();
659
660 // Commas from braced initializer lists will be treated as argument
661 // separators inside macros. Attempt to correct for this with parentheses.
662 // TODO: See if this can be generalized to angle brackets for templates
663 // inside macro arguments.
664
Bob Wilson57217352013-07-27 21:59:57 +0000665 SmallVector<Token, 4> FixedArgTokens;
Richard Trieu79b45382013-07-23 18:01:49 +0000666 unsigned FixedNumArgs = 0;
667 SmallVector<SourceRange, 4> ParenHints, InitLists;
668 if (!GenerateNewArgTokens(*this, ArgTokens, FixedArgTokens, FixedNumArgs,
669 ParenHints, InitLists)) {
670 if (!InitLists.empty()) {
671 DiagnosticBuilder DB =
672 Diag(MacroName,
673 diag::note_init_list_at_beginning_of_macro_argument);
674 for (SmallVector<SourceRange, 4>::iterator
675 Range = InitLists.begin(), RangeEnd = InitLists.end();
676 Range != RangeEnd; ++Range) {
677 if (DB.hasMaxRanges())
678 break;
679 DB << *Range;
680 }
681 }
682 return 0;
683 }
684 if (FixedNumArgs != MinArgsExpected)
685 return 0;
686
687 DiagnosticBuilder DB = Diag(MacroName, diag::note_suggest_parens_for_macro);
688 for (SmallVector<SourceRange, 4>::iterator
689 ParenLocation = ParenHints.begin(), ParenEnd = ParenHints.end();
690 ParenLocation != ParenEnd; ++ParenLocation) {
691 if (DB.hasMaxFixItHints())
692 break;
693 DB << FixItHint::CreateInsertion(ParenLocation->getBegin(), "(");
694 if (DB.hasMaxFixItHints())
695 break;
696 DB << FixItHint::CreateInsertion(ParenLocation->getEnd(), ")");
697 }
698 ArgTokens.swap(FixedArgTokens);
699 NumActuals = FixedNumArgs;
700 }
701
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000702 // See MacroArgs instance var for description of this.
703 bool isVarargsElided = false;
704
Argyrios Kyrtzidisd4635d42012-12-21 01:51:12 +0000705 if (ContainsCodeCompletionTok) {
706 // Recover from not-fully-formed macro invocation during code-completion.
707 Token EOFTok;
708 EOFTok.startToken();
709 EOFTok.setKind(tok::eof);
710 EOFTok.setLocation(Tok.getLocation());
711 EOFTok.setLength(0);
712 for (; NumActuals < MinArgsExpected; ++NumActuals)
713 ArgTokens.push_back(EOFTok);
714 }
715
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000716 if (NumActuals < MinArgsExpected) {
717 // There are several cases where too few arguments is ok, handle them now.
718 if (NumActuals == 0 && MinArgsExpected == 1) {
719 // #define A(X) or #define A(...) ---> A()
720
721 // If there is exactly one argument, and that argument is missing,
722 // then we have an empty "()" argument empty list. This is fine, even if
723 // the macro expects one argument (the argument is just empty).
724 isVarargsElided = MI->isVariadic();
725 } else if (MI->isVariadic() &&
726 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
727 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
728 // Varargs where the named vararg parameter is missing: OK as extension.
729 // #define A(x, ...)
730 // A("blah")
Eli Friedman14d3c792012-11-14 02:18:46 +0000731 //
732 // If the macro contains the comma pasting extension, the diagnostic
733 // is suppressed; we know we'll get another diagnostic later.
734 if (!MI->hasCommaPasting()) {
735 Diag(Tok, diag::ext_missing_varargs_arg);
736 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
737 << MacroName.getIdentifierInfo();
738 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000739
740 // Remember this occurred, allowing us to elide the comma when used for
741 // cases like:
742 // #define A(x, foo...) blah(a, ## foo)
743 // #define B(x, ...) blah(a, ## __VA_ARGS__)
744 // #define C(...) blah(a, ## __VA_ARGS__)
745 // A(x) B(x) C()
746 isVarargsElided = true;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000747 } else if (!ContainsCodeCompletionTok) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000748 // Otherwise, emit the error.
749 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Argyrios Kyrtzidis164fdb62012-12-14 18:53:47 +0000750 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
751 << MacroName.getIdentifierInfo();
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000752 return 0;
753 }
754
755 // Add a marker EOF token to the end of the token list for this argument.
756 SourceLocation EndLoc = Tok.getLocation();
757 Tok.startToken();
758 Tok.setKind(tok::eof);
759 Tok.setLocation(EndLoc);
760 Tok.setLength(0);
761 ArgTokens.push_back(Tok);
762
763 // If we expect two arguments, add both as empty.
764 if (NumActuals == 0 && MinArgsExpected == 2)
765 ArgTokens.push_back(Tok);
766
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000767 } else if (NumActuals > MinArgsExpected && !MI->isVariadic() &&
768 !ContainsCodeCompletionTok) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000769 // Emit the diagnostic at the macro name in case there is a missing ).
770 // Emitting it at the , could be far away from the macro name.
771 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Argyrios Kyrtzidis164fdb62012-12-14 18:53:47 +0000772 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
773 << MacroName.getIdentifierInfo();
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000774 return 0;
775 }
776
777 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
778}
779
780/// \brief Keeps macro expanded tokens for TokenLexers.
781//
782/// Works like a stack; a TokenLexer adds the macro expanded tokens that is
783/// going to lex in the cache and when it finishes the tokens are removed
784/// from the end of the cache.
785Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
786 ArrayRef<Token> tokens) {
787 assert(tokLexer);
788 if (tokens.empty())
789 return 0;
790
791 size_t newIndex = MacroExpandedTokens.size();
792 bool cacheNeedsToGrow = tokens.size() >
793 MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
794 MacroExpandedTokens.append(tokens.begin(), tokens.end());
795
796 if (cacheNeedsToGrow) {
797 // Go through all the TokenLexers whose 'Tokens' pointer points in the
798 // buffer and update the pointers to the (potential) new buffer array.
799 for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) {
800 TokenLexer *prevLexer;
801 size_t tokIndex;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000802 std::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i];
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000803 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
804 }
805 }
806
807 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
808 return MacroExpandedTokens.data() + newIndex;
809}
810
811void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
812 assert(!MacroExpandingLexersStack.empty());
813 size_t tokIndex = MacroExpandingLexersStack.back().second;
814 assert(tokIndex < MacroExpandedTokens.size());
815 // Pop the cached macro expanded tokens from the end.
816 MacroExpandedTokens.resize(tokIndex);
817 MacroExpandingLexersStack.pop_back();
818}
819
820/// ComputeDATE_TIME - Compute the current time, enter it into the specified
821/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
822/// the identifier tokens inserted.
823static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
824 Preprocessor &PP) {
825 time_t TT = time(0);
826 struct tm *TM = localtime(&TT);
827
828 static const char * const Months[] = {
829 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
830 };
831
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000832 {
833 SmallString<32> TmpBuffer;
834 llvm::raw_svector_ostream TmpStream(TmpBuffer);
835 TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
836 TM->tm_mday, TM->tm_year + 1900);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000837 Token TmpTok;
838 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000839 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000840 DATELoc = TmpTok.getLocation();
841 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000842
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000843 {
844 SmallString<32> TmpBuffer;
845 llvm::raw_svector_ostream TmpStream(TmpBuffer);
846 TmpStream << llvm::format("\"%02d:%02d:%02d\"",
847 TM->tm_hour, TM->tm_min, TM->tm_sec);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000848 Token TmpTok;
849 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000850 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000851 TIMELoc = TmpTok.getLocation();
852 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000853}
854
855
856/// HasFeature - Return true if we recognize and implement the feature
857/// specified by the identifier as a standard language feature.
858static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
859 const LangOptions &LangOpts = PP.getLangOpts();
860 StringRef Feature = II->getName();
861
862 // Normalize the feature name, __foo__ becomes foo.
863 if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4)
864 Feature = Feature.substr(2, Feature.size() - 4);
865
866 return llvm::StringSwitch<bool>(Feature)
Will Dietzf54319c2013-01-18 11:30:38 +0000867 .Case("address_sanitizer", LangOpts.Sanitize.Address)
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000868 .Case("attribute_analyzer_noreturn", true)
869 .Case("attribute_availability", true)
870 .Case("attribute_availability_with_message", true)
871 .Case("attribute_cf_returns_not_retained", true)
872 .Case("attribute_cf_returns_retained", true)
873 .Case("attribute_deprecated_with_message", true)
874 .Case("attribute_ext_vector_type", true)
875 .Case("attribute_ns_returns_not_retained", true)
876 .Case("attribute_ns_returns_retained", true)
877 .Case("attribute_ns_consumes_self", true)
878 .Case("attribute_ns_consumed", true)
879 .Case("attribute_cf_consumed", true)
880 .Case("attribute_objc_ivar_unused", true)
881 .Case("attribute_objc_method_family", true)
882 .Case("attribute_overloadable", true)
883 .Case("attribute_unavailable_with_message", true)
884 .Case("attribute_unused_on_fields", true)
885 .Case("blocks", LangOpts.Blocks)
David Blaikie021221d2013-07-29 18:24:03 +0000886 .Case("c_thread_safety_attributes", true)
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000887 .Case("cxx_exceptions", LangOpts.Exceptions)
888 .Case("cxx_rtti", LangOpts.RTTI)
889 .Case("enumerator_attributes", true)
Will Dietzf54319c2013-01-18 11:30:38 +0000890 .Case("memory_sanitizer", LangOpts.Sanitize.Memory)
891 .Case("thread_sanitizer", LangOpts.Sanitize.Thread)
Peter Collingbournec3772752013-08-07 22:47:34 +0000892 .Case("dataflow_sanitizer", LangOpts.Sanitize.DataFlow)
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000893 // Objective-C features
894 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
895 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
896 .Case("objc_arc_weak", LangOpts.ObjCARCWeak)
897 .Case("objc_default_synthesize_properties", LangOpts.ObjC2)
898 .Case("objc_fixed_enum", LangOpts.ObjC2)
899 .Case("objc_instancetype", LangOpts.ObjC2)
900 .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules)
901 .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile())
Ted Kremenekdae8f9f2013-01-04 19:04:44 +0000902 .Case("objc_property_explicit_atomic", true) // Does clang support explicit "atomic" keyword?
Ted Kremenekb0cba4c2013-10-14 23:48:27 +0000903 .Case("objc_protocol_qualifier_mangling", true)
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000904 .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport())
905 .Case("ownership_holds", true)
906 .Case("ownership_returns", true)
907 .Case("ownership_takes", true)
908 .Case("objc_bool", true)
909 .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile())
910 .Case("objc_array_literals", LangOpts.ObjC2)
911 .Case("objc_dictionary_literals", LangOpts.ObjC2)
912 .Case("objc_boxed_expressions", LangOpts.ObjC2)
913 .Case("arc_cf_code_audited", true)
914 // C11 features
915 .Case("c_alignas", LangOpts.C11)
916 .Case("c_atomic", LangOpts.C11)
917 .Case("c_generic_selections", LangOpts.C11)
918 .Case("c_static_assert", LangOpts.C11)
Douglas Gregora7130bf2013-05-02 05:28:32 +0000919 .Case("c_thread_local",
920 LangOpts.C11 && PP.getTargetInfo().isTLSSupported())
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000921 // C++11 features
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000922 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus11)
923 .Case("cxx_alias_templates", LangOpts.CPlusPlus11)
924 .Case("cxx_alignas", LangOpts.CPlusPlus11)
925 .Case("cxx_atomic", LangOpts.CPlusPlus11)
926 .Case("cxx_attributes", LangOpts.CPlusPlus11)
927 .Case("cxx_auto_type", LangOpts.CPlusPlus11)
928 .Case("cxx_constexpr", LangOpts.CPlusPlus11)
929 .Case("cxx_decltype", LangOpts.CPlusPlus11)
930 .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus11)
931 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus11)
932 .Case("cxx_defaulted_functions", LangOpts.CPlusPlus11)
933 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus11)
934 .Case("cxx_deleted_functions", LangOpts.CPlusPlus11)
935 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus11)
936 .Case("cxx_generalized_initializers", LangOpts.CPlusPlus11)
937 .Case("cxx_implicit_moves", LangOpts.CPlusPlus11)
Richard Smith25b555a2013-04-19 17:00:31 +0000938 .Case("cxx_inheriting_constructors", LangOpts.CPlusPlus11)
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000939 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus11)
940 .Case("cxx_lambdas", LangOpts.CPlusPlus11)
941 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus11)
942 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus11)
943 .Case("cxx_noexcept", LangOpts.CPlusPlus11)
944 .Case("cxx_nullptr", LangOpts.CPlusPlus11)
945 .Case("cxx_override_control", LangOpts.CPlusPlus11)
946 .Case("cxx_range_for", LangOpts.CPlusPlus11)
947 .Case("cxx_raw_string_literals", LangOpts.CPlusPlus11)
948 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus11)
949 .Case("cxx_rvalue_references", LangOpts.CPlusPlus11)
950 .Case("cxx_strong_enums", LangOpts.CPlusPlus11)
951 .Case("cxx_static_assert", LangOpts.CPlusPlus11)
Richard Smithb438e622013-09-28 04:37:56 +0000952 .Case("cxx_thread_local",
Douglas Gregora7130bf2013-05-02 05:28:32 +0000953 LangOpts.CPlusPlus11 && PP.getTargetInfo().isTLSSupported())
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000954 .Case("cxx_trailing_return", LangOpts.CPlusPlus11)
955 .Case("cxx_unicode_literals", LangOpts.CPlusPlus11)
956 .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus11)
957 .Case("cxx_user_literals", LangOpts.CPlusPlus11)
958 .Case("cxx_variadic_templates", LangOpts.CPlusPlus11)
Richard Smith0a715422013-05-07 19:32:56 +0000959 // C++1y features
Richard Smith4fb09722013-07-24 17:51:13 +0000960 .Case("cxx_aggregate_nsdmi", LangOpts.CPlusPlus1y)
Richard Smith0a715422013-05-07 19:32:56 +0000961 .Case("cxx_binary_literals", LangOpts.CPlusPlus1y)
Richard Smithc0f7b812013-07-24 17:41:31 +0000962 .Case("cxx_contextual_conversions", LangOpts.CPlusPlus1y)
Richard Smithb438e622013-09-28 04:37:56 +0000963 //.Case("cxx_generic_lambdas", LangOpts.CPlusPlus1y)
964 .Case("cxx_init_captures", LangOpts.CPlusPlus1y)
Richard Smithc0f7b812013-07-24 17:41:31 +0000965 .Case("cxx_relaxed_constexpr", LangOpts.CPlusPlus1y)
Richard Smith9155be12013-05-12 03:09:35 +0000966 .Case("cxx_return_type_deduction", LangOpts.CPlusPlus1y)
Richard Smithb438e622013-09-28 04:37:56 +0000967 //.Case("cxx_runtime_arrays", LangOpts.CPlusPlus1y)
Richard Smithdca0c7a2013-09-27 20:19:41 +0000968 .Case("cxx_variable_templates", LangOpts.CPlusPlus1y)
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000969 // Type traits
970 .Case("has_nothrow_assign", LangOpts.CPlusPlus)
971 .Case("has_nothrow_copy", LangOpts.CPlusPlus)
972 .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
973 .Case("has_trivial_assign", LangOpts.CPlusPlus)
974 .Case("has_trivial_copy", LangOpts.CPlusPlus)
975 .Case("has_trivial_constructor", LangOpts.CPlusPlus)
976 .Case("has_trivial_destructor", LangOpts.CPlusPlus)
977 .Case("has_virtual_destructor", LangOpts.CPlusPlus)
978 .Case("is_abstract", LangOpts.CPlusPlus)
979 .Case("is_base_of", LangOpts.CPlusPlus)
980 .Case("is_class", LangOpts.CPlusPlus)
981 .Case("is_convertible_to", LangOpts.CPlusPlus)
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000982 .Case("is_empty", LangOpts.CPlusPlus)
983 .Case("is_enum", LangOpts.CPlusPlus)
984 .Case("is_final", LangOpts.CPlusPlus)
985 .Case("is_literal", LangOpts.CPlusPlus)
986 .Case("is_standard_layout", LangOpts.CPlusPlus)
987 .Case("is_pod", LangOpts.CPlusPlus)
988 .Case("is_polymorphic", LangOpts.CPlusPlus)
David Majnemera5433082013-10-18 00:33:31 +0000989 .Case("is_sealed", LangOpts.MicrosoftExt)
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000990 .Case("is_trivial", LangOpts.CPlusPlus)
991 .Case("is_trivially_assignable", LangOpts.CPlusPlus)
992 .Case("is_trivially_constructible", LangOpts.CPlusPlus)
993 .Case("is_trivially_copyable", LangOpts.CPlusPlus)
994 .Case("is_union", LangOpts.CPlusPlus)
995 .Case("modules", LangOpts.Modules)
996 .Case("tls", PP.getTargetInfo().isTLSSupported())
997 .Case("underlying_type", LangOpts.CPlusPlus)
998 .Default(false);
999}
1000
1001/// HasExtension - Return true if we recognize and implement the feature
1002/// specified by the identifier, either as an extension or a standard language
1003/// feature.
1004static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) {
1005 if (HasFeature(PP, II))
1006 return true;
1007
1008 // If the use of an extension results in an error diagnostic, extensions are
1009 // effectively unavailable, so just return false here.
1010 if (PP.getDiagnostics().getExtensionHandlingBehavior() ==
1011 DiagnosticsEngine::Ext_Error)
1012 return false;
1013
1014 const LangOptions &LangOpts = PP.getLangOpts();
1015 StringRef Extension = II->getName();
1016
1017 // Normalize the extension name, __foo__ becomes foo.
1018 if (Extension.startswith("__") && Extension.endswith("__") &&
1019 Extension.size() >= 4)
1020 Extension = Extension.substr(2, Extension.size() - 4);
1021
1022 // Because we inherit the feature list from HasFeature, this string switch
1023 // must be less restrictive than HasFeature's.
1024 return llvm::StringSwitch<bool>(Extension)
1025 // C11 features supported by other languages as extensions.
1026 .Case("c_alignas", true)
1027 .Case("c_atomic", true)
1028 .Case("c_generic_selections", true)
1029 .Case("c_static_assert", true)
Ed Schouten401aeba2013-09-14 16:17:20 +00001030 .Case("c_thread_local", PP.getTargetInfo().isTLSSupported())
Richard Smith0a715422013-05-07 19:32:56 +00001031 // C++11 features supported by other languages as extensions.
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001032 .Case("cxx_atomic", LangOpts.CPlusPlus)
1033 .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
1034 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
1035 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
1036 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus)
1037 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
1038 .Case("cxx_override_control", LangOpts.CPlusPlus)
1039 .Case("cxx_range_for", LangOpts.CPlusPlus)
1040 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
1041 .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
Richard Smith0a715422013-05-07 19:32:56 +00001042 // C++1y features supported by other languages as extensions.
1043 .Case("cxx_binary_literals", true)
Richard Smithb438e622013-09-28 04:37:56 +00001044 .Case("cxx_init_captures", LangOpts.CPlusPlus11)
Alp Tokera8bb9c92014-01-15 04:11:24 +00001045 .Case("cxx_variable_templates", LangOpts.CPlusPlus)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001046 .Default(false);
1047}
1048
1049/// HasAttribute - Return true if we recognize and implement the attribute
1050/// specified by the given identifier.
Aaron Ballman0fa06d82014-01-09 22:57:44 +00001051static bool HasAttribute(const IdentifierInfo *II, const llvm::Triple &T) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001052 StringRef Name = II->getName();
1053 // Normalize the attribute name, __foo__ becomes foo.
Aaron Ballman9e264852013-12-06 16:26:55 +00001054 if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__"))
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001055 Name = Name.substr(2, Name.size() - 4);
1056
1057 // FIXME: Do we need to handle namespaces here?
1058 return llvm::StringSwitch<bool>(Name)
1059#include "clang/Lex/AttrSpellings.inc"
1060 .Default(false);
1061}
1062
1063/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
1064/// or '__has_include_next("path")' expression.
1065/// Returns true if successful.
1066static bool EvaluateHasIncludeCommon(Token &Tok,
1067 IdentifierInfo *II, Preprocessor &PP,
1068 const DirectoryLookup *LookupFrom) {
Richard Trieuda031982012-10-22 20:28:48 +00001069 // Save the location of the current token. If a '(' is later found, use
Aaron Ballman5cb24112013-01-15 21:59:46 +00001070 // that location. If not, use the end of this location instead.
Richard Trieuda031982012-10-22 20:28:48 +00001071 SourceLocation LParenLoc = Tok.getLocation();
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001072
Aaron Ballman6ce00002013-01-16 19:32:21 +00001073 // These expressions are only allowed within a preprocessor directive.
1074 if (!PP.isParsingIfOrElifDirective()) {
1075 PP.Diag(LParenLoc, diag::err_pp_directive_required) << II->getName();
1076 return false;
1077 }
1078
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001079 // Get '('.
1080 PP.LexNonComment(Tok);
1081
1082 // Ensure we have a '('.
1083 if (Tok.isNot(tok::l_paren)) {
Richard Trieuda031982012-10-22 20:28:48 +00001084 // No '(', use end of last token.
1085 LParenLoc = PP.getLocForEndOfToken(LParenLoc);
Alp Toker751d6352013-12-30 01:59:29 +00001086 PP.Diag(LParenLoc, diag::err_pp_expected_after) << II << tok::l_paren;
Richard Trieuda031982012-10-22 20:28:48 +00001087 // If the next token looks like a filename or the start of one,
1088 // assume it is and process it as such.
1089 if (!Tok.is(tok::angle_string_literal) && !Tok.is(tok::string_literal) &&
1090 !Tok.is(tok::less))
1091 return false;
1092 } else {
1093 // Save '(' location for possible missing ')' message.
1094 LParenLoc = Tok.getLocation();
1095
Eli Friedmanec94b612013-01-09 02:20:00 +00001096 if (PP.getCurrentLexer()) {
1097 // Get the file name.
1098 PP.getCurrentLexer()->LexIncludeFilename(Tok);
1099 } else {
1100 // We're in a macro, so we can't use LexIncludeFilename; just
1101 // grab the next token.
1102 PP.Lex(Tok);
1103 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001104 }
1105
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001106 // Reserve a buffer to get the spelling.
1107 SmallString<128> FilenameBuffer;
1108 StringRef Filename;
1109 SourceLocation EndLoc;
1110
1111 switch (Tok.getKind()) {
1112 case tok::eod:
1113 // If the token kind is EOD, the error has already been diagnosed.
1114 return false;
1115
1116 case tok::angle_string_literal:
1117 case tok::string_literal: {
1118 bool Invalid = false;
1119 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
1120 if (Invalid)
1121 return false;
1122 break;
1123 }
1124
1125 case tok::less:
1126 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1127 // case, glue the tokens together into FilenameBuffer and interpret those.
1128 FilenameBuffer.push_back('<');
Richard Trieuda031982012-10-22 20:28:48 +00001129 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc)) {
1130 // Let the caller know a <eod> was found by changing the Token kind.
1131 Tok.setKind(tok::eod);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001132 return false; // Found <eod> but no ">"? Diagnostic already emitted.
Richard Trieuda031982012-10-22 20:28:48 +00001133 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001134 Filename = FilenameBuffer.str();
1135 break;
1136 default:
1137 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
1138 return false;
1139 }
1140
Richard Trieuda031982012-10-22 20:28:48 +00001141 SourceLocation FilenameLoc = Tok.getLocation();
1142
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001143 // Get ')'.
1144 PP.LexNonComment(Tok);
1145
1146 // Ensure we have a trailing ).
1147 if (Tok.isNot(tok::r_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001148 PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after)
1149 << II << tok::r_paren;
Alp Tokerec543272013-12-24 09:48:30 +00001150 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001151 return false;
1152 }
1153
1154 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
1155 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1156 // error.
1157 if (Filename.empty())
1158 return false;
1159
1160 // Search include directories.
1161 const DirectoryLookup *CurDir;
1162 const FileEntry *File =
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001163 PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, CurDir, NULL,
1164 NULL, NULL);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001165
1166 // Get the result value. A result of true means the file exists.
1167 return File != 0;
1168}
1169
1170/// EvaluateHasInclude - Process a '__has_include("path")' expression.
1171/// Returns true if successful.
1172static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
1173 Preprocessor &PP) {
1174 return EvaluateHasIncludeCommon(Tok, II, PP, NULL);
1175}
1176
1177/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
1178/// Returns true if successful.
1179static bool EvaluateHasIncludeNext(Token &Tok,
1180 IdentifierInfo *II, Preprocessor &PP) {
1181 // __has_include_next is like __has_include, except that we start
1182 // searching after the current found directory. If we can't do this,
1183 // issue a diagnostic.
1184 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
1185 if (PP.isInPrimaryFile()) {
1186 Lookup = 0;
1187 PP.Diag(Tok, diag::pp_include_next_in_primary);
1188 } else if (Lookup == 0) {
1189 PP.Diag(Tok, diag::pp_include_next_absolute_path);
1190 } else {
1191 // Start looking up in the next directory.
1192 ++Lookup;
1193 }
1194
1195 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup);
1196}
1197
Douglas Gregorc83de302012-09-25 15:44:52 +00001198/// \brief Process __building_module(identifier) expression.
1199/// \returns true if we are building the named module, false otherwise.
1200static bool EvaluateBuildingModule(Token &Tok,
1201 IdentifierInfo *II, Preprocessor &PP) {
1202 // Get '('.
1203 PP.LexNonComment(Tok);
1204
1205 // Ensure we have a '('.
1206 if (Tok.isNot(tok::l_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001207 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1208 << tok::l_paren;
Douglas Gregorc83de302012-09-25 15:44:52 +00001209 return false;
1210 }
1211
1212 // Save '(' location for possible missing ')' message.
1213 SourceLocation LParenLoc = Tok.getLocation();
1214
1215 // Get the module name.
1216 PP.LexNonComment(Tok);
1217
1218 // Ensure that we have an identifier.
1219 if (Tok.isNot(tok::identifier)) {
1220 PP.Diag(Tok.getLocation(), diag::err_expected_id_building_module);
1221 return false;
1222 }
1223
1224 bool Result
1225 = Tok.getIdentifierInfo()->getName() == PP.getLangOpts().CurrentModule;
1226
1227 // Get ')'.
1228 PP.LexNonComment(Tok);
1229
1230 // Ensure we have a trailing ).
1231 if (Tok.isNot(tok::r_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001232 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1233 << tok::r_paren;
Alp Tokerec543272013-12-24 09:48:30 +00001234 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
Douglas Gregorc83de302012-09-25 15:44:52 +00001235 return false;
1236 }
1237
1238 return Result;
1239}
1240
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001241/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1242/// as a builtin macro, handle it and return the next token as 'Tok'.
1243void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
1244 // Figure out which token this is.
1245 IdentifierInfo *II = Tok.getIdentifierInfo();
1246 assert(II && "Can't be a macro without id info!");
1247
1248 // If this is an _Pragma or Microsoft __pragma directive, expand it,
1249 // invoke the pragma handler, then lex the token after it.
1250 if (II == Ident_Pragma)
1251 return Handle_Pragma(Tok);
1252 else if (II == Ident__pragma) // in non-MS mode this is null
1253 return HandleMicrosoft__pragma(Tok);
1254
1255 ++NumBuiltinMacroExpanded;
1256
1257 SmallString<128> TmpBuffer;
1258 llvm::raw_svector_ostream OS(TmpBuffer);
1259
1260 // Set up the return result.
1261 Tok.setIdentifierInfo(0);
1262 Tok.clearFlag(Token::NeedsCleaning);
1263
1264 if (II == Ident__LINE__) {
1265 // C99 6.10.8: "__LINE__: The presumed line number (within the current
1266 // source file) of the current source line (an integer constant)". This can
1267 // be affected by #line.
1268 SourceLocation Loc = Tok.getLocation();
1269
1270 // Advance to the location of the first _, this might not be the first byte
1271 // of the token if it starts with an escaped newline.
1272 Loc = AdvanceToTokenCharacter(Loc, 0);
1273
1274 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
1275 // a macro expansion. This doesn't matter for object-like macros, but
1276 // can matter for a function-like macro that expands to contain __LINE__.
1277 // Skip down through expansion points until we find a file loc for the
1278 // end of the expansion history.
1279 Loc = SourceMgr.getExpansionRange(Loc).second;
1280 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
1281
1282 // __LINE__ expands to a simple numeric value.
1283 OS << (PLoc.isValid()? PLoc.getLine() : 1);
1284 Tok.setKind(tok::numeric_constant);
1285 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
1286 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
1287 // character string literal)". This can be affected by #line.
1288 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1289
1290 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
1291 // #include stack instead of the current file.
1292 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
1293 SourceLocation NextLoc = PLoc.getIncludeLoc();
1294 while (NextLoc.isValid()) {
1295 PLoc = SourceMgr.getPresumedLoc(NextLoc);
1296 if (PLoc.isInvalid())
1297 break;
1298
1299 NextLoc = PLoc.getIncludeLoc();
1300 }
1301 }
1302
1303 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
1304 SmallString<128> FN;
1305 if (PLoc.isValid()) {
1306 FN += PLoc.getFilename();
1307 Lexer::Stringify(FN);
1308 OS << '"' << FN.str() << '"';
1309 }
1310 Tok.setKind(tok::string_literal);
1311 } else if (II == Ident__DATE__) {
1312 if (!DATELoc.isValid())
1313 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1314 Tok.setKind(tok::string_literal);
1315 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1316 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
1317 Tok.getLocation(),
1318 Tok.getLength()));
1319 return;
1320 } else if (II == Ident__TIME__) {
1321 if (!TIMELoc.isValid())
1322 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1323 Tok.setKind(tok::string_literal);
1324 Tok.setLength(strlen("\"hh:mm:ss\""));
1325 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
1326 Tok.getLocation(),
1327 Tok.getLength()));
1328 return;
1329 } else if (II == Ident__INCLUDE_LEVEL__) {
1330 // Compute the presumed include depth of this token. This can be affected
1331 // by GNU line markers.
1332 unsigned Depth = 0;
1333
1334 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1335 if (PLoc.isValid()) {
1336 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1337 for (; PLoc.isValid(); ++Depth)
1338 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1339 }
1340
1341 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1342 OS << Depth;
1343 Tok.setKind(tok::numeric_constant);
1344 } else if (II == Ident__TIMESTAMP__) {
1345 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1346 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1347
1348 // Get the file that we are lexing out of. If we're currently lexing from
1349 // a macro, dig into the include stack.
1350 const FileEntry *CurFile = 0;
1351 PreprocessorLexer *TheLexer = getCurrentFileLexer();
1352
1353 if (TheLexer)
1354 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
1355
1356 const char *Result;
1357 if (CurFile) {
1358 time_t TT = CurFile->getModificationTime();
1359 struct tm *TM = localtime(&TT);
1360 Result = asctime(TM);
1361 } else {
1362 Result = "??? ??? ?? ??:??:?? ????\n";
1363 }
1364 // Surround the string with " and strip the trailing newline.
1365 OS << '"' << StringRef(Result, strlen(Result)-1) << '"';
1366 Tok.setKind(tok::string_literal);
1367 } else if (II == Ident__COUNTER__) {
1368 // __COUNTER__ expands to a simple numeric value.
1369 OS << CounterValue++;
1370 Tok.setKind(tok::numeric_constant);
1371 } else if (II == Ident__has_feature ||
1372 II == Ident__has_extension ||
1373 II == Ident__has_builtin ||
1374 II == Ident__has_attribute) {
1375 // The argument to these builtins should be a parenthesized identifier.
1376 SourceLocation StartLoc = Tok.getLocation();
1377
1378 bool IsValid = false;
1379 IdentifierInfo *FeatureII = 0;
1380
1381 // Read the '('.
Andy Gibbsd41d0942012-11-17 19:18:27 +00001382 LexUnexpandedToken(Tok);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001383 if (Tok.is(tok::l_paren)) {
1384 // Read the identifier
Andy Gibbsd41d0942012-11-17 19:18:27 +00001385 LexUnexpandedToken(Tok);
Richard Smithbaf29122013-07-09 00:57:56 +00001386 if ((FeatureII = Tok.getIdentifierInfo())) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001387 // Read the ')'.
Andy Gibbsd41d0942012-11-17 19:18:27 +00001388 LexUnexpandedToken(Tok);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001389 if (Tok.is(tok::r_paren))
1390 IsValid = true;
1391 }
1392 }
1393
1394 bool Value = false;
1395 if (!IsValid)
1396 Diag(StartLoc, diag::err_feature_check_malformed);
1397 else if (II == Ident__has_builtin) {
1398 // Check for a builtin is trivial.
1399 Value = FeatureII->getBuiltinID() != 0;
1400 } else if (II == Ident__has_attribute)
Aaron Ballman0fa06d82014-01-09 22:57:44 +00001401 Value = HasAttribute(FeatureII, getTargetInfo().getTriple());
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}