blob: ebf606e9406f7ed08aa900b14263866e37afe6bd [file] [log] [blame]
Chris Lattnera3b605e2008-03-09 03:13:06 +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"
16#include "MacroArgs.h"
17#include "clang/Lex/MacroInfo.h"
18#include "clang/Basic/SourceManager.h"
19#include "clang/Basic/FileManager.h"
Eric Christopher1f84f8d2010-06-24 02:02:00 +000020#include "clang/Basic/TargetInfo.h"
Chris Lattner500d3292009-01-29 05:15:15 +000021#include "clang/Lex/LexDiagnostic.h"
Benjamin Kramer32592e82010-01-09 18:53:11 +000022#include "llvm/ADT/StringSwitch.h"
Benjamin Kramerb1765912010-01-27 16:38:22 +000023#include "llvm/Support/raw_ostream.h"
Chris Lattner3daed522009-03-02 22:20:04 +000024#include <cstdio>
Chris Lattnerf90a2482008-03-18 05:59:11 +000025#include <ctime>
Chris Lattnera3b605e2008-03-09 03:13:06 +000026using namespace clang;
27
28/// setMacroInfo - Specify a macro for this identifier.
29///
30void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
Chris Lattner555589d2009-04-10 21:17:07 +000031 if (MI) {
Chris Lattnera3b605e2008-03-09 03:13:06 +000032 Macros[II] = MI;
33 II->setHasMacroDefinition(true);
Chris Lattner555589d2009-04-10 21:17:07 +000034 } else if (II->hasMacroDefinition()) {
35 Macros.erase(II);
36 II->setHasMacroDefinition(false);
Chris Lattnera3b605e2008-03-09 03:13:06 +000037 }
38}
39
40/// RegisterBuiltinMacro - Register the specified identifier in the identifier
41/// table and mark it as a builtin macro to be expanded.
Chris Lattner148772a2009-06-13 07:13:28 +000042static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
Chris Lattnera3b605e2008-03-09 03:13:06 +000043 // Get the identifier.
Chris Lattner148772a2009-06-13 07:13:28 +000044 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
Mike Stump1eb44332009-09-09 15:08:12 +000045
Chris Lattnera3b605e2008-03-09 03:13:06 +000046 // Mark it as being a macro that is builtin.
Chris Lattner148772a2009-06-13 07:13:28 +000047 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +000048 MI->setIsBuiltinMacro();
Chris Lattner148772a2009-06-13 07:13:28 +000049 PP.setMacroInfo(Id, MI);
Chris Lattnera3b605e2008-03-09 03:13:06 +000050 return Id;
51}
52
53
54/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
55/// identifier table.
56void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner148772a2009-06-13 07:13:28 +000057 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
58 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
59 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
60 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
61 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
62 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
Mike Stump1eb44332009-09-09 15:08:12 +000063
Chris Lattnera3b605e2008-03-09 03:13:06 +000064 // GCC Extensions.
Chris Lattner148772a2009-06-13 07:13:28 +000065 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
66 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
67 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
Mike Stump1eb44332009-09-09 15:08:12 +000068
Chris Lattner148772a2009-06-13 07:13:28 +000069 // Clang Extensions.
John Thompson92bd8c72009-11-02 22:28:12 +000070 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
71 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
72 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
73 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
Chris Lattnera3b605e2008-03-09 03:13:06 +000074}
75
76/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
77/// in its expansion, currently expands to that token literally.
78static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
79 const IdentifierInfo *MacroIdent,
80 Preprocessor &PP) {
81 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
82
83 // If the token isn't an identifier, it's always literally expanded.
84 if (II == 0) return true;
Mike Stump1eb44332009-09-09 15:08:12 +000085
Chris Lattnera3b605e2008-03-09 03:13:06 +000086 // If the identifier is a macro, and if that macro is enabled, it may be
87 // expanded so it's not a trivial expansion.
88 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
89 // Fast expanding "#define X X" is ok, because X would be disabled.
90 II != MacroIdent)
91 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000092
Chris Lattnera3b605e2008-03-09 03:13:06 +000093 // If this is an object-like macro invocation, it is safe to trivially expand
94 // it.
95 if (MI->isObjectLike()) return true;
96
97 // If this is a function-like macro invocation, it's safe to trivially expand
98 // as long as the identifier is not a macro argument.
99 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
100 I != E; ++I)
101 if (*I == II)
102 return false; // Identifier is a macro argument.
Mike Stump1eb44332009-09-09 15:08:12 +0000103
Chris Lattnera3b605e2008-03-09 03:13:06 +0000104 return true;
105}
106
107
108/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
109/// lexed is a '('. If so, consume the token and return true, if not, this
110/// method should have no observable side-effect on the lexed tokens.
111bool Preprocessor::isNextPPTokenLParen() {
112 // Do some quick tests for rejection cases.
113 unsigned Val;
114 if (CurLexer)
115 Val = CurLexer->isNextPPTokenLParen();
Ted Kremenek1a531572008-11-19 22:43:49 +0000116 else if (CurPTHLexer)
117 Val = CurPTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000118 else
119 Val = CurTokenLexer->isNextTokenLParen();
Mike Stump1eb44332009-09-09 15:08:12 +0000120
Chris Lattnera3b605e2008-03-09 03:13:06 +0000121 if (Val == 2) {
122 // We have run off the end. If it's a source file we don't
123 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
124 // macro stack.
Ted Kremenek17ff58a2008-11-19 22:21:33 +0000125 if (CurPPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000126 return false;
127 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
128 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
129 if (Entry.TheLexer)
130 Val = Entry.TheLexer->isNextPPTokenLParen();
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000131 else if (Entry.ThePTHLexer)
132 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000133 else
134 Val = Entry.TheTokenLexer->isNextTokenLParen();
Mike Stump1eb44332009-09-09 15:08:12 +0000135
Chris Lattnera3b605e2008-03-09 03:13:06 +0000136 if (Val != 2)
137 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000138
Chris Lattnera3b605e2008-03-09 03:13:06 +0000139 // Ran off the end of a source file?
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000140 if (Entry.ThePPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000141 return false;
142 }
143 }
144
145 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
146 // have found something that isn't a '(' or we found the end of the
147 // translation unit. In either case, return false.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000148 return Val == 1;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000149}
150
151/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
152/// expanded as a macro, handle it and return the next token as 'Identifier'.
Mike Stump1eb44332009-09-09 15:08:12 +0000153bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000154 MacroInfo *MI) {
Chris Lattnerba9eee32009-03-12 17:31:43 +0000155 if (Callbacks) Callbacks->MacroExpands(Identifier, MI);
Mike Stump1eb44332009-09-09 15:08:12 +0000156
Douglas Gregor13678972010-01-26 19:43:43 +0000157 // If this is a macro expansion in the "#if !defined(x)" line for the file,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000158 // then the macro could expand to different things in other contexts, we need
159 // to disable the optimization in this case.
Ted Kremenek68a91d52008-11-18 01:12:54 +0000160 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
Mike Stump1eb44332009-09-09 15:08:12 +0000161
Chris Lattnera3b605e2008-03-09 03:13:06 +0000162 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
163 if (MI->isBuiltinMacro()) {
164 ExpandBuiltinMacro(Identifier);
165 return false;
166 }
Mike Stump1eb44332009-09-09 15:08:12 +0000167
Chris Lattnera3b605e2008-03-09 03:13:06 +0000168 /// Args - If this is a function-like macro expansion, this contains,
169 /// for each macro argument, the list of tokens that were provided to the
170 /// invocation.
171 MacroArgs *Args = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000172
Chris Lattnere7fb4842009-02-15 20:52:18 +0000173 // Remember where the end of the instantiation occurred. For an object-like
174 // macro, this is the identifier. For a function-like macro, this is the ')'.
175 SourceLocation InstantiationEnd = Identifier.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000176
Chris Lattnera3b605e2008-03-09 03:13:06 +0000177 // If this is a function-like macro, read the arguments.
178 if (MI->isFunctionLike()) {
179 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000180 // name isn't a '(', this macro should not be expanded.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000181 if (!isNextPPTokenLParen())
182 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000183
Chris Lattnera3b605e2008-03-09 03:13:06 +0000184 // Remember that we are now parsing the arguments to a macro invocation.
185 // Preprocessor directives used inside macro arguments are not portable, and
186 // this enables the warning.
187 InMacroArgs = true;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000188 Args = ReadFunctionLikeMacroArgs(Identifier, MI, InstantiationEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000189
Chris Lattnera3b605e2008-03-09 03:13:06 +0000190 // Finished parsing args.
191 InMacroArgs = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000192
Chris Lattnera3b605e2008-03-09 03:13:06 +0000193 // If there was an error parsing the arguments, bail out.
194 if (Args == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Chris Lattnera3b605e2008-03-09 03:13:06 +0000196 ++NumFnMacroExpanded;
197 } else {
198 ++NumMacroExpanded;
199 }
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Chris Lattnera3b605e2008-03-09 03:13:06 +0000201 // Notice that this macro has been used.
202 MI->setIsUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +0000203
Chris Lattnera3b605e2008-03-09 03:13:06 +0000204 // If we started lexing a macro, enter the macro expansion body.
Mike Stump1eb44332009-09-09 15:08:12 +0000205
Chris Lattnera3b605e2008-03-09 03:13:06 +0000206 // If this macro expands to no tokens, don't bother to push it onto the
207 // expansion stack, only to take it right back off.
208 if (MI->getNumTokens() == 0) {
209 // No need for arg info.
Chris Lattner561395b2009-12-14 22:12:52 +0000210 if (Args) Args->destroy(*this);
Mike Stump1eb44332009-09-09 15:08:12 +0000211
Chris Lattnera3b605e2008-03-09 03:13:06 +0000212 // Ignore this macro use, just return the next token in the current
213 // buffer.
214 bool HadLeadingSpace = Identifier.hasLeadingSpace();
215 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
Mike Stump1eb44332009-09-09 15:08:12 +0000216
Chris Lattnera3b605e2008-03-09 03:13:06 +0000217 Lex(Identifier);
Mike Stump1eb44332009-09-09 15:08:12 +0000218
Chris Lattnera3b605e2008-03-09 03:13:06 +0000219 // If the identifier isn't on some OTHER line, inherit the leading
220 // whitespace/first-on-a-line property of this token. This handles
221 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
222 // empty.
223 if (!Identifier.isAtStartOfLine()) {
224 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
225 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
226 }
227 ++NumFastMacroExpanded;
228 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000229
Chris Lattnera3b605e2008-03-09 03:13:06 +0000230 } else if (MI->getNumTokens() == 1 &&
231 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000232 *this)) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000233 // Otherwise, if this macro expands into a single trivially-expanded
Mike Stump1eb44332009-09-09 15:08:12 +0000234 // token: expand it now. This handles common cases like
Chris Lattnera3b605e2008-03-09 03:13:06 +0000235 // "#define VAL 42".
Sam Bishop9a4939f2008-03-21 07:13:02 +0000236
237 // No need for arg info.
Chris Lattner561395b2009-12-14 22:12:52 +0000238 if (Args) Args->destroy(*this);
Sam Bishop9a4939f2008-03-21 07:13:02 +0000239
Chris Lattnera3b605e2008-03-09 03:13:06 +0000240 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
241 // identifier to the expanded token.
242 bool isAtStartOfLine = Identifier.isAtStartOfLine();
243 bool hasLeadingSpace = Identifier.hasLeadingSpace();
Mike Stump1eb44332009-09-09 15:08:12 +0000244
Chris Lattnera3b605e2008-03-09 03:13:06 +0000245 // Remember where the token is instantiated.
246 SourceLocation InstantiateLoc = Identifier.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000247
Chris Lattnera3b605e2008-03-09 03:13:06 +0000248 // Replace the result token.
249 Identifier = MI->getReplacementToken(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000250
Chris Lattnera3b605e2008-03-09 03:13:06 +0000251 // Restore the StartOfLine/LeadingSpace markers.
252 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
253 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +0000254
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000255 // Update the tokens location to include both its instantiation and physical
Chris Lattnera3b605e2008-03-09 03:13:06 +0000256 // locations.
257 SourceLocation Loc =
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000258 SourceMgr.createInstantiationLoc(Identifier.getLocation(), InstantiateLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000259 InstantiationEnd,Identifier.getLength());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000260 Identifier.setLocation(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000261
Chris Lattner8ff66de2010-03-26 17:49:16 +0000262 // If this is a disabled macro or #define X X, we must mark the result as
263 // unexpandable.
264 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
265 if (MacroInfo *NewMI = getMacroInfo(NewII))
266 if (!NewMI->isEnabled() || NewMI == MI)
267 Identifier.setFlag(Token::DisableExpand);
268 }
Mike Stump1eb44332009-09-09 15:08:12 +0000269
Chris Lattnera3b605e2008-03-09 03:13:06 +0000270 // Since this is not an identifier token, it can't be macro expanded, so
271 // we're done.
272 ++NumFastMacroExpanded;
273 return false;
274 }
Mike Stump1eb44332009-09-09 15:08:12 +0000275
Chris Lattnera3b605e2008-03-09 03:13:06 +0000276 // Start expanding the macro.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000277 EnterMacro(Identifier, InstantiationEnd, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000278
Chris Lattnera3b605e2008-03-09 03:13:06 +0000279 // Now that the macro is at the top of the include stack, ask the
280 // preprocessor to read the next token from it.
281 Lex(Identifier);
282 return false;
283}
284
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000285/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
286/// token is the '(' of the macro, this method is invoked to read all of the
287/// actual arguments specified for the macro invocation. This returns null on
288/// error.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000289MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000290 MacroInfo *MI,
291 SourceLocation &MacroEnd) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000292 // The number of fixed arguments to parse.
293 unsigned NumFixedArgsLeft = MI->getNumArgs();
294 bool isVariadic = MI->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000295
Chris Lattnera3b605e2008-03-09 03:13:06 +0000296 // Outer loop, while there are more arguments, keep reading them.
297 Token Tok;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000298
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000299 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
300 // an argument value in a macro could expand to ',' or '(' or ')'.
301 LexUnexpandedToken(Tok);
302 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
Mike Stump1eb44332009-09-09 15:08:12 +0000303
Chris Lattnera3b605e2008-03-09 03:13:06 +0000304 // ArgTokens - Build up a list of tokens that make up each argument. Each
305 // argument is separated by an EOF token. Use a SmallVector so we can avoid
306 // heap allocations in the common case.
307 llvm::SmallVector<Token, 64> ArgTokens;
308
309 unsigned NumActuals = 0;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000310 while (Tok.isNot(tok::r_paren)) {
311 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
312 "only expect argument separators here");
Mike Stump1eb44332009-09-09 15:08:12 +0000313
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000314 unsigned ArgTokenStart = ArgTokens.size();
315 SourceLocation ArgStartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000316
Chris Lattnera3b605e2008-03-09 03:13:06 +0000317 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
318 // that we already consumed the first one.
319 unsigned NumParens = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Chris Lattnera3b605e2008-03-09 03:13:06 +0000321 while (1) {
322 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
323 // an argument value in a macro could expand to ',' or '(' or ')'.
324 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Chris Lattnera3b605e2008-03-09 03:13:06 +0000326 if (Tok.is(tok::eof) || Tok.is(tok::eom)) { // "#if f(<eof>" & "#if f(\n"
327 Diag(MacroName, diag::err_unterm_macro_invoc);
328 // Do not lose the EOF/EOM. Return it to the client.
329 MacroName = Tok;
330 return 0;
331 } else if (Tok.is(tok::r_paren)) {
332 // If we found the ) token, the macro arg list is done.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000333 if (NumParens-- == 0) {
334 MacroEnd = Tok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000335 break;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000336 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000337 } else if (Tok.is(tok::l_paren)) {
338 ++NumParens;
339 } else if (Tok.is(tok::comma) && NumParens == 0) {
340 // Comma ends this argument if there are more fixed arguments expected.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000341 // However, if this is a variadic macro, and this is part of the
Mike Stump1eb44332009-09-09 15:08:12 +0000342 // variadic part, then the comma is just an argument token.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000343 if (!isVariadic) break;
344 if (NumFixedArgsLeft > 1)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000345 break;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000346 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
347 // If this is a comment token in the argument list and we're just in
348 // -C mode (not -CC mode), discard the comment.
349 continue;
Chris Lattner5c497a82009-04-18 06:44:18 +0000350 } else if (Tok.getIdentifierInfo() != 0) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000351 // Reading macro arguments can cause macros that we are currently
352 // expanding from to be popped off the expansion stack. Doing so causes
353 // them to be reenabled for expansion. Here we record whether any
354 // identifiers we lex as macro arguments correspond to disabled macros.
Mike Stump1eb44332009-09-09 15:08:12 +0000355 // If so, we mark the token as noexpand. This is a subtle aspect of
Chris Lattnera3b605e2008-03-09 03:13:06 +0000356 // C99 6.10.3.4p2.
357 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
358 if (!MI->isEnabled())
359 Tok.setFlag(Token::DisableExpand);
360 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000361 ArgTokens.push_back(Tok);
362 }
Mike Stump1eb44332009-09-09 15:08:12 +0000363
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000364 // If this was an empty argument list foo(), don't add this as an empty
365 // argument.
366 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
367 break;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000368
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000369 // If this is not a variadic macro, and too many args were specified, emit
370 // an error.
371 if (!isVariadic && NumFixedArgsLeft == 0) {
372 if (ArgTokens.size() != ArgTokenStart)
373 ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000375 // Emit the diagnostic at the macro name in case there is a missing ).
376 // Emitting it at the , could be far away from the macro name.
377 Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
378 return 0;
379 }
Mike Stump1eb44332009-09-09 15:08:12 +0000380
Chris Lattnera3b605e2008-03-09 03:13:06 +0000381 // Empty arguments are standard in C99 and supported as an extension in
382 // other modes.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000383 if (ArgTokens.size() == ArgTokenStart && !Features.C99)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000384 Diag(Tok, diag::ext_empty_fnmacro_arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000385
Chris Lattnera3b605e2008-03-09 03:13:06 +0000386 // Add a marker EOF token to the end of the token list for this argument.
387 Token EOFTok;
388 EOFTok.startToken();
389 EOFTok.setKind(tok::eof);
Chris Lattnere7689882009-01-26 20:24:53 +0000390 EOFTok.setLocation(Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000391 EOFTok.setLength(0);
392 ArgTokens.push_back(EOFTok);
393 ++NumActuals;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000394 assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
Chris Lattnera3b605e2008-03-09 03:13:06 +0000395 --NumFixedArgsLeft;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000396 }
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Chris Lattnera3b605e2008-03-09 03:13:06 +0000398 // Okay, we either found the r_paren. Check to see if we parsed too few
399 // arguments.
400 unsigned MinArgsExpected = MI->getNumArgs();
Mike Stump1eb44332009-09-09 15:08:12 +0000401
Chris Lattnera3b605e2008-03-09 03:13:06 +0000402 // See MacroArgs instance var for description of this.
403 bool isVarargsElided = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000404
Chris Lattnera3b605e2008-03-09 03:13:06 +0000405 if (NumActuals < MinArgsExpected) {
406 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner97e2de12009-04-20 21:08:10 +0000407 if (NumActuals == 0 && MinArgsExpected == 1) {
408 // #define A(X) or #define A(...) ---> A()
Mike Stump1eb44332009-09-09 15:08:12 +0000409
Chris Lattner97e2de12009-04-20 21:08:10 +0000410 // If there is exactly one argument, and that argument is missing,
411 // then we have an empty "()" argument empty list. This is fine, even if
412 // the macro expects one argument (the argument is just empty).
413 isVarargsElided = MI->isVariadic();
414 } else if (MI->isVariadic() &&
415 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
416 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
Chris Lattnera3b605e2008-03-09 03:13:06 +0000417 // Varargs where the named vararg parameter is missing: ok as extension.
418 // #define A(x, ...)
419 // A("blah")
420 Diag(Tok, diag::ext_missing_varargs_arg);
421
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000422 // Remember this occurred, allowing us to elide the comma when used for
Chris Lattner63bc0352008-05-08 05:10:33 +0000423 // cases like:
Mike Stump1eb44332009-09-09 15:08:12 +0000424 // #define A(x, foo...) blah(a, ## foo)
425 // #define B(x, ...) blah(a, ## __VA_ARGS__)
426 // #define C(...) blah(a, ## __VA_ARGS__)
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000427 // A(x) B(x) C()
Chris Lattner97e2de12009-04-20 21:08:10 +0000428 isVarargsElided = true;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000429 } else {
430 // Otherwise, emit the error.
431 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
432 return 0;
433 }
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Chris Lattnera3b605e2008-03-09 03:13:06 +0000435 // Add a marker EOF token to the end of the token list for this argument.
436 SourceLocation EndLoc = Tok.getLocation();
437 Tok.startToken();
438 Tok.setKind(tok::eof);
439 Tok.setLocation(EndLoc);
440 Tok.setLength(0);
441 ArgTokens.push_back(Tok);
Chris Lattner9fc9e772009-05-13 00:55:26 +0000442
443 // If we expect two arguments, add both as empty.
444 if (NumActuals == 0 && MinArgsExpected == 2)
445 ArgTokens.push_back(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000446
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000447 } else if (NumActuals > MinArgsExpected && !MI->isVariadic()) {
448 // Emit the diagnostic at the macro name in case there is a missing ).
449 // Emitting it at the , could be far away from the macro name.
450 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
451 return 0;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000452 }
Mike Stump1eb44332009-09-09 15:08:12 +0000453
Jay Foadbeaaccd2009-05-21 09:52:38 +0000454 return MacroArgs::create(MI, ArgTokens.data(), ArgTokens.size(),
Chris Lattner561395b2009-12-14 22:12:52 +0000455 isVarargsElided, *this);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000456}
457
458/// ComputeDATE_TIME - Compute the current time, enter it into the specified
459/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
460/// the identifier tokens inserted.
461static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
462 Preprocessor &PP) {
463 time_t TT = time(0);
464 struct tm *TM = localtime(&TT);
Mike Stump1eb44332009-09-09 15:08:12 +0000465
Chris Lattnera3b605e2008-03-09 03:13:06 +0000466 static const char * const Months[] = {
467 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
468 };
Mike Stump1eb44332009-09-09 15:08:12 +0000469
Chris Lattnera3b605e2008-03-09 03:13:06 +0000470 char TmpBuffer[100];
Mike Stump1eb44332009-09-09 15:08:12 +0000471 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000472 TM->tm_year+1900);
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Chris Lattner47246be2009-01-26 19:29:26 +0000474 Token TmpTok;
475 TmpTok.startToken();
476 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
477 DATELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000478
479 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
Chris Lattner47246be2009-01-26 19:29:26 +0000480 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
481 TIMELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000482}
483
Chris Lattner148772a2009-06-13 07:13:28 +0000484
485/// HasFeature - Return true if we recognize and implement the specified feature
486/// specified by the identifier.
487static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
488 const LangOptions &LangOpts = PP.getLangOptions();
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Benjamin Kramer32592e82010-01-09 18:53:11 +0000490 return llvm::StringSwitch<bool>(II->getName())
Benjamin Kramer32592e82010-01-09 18:53:11 +0000491 .Case("attribute_analyzer_noreturn", true)
Ted Kremenek13593002010-02-18 00:06:04 +0000492 .Case("attribute_cf_returns_not_retained", true)
Benjamin Kramer32592e82010-01-09 18:53:11 +0000493 .Case("attribute_cf_returns_retained", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000494 .Case("attribute_ext_vector_type", true)
Ted Kremenek13593002010-02-18 00:06:04 +0000495 .Case("attribute_ns_returns_not_retained", true)
496 .Case("attribute_ns_returns_retained", true)
Ted Kremenek444b0352010-03-05 22:43:32 +0000497 .Case("attribute_objc_ivar_unused", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000498 .Case("attribute_overloadable", true)
499 .Case("blocks", LangOpts.Blocks)
500 .Case("cxx_attributes", LangOpts.CPlusPlus0x)
501 .Case("cxx_auto_type", LangOpts.CPlusPlus0x)
502 .Case("cxx_decltype", LangOpts.CPlusPlus0x)
503 .Case("cxx_deleted_functions", LangOpts.CPlusPlus0x)
504 .Case("cxx_exceptions", LangOpts.Exceptions)
505 .Case("cxx_rtti", LangOpts.RTTI)
506 .Case("cxx_static_assert", LangOpts.CPlusPlus0x)
507 .Case("objc_nonfragile_abi", LangOpts.ObjCNonFragileABI)
Ted Kremenek3ff9d112010-04-29 02:06:46 +0000508 .Case("objc_weak_class", LangOpts.ObjCNonFragileABI)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000509 //.Case("cxx_concepts", false)
510 //.Case("cxx_lambdas", false)
511 //.Case("cxx_nullptr", false)
512 //.Case("cxx_rvalue_references", false)
513 //.Case("cxx_variadic_templates", false)
Eric Christopher1f84f8d2010-06-24 02:02:00 +0000514 .Case("tls", PP.getTargetInfo().isTLSSupported())
Benjamin Kramer32592e82010-01-09 18:53:11 +0000515 .Default(false);
Chris Lattner148772a2009-06-13 07:13:28 +0000516}
517
John Thompson92bd8c72009-11-02 22:28:12 +0000518/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
519/// or '__has_include_next("path")' expression.
520/// Returns true if successful.
521static bool EvaluateHasIncludeCommon(bool &Result, Token &Tok,
522 IdentifierInfo *II, Preprocessor &PP,
523 const DirectoryLookup *LookupFrom) {
524 SourceLocation LParenLoc;
525
526 // Get '('.
527 PP.LexNonComment(Tok);
528
529 // Ensure we have a '('.
530 if (Tok.isNot(tok::l_paren)) {
531 PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
532 return false;
533 }
534
535 // Save '(' location for possible missing ')' message.
536 LParenLoc = Tok.getLocation();
537
538 // Get the file name.
539 PP.getCurrentLexer()->LexIncludeFilename(Tok);
540
541 // Reserve a buffer to get the spelling.
Chris Lattnera1394812010-01-10 01:35:12 +0000542 llvm::SmallString<128> FilenameBuffer;
543 llvm::StringRef Filename;
John Thompson92bd8c72009-11-02 22:28:12 +0000544
545 switch (Tok.getKind()) {
546 case tok::eom:
547 // If the token kind is EOM, the error has already been diagnosed.
548 return false;
549
550 case tok::angle_string_literal:
Douglas Gregor453091c2010-03-16 22:30:13 +0000551 case tok::string_literal: {
552 bool Invalid = false;
553 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
554 if (Invalid)
555 return false;
John Thompson92bd8c72009-11-02 22:28:12 +0000556 break;
Douglas Gregor453091c2010-03-16 22:30:13 +0000557 }
John Thompson92bd8c72009-11-02 22:28:12 +0000558
559 case tok::less:
560 // This could be a <foo/bar.h> file coming from a macro expansion. In this
561 // case, glue the tokens together into FilenameBuffer and interpret those.
562 FilenameBuffer.push_back('<');
563 if (PP.ConcatenateIncludeName(FilenameBuffer))
564 return false; // Found <eom> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +0000565 Filename = FilenameBuffer.str();
John Thompson92bd8c72009-11-02 22:28:12 +0000566 break;
567 default:
568 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
569 return false;
570 }
571
Chris Lattnera1394812010-01-10 01:35:12 +0000572 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
John Thompson92bd8c72009-11-02 22:28:12 +0000573 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
574 // error.
Chris Lattnera1394812010-01-10 01:35:12 +0000575 if (Filename.empty())
John Thompson92bd8c72009-11-02 22:28:12 +0000576 return false;
John Thompson92bd8c72009-11-02 22:28:12 +0000577
578 // Search include directories.
579 const DirectoryLookup *CurDir;
Chris Lattnerf45b6462010-01-22 00:14:44 +0000580 const FileEntry *File = PP.LookupFile(Filename, isAngled, LookupFrom, CurDir);
John Thompson92bd8c72009-11-02 22:28:12 +0000581
582 // Get the result value. Result = true means the file exists.
583 Result = File != 0;
584
585 // Get ')'.
586 PP.LexNonComment(Tok);
587
588 // Ensure we have a trailing ).
589 if (Tok.isNot(tok::r_paren)) {
590 PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
591 PP.Diag(LParenLoc, diag::note_matching) << "(";
592 return false;
593 }
594
595 return true;
596}
597
598/// EvaluateHasInclude - Process a '__has_include("path")' expression.
599/// Returns true if successful.
600static bool EvaluateHasInclude(bool &Result, Token &Tok, IdentifierInfo *II,
601 Preprocessor &PP) {
602 return(EvaluateHasIncludeCommon(Result, Tok, II, PP, NULL));
603}
604
605/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
606/// Returns true if successful.
607static bool EvaluateHasIncludeNext(bool &Result, Token &Tok,
608 IdentifierInfo *II, Preprocessor &PP) {
609 // __has_include_next is like __has_include, except that we start
610 // searching after the current found directory. If we can't do this,
611 // issue a diagnostic.
612 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
613 if (PP.isInPrimaryFile()) {
614 Lookup = 0;
615 PP.Diag(Tok, diag::pp_include_next_in_primary);
616 } else if (Lookup == 0) {
617 PP.Diag(Tok, diag::pp_include_next_absolute_path);
618 } else {
619 // Start looking up in the next directory.
620 ++Lookup;
621 }
622
623 return(EvaluateHasIncludeCommon(Result, Tok, II, PP, Lookup));
624}
Chris Lattner148772a2009-06-13 07:13:28 +0000625
Chris Lattnera3b605e2008-03-09 03:13:06 +0000626/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
627/// as a builtin macro, handle it and return the next token as 'Tok'.
628void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
629 // Figure out which token this is.
630 IdentifierInfo *II = Tok.getIdentifierInfo();
631 assert(II && "Can't be a macro without id info!");
Mike Stump1eb44332009-09-09 15:08:12 +0000632
Chris Lattnera3b605e2008-03-09 03:13:06 +0000633 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
634 // lex the token after it.
635 if (II == Ident_Pragma)
636 return Handle_Pragma(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000637
Chris Lattnera3b605e2008-03-09 03:13:06 +0000638 ++NumBuiltinMacroExpanded;
639
Benjamin Kramerb1765912010-01-27 16:38:22 +0000640 llvm::SmallString<128> TmpBuffer;
641 llvm::raw_svector_ostream OS(TmpBuffer);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000642
643 // Set up the return result.
644 Tok.setIdentifierInfo(0);
645 Tok.clearFlag(Token::NeedsCleaning);
Mike Stump1eb44332009-09-09 15:08:12 +0000646
Chris Lattnera3b605e2008-03-09 03:13:06 +0000647 if (II == Ident__LINE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000648 // C99 6.10.8: "__LINE__: The presumed line number (within the current
649 // source file) of the current source line (an integer constant)". This can
650 // be affected by #line.
Chris Lattner081927b2009-02-15 21:06:39 +0000651 SourceLocation Loc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000652
Chris Lattnerdff070f2009-04-18 22:29:33 +0000653 // Advance to the location of the first _, this might not be the first byte
654 // of the token if it starts with an escaped newline.
655 Loc = AdvanceToTokenCharacter(Loc, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000656
Chris Lattner081927b2009-02-15 21:06:39 +0000657 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
658 // a macro instantiation. This doesn't matter for object-like macros, but
659 // can matter for a function-like macro that expands to contain __LINE__.
660 // Skip down through instantiation points until we find a file loc for the
661 // end of the instantiation history.
Chris Lattner66781332009-02-15 21:26:50 +0000662 Loc = SourceMgr.getInstantiationRange(Loc).second;
Chris Lattner081927b2009-02-15 21:06:39 +0000663 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000664
Chris Lattner1fa49532009-03-08 08:08:45 +0000665 // __LINE__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +0000666 OS << PLoc.getLine();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000667 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000668 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000669 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
670 // character string literal)". This can be affected by #line.
671 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
672
673 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
674 // #include stack instead of the current file.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000675 if (II == Ident__BASE_FILE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000676 SourceLocation NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000677 while (NextLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000678 PLoc = SourceMgr.getPresumedLoc(NextLoc);
679 NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000680 }
681 }
Mike Stump1eb44332009-09-09 15:08:12 +0000682
Chris Lattnera3b605e2008-03-09 03:13:06 +0000683 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Benjamin Kramerb1765912010-01-27 16:38:22 +0000684 llvm::SmallString<128> FN;
685 FN += PLoc.getFilename();
686 Lexer::Stringify(FN);
687 OS << '"' << FN.str() << '"';
Chris Lattnera3b605e2008-03-09 03:13:06 +0000688 Tok.setKind(tok::string_literal);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000689 } else if (II == Ident__DATE__) {
690 if (!DATELoc.isValid())
691 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
692 Tok.setKind(tok::string_literal);
693 Tok.setLength(strlen("\"Mmm dd yyyy\""));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000694 Tok.setLocation(SourceMgr.createInstantiationLoc(DATELoc, Tok.getLocation(),
Chris Lattnere7fb4842009-02-15 20:52:18 +0000695 Tok.getLocation(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000696 Tok.getLength()));
Benjamin Kramerb1765912010-01-27 16:38:22 +0000697 return;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000698 } else if (II == Ident__TIME__) {
699 if (!TIMELoc.isValid())
700 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
701 Tok.setKind(tok::string_literal);
702 Tok.setLength(strlen("\"hh:mm:ss\""));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000703 Tok.setLocation(SourceMgr.createInstantiationLoc(TIMELoc, Tok.getLocation(),
Chris Lattnere7fb4842009-02-15 20:52:18 +0000704 Tok.getLocation(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000705 Tok.getLength()));
Benjamin Kramerb1765912010-01-27 16:38:22 +0000706 return;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000707 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000708 // Compute the presumed include depth of this token. This can be affected
709 // by GNU line markers.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000710 unsigned Depth = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000711
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000712 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
713 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
714 for (; PLoc.isValid(); ++Depth)
715 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
Mike Stump1eb44332009-09-09 15:08:12 +0000716
Chris Lattner1fa49532009-03-08 08:08:45 +0000717 // __INCLUDE_LEVEL__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +0000718 OS << Depth;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000719 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000720 } else if (II == Ident__TIMESTAMP__) {
721 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
722 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000723
724 // Get the file that we are lexing out of. If we're currently lexing from
725 // a macro, dig into the include stack.
726 const FileEntry *CurFile = 0;
Ted Kremeneka275a192008-11-20 01:35:24 +0000727 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Mike Stump1eb44332009-09-09 15:08:12 +0000728
Chris Lattnera3b605e2008-03-09 03:13:06 +0000729 if (TheLexer)
Ted Kremenekac80c6e2008-11-19 22:55:25 +0000730 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Chris Lattnera3b605e2008-03-09 03:13:06 +0000732 const char *Result;
733 if (CurFile) {
734 time_t TT = CurFile->getModificationTime();
735 struct tm *TM = localtime(&TT);
736 Result = asctime(TM);
737 } else {
738 Result = "??? ??? ?? ??:??:?? ????\n";
739 }
Benjamin Kramerb1765912010-01-27 16:38:22 +0000740 // Surround the string with " and strip the trailing newline.
741 OS << '"' << llvm::StringRef(Result, strlen(Result)-1) << '"';
Chris Lattnera3b605e2008-03-09 03:13:06 +0000742 Tok.setKind(tok::string_literal);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000743 } else if (II == Ident__COUNTER__) {
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000744 // __COUNTER__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +0000745 OS << CounterValue++;
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000746 Tok.setKind(tok::numeric_constant);
Chris Lattner148772a2009-06-13 07:13:28 +0000747 } else if (II == Ident__has_feature ||
748 II == Ident__has_builtin) {
749 // The argument to these two builtins should be a parenthesized identifier.
750 SourceLocation StartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000751
Chris Lattner148772a2009-06-13 07:13:28 +0000752 bool IsValid = false;
753 IdentifierInfo *FeatureII = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000754
Chris Lattner148772a2009-06-13 07:13:28 +0000755 // Read the '('.
756 Lex(Tok);
757 if (Tok.is(tok::l_paren)) {
758 // Read the identifier
759 Lex(Tok);
760 if (Tok.is(tok::identifier)) {
761 FeatureII = Tok.getIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Chris Lattner148772a2009-06-13 07:13:28 +0000763 // Read the ')'.
764 Lex(Tok);
765 if (Tok.is(tok::r_paren))
766 IsValid = true;
767 }
768 }
Mike Stump1eb44332009-09-09 15:08:12 +0000769
Chris Lattner148772a2009-06-13 07:13:28 +0000770 bool Value = false;
771 if (!IsValid)
772 Diag(StartLoc, diag::err_feature_check_malformed);
773 else if (II == Ident__has_builtin) {
Mike Stump1eb44332009-09-09 15:08:12 +0000774 // Check for a builtin is trivial.
Chris Lattner148772a2009-06-13 07:13:28 +0000775 Value = FeatureII->getBuiltinID() != 0;
776 } else {
777 assert(II == Ident__has_feature && "Must be feature check");
778 Value = HasFeature(*this, FeatureII);
779 }
Mike Stump1eb44332009-09-09 15:08:12 +0000780
Benjamin Kramerb1765912010-01-27 16:38:22 +0000781 OS << (int)Value;
Chris Lattner148772a2009-06-13 07:13:28 +0000782 Tok.setKind(tok::numeric_constant);
John Thompson92bd8c72009-11-02 22:28:12 +0000783 } else if (II == Ident__has_include ||
784 II == Ident__has_include_next) {
785 // The argument to these two builtins should be a parenthesized
786 // file name string literal using angle brackets (<>) or
787 // double-quotes ("").
788 bool Value = false;
789 bool IsValid;
790 if (II == Ident__has_include)
791 IsValid = EvaluateHasInclude(Value, Tok, II, *this);
792 else
793 IsValid = EvaluateHasIncludeNext(Value, Tok, II, *this);
Benjamin Kramerb1765912010-01-27 16:38:22 +0000794 OS << (int)Value;
John Thompson92bd8c72009-11-02 22:28:12 +0000795 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000796 } else {
797 assert(0 && "Unknown identifier!");
798 }
Benjamin Kramerb1765912010-01-27 16:38:22 +0000799 CreateString(OS.str().data(), OS.str().size(), Tok, Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000800}