blob: 8dccae1aaa3686e743c17687d14d93211219ac49 [file] [log] [blame]
Joao Matos3e1ec722012-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//
10// This file implements the top level handling of macro expasion for the
11// preprocessor.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Preprocessor.h"
Argyrios Kyrtzidisdd08a0c2013-05-03 22:31:32 +000016#include "clang/Lex/MacroArgs.h"
Joao Matos3e1ec722012-08-31 21:34:27 +000017#include "clang/Basic/FileManager.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000018#include "clang/Basic/SourceManager.h"
Joao Matos3e1ec722012-08-31 21:34:27 +000019#include "clang/Basic/TargetInfo.h"
Joao Matos3e1ec722012-08-31 21:34:27 +000020#include "clang/Lex/CodeCompletionHandler.h"
21#include "clang/Lex/ExternalPreprocessorSource.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000022#include "clang/Lex/LexDiagnostic.h"
23#include "clang/Lex/MacroInfo.h"
24#include "llvm/ADT/STLExtras.h"
Andy Gibbs02a17682012-11-17 19:15:38 +000025#include "llvm/ADT/SmallString.h"
Joao Matos3e1ec722012-08-31 21:34:27 +000026#include "llvm/ADT/StringSwitch.h"
Joao Matos3e1ec722012-08-31 21:34:27 +000027#include "llvm/Config/llvm-config.h"
Joao Matos3e1ec722012-08-31 21:34:27 +000028#include "llvm/Support/ErrorHandling.h"
Dmitri Gribenko33d054b2012-09-24 20:56:28 +000029#include "llvm/Support/Format.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000030#include "llvm/Support/raw_ostream.h"
Joao Matos3e1ec722012-08-31 21:34:27 +000031#include <cstdio>
32#include <ctime>
33using namespace clang;
34
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +000035MacroDirective *
36Preprocessor::getMacroDirectiveHistory(const IdentifierInfo *II) const {
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +000037 assert(II->hadMacroDefinition() && "Identifier has not been not a macro!");
Joao Matos3e1ec722012-08-31 21:34:27 +000038
39 macro_iterator Pos = Macros.find(II);
Joao Matos3e1ec722012-08-31 21:34:27 +000040 assert(Pos != Macros.end() && "Identifier macro info is missing!");
Joao Matos3e1ec722012-08-31 21:34:27 +000041 return Pos->second;
42}
43
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +000044void Preprocessor::appendMacroDirective(IdentifierInfo *II, MacroDirective *MD){
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +000045 assert(MD && "MacroDirective should be non-zero!");
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +000046 assert(!MD->getPrevious() && "Already attached to a MacroDirective history.");
Douglas Gregor6c6c54a2012-10-11 00:46:49 +000047
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +000048 MacroDirective *&StoredMD = Macros[II];
49 MD->setPrevious(StoredMD);
50 StoredMD = MD;
Argyrios Kyrtzidisc56fff72013-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 Matos3e1ec722012-08-31 21:34:27 +000055 II->setChangedSinceDeserialization();
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +000056}
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +000057
Argyrios Kyrtzidis9317ab92013-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 Matos3e1ec722012-08-31 21:34:27 +000069}
70
Joao Matos3e1ec722012-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 Kyrtzidisc56fff72013-03-26 17:17:01 +000080 PP.appendDefMacroDirective(Id, MI);
Joao Matos3e1ec722012-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
100 // Clang Extensions.
101 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
102 Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension");
103 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
104 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
105 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
106 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
107 Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning");
108
Douglas Gregorb09de512012-09-25 15:44:52 +0000109 // Modules.
110 if (LangOpts.Modules) {
111 Ident__building_module = RegisterBuiltinMacro(*this, "__building_module");
112
113 // __MODULE__
114 if (!LangOpts.CurrentModule.empty())
115 Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__");
116 else
117 Ident__MODULE__ = 0;
118 } else {
119 Ident__building_module = 0;
120 Ident__MODULE__ = 0;
121 }
122
Joao Matos3e1ec722012-08-31 21:34:27 +0000123 // Microsoft Extensions.
124 if (LangOpts.MicrosoftExt)
125 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
126 else
127 Ident__pragma = 0;
128}
129
130/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
131/// in its expansion, currently expands to that token literally.
132static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
133 const IdentifierInfo *MacroIdent,
134 Preprocessor &PP) {
135 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
136
137 // If the token isn't an identifier, it's always literally expanded.
138 if (II == 0) return true;
139
140 // If the information about this identifier is out of date, update it from
141 // the external source.
142 if (II->isOutOfDate())
143 PP.getExternalSource()->updateOutOfDateIdentifier(*II);
144
145 // If the identifier is a macro, and if that macro is enabled, it may be
146 // expanded so it's not a trivial expansion.
147 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
148 // Fast expanding "#define X X" is ok, because X would be disabled.
149 II != MacroIdent)
150 return false;
151
152 // If this is an object-like macro invocation, it is safe to trivially expand
153 // it.
154 if (MI->isObjectLike()) return true;
155
156 // If this is a function-like macro invocation, it's safe to trivially expand
157 // as long as the identifier is not a macro argument.
158 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
159 I != E; ++I)
160 if (*I == II)
161 return false; // Identifier is a macro argument.
162
163 return true;
164}
165
166
167/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
168/// lexed is a '('. If so, consume the token and return true, if not, this
169/// method should have no observable side-effect on the lexed tokens.
170bool Preprocessor::isNextPPTokenLParen() {
171 // Do some quick tests for rejection cases.
172 unsigned Val;
173 if (CurLexer)
174 Val = CurLexer->isNextPPTokenLParen();
175 else if (CurPTHLexer)
176 Val = CurPTHLexer->isNextPPTokenLParen();
177 else
178 Val = CurTokenLexer->isNextTokenLParen();
179
180 if (Val == 2) {
181 // We have run off the end. If it's a source file we don't
182 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
183 // macro stack.
184 if (CurPPLexer)
185 return false;
186 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
187 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
188 if (Entry.TheLexer)
189 Val = Entry.TheLexer->isNextPPTokenLParen();
190 else if (Entry.ThePTHLexer)
191 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
192 else
193 Val = Entry.TheTokenLexer->isNextTokenLParen();
194
195 if (Val != 2)
196 break;
197
198 // Ran off the end of a source file?
199 if (Entry.ThePPLexer)
200 return false;
201 }
202 }
203
204 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
205 // have found something that isn't a '(' or we found the end of the
206 // translation unit. In either case, return false.
207 return Val == 1;
208}
209
210/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
211/// expanded as a macro, handle it and return the next token as 'Identifier'.
212bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +0000213 MacroDirective *MD) {
Argyrios Kyrtzidis35803282013-03-27 01:25:19 +0000214 MacroDirective::DefInfo Def = MD->getDefinition();
215 assert(Def.isValid());
216 MacroInfo *MI = Def.getMacroInfo();
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +0000217
Joao Matos3e1ec722012-08-31 21:34:27 +0000218 // If this is a macro expansion in the "#if !defined(x)" line for the file,
219 // then the macro could expand to different things in other contexts, we need
220 // to disable the optimization in this case.
221 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
222
223 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
224 if (MI->isBuiltinMacro()) {
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +0000225 if (Callbacks) Callbacks->MacroExpands(Identifier, MD,
Argyrios Kyrtzidisdd08a0c2013-05-03 22:31:32 +0000226 Identifier.getLocation(),/*Args=*/0);
Joao Matos3e1ec722012-08-31 21:34:27 +0000227 ExpandBuiltinMacro(Identifier);
228 return false;
229 }
230
231 /// Args - If this is a function-like macro expansion, this contains,
232 /// for each macro argument, the list of tokens that were provided to the
233 /// invocation.
234 MacroArgs *Args = 0;
235
236 // Remember where the end of the expansion occurred. For an object-like
237 // macro, this is the identifier. For a function-like macro, this is the ')'.
238 SourceLocation ExpansionEnd = Identifier.getLocation();
239
240 // If this is a function-like macro, read the arguments.
241 if (MI->isFunctionLike()) {
242 // C99 6.10.3p10: If the preprocessing token immediately after the macro
243 // name isn't a '(', this macro should not be expanded.
244 if (!isNextPPTokenLParen())
245 return true;
246
247 // Remember that we are now parsing the arguments to a macro invocation.
248 // Preprocessor directives used inside macro arguments are not portable, and
249 // this enables the warning.
250 InMacroArgs = true;
251 Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd);
252
253 // Finished parsing args.
254 InMacroArgs = false;
255
256 // If there was an error parsing the arguments, bail out.
257 if (Args == 0) return false;
258
259 ++NumFnMacroExpanded;
260 } else {
261 ++NumMacroExpanded;
262 }
263
264 // Notice that this macro has been used.
265 markMacroAsUsed(MI);
266
267 // Remember where the token is expanded.
268 SourceLocation ExpandLoc = Identifier.getLocation();
269 SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
270
271 if (Callbacks) {
272 if (InMacroArgs) {
273 // We can have macro expansion inside a conditional directive while
274 // reading the function macro arguments. To ensure, in that case, that
275 // MacroExpands callbacks still happen in source order, queue this
276 // callback to have it happen after the function macro callback.
277 DelayedMacroExpandsCallbacks.push_back(
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +0000278 MacroExpandsInfo(Identifier, MD, ExpansionRange));
Joao Matos3e1ec722012-08-31 21:34:27 +0000279 } else {
Argyrios Kyrtzidisdd08a0c2013-05-03 22:31:32 +0000280 Callbacks->MacroExpands(Identifier, MD, ExpansionRange, Args);
Joao Matos3e1ec722012-08-31 21:34:27 +0000281 if (!DelayedMacroExpandsCallbacks.empty()) {
282 for (unsigned i=0, e = DelayedMacroExpandsCallbacks.size(); i!=e; ++i) {
283 MacroExpandsInfo &Info = DelayedMacroExpandsCallbacks[i];
Argyrios Kyrtzidisdd08a0c2013-05-03 22:31:32 +0000284 // FIXME: We lose macro args info with delayed callback.
285 Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range, /*Args=*/0);
Joao Matos3e1ec722012-08-31 21:34:27 +0000286 }
287 DelayedMacroExpandsCallbacks.clear();
288 }
289 }
290 }
Douglas Gregore8219a62012-10-11 21:07:39 +0000291
292 // If the macro definition is ambiguous, complain.
Argyrios Kyrtzidis35803282013-03-27 01:25:19 +0000293 if (Def.getDirective()->isAmbiguous()) {
Douglas Gregore8219a62012-10-11 21:07:39 +0000294 Diag(Identifier, diag::warn_pp_ambiguous_macro)
295 << Identifier.getIdentifierInfo();
296 Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)
297 << Identifier.getIdentifierInfo();
Argyrios Kyrtzidis35803282013-03-27 01:25:19 +0000298 for (MacroDirective::DefInfo PrevDef = Def.getPreviousDefinition();
299 PrevDef && !PrevDef.isUndefined();
300 PrevDef = PrevDef.getPreviousDefinition()) {
301 if (PrevDef.getDirective()->isAmbiguous()) {
302 Diag(PrevDef.getMacroInfo()->getDefinitionLoc(),
303 diag::note_pp_ambiguous_macro_other)
Douglas Gregore8219a62012-10-11 21:07:39 +0000304 << Identifier.getIdentifierInfo();
305 }
306 }
307 }
308
Joao Matos3e1ec722012-08-31 21:34:27 +0000309 // If we started lexing a macro, enter the macro expansion body.
310
311 // If this macro expands to no tokens, don't bother to push it onto the
312 // expansion stack, only to take it right back off.
313 if (MI->getNumTokens() == 0) {
314 // No need for arg info.
315 if (Args) Args->destroy(*this);
316
317 // Ignore this macro use, just return the next token in the current
318 // buffer.
319 bool HadLeadingSpace = Identifier.hasLeadingSpace();
320 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
321
322 Lex(Identifier);
323
324 // If the identifier isn't on some OTHER line, inherit the leading
325 // whitespace/first-on-a-line property of this token. This handles
326 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
327 // empty.
328 if (!Identifier.isAtStartOfLine()) {
329 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
330 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
331 }
332 Identifier.setFlag(Token::LeadingEmptyMacro);
333 ++NumFastMacroExpanded;
334 return false;
335
336 } else if (MI->getNumTokens() == 1 &&
337 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
338 *this)) {
339 // Otherwise, if this macro expands into a single trivially-expanded
340 // token: expand it now. This handles common cases like
341 // "#define VAL 42".
342
343 // No need for arg info.
344 if (Args) Args->destroy(*this);
345
346 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
347 // identifier to the expanded token.
348 bool isAtStartOfLine = Identifier.isAtStartOfLine();
349 bool hasLeadingSpace = Identifier.hasLeadingSpace();
350
351 // Replace the result token.
352 Identifier = MI->getReplacementToken(0);
353
354 // Restore the StartOfLine/LeadingSpace markers.
355 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
356 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
357
358 // Update the tokens location to include both its expansion and physical
359 // locations.
360 SourceLocation Loc =
361 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
362 ExpansionEnd,Identifier.getLength());
363 Identifier.setLocation(Loc);
364
365 // If this is a disabled macro or #define X X, we must mark the result as
366 // unexpandable.
367 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
368 if (MacroInfo *NewMI = getMacroInfo(NewII))
369 if (!NewMI->isEnabled() || NewMI == MI) {
370 Identifier.setFlag(Token::DisableExpand);
Douglas Gregor40f56e52013-01-30 23:10:17 +0000371 // Don't warn for "#define X X" like "#define bool bool" from
372 // stdbool.h.
373 if (NewMI != MI || MI->isFunctionLike())
374 Diag(Identifier, diag::pp_disabled_macro_expansion);
Joao Matos3e1ec722012-08-31 21:34:27 +0000375 }
376 }
377
378 // Since this is not an identifier token, it can't be macro expanded, so
379 // we're done.
380 ++NumFastMacroExpanded;
381 return false;
382 }
383
384 // Start expanding the macro.
385 EnterMacro(Identifier, ExpansionEnd, MI, Args);
386
387 // Now that the macro is at the top of the include stack, ask the
388 // preprocessor to read the next token from it.
389 Lex(Identifier);
390 return false;
391}
392
Richard Trieu5940bf32013-07-23 18:01:49 +0000393enum Bracket {
394 Brace,
395 Paren
396};
397
398/// CheckMatchedBrackets - Returns true if the braces and parentheses in the
399/// token vector are properly nested.
400static bool CheckMatchedBrackets(const SmallVectorImpl<Token> &Tokens) {
401 SmallVector<Bracket, 8> Brackets;
402 for (SmallVectorImpl<Token>::const_iterator I = Tokens.begin(),
403 E = Tokens.end();
404 I != E; ++I) {
405 if (I->is(tok::l_paren)) {
406 Brackets.push_back(Paren);
407 } else if (I->is(tok::r_paren)) {
408 if (Brackets.empty() || Brackets.back() == Brace)
409 return false;
410 Brackets.pop_back();
411 } else if (I->is(tok::l_brace)) {
412 Brackets.push_back(Brace);
413 } else if (I->is(tok::r_brace)) {
414 if (Brackets.empty() || Brackets.back() == Paren)
415 return false;
416 Brackets.pop_back();
417 }
418 }
419 if (!Brackets.empty())
420 return false;
421 return true;
422}
423
424/// GenerateNewArgTokens - Returns true if OldTokens can be converted to a new
425/// vector of tokens in NewTokens. The new number of arguments will be placed
426/// in NumArgs and the ranges which need to surrounded in parentheses will be
427/// in ParenHints.
428/// Returns false if the token stream cannot be changed. If this is because
429/// of an initializer list starting a macro argument, the range of those
430/// initializer lists will be place in InitLists.
431static bool GenerateNewArgTokens(Preprocessor &PP,
432 SmallVectorImpl<Token> &OldTokens,
433 SmallVectorImpl<Token> &NewTokens,
434 unsigned &NumArgs,
435 SmallVectorImpl<SourceRange> &ParenHints,
436 SmallVectorImpl<SourceRange> &InitLists) {
437 if (!CheckMatchedBrackets(OldTokens))
438 return false;
439
440 // Once it is known that the brackets are matched, only a simple count of the
441 // braces is needed.
442 unsigned Braces = 0;
443
444 // First token of a new macro argument.
445 SmallVectorImpl<Token>::iterator ArgStartIterator = OldTokens.begin();
446
447 // First closing brace in a new macro argument. Used to generate
448 // SourceRanges for InitLists.
449 SmallVectorImpl<Token>::iterator ClosingBrace = OldTokens.end();
450 NumArgs = 0;
451 Token TempToken;
452 // Set to true when a macro separator token is found inside a braced list.
453 // If true, the fixed argument spans multiple old arguments and ParenHints
454 // will be updated.
455 bool FoundSeparatorToken = false;
456 for (SmallVectorImpl<Token>::iterator I = OldTokens.begin(),
457 E = OldTokens.end();
458 I != E; ++I) {
459 if (I->is(tok::l_brace)) {
460 ++Braces;
461 } else if (I->is(tok::r_brace)) {
462 --Braces;
463 if (Braces == 0 && ClosingBrace == E && FoundSeparatorToken)
464 ClosingBrace = I;
465 } else if (I->is(tok::eof)) {
466 // EOF token is used to separate macro arguments
467 if (Braces != 0) {
468 // Assume comma separator is actually braced list separator and change
469 // it back to a comma.
470 FoundSeparatorToken = true;
471 I->setKind(tok::comma);
472 I->setLength(1);
473 } else { // Braces == 0
474 // Separator token still separates arguments.
475 ++NumArgs;
476
477 // If the argument starts with a brace, it can't be fixed with
478 // parentheses. A different diagnostic will be given.
479 if (FoundSeparatorToken && ArgStartIterator->is(tok::l_brace)) {
480 InitLists.push_back(
481 SourceRange(ArgStartIterator->getLocation(),
482 PP.getLocForEndOfToken(ClosingBrace->getLocation())));
483 ClosingBrace = E;
484 }
485
486 // Add left paren
487 if (FoundSeparatorToken) {
488 TempToken.startToken();
489 TempToken.setKind(tok::l_paren);
490 TempToken.setLocation(ArgStartIterator->getLocation());
491 TempToken.setLength(0);
492 NewTokens.push_back(TempToken);
493 }
494
495 // Copy over argument tokens
496 NewTokens.insert(NewTokens.end(), ArgStartIterator, I);
497
498 // Add right paren and store the paren locations in ParenHints
499 if (FoundSeparatorToken) {
500 SourceLocation Loc = PP.getLocForEndOfToken((I - 1)->getLocation());
501 TempToken.startToken();
502 TempToken.setKind(tok::r_paren);
503 TempToken.setLocation(Loc);
504 TempToken.setLength(0);
505 NewTokens.push_back(TempToken);
506 ParenHints.push_back(SourceRange(ArgStartIterator->getLocation(),
507 Loc));
508 }
509
510 // Copy separator token
511 NewTokens.push_back(*I);
512
513 // Reset values
514 ArgStartIterator = I + 1;
515 FoundSeparatorToken = false;
516 }
517 }
518 }
519
520 return !ParenHints.empty() && InitLists.empty();
521}
522
Joao Matos3e1ec722012-08-31 21:34:27 +0000523/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
524/// token is the '(' of the macro, this method is invoked to read all of the
525/// actual arguments specified for the macro invocation. This returns null on
526/// error.
527MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
528 MacroInfo *MI,
529 SourceLocation &MacroEnd) {
530 // The number of fixed arguments to parse.
531 unsigned NumFixedArgsLeft = MI->getNumArgs();
532 bool isVariadic = MI->isVariadic();
533
534 // Outer loop, while there are more arguments, keep reading them.
535 Token Tok;
536
537 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
538 // an argument value in a macro could expand to ',' or '(' or ')'.
539 LexUnexpandedToken(Tok);
540 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
541
542 // ArgTokens - Build up a list of tokens that make up each argument. Each
543 // argument is separated by an EOF token. Use a SmallVector so we can avoid
544 // heap allocations in the common case.
545 SmallVector<Token, 64> ArgTokens;
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000546 bool ContainsCodeCompletionTok = false;
Joao Matos3e1ec722012-08-31 21:34:27 +0000547
Richard Trieu5940bf32013-07-23 18:01:49 +0000548 SourceLocation TooManyArgsLoc;
549
Joao Matos3e1ec722012-08-31 21:34:27 +0000550 unsigned NumActuals = 0;
551 while (Tok.isNot(tok::r_paren)) {
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000552 if (ContainsCodeCompletionTok && (Tok.is(tok::eof) || Tok.is(tok::eod)))
553 break;
554
Joao Matos3e1ec722012-08-31 21:34:27 +0000555 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
556 "only expect argument separators here");
557
558 unsigned ArgTokenStart = ArgTokens.size();
559 SourceLocation ArgStartLoc = Tok.getLocation();
560
561 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
562 // that we already consumed the first one.
563 unsigned NumParens = 0;
564
565 while (1) {
566 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
567 // an argument value in a macro could expand to ',' or '(' or ')'.
568 LexUnexpandedToken(Tok);
569
570 if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n"
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000571 if (!ContainsCodeCompletionTok) {
572 Diag(MacroName, diag::err_unterm_macro_invoc);
573 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
574 << MacroName.getIdentifierInfo();
575 // Do not lose the EOF/EOD. Return it to the client.
576 MacroName = Tok;
577 return 0;
578 } else {
Argyrios Kyrtzidisbb06b502012-12-22 04:48:10 +0000579 // Do not lose the EOF/EOD.
580 Token *Toks = new Token[1];
581 Toks[0] = Tok;
582 EnterTokenStream(Toks, 1, true, true);
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000583 break;
584 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000585 } else if (Tok.is(tok::r_paren)) {
586 // If we found the ) token, the macro arg list is done.
587 if (NumParens-- == 0) {
588 MacroEnd = Tok.getLocation();
589 break;
590 }
591 } else if (Tok.is(tok::l_paren)) {
592 ++NumParens;
Reid Kleckner11be0642013-06-26 17:16:08 +0000593 } else if (Tok.is(tok::comma) && NumParens == 0 &&
594 !(Tok.getFlags() & Token::IgnoredComma)) {
595 // In Microsoft-compatibility mode, single commas from nested macro
596 // expansions should not be considered as argument separators. We test
597 // for this with the IgnoredComma token flag above.
598
Joao Matos3e1ec722012-08-31 21:34:27 +0000599 // Comma ends this argument if there are more fixed arguments expected.
600 // However, if this is a variadic macro, and this is part of the
601 // variadic part, then the comma is just an argument token.
602 if (!isVariadic) break;
603 if (NumFixedArgsLeft > 1)
604 break;
605 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
606 // If this is a comment token in the argument list and we're just in
607 // -C mode (not -CC mode), discard the comment.
608 continue;
609 } else if (Tok.getIdentifierInfo() != 0) {
610 // Reading macro arguments can cause macros that we are currently
611 // expanding from to be popped off the expansion stack. Doing so causes
612 // them to be reenabled for expansion. Here we record whether any
613 // identifiers we lex as macro arguments correspond to disabled macros.
614 // If so, we mark the token as noexpand. This is a subtle aspect of
615 // C99 6.10.3.4p2.
616 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
617 if (!MI->isEnabled())
618 Tok.setFlag(Token::DisableExpand);
619 } else if (Tok.is(tok::code_completion)) {
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000620 ContainsCodeCompletionTok = true;
Joao Matos3e1ec722012-08-31 21:34:27 +0000621 if (CodeComplete)
622 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
623 MI, NumActuals);
624 // Don't mark that we reached the code-completion point because the
625 // parser is going to handle the token and there will be another
626 // code-completion callback.
627 }
628
629 ArgTokens.push_back(Tok);
630 }
631
632 // If this was an empty argument list foo(), don't add this as an empty
633 // argument.
634 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
635 break;
636
637 // If this is not a variadic macro, and too many args were specified, emit
638 // an error.
Richard Trieu5940bf32013-07-23 18:01:49 +0000639 if (!isVariadic && NumFixedArgsLeft == 0 && TooManyArgsLoc.isInvalid()) {
Joao Matos3e1ec722012-08-31 21:34:27 +0000640 if (ArgTokens.size() != ArgTokenStart)
Richard Trieu5940bf32013-07-23 18:01:49 +0000641 TooManyArgsLoc = ArgTokens[ArgTokenStart].getLocation();
642 else
643 TooManyArgsLoc = ArgStartLoc;
Joao Matos3e1ec722012-08-31 21:34:27 +0000644 }
645
Richard Trieu5940bf32013-07-23 18:01:49 +0000646 // Empty arguments are standard in C99 and C++0x, and are supported as an
647 // extension in other modes.
Joao Matos3e1ec722012-08-31 21:34:27 +0000648 if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99)
Richard Smith80ad52f2013-01-02 11:42:31 +0000649 Diag(Tok, LangOpts.CPlusPlus11 ?
Joao Matos3e1ec722012-08-31 21:34:27 +0000650 diag::warn_cxx98_compat_empty_fnmacro_arg :
651 diag::ext_empty_fnmacro_arg);
652
653 // Add a marker EOF token to the end of the token list for this argument.
654 Token EOFTok;
655 EOFTok.startToken();
656 EOFTok.setKind(tok::eof);
657 EOFTok.setLocation(Tok.getLocation());
658 EOFTok.setLength(0);
659 ArgTokens.push_back(EOFTok);
660 ++NumActuals;
Richard Trieu5940bf32013-07-23 18:01:49 +0000661 if (!ContainsCodeCompletionTok && NumFixedArgsLeft != 0)
Argyrios Kyrtzidisfdf57062013-02-22 22:28:58 +0000662 --NumFixedArgsLeft;
Joao Matos3e1ec722012-08-31 21:34:27 +0000663 }
664
665 // Okay, we either found the r_paren. Check to see if we parsed too few
666 // arguments.
667 unsigned MinArgsExpected = MI->getNumArgs();
668
Richard Trieu5940bf32013-07-23 18:01:49 +0000669 // If this is not a variadic macro, and too many args were specified, emit
670 // an error.
671 if (!isVariadic && NumActuals > MinArgsExpected &&
672 !ContainsCodeCompletionTok) {
673 // Emit the diagnostic at the macro name in case there is a missing ).
674 // Emitting it at the , could be far away from the macro name.
675 Diag(TooManyArgsLoc, diag::err_too_many_args_in_macro_invoc);
676 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
677 << MacroName.getIdentifierInfo();
678
679 // Commas from braced initializer lists will be treated as argument
680 // separators inside macros. Attempt to correct for this with parentheses.
681 // TODO: See if this can be generalized to angle brackets for templates
682 // inside macro arguments.
683
684 SmallVector<Token, 64> FixedArgTokens;
685 unsigned FixedNumArgs = 0;
686 SmallVector<SourceRange, 4> ParenHints, InitLists;
687 if (!GenerateNewArgTokens(*this, ArgTokens, FixedArgTokens, FixedNumArgs,
688 ParenHints, InitLists)) {
689 if (!InitLists.empty()) {
690 DiagnosticBuilder DB =
691 Diag(MacroName,
692 diag::note_init_list_at_beginning_of_macro_argument);
693 for (SmallVector<SourceRange, 4>::iterator
694 Range = InitLists.begin(), RangeEnd = InitLists.end();
695 Range != RangeEnd; ++Range) {
696 if (DB.hasMaxRanges())
697 break;
698 DB << *Range;
699 }
700 }
701 return 0;
702 }
703 if (FixedNumArgs != MinArgsExpected)
704 return 0;
705
706 DiagnosticBuilder DB = Diag(MacroName, diag::note_suggest_parens_for_macro);
707 for (SmallVector<SourceRange, 4>::iterator
708 ParenLocation = ParenHints.begin(), ParenEnd = ParenHints.end();
709 ParenLocation != ParenEnd; ++ParenLocation) {
710 if (DB.hasMaxFixItHints())
711 break;
712 DB << FixItHint::CreateInsertion(ParenLocation->getBegin(), "(");
713 if (DB.hasMaxFixItHints())
714 break;
715 DB << FixItHint::CreateInsertion(ParenLocation->getEnd(), ")");
716 }
717 ArgTokens.swap(FixedArgTokens);
718 NumActuals = FixedNumArgs;
719 }
720
Joao Matos3e1ec722012-08-31 21:34:27 +0000721 // See MacroArgs instance var for description of this.
722 bool isVarargsElided = false;
723
Argyrios Kyrtzidisf1e5b152012-12-21 01:51:12 +0000724 if (ContainsCodeCompletionTok) {
725 // Recover from not-fully-formed macro invocation during code-completion.
726 Token EOFTok;
727 EOFTok.startToken();
728 EOFTok.setKind(tok::eof);
729 EOFTok.setLocation(Tok.getLocation());
730 EOFTok.setLength(0);
731 for (; NumActuals < MinArgsExpected; ++NumActuals)
732 ArgTokens.push_back(EOFTok);
733 }
734
Joao Matos3e1ec722012-08-31 21:34:27 +0000735 if (NumActuals < MinArgsExpected) {
736 // There are several cases where too few arguments is ok, handle them now.
737 if (NumActuals == 0 && MinArgsExpected == 1) {
738 // #define A(X) or #define A(...) ---> A()
739
740 // If there is exactly one argument, and that argument is missing,
741 // then we have an empty "()" argument empty list. This is fine, even if
742 // the macro expects one argument (the argument is just empty).
743 isVarargsElided = MI->isVariadic();
744 } else if (MI->isVariadic() &&
745 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
746 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
747 // Varargs where the named vararg parameter is missing: OK as extension.
748 // #define A(x, ...)
749 // A("blah")
Eli Friedman4fa4b482012-11-14 02:18:46 +0000750 //
751 // If the macro contains the comma pasting extension, the diagnostic
752 // is suppressed; we know we'll get another diagnostic later.
753 if (!MI->hasCommaPasting()) {
754 Diag(Tok, diag::ext_missing_varargs_arg);
755 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
756 << MacroName.getIdentifierInfo();
757 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000758
759 // Remember this occurred, allowing us to elide the comma when used for
760 // cases like:
761 // #define A(x, foo...) blah(a, ## foo)
762 // #define B(x, ...) blah(a, ## __VA_ARGS__)
763 // #define C(...) blah(a, ## __VA_ARGS__)
764 // A(x) B(x) C()
765 isVarargsElided = true;
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000766 } else if (!ContainsCodeCompletionTok) {
Joao Matos3e1ec722012-08-31 21:34:27 +0000767 // Otherwise, emit the error.
768 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Argyrios Kyrtzidis0ee8de72012-12-14 18:53:47 +0000769 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
770 << MacroName.getIdentifierInfo();
Joao Matos3e1ec722012-08-31 21:34:27 +0000771 return 0;
772 }
773
774 // Add a marker EOF token to the end of the token list for this argument.
775 SourceLocation EndLoc = Tok.getLocation();
776 Tok.startToken();
777 Tok.setKind(tok::eof);
778 Tok.setLocation(EndLoc);
779 Tok.setLength(0);
780 ArgTokens.push_back(Tok);
781
782 // If we expect two arguments, add both as empty.
783 if (NumActuals == 0 && MinArgsExpected == 2)
784 ArgTokens.push_back(Tok);
785
Argyrios Kyrtzidiscd0fd182012-12-21 01:17:20 +0000786 } else if (NumActuals > MinArgsExpected && !MI->isVariadic() &&
787 !ContainsCodeCompletionTok) {
Joao Matos3e1ec722012-08-31 21:34:27 +0000788 // Emit the diagnostic at the macro name in case there is a missing ).
789 // Emitting it at the , could be far away from the macro name.
790 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Argyrios Kyrtzidis0ee8de72012-12-14 18:53:47 +0000791 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
792 << MacroName.getIdentifierInfo();
Joao Matos3e1ec722012-08-31 21:34:27 +0000793 return 0;
794 }
795
796 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
797}
798
799/// \brief Keeps macro expanded tokens for TokenLexers.
800//
801/// Works like a stack; a TokenLexer adds the macro expanded tokens that is
802/// going to lex in the cache and when it finishes the tokens are removed
803/// from the end of the cache.
804Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
805 ArrayRef<Token> tokens) {
806 assert(tokLexer);
807 if (tokens.empty())
808 return 0;
809
810 size_t newIndex = MacroExpandedTokens.size();
811 bool cacheNeedsToGrow = tokens.size() >
812 MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
813 MacroExpandedTokens.append(tokens.begin(), tokens.end());
814
815 if (cacheNeedsToGrow) {
816 // Go through all the TokenLexers whose 'Tokens' pointer points in the
817 // buffer and update the pointers to the (potential) new buffer array.
818 for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) {
819 TokenLexer *prevLexer;
820 size_t tokIndex;
821 llvm::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i];
822 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
823 }
824 }
825
826 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
827 return MacroExpandedTokens.data() + newIndex;
828}
829
830void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
831 assert(!MacroExpandingLexersStack.empty());
832 size_t tokIndex = MacroExpandingLexersStack.back().second;
833 assert(tokIndex < MacroExpandedTokens.size());
834 // Pop the cached macro expanded tokens from the end.
835 MacroExpandedTokens.resize(tokIndex);
836 MacroExpandingLexersStack.pop_back();
837}
838
839/// ComputeDATE_TIME - Compute the current time, enter it into the specified
840/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
841/// the identifier tokens inserted.
842static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
843 Preprocessor &PP) {
844 time_t TT = time(0);
845 struct tm *TM = localtime(&TT);
846
847 static const char * const Months[] = {
848 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
849 };
850
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000851 {
852 SmallString<32> TmpBuffer;
853 llvm::raw_svector_ostream TmpStream(TmpBuffer);
854 TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
855 TM->tm_mday, TM->tm_year + 1900);
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000856 Token TmpTok;
857 TmpTok.startToken();
Dmitri Gribenko374b3832012-09-24 21:07:17 +0000858 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000859 DATELoc = TmpTok.getLocation();
860 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000861
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000862 {
863 SmallString<32> TmpBuffer;
864 llvm::raw_svector_ostream TmpStream(TmpBuffer);
865 TmpStream << llvm::format("\"%02d:%02d:%02d\"",
866 TM->tm_hour, TM->tm_min, TM->tm_sec);
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000867 Token TmpTok;
868 TmpTok.startToken();
Dmitri Gribenko374b3832012-09-24 21:07:17 +0000869 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenko33d054b2012-09-24 20:56:28 +0000870 TIMELoc = TmpTok.getLocation();
871 }
Joao Matos3e1ec722012-08-31 21:34:27 +0000872}
873
874
875/// HasFeature - Return true if we recognize and implement the feature
876/// specified by the identifier as a standard language feature.
877static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
878 const LangOptions &LangOpts = PP.getLangOpts();
879 StringRef Feature = II->getName();
880
881 // Normalize the feature name, __foo__ becomes foo.
882 if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4)
883 Feature = Feature.substr(2, Feature.size() - 4);
884
885 return llvm::StringSwitch<bool>(Feature)
Will Dietz4f45bc02013-01-18 11:30:38 +0000886 .Case("address_sanitizer", LangOpts.Sanitize.Address)
Joao Matos3e1ec722012-08-31 21:34:27 +0000887 .Case("attribute_analyzer_noreturn", true)
888 .Case("attribute_availability", true)
889 .Case("attribute_availability_with_message", true)
890 .Case("attribute_cf_returns_not_retained", true)
891 .Case("attribute_cf_returns_retained", true)
892 .Case("attribute_deprecated_with_message", true)
893 .Case("attribute_ext_vector_type", true)
894 .Case("attribute_ns_returns_not_retained", true)
895 .Case("attribute_ns_returns_retained", true)
896 .Case("attribute_ns_consumes_self", true)
897 .Case("attribute_ns_consumed", true)
898 .Case("attribute_cf_consumed", true)
899 .Case("attribute_objc_ivar_unused", true)
900 .Case("attribute_objc_method_family", true)
901 .Case("attribute_overloadable", true)
902 .Case("attribute_unavailable_with_message", true)
903 .Case("attribute_unused_on_fields", true)
904 .Case("blocks", LangOpts.Blocks)
905 .Case("cxx_exceptions", LangOpts.Exceptions)
906 .Case("cxx_rtti", LangOpts.RTTI)
907 .Case("enumerator_attributes", true)
Will Dietz4f45bc02013-01-18 11:30:38 +0000908 .Case("memory_sanitizer", LangOpts.Sanitize.Memory)
909 .Case("thread_sanitizer", LangOpts.Sanitize.Thread)
Joao Matos3e1ec722012-08-31 21:34:27 +0000910 // Objective-C features
911 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
912 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
913 .Case("objc_arc_weak", LangOpts.ObjCARCWeak)
914 .Case("objc_default_synthesize_properties", LangOpts.ObjC2)
915 .Case("objc_fixed_enum", LangOpts.ObjC2)
916 .Case("objc_instancetype", LangOpts.ObjC2)
917 .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules)
918 .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile())
Ted Kremeneke4057c22013-01-04 19:04:44 +0000919 .Case("objc_property_explicit_atomic", true) // Does clang support explicit "atomic" keyword?
Joao Matos3e1ec722012-08-31 21:34:27 +0000920 .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport())
921 .Case("ownership_holds", true)
922 .Case("ownership_returns", true)
923 .Case("ownership_takes", true)
924 .Case("objc_bool", true)
925 .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile())
926 .Case("objc_array_literals", LangOpts.ObjC2)
927 .Case("objc_dictionary_literals", LangOpts.ObjC2)
928 .Case("objc_boxed_expressions", LangOpts.ObjC2)
929 .Case("arc_cf_code_audited", true)
930 // C11 features
931 .Case("c_alignas", LangOpts.C11)
932 .Case("c_atomic", LangOpts.C11)
933 .Case("c_generic_selections", LangOpts.C11)
934 .Case("c_static_assert", LangOpts.C11)
Douglas Gregore87c5bd2013-05-02 05:28:32 +0000935 .Case("c_thread_local",
936 LangOpts.C11 && PP.getTargetInfo().isTLSSupported())
Joao Matos3e1ec722012-08-31 21:34:27 +0000937 // C++11 features
Richard Smith80ad52f2013-01-02 11:42:31 +0000938 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus11)
939 .Case("cxx_alias_templates", LangOpts.CPlusPlus11)
940 .Case("cxx_alignas", LangOpts.CPlusPlus11)
941 .Case("cxx_atomic", LangOpts.CPlusPlus11)
942 .Case("cxx_attributes", LangOpts.CPlusPlus11)
943 .Case("cxx_auto_type", LangOpts.CPlusPlus11)
944 .Case("cxx_constexpr", LangOpts.CPlusPlus11)
945 .Case("cxx_decltype", LangOpts.CPlusPlus11)
946 .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus11)
947 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus11)
948 .Case("cxx_defaulted_functions", LangOpts.CPlusPlus11)
949 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus11)
950 .Case("cxx_deleted_functions", LangOpts.CPlusPlus11)
951 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus11)
952 .Case("cxx_generalized_initializers", LangOpts.CPlusPlus11)
953 .Case("cxx_implicit_moves", LangOpts.CPlusPlus11)
Richard Smithe6e68b52013-04-19 17:00:31 +0000954 .Case("cxx_inheriting_constructors", LangOpts.CPlusPlus11)
Richard Smith80ad52f2013-01-02 11:42:31 +0000955 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus11)
956 .Case("cxx_lambdas", LangOpts.CPlusPlus11)
957 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus11)
958 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus11)
959 .Case("cxx_noexcept", LangOpts.CPlusPlus11)
960 .Case("cxx_nullptr", LangOpts.CPlusPlus11)
961 .Case("cxx_override_control", LangOpts.CPlusPlus11)
962 .Case("cxx_range_for", LangOpts.CPlusPlus11)
963 .Case("cxx_raw_string_literals", LangOpts.CPlusPlus11)
964 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus11)
965 .Case("cxx_rvalue_references", LangOpts.CPlusPlus11)
966 .Case("cxx_strong_enums", LangOpts.CPlusPlus11)
967 .Case("cxx_static_assert", LangOpts.CPlusPlus11)
Douglas Gregore87c5bd2013-05-02 05:28:32 +0000968 .Case("cxx_thread_local",
969 LangOpts.CPlusPlus11 && PP.getTargetInfo().isTLSSupported())
Richard Smith80ad52f2013-01-02 11:42:31 +0000970 .Case("cxx_trailing_return", LangOpts.CPlusPlus11)
971 .Case("cxx_unicode_literals", LangOpts.CPlusPlus11)
972 .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus11)
973 .Case("cxx_user_literals", LangOpts.CPlusPlus11)
974 .Case("cxx_variadic_templates", LangOpts.CPlusPlus11)
Richard Smith7f0ffb32013-05-07 19:32:56 +0000975 // C++1y features
976 .Case("cxx_binary_literals", LangOpts.CPlusPlus1y)
977 //.Case("cxx_contextual_conversions", LangOpts.CPlusPlus1y)
978 //.Case("cxx_generalized_capture", LangOpts.CPlusPlus1y)
979 //.Case("cxx_generic_lambda", LangOpts.CPlusPlus1y)
980 //.Case("cxx_relaxed_constexpr", LangOpts.CPlusPlus1y)
Richard Smithf45c2992013-05-12 03:09:35 +0000981 .Case("cxx_return_type_deduction", LangOpts.CPlusPlus1y)
Richard Smith7f0ffb32013-05-07 19:32:56 +0000982 //.Case("cxx_runtime_array", LangOpts.CPlusPlus1y)
983 .Case("cxx_aggregate_nsdmi", LangOpts.CPlusPlus1y)
984 //.Case("cxx_variable_templates", LangOpts.CPlusPlus1y)
Joao Matos3e1ec722012-08-31 21:34:27 +0000985 // Type traits
986 .Case("has_nothrow_assign", LangOpts.CPlusPlus)
987 .Case("has_nothrow_copy", LangOpts.CPlusPlus)
988 .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
989 .Case("has_trivial_assign", LangOpts.CPlusPlus)
990 .Case("has_trivial_copy", LangOpts.CPlusPlus)
991 .Case("has_trivial_constructor", LangOpts.CPlusPlus)
992 .Case("has_trivial_destructor", LangOpts.CPlusPlus)
993 .Case("has_virtual_destructor", LangOpts.CPlusPlus)
994 .Case("is_abstract", LangOpts.CPlusPlus)
995 .Case("is_base_of", LangOpts.CPlusPlus)
996 .Case("is_class", LangOpts.CPlusPlus)
997 .Case("is_convertible_to", LangOpts.CPlusPlus)
Joao Matos3e1ec722012-08-31 21:34:27 +0000998 .Case("is_empty", LangOpts.CPlusPlus)
999 .Case("is_enum", LangOpts.CPlusPlus)
1000 .Case("is_final", LangOpts.CPlusPlus)
1001 .Case("is_literal", LangOpts.CPlusPlus)
1002 .Case("is_standard_layout", LangOpts.CPlusPlus)
1003 .Case("is_pod", LangOpts.CPlusPlus)
1004 .Case("is_polymorphic", LangOpts.CPlusPlus)
1005 .Case("is_trivial", LangOpts.CPlusPlus)
1006 .Case("is_trivially_assignable", LangOpts.CPlusPlus)
1007 .Case("is_trivially_constructible", LangOpts.CPlusPlus)
1008 .Case("is_trivially_copyable", LangOpts.CPlusPlus)
1009 .Case("is_union", LangOpts.CPlusPlus)
1010 .Case("modules", LangOpts.Modules)
1011 .Case("tls", PP.getTargetInfo().isTLSSupported())
1012 .Case("underlying_type", LangOpts.CPlusPlus)
1013 .Default(false);
1014}
1015
1016/// HasExtension - Return true if we recognize and implement the feature
1017/// specified by the identifier, either as an extension or a standard language
1018/// feature.
1019static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) {
1020 if (HasFeature(PP, II))
1021 return true;
1022
1023 // If the use of an extension results in an error diagnostic, extensions are
1024 // effectively unavailable, so just return false here.
1025 if (PP.getDiagnostics().getExtensionHandlingBehavior() ==
1026 DiagnosticsEngine::Ext_Error)
1027 return false;
1028
1029 const LangOptions &LangOpts = PP.getLangOpts();
1030 StringRef Extension = II->getName();
1031
1032 // Normalize the extension name, __foo__ becomes foo.
1033 if (Extension.startswith("__") && Extension.endswith("__") &&
1034 Extension.size() >= 4)
1035 Extension = Extension.substr(2, Extension.size() - 4);
1036
1037 // Because we inherit the feature list from HasFeature, this string switch
1038 // must be less restrictive than HasFeature's.
1039 return llvm::StringSwitch<bool>(Extension)
1040 // C11 features supported by other languages as extensions.
1041 .Case("c_alignas", true)
1042 .Case("c_atomic", true)
1043 .Case("c_generic_selections", true)
1044 .Case("c_static_assert", true)
Richard Smith7f0ffb32013-05-07 19:32:56 +00001045 // C++11 features supported by other languages as extensions.
Joao Matos3e1ec722012-08-31 21:34:27 +00001046 .Case("cxx_atomic", LangOpts.CPlusPlus)
1047 .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
1048 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
1049 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
1050 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus)
1051 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
1052 .Case("cxx_override_control", LangOpts.CPlusPlus)
1053 .Case("cxx_range_for", LangOpts.CPlusPlus)
1054 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
1055 .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
Richard Smith7f0ffb32013-05-07 19:32:56 +00001056 // C++1y features supported by other languages as extensions.
1057 .Case("cxx_binary_literals", true)
Joao Matos3e1ec722012-08-31 21:34:27 +00001058 .Default(false);
1059}
1060
1061/// HasAttribute - Return true if we recognize and implement the attribute
1062/// specified by the given identifier.
1063static bool HasAttribute(const IdentifierInfo *II) {
1064 StringRef Name = II->getName();
1065 // Normalize the attribute name, __foo__ becomes foo.
1066 if (Name.startswith("__") && Name.endswith("__") && Name.size() >= 4)
1067 Name = Name.substr(2, Name.size() - 4);
1068
1069 // FIXME: Do we need to handle namespaces here?
1070 return llvm::StringSwitch<bool>(Name)
1071#include "clang/Lex/AttrSpellings.inc"
1072 .Default(false);
1073}
1074
1075/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
1076/// or '__has_include_next("path")' expression.
1077/// Returns true if successful.
1078static bool EvaluateHasIncludeCommon(Token &Tok,
1079 IdentifierInfo *II, Preprocessor &PP,
1080 const DirectoryLookup *LookupFrom) {
Richard Trieu97bc3d52012-10-22 20:28:48 +00001081 // Save the location of the current token. If a '(' is later found, use
Aaron Ballman6b716c52013-01-15 21:59:46 +00001082 // that location. If not, use the end of this location instead.
Richard Trieu97bc3d52012-10-22 20:28:48 +00001083 SourceLocation LParenLoc = Tok.getLocation();
Joao Matos3e1ec722012-08-31 21:34:27 +00001084
Aaron Ballman31672b12013-01-16 19:32:21 +00001085 // These expressions are only allowed within a preprocessor directive.
1086 if (!PP.isParsingIfOrElifDirective()) {
1087 PP.Diag(LParenLoc, diag::err_pp_directive_required) << II->getName();
1088 return false;
1089 }
1090
Joao Matos3e1ec722012-08-31 21:34:27 +00001091 // Get '('.
1092 PP.LexNonComment(Tok);
1093
1094 // Ensure we have a '('.
1095 if (Tok.isNot(tok::l_paren)) {
Richard Trieu97bc3d52012-10-22 20:28:48 +00001096 // No '(', use end of last token.
1097 LParenLoc = PP.getLocForEndOfToken(LParenLoc);
1098 PP.Diag(LParenLoc, diag::err_pp_missing_lparen) << II->getName();
1099 // If the next token looks like a filename or the start of one,
1100 // assume it is and process it as such.
1101 if (!Tok.is(tok::angle_string_literal) && !Tok.is(tok::string_literal) &&
1102 !Tok.is(tok::less))
1103 return false;
1104 } else {
1105 // Save '(' location for possible missing ')' message.
1106 LParenLoc = Tok.getLocation();
1107
Eli Friedmana0f2d022013-01-09 02:20:00 +00001108 if (PP.getCurrentLexer()) {
1109 // Get the file name.
1110 PP.getCurrentLexer()->LexIncludeFilename(Tok);
1111 } else {
1112 // We're in a macro, so we can't use LexIncludeFilename; just
1113 // grab the next token.
1114 PP.Lex(Tok);
1115 }
Joao Matos3e1ec722012-08-31 21:34:27 +00001116 }
1117
Joao Matos3e1ec722012-08-31 21:34:27 +00001118 // Reserve a buffer to get the spelling.
1119 SmallString<128> FilenameBuffer;
1120 StringRef Filename;
1121 SourceLocation EndLoc;
1122
1123 switch (Tok.getKind()) {
1124 case tok::eod:
1125 // If the token kind is EOD, the error has already been diagnosed.
1126 return false;
1127
1128 case tok::angle_string_literal:
1129 case tok::string_literal: {
1130 bool Invalid = false;
1131 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
1132 if (Invalid)
1133 return false;
1134 break;
1135 }
1136
1137 case tok::less:
1138 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1139 // case, glue the tokens together into FilenameBuffer and interpret those.
1140 FilenameBuffer.push_back('<');
Richard Trieu97bc3d52012-10-22 20:28:48 +00001141 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc)) {
1142 // Let the caller know a <eod> was found by changing the Token kind.
1143 Tok.setKind(tok::eod);
Joao Matos3e1ec722012-08-31 21:34:27 +00001144 return false; // Found <eod> but no ">"? Diagnostic already emitted.
Richard Trieu97bc3d52012-10-22 20:28:48 +00001145 }
Joao Matos3e1ec722012-08-31 21:34:27 +00001146 Filename = FilenameBuffer.str();
1147 break;
1148 default:
1149 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
1150 return false;
1151 }
1152
Richard Trieu97bc3d52012-10-22 20:28:48 +00001153 SourceLocation FilenameLoc = Tok.getLocation();
1154
Joao Matos3e1ec722012-08-31 21:34:27 +00001155 // Get ')'.
1156 PP.LexNonComment(Tok);
1157
1158 // Ensure we have a trailing ).
1159 if (Tok.isNot(tok::r_paren)) {
Richard Trieu97bc3d52012-10-22 20:28:48 +00001160 PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_missing_rparen)
1161 << II->getName();
Joao Matos3e1ec722012-08-31 21:34:27 +00001162 PP.Diag(LParenLoc, diag::note_matching) << "(";
1163 return false;
1164 }
1165
1166 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
1167 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1168 // error.
1169 if (Filename.empty())
1170 return false;
1171
1172 // Search include directories.
1173 const DirectoryLookup *CurDir;
1174 const FileEntry *File =
Lawrence Crowlbc3f6282013-06-20 21:14:14 +00001175 PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, CurDir, NULL,
1176 NULL, NULL);
Joao Matos3e1ec722012-08-31 21:34:27 +00001177
1178 // Get the result value. A result of true means the file exists.
1179 return File != 0;
1180}
1181
1182/// EvaluateHasInclude - Process a '__has_include("path")' expression.
1183/// Returns true if successful.
1184static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
1185 Preprocessor &PP) {
1186 return EvaluateHasIncludeCommon(Tok, II, PP, NULL);
1187}
1188
1189/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
1190/// Returns true if successful.
1191static bool EvaluateHasIncludeNext(Token &Tok,
1192 IdentifierInfo *II, Preprocessor &PP) {
1193 // __has_include_next is like __has_include, except that we start
1194 // searching after the current found directory. If we can't do this,
1195 // issue a diagnostic.
1196 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
1197 if (PP.isInPrimaryFile()) {
1198 Lookup = 0;
1199 PP.Diag(Tok, diag::pp_include_next_in_primary);
1200 } else if (Lookup == 0) {
1201 PP.Diag(Tok, diag::pp_include_next_absolute_path);
1202 } else {
1203 // Start looking up in the next directory.
1204 ++Lookup;
1205 }
1206
1207 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup);
1208}
1209
Douglas Gregorb09de512012-09-25 15:44:52 +00001210/// \brief Process __building_module(identifier) expression.
1211/// \returns true if we are building the named module, false otherwise.
1212static bool EvaluateBuildingModule(Token &Tok,
1213 IdentifierInfo *II, Preprocessor &PP) {
1214 // Get '('.
1215 PP.LexNonComment(Tok);
1216
1217 // Ensure we have a '('.
1218 if (Tok.isNot(tok::l_paren)) {
1219 PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
1220 return false;
1221 }
1222
1223 // Save '(' location for possible missing ')' message.
1224 SourceLocation LParenLoc = Tok.getLocation();
1225
1226 // Get the module name.
1227 PP.LexNonComment(Tok);
1228
1229 // Ensure that we have an identifier.
1230 if (Tok.isNot(tok::identifier)) {
1231 PP.Diag(Tok.getLocation(), diag::err_expected_id_building_module);
1232 return false;
1233 }
1234
1235 bool Result
1236 = Tok.getIdentifierInfo()->getName() == PP.getLangOpts().CurrentModule;
1237
1238 // Get ')'.
1239 PP.LexNonComment(Tok);
1240
1241 // Ensure we have a trailing ).
1242 if (Tok.isNot(tok::r_paren)) {
1243 PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
1244 PP.Diag(LParenLoc, diag::note_matching) << "(";
1245 return false;
1246 }
1247
1248 return Result;
1249}
1250
Joao Matos3e1ec722012-08-31 21:34:27 +00001251/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1252/// as a builtin macro, handle it and return the next token as 'Tok'.
1253void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
1254 // Figure out which token this is.
1255 IdentifierInfo *II = Tok.getIdentifierInfo();
1256 assert(II && "Can't be a macro without id info!");
1257
1258 // If this is an _Pragma or Microsoft __pragma directive, expand it,
1259 // invoke the pragma handler, then lex the token after it.
1260 if (II == Ident_Pragma)
1261 return Handle_Pragma(Tok);
1262 else if (II == Ident__pragma) // in non-MS mode this is null
1263 return HandleMicrosoft__pragma(Tok);
1264
1265 ++NumBuiltinMacroExpanded;
1266
1267 SmallString<128> TmpBuffer;
1268 llvm::raw_svector_ostream OS(TmpBuffer);
1269
1270 // Set up the return result.
1271 Tok.setIdentifierInfo(0);
1272 Tok.clearFlag(Token::NeedsCleaning);
1273
1274 if (II == Ident__LINE__) {
1275 // C99 6.10.8: "__LINE__: The presumed line number (within the current
1276 // source file) of the current source line (an integer constant)". This can
1277 // be affected by #line.
1278 SourceLocation Loc = Tok.getLocation();
1279
1280 // Advance to the location of the first _, this might not be the first byte
1281 // of the token if it starts with an escaped newline.
1282 Loc = AdvanceToTokenCharacter(Loc, 0);
1283
1284 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
1285 // a macro expansion. This doesn't matter for object-like macros, but
1286 // can matter for a function-like macro that expands to contain __LINE__.
1287 // Skip down through expansion points until we find a file loc for the
1288 // end of the expansion history.
1289 Loc = SourceMgr.getExpansionRange(Loc).second;
1290 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
1291
1292 // __LINE__ expands to a simple numeric value.
1293 OS << (PLoc.isValid()? PLoc.getLine() : 1);
1294 Tok.setKind(tok::numeric_constant);
1295 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
1296 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
1297 // character string literal)". This can be affected by #line.
1298 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1299
1300 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
1301 // #include stack instead of the current file.
1302 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
1303 SourceLocation NextLoc = PLoc.getIncludeLoc();
1304 while (NextLoc.isValid()) {
1305 PLoc = SourceMgr.getPresumedLoc(NextLoc);
1306 if (PLoc.isInvalid())
1307 break;
1308
1309 NextLoc = PLoc.getIncludeLoc();
1310 }
1311 }
1312
1313 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
1314 SmallString<128> FN;
1315 if (PLoc.isValid()) {
1316 FN += PLoc.getFilename();
1317 Lexer::Stringify(FN);
1318 OS << '"' << FN.str() << '"';
1319 }
1320 Tok.setKind(tok::string_literal);
1321 } else if (II == Ident__DATE__) {
1322 if (!DATELoc.isValid())
1323 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1324 Tok.setKind(tok::string_literal);
1325 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1326 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
1327 Tok.getLocation(),
1328 Tok.getLength()));
1329 return;
1330 } else if (II == Ident__TIME__) {
1331 if (!TIMELoc.isValid())
1332 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1333 Tok.setKind(tok::string_literal);
1334 Tok.setLength(strlen("\"hh:mm:ss\""));
1335 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
1336 Tok.getLocation(),
1337 Tok.getLength()));
1338 return;
1339 } else if (II == Ident__INCLUDE_LEVEL__) {
1340 // Compute the presumed include depth of this token. This can be affected
1341 // by GNU line markers.
1342 unsigned Depth = 0;
1343
1344 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1345 if (PLoc.isValid()) {
1346 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1347 for (; PLoc.isValid(); ++Depth)
1348 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1349 }
1350
1351 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1352 OS << Depth;
1353 Tok.setKind(tok::numeric_constant);
1354 } else if (II == Ident__TIMESTAMP__) {
1355 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1356 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1357
1358 // Get the file that we are lexing out of. If we're currently lexing from
1359 // a macro, dig into the include stack.
1360 const FileEntry *CurFile = 0;
1361 PreprocessorLexer *TheLexer = getCurrentFileLexer();
1362
1363 if (TheLexer)
1364 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
1365
1366 const char *Result;
1367 if (CurFile) {
1368 time_t TT = CurFile->getModificationTime();
1369 struct tm *TM = localtime(&TT);
1370 Result = asctime(TM);
1371 } else {
1372 Result = "??? ??? ?? ??:??:?? ????\n";
1373 }
1374 // Surround the string with " and strip the trailing newline.
1375 OS << '"' << StringRef(Result, strlen(Result)-1) << '"';
1376 Tok.setKind(tok::string_literal);
1377 } else if (II == Ident__COUNTER__) {
1378 // __COUNTER__ expands to a simple numeric value.
1379 OS << CounterValue++;
1380 Tok.setKind(tok::numeric_constant);
1381 } else if (II == Ident__has_feature ||
1382 II == Ident__has_extension ||
1383 II == Ident__has_builtin ||
1384 II == Ident__has_attribute) {
1385 // The argument to these builtins should be a parenthesized identifier.
1386 SourceLocation StartLoc = Tok.getLocation();
1387
1388 bool IsValid = false;
1389 IdentifierInfo *FeatureII = 0;
1390
1391 // Read the '('.
Andy Gibbs3f03b582012-11-17 19:18:27 +00001392 LexUnexpandedToken(Tok);
Joao Matos3e1ec722012-08-31 21:34:27 +00001393 if (Tok.is(tok::l_paren)) {
1394 // Read the identifier
Andy Gibbs3f03b582012-11-17 19:18:27 +00001395 LexUnexpandedToken(Tok);
Richard Smith899022b2013-07-09 00:57:56 +00001396 if ((FeatureII = Tok.getIdentifierInfo())) {
Joao Matos3e1ec722012-08-31 21:34:27 +00001397 // Read the ')'.
Andy Gibbs3f03b582012-11-17 19:18:27 +00001398 LexUnexpandedToken(Tok);
Joao Matos3e1ec722012-08-31 21:34:27 +00001399 if (Tok.is(tok::r_paren))
1400 IsValid = true;
1401 }
1402 }
1403
1404 bool Value = false;
1405 if (!IsValid)
1406 Diag(StartLoc, diag::err_feature_check_malformed);
1407 else if (II == Ident__has_builtin) {
1408 // Check for a builtin is trivial.
1409 Value = FeatureII->getBuiltinID() != 0;
1410 } else if (II == Ident__has_attribute)
1411 Value = HasAttribute(FeatureII);
1412 else if (II == Ident__has_extension)
1413 Value = HasExtension(*this, FeatureII);
1414 else {
1415 assert(II == Ident__has_feature && "Must be feature check");
1416 Value = HasFeature(*this, FeatureII);
1417 }
1418
1419 OS << (int)Value;
1420 if (IsValid)
1421 Tok.setKind(tok::numeric_constant);
1422 } else if (II == Ident__has_include ||
1423 II == Ident__has_include_next) {
1424 // The argument to these two builtins should be a parenthesized
1425 // file name string literal using angle brackets (<>) or
1426 // double-quotes ("").
1427 bool Value;
1428 if (II == Ident__has_include)
1429 Value = EvaluateHasInclude(Tok, II, *this);
1430 else
1431 Value = EvaluateHasIncludeNext(Tok, II, *this);
1432 OS << (int)Value;
Richard Trieu97bc3d52012-10-22 20:28:48 +00001433 if (Tok.is(tok::r_paren))
1434 Tok.setKind(tok::numeric_constant);
Joao Matos3e1ec722012-08-31 21:34:27 +00001435 } else if (II == Ident__has_warning) {
1436 // The argument should be a parenthesized string literal.
1437 // The argument to these builtins should be a parenthesized identifier.
1438 SourceLocation StartLoc = Tok.getLocation();
1439 bool IsValid = false;
1440 bool Value = false;
1441 // Read the '('.
Andy Gibbs02a17682012-11-17 19:15:38 +00001442 LexUnexpandedToken(Tok);
Joao Matos3e1ec722012-08-31 21:34:27 +00001443 do {
Andy Gibbs02a17682012-11-17 19:15:38 +00001444 if (Tok.isNot(tok::l_paren)) {
1445 Diag(StartLoc, diag::err_warning_check_malformed);
1446 break;
Joao Matos3e1ec722012-08-31 21:34:27 +00001447 }
Andy Gibbs02a17682012-11-17 19:15:38 +00001448
1449 LexUnexpandedToken(Tok);
1450 std::string WarningName;
1451 SourceLocation StrStartLoc = Tok.getLocation();
Andy Gibbs97f84612012-11-17 19:16:52 +00001452 if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",
1453 /*MacroExpansion=*/false)) {
Andy Gibbs02a17682012-11-17 19:15:38 +00001454 // Eat tokens until ')'.
Andy Gibbs6d534d42012-11-17 22:17:28 +00001455 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) &&
1456 Tok.isNot(tok::eof))
Andy Gibbs02a17682012-11-17 19:15:38 +00001457 LexUnexpandedToken(Tok);
1458 break;
1459 }
1460
1461 // Is the end a ')'?
1462 if (!(IsValid = Tok.is(tok::r_paren))) {
1463 Diag(StartLoc, diag::err_warning_check_malformed);
1464 break;
1465 }
1466
1467 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1468 WarningName[1] != 'W') {
1469 Diag(StrStartLoc, diag::warn_has_warning_invalid_option);
1470 break;
1471 }
1472
1473 // Finally, check if the warning flags maps to a diagnostic group.
1474 // We construct a SmallVector here to talk to getDiagnosticIDs().
1475 // Although we don't use the result, this isn't a hot path, and not
1476 // worth special casing.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001477 SmallVector<diag::kind, 10> Diags;
Andy Gibbs02a17682012-11-17 19:15:38 +00001478 Value = !getDiagnostics().getDiagnosticIDs()->
1479 getDiagnosticsInGroup(WarningName.substr(2), Diags);
Joao Matos3e1ec722012-08-31 21:34:27 +00001480 } while (false);
Joao Matos3e1ec722012-08-31 21:34:27 +00001481
1482 OS << (int)Value;
Andy Gibbsb9971ba2012-11-17 19:14:53 +00001483 if (IsValid)
1484 Tok.setKind(tok::numeric_constant);
Douglas Gregorb09de512012-09-25 15:44:52 +00001485 } else if (II == Ident__building_module) {
1486 // The argument to this builtin should be an identifier. The
1487 // builtin evaluates to 1 when that identifier names the module we are
1488 // currently building.
1489 OS << (int)EvaluateBuildingModule(Tok, II, *this);
1490 Tok.setKind(tok::numeric_constant);
1491 } else if (II == Ident__MODULE__) {
1492 // The current module as an identifier.
1493 OS << getLangOpts().CurrentModule;
1494 IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);
1495 Tok.setIdentifierInfo(ModuleII);
1496 Tok.setKind(ModuleII->getTokenID());
Joao Matos3e1ec722012-08-31 21:34:27 +00001497 } else {
1498 llvm_unreachable("Unknown identifier!");
1499 }
Dmitri Gribenko374b3832012-09-24 21:07:17 +00001500 CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation());
Joao Matos3e1ec722012-08-31 21:34:27 +00001501}
1502
1503void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
1504 // If the 'used' status changed, and the macro requires 'unused' warning,
1505 // remove its SourceLocation from the warn-for-unused-macro locations.
1506 if (MI->isWarnIfUnused() && !MI->isUsed())
1507 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1508 MI->setIsUsed(true);
1509}