blob: cc294ee2665c46ef70d1d2f6e88c46d616c38a35 [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"
Douglas Gregorf29c5232010-08-24 22:20:20 +000022#include "clang/Lex/CodeCompletionHandler.h"
Douglas Gregor295a2a62010-10-30 00:23:06 +000023#include "clang/Lex/ExternalPreprocessorSource.h"
Benjamin Kramer32592e82010-01-09 18:53:11 +000024#include "llvm/ADT/StringSwitch.h"
Douglas Gregor6665ffb2010-11-09 05:43:53 +000025#include "llvm/Config/config.h"
Benjamin Kramerb1765912010-01-27 16:38:22 +000026#include "llvm/Support/raw_ostream.h"
Chris Lattner3daed522009-03-02 22:20:04 +000027#include <cstdio>
Chris Lattnerf90a2482008-03-18 05:59:11 +000028#include <ctime>
Chris Lattnera3b605e2008-03-09 03:13:06 +000029using namespace clang;
30
Douglas Gregor295a2a62010-10-30 00:23:06 +000031MacroInfo *Preprocessor::getInfoForMacro(IdentifierInfo *II) const {
32 assert(II->hasMacroDefinition() && "Identifier is not a macro!");
33
34 llvm::DenseMap<IdentifierInfo*, MacroInfo*>::const_iterator Pos
35 = Macros.find(II);
36 if (Pos == Macros.end()) {
37 // Load this macro from the external source.
38 getExternalSource()->LoadMacroDefinition(II);
39 Pos = Macros.find(II);
40 }
41 assert(Pos != Macros.end() && "Identifier macro info is missing!");
42 return Pos->second;
43}
44
Chris Lattnera3b605e2008-03-09 03:13:06 +000045/// setMacroInfo - Specify a macro for this identifier.
46///
47void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
Chris Lattner555589d2009-04-10 21:17:07 +000048 if (MI) {
Chris Lattnera3b605e2008-03-09 03:13:06 +000049 Macros[II] = MI;
50 II->setHasMacroDefinition(true);
Chris Lattner555589d2009-04-10 21:17:07 +000051 } else if (II->hasMacroDefinition()) {
52 Macros.erase(II);
53 II->setHasMacroDefinition(false);
Chris Lattnera3b605e2008-03-09 03:13:06 +000054 }
55}
56
57/// RegisterBuiltinMacro - Register the specified identifier in the identifier
58/// table and mark it as a builtin macro to be expanded.
Chris Lattner148772a2009-06-13 07:13:28 +000059static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
Chris Lattnera3b605e2008-03-09 03:13:06 +000060 // Get the identifier.
Chris Lattner148772a2009-06-13 07:13:28 +000061 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
Mike Stump1eb44332009-09-09 15:08:12 +000062
Chris Lattnera3b605e2008-03-09 03:13:06 +000063 // Mark it as being a macro that is builtin.
Chris Lattner148772a2009-06-13 07:13:28 +000064 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +000065 MI->setIsBuiltinMacro();
Chris Lattner148772a2009-06-13 07:13:28 +000066 PP.setMacroInfo(Id, MI);
Chris Lattnera3b605e2008-03-09 03:13:06 +000067 return Id;
68}
69
70
71/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
72/// identifier table.
73void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner148772a2009-06-13 07:13:28 +000074 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
75 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
76 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
77 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
78 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
79 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
Mike Stump1eb44332009-09-09 15:08:12 +000080
Chris Lattnera3b605e2008-03-09 03:13:06 +000081 // GCC Extensions.
Chris Lattner148772a2009-06-13 07:13:28 +000082 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
83 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
84 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
Mike Stump1eb44332009-09-09 15:08:12 +000085
Chris Lattner148772a2009-06-13 07:13:28 +000086 // Clang Extensions.
John Thompson92bd8c72009-11-02 22:28:12 +000087 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
88 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
Anders Carlssoncae50952010-10-20 02:31:43 +000089 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
John Thompson92bd8c72009-11-02 22:28:12 +000090 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
91 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
John McCall1ef8a2e2010-08-28 22:34:47 +000092
93 // Microsoft Extensions.
94 if (Features.Microsoft)
95 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
96 else
97 Ident__pragma = 0;
Chris Lattnera3b605e2008-03-09 03:13:06 +000098}
99
100/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
101/// in its expansion, currently expands to that token literally.
102static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
103 const IdentifierInfo *MacroIdent,
104 Preprocessor &PP) {
105 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
106
107 // If the token isn't an identifier, it's always literally expanded.
108 if (II == 0) return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000109
Chris Lattnera3b605e2008-03-09 03:13:06 +0000110 // If the identifier is a macro, and if that macro is enabled, it may be
111 // expanded so it's not a trivial expansion.
112 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
113 // Fast expanding "#define X X" is ok, because X would be disabled.
114 II != MacroIdent)
115 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000116
Chris Lattnera3b605e2008-03-09 03:13:06 +0000117 // If this is an object-like macro invocation, it is safe to trivially expand
118 // it.
119 if (MI->isObjectLike()) return true;
120
121 // If this is a function-like macro invocation, it's safe to trivially expand
122 // as long as the identifier is not a macro argument.
123 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
124 I != E; ++I)
125 if (*I == II)
126 return false; // Identifier is a macro argument.
Mike Stump1eb44332009-09-09 15:08:12 +0000127
Chris Lattnera3b605e2008-03-09 03:13:06 +0000128 return true;
129}
130
131
132/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
133/// lexed is a '('. If so, consume the token and return true, if not, this
134/// method should have no observable side-effect on the lexed tokens.
135bool Preprocessor::isNextPPTokenLParen() {
136 // Do some quick tests for rejection cases.
137 unsigned Val;
138 if (CurLexer)
139 Val = CurLexer->isNextPPTokenLParen();
Ted Kremenek1a531572008-11-19 22:43:49 +0000140 else if (CurPTHLexer)
141 Val = CurPTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000142 else
143 Val = CurTokenLexer->isNextTokenLParen();
Mike Stump1eb44332009-09-09 15:08:12 +0000144
Chris Lattnera3b605e2008-03-09 03:13:06 +0000145 if (Val == 2) {
146 // We have run off the end. If it's a source file we don't
147 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
148 // macro stack.
Ted Kremenek17ff58a2008-11-19 22:21:33 +0000149 if (CurPPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000150 return false;
151 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
152 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
153 if (Entry.TheLexer)
154 Val = Entry.TheLexer->isNextPPTokenLParen();
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000155 else if (Entry.ThePTHLexer)
156 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000157 else
158 Val = Entry.TheTokenLexer->isNextTokenLParen();
Mike Stump1eb44332009-09-09 15:08:12 +0000159
Chris Lattnera3b605e2008-03-09 03:13:06 +0000160 if (Val != 2)
161 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000162
Chris Lattnera3b605e2008-03-09 03:13:06 +0000163 // Ran off the end of a source file?
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000164 if (Entry.ThePPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000165 return false;
166 }
167 }
168
169 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
170 // have found something that isn't a '(' or we found the end of the
171 // translation unit. In either case, return false.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000172 return Val == 1;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000173}
174
175/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
176/// expanded as a macro, handle it and return the next token as 'Identifier'.
Mike Stump1eb44332009-09-09 15:08:12 +0000177bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000178 MacroInfo *MI) {
Chris Lattnerba9eee32009-03-12 17:31:43 +0000179 if (Callbacks) Callbacks->MacroExpands(Identifier, MI);
Mike Stump1eb44332009-09-09 15:08:12 +0000180
Douglas Gregor13678972010-01-26 19:43:43 +0000181 // If this is a macro expansion in the "#if !defined(x)" line for the file,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000182 // then the macro could expand to different things in other contexts, we need
183 // to disable the optimization in this case.
Ted Kremenek68a91d52008-11-18 01:12:54 +0000184 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
Mike Stump1eb44332009-09-09 15:08:12 +0000185
Chris Lattnera3b605e2008-03-09 03:13:06 +0000186 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
187 if (MI->isBuiltinMacro()) {
188 ExpandBuiltinMacro(Identifier);
189 return false;
190 }
Mike Stump1eb44332009-09-09 15:08:12 +0000191
Chris Lattnera3b605e2008-03-09 03:13:06 +0000192 /// Args - If this is a function-like macro expansion, this contains,
193 /// for each macro argument, the list of tokens that were provided to the
194 /// invocation.
195 MacroArgs *Args = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Chris Lattnere7fb4842009-02-15 20:52:18 +0000197 // Remember where the end of the instantiation occurred. For an object-like
198 // macro, this is the identifier. For a function-like macro, this is the ')'.
199 SourceLocation InstantiationEnd = Identifier.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Chris Lattnera3b605e2008-03-09 03:13:06 +0000201 // If this is a function-like macro, read the arguments.
202 if (MI->isFunctionLike()) {
203 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000204 // name isn't a '(', this macro should not be expanded.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000205 if (!isNextPPTokenLParen())
206 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000207
Chris Lattnera3b605e2008-03-09 03:13:06 +0000208 // Remember that we are now parsing the arguments to a macro invocation.
209 // Preprocessor directives used inside macro arguments are not portable, and
210 // this enables the warning.
211 InMacroArgs = true;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000212 Args = ReadFunctionLikeMacroArgs(Identifier, MI, InstantiationEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000213
Chris Lattnera3b605e2008-03-09 03:13:06 +0000214 // Finished parsing args.
215 InMacroArgs = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000216
Chris Lattnera3b605e2008-03-09 03:13:06 +0000217 // If there was an error parsing the arguments, bail out.
218 if (Args == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000219
Chris Lattnera3b605e2008-03-09 03:13:06 +0000220 ++NumFnMacroExpanded;
221 } else {
222 ++NumMacroExpanded;
223 }
Mike Stump1eb44332009-09-09 15:08:12 +0000224
Chris Lattnera3b605e2008-03-09 03:13:06 +0000225 // Notice that this macro has been used.
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000226 markMacroAsUsed(MI);
Mike Stump1eb44332009-09-09 15:08:12 +0000227
Chris Lattnera3b605e2008-03-09 03:13:06 +0000228 // If we started lexing a macro, enter the macro expansion body.
Mike Stump1eb44332009-09-09 15:08:12 +0000229
Chris Lattnera3b605e2008-03-09 03:13:06 +0000230 // If this macro expands to no tokens, don't bother to push it onto the
231 // expansion stack, only to take it right back off.
232 if (MI->getNumTokens() == 0) {
233 // No need for arg info.
Chris Lattner561395b2009-12-14 22:12:52 +0000234 if (Args) Args->destroy(*this);
Mike Stump1eb44332009-09-09 15:08:12 +0000235
Chris Lattnera3b605e2008-03-09 03:13:06 +0000236 // Ignore this macro use, just return the next token in the current
237 // buffer.
238 bool HadLeadingSpace = Identifier.hasLeadingSpace();
239 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
Mike Stump1eb44332009-09-09 15:08:12 +0000240
Chris Lattnera3b605e2008-03-09 03:13:06 +0000241 Lex(Identifier);
Mike Stump1eb44332009-09-09 15:08:12 +0000242
Chris Lattnera3b605e2008-03-09 03:13:06 +0000243 // If the identifier isn't on some OTHER line, inherit the leading
244 // whitespace/first-on-a-line property of this token. This handles
245 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
246 // empty.
247 if (!Identifier.isAtStartOfLine()) {
248 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
249 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
250 }
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000251 Identifier.setFlag(Token::LeadingEmptyMacro);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000252 ++NumFastMacroExpanded;
253 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000254
Chris Lattnera3b605e2008-03-09 03:13:06 +0000255 } else if (MI->getNumTokens() == 1 &&
256 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000257 *this)) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000258 // Otherwise, if this macro expands into a single trivially-expanded
Mike Stump1eb44332009-09-09 15:08:12 +0000259 // token: expand it now. This handles common cases like
Chris Lattnera3b605e2008-03-09 03:13:06 +0000260 // "#define VAL 42".
Sam Bishop9a4939f2008-03-21 07:13:02 +0000261
262 // No need for arg info.
Chris Lattner561395b2009-12-14 22:12:52 +0000263 if (Args) Args->destroy(*this);
Sam Bishop9a4939f2008-03-21 07:13:02 +0000264
Chris Lattnera3b605e2008-03-09 03:13:06 +0000265 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
266 // identifier to the expanded token.
267 bool isAtStartOfLine = Identifier.isAtStartOfLine();
268 bool hasLeadingSpace = Identifier.hasLeadingSpace();
Mike Stump1eb44332009-09-09 15:08:12 +0000269
Chris Lattnera3b605e2008-03-09 03:13:06 +0000270 // Remember where the token is instantiated.
271 SourceLocation InstantiateLoc = Identifier.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000272
Chris Lattnera3b605e2008-03-09 03:13:06 +0000273 // Replace the result token.
274 Identifier = MI->getReplacementToken(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000275
Chris Lattnera3b605e2008-03-09 03:13:06 +0000276 // Restore the StartOfLine/LeadingSpace markers.
277 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
278 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000280 // Update the tokens location to include both its instantiation and physical
Chris Lattnera3b605e2008-03-09 03:13:06 +0000281 // locations.
282 SourceLocation Loc =
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000283 SourceMgr.createInstantiationLoc(Identifier.getLocation(), InstantiateLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000284 InstantiationEnd,Identifier.getLength());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000285 Identifier.setLocation(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000286
Chris Lattner8ff66de2010-03-26 17:49:16 +0000287 // If this is a disabled macro or #define X X, we must mark the result as
288 // unexpandable.
289 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
290 if (MacroInfo *NewMI = getMacroInfo(NewII))
291 if (!NewMI->isEnabled() || NewMI == MI)
292 Identifier.setFlag(Token::DisableExpand);
293 }
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Chris Lattnera3b605e2008-03-09 03:13:06 +0000295 // Since this is not an identifier token, it can't be macro expanded, so
296 // we're done.
297 ++NumFastMacroExpanded;
298 return false;
299 }
Mike Stump1eb44332009-09-09 15:08:12 +0000300
Chris Lattnera3b605e2008-03-09 03:13:06 +0000301 // Start expanding the macro.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000302 EnterMacro(Identifier, InstantiationEnd, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000303
Chris Lattnera3b605e2008-03-09 03:13:06 +0000304 // Now that the macro is at the top of the include stack, ask the
305 // preprocessor to read the next token from it.
306 Lex(Identifier);
307 return false;
308}
309
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000310/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
311/// token is the '(' of the macro, this method is invoked to read all of the
312/// actual arguments specified for the macro invocation. This returns null on
313/// error.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000314MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000315 MacroInfo *MI,
316 SourceLocation &MacroEnd) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000317 // The number of fixed arguments to parse.
318 unsigned NumFixedArgsLeft = MI->getNumArgs();
319 bool isVariadic = MI->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Chris Lattnera3b605e2008-03-09 03:13:06 +0000321 // Outer loop, while there are more arguments, keep reading them.
322 Token Tok;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000323
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000324 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
325 // an argument value in a macro could expand to ',' or '(' or ')'.
326 LexUnexpandedToken(Tok);
327 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
Mike Stump1eb44332009-09-09 15:08:12 +0000328
Chris Lattnera3b605e2008-03-09 03:13:06 +0000329 // ArgTokens - Build up a list of tokens that make up each argument. Each
330 // argument is separated by an EOF token. Use a SmallVector so we can avoid
331 // heap allocations in the common case.
332 llvm::SmallVector<Token, 64> ArgTokens;
333
334 unsigned NumActuals = 0;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000335 while (Tok.isNot(tok::r_paren)) {
336 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
337 "only expect argument separators here");
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000339 unsigned ArgTokenStart = ArgTokens.size();
340 SourceLocation ArgStartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Chris Lattnera3b605e2008-03-09 03:13:06 +0000342 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
343 // that we already consumed the first one.
344 unsigned NumParens = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Chris Lattnera3b605e2008-03-09 03:13:06 +0000346 while (1) {
347 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
348 // an argument value in a macro could expand to ',' or '(' or ')'.
349 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000350
Douglas Gregorf29c5232010-08-24 22:20:20 +0000351 if (Tok.is(tok::code_completion)) {
352 if (CodeComplete)
353 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
354 MI, NumActuals);
355 LexUnexpandedToken(Tok);
356 }
357
Chris Lattnera3b605e2008-03-09 03:13:06 +0000358 if (Tok.is(tok::eof) || Tok.is(tok::eom)) { // "#if f(<eof>" & "#if f(\n"
359 Diag(MacroName, diag::err_unterm_macro_invoc);
360 // Do not lose the EOF/EOM. Return it to the client.
361 MacroName = Tok;
362 return 0;
363 } else if (Tok.is(tok::r_paren)) {
364 // If we found the ) token, the macro arg list is done.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000365 if (NumParens-- == 0) {
366 MacroEnd = Tok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000367 break;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000368 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000369 } else if (Tok.is(tok::l_paren)) {
370 ++NumParens;
371 } else if (Tok.is(tok::comma) && NumParens == 0) {
372 // Comma ends this argument if there are more fixed arguments expected.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000373 // However, if this is a variadic macro, and this is part of the
Mike Stump1eb44332009-09-09 15:08:12 +0000374 // variadic part, then the comma is just an argument token.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000375 if (!isVariadic) break;
376 if (NumFixedArgsLeft > 1)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000377 break;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000378 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
379 // If this is a comment token in the argument list and we're just in
380 // -C mode (not -CC mode), discard the comment.
381 continue;
Chris Lattner5c497a82009-04-18 06:44:18 +0000382 } else if (Tok.getIdentifierInfo() != 0) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000383 // Reading macro arguments can cause macros that we are currently
384 // expanding from to be popped off the expansion stack. Doing so causes
385 // them to be reenabled for expansion. Here we record whether any
386 // identifiers we lex as macro arguments correspond to disabled macros.
Mike Stump1eb44332009-09-09 15:08:12 +0000387 // If so, we mark the token as noexpand. This is a subtle aspect of
Chris Lattnera3b605e2008-03-09 03:13:06 +0000388 // C99 6.10.3.4p2.
389 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
390 if (!MI->isEnabled())
391 Tok.setFlag(Token::DisableExpand);
392 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000393 ArgTokens.push_back(Tok);
394 }
Mike Stump1eb44332009-09-09 15:08:12 +0000395
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000396 // If this was an empty argument list foo(), don't add this as an empty
397 // argument.
398 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
399 break;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000400
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000401 // If this is not a variadic macro, and too many args were specified, emit
402 // an error.
403 if (!isVariadic && NumFixedArgsLeft == 0) {
404 if (ArgTokens.size() != ArgTokenStart)
405 ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000407 // Emit the diagnostic at the macro name in case there is a missing ).
408 // Emitting it at the , could be far away from the macro name.
409 Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
410 return 0;
411 }
Mike Stump1eb44332009-09-09 15:08:12 +0000412
Chris Lattnera3b605e2008-03-09 03:13:06 +0000413 // Empty arguments are standard in C99 and supported as an extension in
414 // other modes.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000415 if (ArgTokens.size() == ArgTokenStart && !Features.C99)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000416 Diag(Tok, diag::ext_empty_fnmacro_arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Chris Lattnera3b605e2008-03-09 03:13:06 +0000418 // Add a marker EOF token to the end of the token list for this argument.
419 Token EOFTok;
420 EOFTok.startToken();
421 EOFTok.setKind(tok::eof);
Chris Lattnere7689882009-01-26 20:24:53 +0000422 EOFTok.setLocation(Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000423 EOFTok.setLength(0);
424 ArgTokens.push_back(EOFTok);
425 ++NumActuals;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000426 assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
Chris Lattnera3b605e2008-03-09 03:13:06 +0000427 --NumFixedArgsLeft;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000428 }
Mike Stump1eb44332009-09-09 15:08:12 +0000429
Chris Lattnera3b605e2008-03-09 03:13:06 +0000430 // Okay, we either found the r_paren. Check to see if we parsed too few
431 // arguments.
432 unsigned MinArgsExpected = MI->getNumArgs();
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Chris Lattnera3b605e2008-03-09 03:13:06 +0000434 // See MacroArgs instance var for description of this.
435 bool isVarargsElided = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000436
Chris Lattnera3b605e2008-03-09 03:13:06 +0000437 if (NumActuals < MinArgsExpected) {
438 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner97e2de12009-04-20 21:08:10 +0000439 if (NumActuals == 0 && MinArgsExpected == 1) {
440 // #define A(X) or #define A(...) ---> A()
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Chris Lattner97e2de12009-04-20 21:08:10 +0000442 // If there is exactly one argument, and that argument is missing,
443 // then we have an empty "()" argument empty list. This is fine, even if
444 // the macro expects one argument (the argument is just empty).
445 isVarargsElided = MI->isVariadic();
446 } else if (MI->isVariadic() &&
447 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
448 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
Chris Lattnera3b605e2008-03-09 03:13:06 +0000449 // Varargs where the named vararg parameter is missing: ok as extension.
450 // #define A(x, ...)
451 // A("blah")
452 Diag(Tok, diag::ext_missing_varargs_arg);
453
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000454 // Remember this occurred, allowing us to elide the comma when used for
Chris Lattner63bc0352008-05-08 05:10:33 +0000455 // cases like:
Mike Stump1eb44332009-09-09 15:08:12 +0000456 // #define A(x, foo...) blah(a, ## foo)
457 // #define B(x, ...) blah(a, ## __VA_ARGS__)
458 // #define C(...) blah(a, ## __VA_ARGS__)
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000459 // A(x) B(x) C()
Chris Lattner97e2de12009-04-20 21:08:10 +0000460 isVarargsElided = true;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000461 } else {
462 // Otherwise, emit the error.
463 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
464 return 0;
465 }
Mike Stump1eb44332009-09-09 15:08:12 +0000466
Chris Lattnera3b605e2008-03-09 03:13:06 +0000467 // Add a marker EOF token to the end of the token list for this argument.
468 SourceLocation EndLoc = Tok.getLocation();
469 Tok.startToken();
470 Tok.setKind(tok::eof);
471 Tok.setLocation(EndLoc);
472 Tok.setLength(0);
473 ArgTokens.push_back(Tok);
Chris Lattner9fc9e772009-05-13 00:55:26 +0000474
475 // If we expect two arguments, add both as empty.
476 if (NumActuals == 0 && MinArgsExpected == 2)
477 ArgTokens.push_back(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000478
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000479 } else if (NumActuals > MinArgsExpected && !MI->isVariadic()) {
480 // Emit the diagnostic at the macro name in case there is a missing ).
481 // Emitting it at the , could be far away from the macro name.
482 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
483 return 0;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000484 }
Mike Stump1eb44332009-09-09 15:08:12 +0000485
Jay Foadbeaaccd2009-05-21 09:52:38 +0000486 return MacroArgs::create(MI, ArgTokens.data(), ArgTokens.size(),
Chris Lattner561395b2009-12-14 22:12:52 +0000487 isVarargsElided, *this);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000488}
489
490/// ComputeDATE_TIME - Compute the current time, enter it into the specified
491/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
492/// the identifier tokens inserted.
493static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
494 Preprocessor &PP) {
495 time_t TT = time(0);
496 struct tm *TM = localtime(&TT);
Mike Stump1eb44332009-09-09 15:08:12 +0000497
Chris Lattnera3b605e2008-03-09 03:13:06 +0000498 static const char * const Months[] = {
499 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
500 };
Mike Stump1eb44332009-09-09 15:08:12 +0000501
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000502 char TmpBuffer[32];
Douglas Gregorb87b29e2010-11-09 04:38:09 +0000503#ifdef LLVM_ON_WIN32
504 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
505 TM->tm_year+1900);
506#else
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000507 snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000508 TM->tm_year+1900);
Douglas Gregorb87b29e2010-11-09 04:38:09 +0000509#endif
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Chris Lattner47246be2009-01-26 19:29:26 +0000511 Token TmpTok;
512 TmpTok.startToken();
513 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
514 DATELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000515
NAKAMURA Takumi513038d2010-11-09 06:27:32 +0000516#ifdef LLVM_ON_WIN32
517 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
518#else
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000519 snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
NAKAMURA Takumi513038d2010-11-09 06:27:32 +0000520#endif
Chris Lattner47246be2009-01-26 19:29:26 +0000521 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
522 TIMELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000523}
524
Chris Lattner148772a2009-06-13 07:13:28 +0000525
526/// HasFeature - Return true if we recognize and implement the specified feature
527/// specified by the identifier.
528static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
529 const LangOptions &LangOpts = PP.getLangOptions();
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Benjamin Kramer32592e82010-01-09 18:53:11 +0000531 return llvm::StringSwitch<bool>(II->getName())
Benjamin Kramer32592e82010-01-09 18:53:11 +0000532 .Case("attribute_analyzer_noreturn", true)
Ted Kremenek13593002010-02-18 00:06:04 +0000533 .Case("attribute_cf_returns_not_retained", true)
Benjamin Kramer32592e82010-01-09 18:53:11 +0000534 .Case("attribute_cf_returns_retained", true)
John McCall48209082010-11-08 19:48:17 +0000535 .Case("attribute_deprecated_with_message", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000536 .Case("attribute_ext_vector_type", true)
Ted Kremenek13593002010-02-18 00:06:04 +0000537 .Case("attribute_ns_returns_not_retained", true)
538 .Case("attribute_ns_returns_retained", true)
Ted Kremenek12b94342011-01-27 06:54:14 +0000539 .Case("attribute_ns_consumes_self", true)
Ted Kremenek11fe1752011-01-27 18:43:03 +0000540 .Case("attribute_ns_consumed", true)
541 .Case("attribute_cf_consumed", true)
Ted Kremenek444b0352010-03-05 22:43:32 +0000542 .Case("attribute_objc_ivar_unused", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000543 .Case("attribute_overloadable", true)
John McCall48209082010-11-08 19:48:17 +0000544 .Case("attribute_unavailable_with_message", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000545 .Case("blocks", LangOpts.Blocks)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000546 .Case("cxx_exceptions", LangOpts.Exceptions)
547 .Case("cxx_rtti", LangOpts.RTTI)
John McCall48209082010-11-08 19:48:17 +0000548 .Case("enumerator_attributes", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000549 .Case("objc_nonfragile_abi", LangOpts.ObjCNonFragileABI)
Ted Kremenek3ff9d112010-04-29 02:06:46 +0000550 .Case("objc_weak_class", LangOpts.ObjCNonFragileABI)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000551 .Case("ownership_holds", true)
552 .Case("ownership_returns", true)
553 .Case("ownership_takes", true)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000554 // C++0x features
555 .Case("cxx_attributes", LangOpts.CPlusPlus0x)
556 //.Case("cxx_auto_type", false)
557 .Case("cxx_decltype", LangOpts.CPlusPlus0x)
Douglas Gregor07508002011-02-05 20:35:30 +0000558 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000559 .Case("cxx_deleted_functions", LangOpts.CPlusPlus0x)
560 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus0x)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000561 //.Case("cxx_lambdas", false)
562 //.Case("cxx_nullptr", false)
Douglas Gregor56209ff2011-01-26 21:25:54 +0000563 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000564 .Case("cxx_rvalue_references", LangOpts.CPlusPlus0x)
565 .Case("cxx_strong_enums", LangOpts.CPlusPlus0x)
566 .Case("cxx_static_assert", LangOpts.CPlusPlus0x)
567 .Case("cxx_trailing_return", LangOpts.CPlusPlus0x)
568 .Case("cxx_variadic_templates", LangOpts.CPlusPlus0x)
Douglas Gregorafdf1372011-02-03 21:57:35 +0000569 // Type traits
570 .Case("has_nothrow_assign", LangOpts.CPlusPlus)
571 .Case("has_nothrow_copy", LangOpts.CPlusPlus)
572 .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
573 .Case("has_trivial_assign", LangOpts.CPlusPlus)
574 .Case("has_trivial_copy", LangOpts.CPlusPlus)
575 .Case("has_trivial_constructor", LangOpts.CPlusPlus)
576 .Case("has_trivial_destructor", LangOpts.CPlusPlus)
577 .Case("has_virtual_destructor", LangOpts.CPlusPlus)
578 .Case("is_abstract", LangOpts.CPlusPlus)
579 .Case("is_base_of", LangOpts.CPlusPlus)
580 .Case("is_class", LangOpts.CPlusPlus)
581 .Case("is_convertible_to", LangOpts.CPlusPlus)
582 .Case("is_empty", LangOpts.CPlusPlus)
583 .Case("is_enum", LangOpts.CPlusPlus)
584 .Case("is_pod", LangOpts.CPlusPlus)
585 .Case("is_polymorphic", LangOpts.CPlusPlus)
586 .Case("is_union", LangOpts.CPlusPlus)
587 .Case("is_literal", LangOpts.CPlusPlus)
Eric Christopher1f84f8d2010-06-24 02:02:00 +0000588 .Case("tls", PP.getTargetInfo().isTLSSupported())
Benjamin Kramer32592e82010-01-09 18:53:11 +0000589 .Default(false);
Chris Lattner148772a2009-06-13 07:13:28 +0000590}
591
Anders Carlssoncae50952010-10-20 02:31:43 +0000592/// HasAttribute - Return true if we recognize and implement the attribute
593/// specified by the given identifier.
594static bool HasAttribute(const IdentifierInfo *II) {
595 return llvm::StringSwitch<bool>(II->getName())
596#include "clang/Lex/AttrSpellings.inc"
597 .Default(false);
598}
599
John Thompson92bd8c72009-11-02 22:28:12 +0000600/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
601/// or '__has_include_next("path")' expression.
602/// Returns true if successful.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000603static bool EvaluateHasIncludeCommon(Token &Tok,
604 IdentifierInfo *II, Preprocessor &PP,
605 const DirectoryLookup *LookupFrom) {
John Thompson92bd8c72009-11-02 22:28:12 +0000606 SourceLocation LParenLoc;
607
608 // Get '('.
609 PP.LexNonComment(Tok);
610
611 // Ensure we have a '('.
612 if (Tok.isNot(tok::l_paren)) {
613 PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
614 return false;
615 }
616
617 // Save '(' location for possible missing ')' message.
618 LParenLoc = Tok.getLocation();
619
620 // Get the file name.
621 PP.getCurrentLexer()->LexIncludeFilename(Tok);
622
623 // Reserve a buffer to get the spelling.
Chris Lattnera1394812010-01-10 01:35:12 +0000624 llvm::SmallString<128> FilenameBuffer;
625 llvm::StringRef Filename;
Douglas Gregorecdcb882010-10-20 22:00:55 +0000626 SourceLocation EndLoc;
627
John Thompson92bd8c72009-11-02 22:28:12 +0000628 switch (Tok.getKind()) {
629 case tok::eom:
630 // If the token kind is EOM, the error has already been diagnosed.
631 return false;
632
633 case tok::angle_string_literal:
Douglas Gregor453091c2010-03-16 22:30:13 +0000634 case tok::string_literal: {
635 bool Invalid = false;
636 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
637 if (Invalid)
638 return false;
John Thompson92bd8c72009-11-02 22:28:12 +0000639 break;
Douglas Gregor453091c2010-03-16 22:30:13 +0000640 }
John Thompson92bd8c72009-11-02 22:28:12 +0000641
642 case tok::less:
643 // This could be a <foo/bar.h> file coming from a macro expansion. In this
644 // case, glue the tokens together into FilenameBuffer and interpret those.
645 FilenameBuffer.push_back('<');
Douglas Gregorecdcb882010-10-20 22:00:55 +0000646 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc))
John Thompson92bd8c72009-11-02 22:28:12 +0000647 return false; // Found <eom> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +0000648 Filename = FilenameBuffer.str();
John Thompson92bd8c72009-11-02 22:28:12 +0000649 break;
650 default:
651 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
652 return false;
653 }
654
Chris Lattnera1394812010-01-10 01:35:12 +0000655 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
John Thompson92bd8c72009-11-02 22:28:12 +0000656 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
657 // error.
Chris Lattnera1394812010-01-10 01:35:12 +0000658 if (Filename.empty())
John Thompson92bd8c72009-11-02 22:28:12 +0000659 return false;
John Thompson92bd8c72009-11-02 22:28:12 +0000660
661 // Search include directories.
662 const DirectoryLookup *CurDir;
Chris Lattnerf45b6462010-01-22 00:14:44 +0000663 const FileEntry *File = PP.LookupFile(Filename, isAngled, LookupFrom, CurDir);
John Thompson92bd8c72009-11-02 22:28:12 +0000664
665 // Get the result value. Result = true means the file exists.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000666 bool Result = File != 0;
John Thompson92bd8c72009-11-02 22:28:12 +0000667
668 // Get ')'.
669 PP.LexNonComment(Tok);
670
671 // Ensure we have a trailing ).
672 if (Tok.isNot(tok::r_paren)) {
673 PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
674 PP.Diag(LParenLoc, diag::note_matching) << "(";
675 return false;
676 }
677
Chris Lattner3ed572e2011-01-15 06:57:04 +0000678 return Result;
John Thompson92bd8c72009-11-02 22:28:12 +0000679}
680
681/// EvaluateHasInclude - Process a '__has_include("path")' expression.
682/// Returns true if successful.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000683static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
John Thompson92bd8c72009-11-02 22:28:12 +0000684 Preprocessor &PP) {
Chris Lattner3ed572e2011-01-15 06:57:04 +0000685 return EvaluateHasIncludeCommon(Tok, II, PP, NULL);
John Thompson92bd8c72009-11-02 22:28:12 +0000686}
687
688/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
689/// Returns true if successful.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000690static bool EvaluateHasIncludeNext(Token &Tok,
John Thompson92bd8c72009-11-02 22:28:12 +0000691 IdentifierInfo *II, Preprocessor &PP) {
692 // __has_include_next is like __has_include, except that we start
693 // searching after the current found directory. If we can't do this,
694 // issue a diagnostic.
695 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
696 if (PP.isInPrimaryFile()) {
697 Lookup = 0;
698 PP.Diag(Tok, diag::pp_include_next_in_primary);
699 } else if (Lookup == 0) {
700 PP.Diag(Tok, diag::pp_include_next_absolute_path);
701 } else {
702 // Start looking up in the next directory.
703 ++Lookup;
704 }
705
Chris Lattner3ed572e2011-01-15 06:57:04 +0000706 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup);
John Thompson92bd8c72009-11-02 22:28:12 +0000707}
Chris Lattner148772a2009-06-13 07:13:28 +0000708
Chris Lattnera3b605e2008-03-09 03:13:06 +0000709/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
710/// as a builtin macro, handle it and return the next token as 'Tok'.
711void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
712 // Figure out which token this is.
713 IdentifierInfo *II = Tok.getIdentifierInfo();
714 assert(II && "Can't be a macro without id info!");
Mike Stump1eb44332009-09-09 15:08:12 +0000715
John McCall1ef8a2e2010-08-28 22:34:47 +0000716 // If this is an _Pragma or Microsoft __pragma directive, expand it,
717 // invoke the pragma handler, then lex the token after it.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000718 if (II == Ident_Pragma)
719 return Handle_Pragma(Tok);
John McCall1ef8a2e2010-08-28 22:34:47 +0000720 else if (II == Ident__pragma) // in non-MS mode this is null
721 return HandleMicrosoft__pragma(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000722
Chris Lattnera3b605e2008-03-09 03:13:06 +0000723 ++NumBuiltinMacroExpanded;
724
Benjamin Kramerb1765912010-01-27 16:38:22 +0000725 llvm::SmallString<128> TmpBuffer;
726 llvm::raw_svector_ostream OS(TmpBuffer);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000727
728 // Set up the return result.
729 Tok.setIdentifierInfo(0);
730 Tok.clearFlag(Token::NeedsCleaning);
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Chris Lattnera3b605e2008-03-09 03:13:06 +0000732 if (II == Ident__LINE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000733 // C99 6.10.8: "__LINE__: The presumed line number (within the current
734 // source file) of the current source line (an integer constant)". This can
735 // be affected by #line.
Chris Lattner081927b2009-02-15 21:06:39 +0000736 SourceLocation Loc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000737
Chris Lattnerdff070f2009-04-18 22:29:33 +0000738 // Advance to the location of the first _, this might not be the first byte
739 // of the token if it starts with an escaped newline.
740 Loc = AdvanceToTokenCharacter(Loc, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000741
Chris Lattner081927b2009-02-15 21:06:39 +0000742 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
743 // a macro instantiation. This doesn't matter for object-like macros, but
744 // can matter for a function-like macro that expands to contain __LINE__.
745 // Skip down through instantiation points until we find a file loc for the
746 // end of the instantiation history.
Chris Lattner66781332009-02-15 21:26:50 +0000747 Loc = SourceMgr.getInstantiationRange(Loc).second;
Chris Lattner081927b2009-02-15 21:06:39 +0000748 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000749
Chris Lattner1fa49532009-03-08 08:08:45 +0000750 // __LINE__ expands to a simple numeric value.
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000751 OS << (PLoc.isValid()? PLoc.getLine() : 1);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000752 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000753 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000754 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
755 // character string literal)". This can be affected by #line.
756 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
757
758 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
759 // #include stack instead of the current file.
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000760 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000761 SourceLocation NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000762 while (NextLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000763 PLoc = SourceMgr.getPresumedLoc(NextLoc);
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000764 if (PLoc.isInvalid())
765 break;
766
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000767 NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000768 }
769 }
Mike Stump1eb44332009-09-09 15:08:12 +0000770
Chris Lattnera3b605e2008-03-09 03:13:06 +0000771 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Benjamin Kramerb1765912010-01-27 16:38:22 +0000772 llvm::SmallString<128> FN;
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000773 if (PLoc.isValid()) {
774 FN += PLoc.getFilename();
775 Lexer::Stringify(FN);
776 OS << '"' << FN.str() << '"';
777 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000778 Tok.setKind(tok::string_literal);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000779 } else if (II == Ident__DATE__) {
780 if (!DATELoc.isValid())
781 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
782 Tok.setKind(tok::string_literal);
783 Tok.setLength(strlen("\"Mmm dd yyyy\""));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000784 Tok.setLocation(SourceMgr.createInstantiationLoc(DATELoc, Tok.getLocation(),
Chris Lattnere7fb4842009-02-15 20:52:18 +0000785 Tok.getLocation(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000786 Tok.getLength()));
Benjamin Kramerb1765912010-01-27 16:38:22 +0000787 return;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000788 } else if (II == Ident__TIME__) {
789 if (!TIMELoc.isValid())
790 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
791 Tok.setKind(tok::string_literal);
792 Tok.setLength(strlen("\"hh:mm:ss\""));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000793 Tok.setLocation(SourceMgr.createInstantiationLoc(TIMELoc, Tok.getLocation(),
Chris Lattnere7fb4842009-02-15 20:52:18 +0000794 Tok.getLocation(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000795 Tok.getLength()));
Benjamin Kramerb1765912010-01-27 16:38:22 +0000796 return;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000797 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000798 // Compute the presumed include depth of this token. This can be affected
799 // by GNU line markers.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000800 unsigned Depth = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000801
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000802 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000803 if (PLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000804 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000805 for (; PLoc.isValid(); ++Depth)
806 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
807 }
Mike Stump1eb44332009-09-09 15:08:12 +0000808
Chris Lattner1fa49532009-03-08 08:08:45 +0000809 // __INCLUDE_LEVEL__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +0000810 OS << Depth;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000811 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000812 } else if (II == Ident__TIMESTAMP__) {
813 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
814 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000815
816 // Get the file that we are lexing out of. If we're currently lexing from
817 // a macro, dig into the include stack.
818 const FileEntry *CurFile = 0;
Ted Kremeneka275a192008-11-20 01:35:24 +0000819 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Mike Stump1eb44332009-09-09 15:08:12 +0000820
Chris Lattnera3b605e2008-03-09 03:13:06 +0000821 if (TheLexer)
Ted Kremenekac80c6e2008-11-19 22:55:25 +0000822 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000823
Chris Lattnera3b605e2008-03-09 03:13:06 +0000824 const char *Result;
825 if (CurFile) {
826 time_t TT = CurFile->getModificationTime();
827 struct tm *TM = localtime(&TT);
828 Result = asctime(TM);
829 } else {
830 Result = "??? ??? ?? ??:??:?? ????\n";
831 }
Benjamin Kramerb1765912010-01-27 16:38:22 +0000832 // Surround the string with " and strip the trailing newline.
833 OS << '"' << llvm::StringRef(Result, strlen(Result)-1) << '"';
Chris Lattnera3b605e2008-03-09 03:13:06 +0000834 Tok.setKind(tok::string_literal);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000835 } else if (II == Ident__COUNTER__) {
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000836 // __COUNTER__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +0000837 OS << CounterValue++;
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000838 Tok.setKind(tok::numeric_constant);
Chris Lattner148772a2009-06-13 07:13:28 +0000839 } else if (II == Ident__has_feature ||
Anders Carlssoncae50952010-10-20 02:31:43 +0000840 II == Ident__has_builtin ||
841 II == Ident__has_attribute) {
Chris Lattner148772a2009-06-13 07:13:28 +0000842 // The argument to these two builtins should be a parenthesized identifier.
843 SourceLocation StartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000844
Chris Lattner148772a2009-06-13 07:13:28 +0000845 bool IsValid = false;
846 IdentifierInfo *FeatureII = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000847
Chris Lattner148772a2009-06-13 07:13:28 +0000848 // Read the '('.
849 Lex(Tok);
850 if (Tok.is(tok::l_paren)) {
851 // Read the identifier
852 Lex(Tok);
853 if (Tok.is(tok::identifier)) {
854 FeatureII = Tok.getIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000855
Chris Lattner148772a2009-06-13 07:13:28 +0000856 // Read the ')'.
857 Lex(Tok);
858 if (Tok.is(tok::r_paren))
859 IsValid = true;
860 }
861 }
Mike Stump1eb44332009-09-09 15:08:12 +0000862
Chris Lattner148772a2009-06-13 07:13:28 +0000863 bool Value = false;
864 if (!IsValid)
865 Diag(StartLoc, diag::err_feature_check_malformed);
866 else if (II == Ident__has_builtin) {
Mike Stump1eb44332009-09-09 15:08:12 +0000867 // Check for a builtin is trivial.
Chris Lattner148772a2009-06-13 07:13:28 +0000868 Value = FeatureII->getBuiltinID() != 0;
Anders Carlssoncae50952010-10-20 02:31:43 +0000869 } else if (II == Ident__has_attribute)
870 Value = HasAttribute(FeatureII);
871 else {
Chris Lattner148772a2009-06-13 07:13:28 +0000872 assert(II == Ident__has_feature && "Must be feature check");
873 Value = HasFeature(*this, FeatureII);
874 }
Mike Stump1eb44332009-09-09 15:08:12 +0000875
Benjamin Kramerb1765912010-01-27 16:38:22 +0000876 OS << (int)Value;
Chris Lattner148772a2009-06-13 07:13:28 +0000877 Tok.setKind(tok::numeric_constant);
John Thompson92bd8c72009-11-02 22:28:12 +0000878 } else if (II == Ident__has_include ||
879 II == Ident__has_include_next) {
880 // The argument to these two builtins should be a parenthesized
881 // file name string literal using angle brackets (<>) or
882 // double-quotes ("").
Chris Lattner3ed572e2011-01-15 06:57:04 +0000883 bool Value;
John Thompson92bd8c72009-11-02 22:28:12 +0000884 if (II == Ident__has_include)
Chris Lattner3ed572e2011-01-15 06:57:04 +0000885 Value = EvaluateHasInclude(Tok, II, *this);
John Thompson92bd8c72009-11-02 22:28:12 +0000886 else
Chris Lattner3ed572e2011-01-15 06:57:04 +0000887 Value = EvaluateHasIncludeNext(Tok, II, *this);
Benjamin Kramerb1765912010-01-27 16:38:22 +0000888 OS << (int)Value;
John Thompson92bd8c72009-11-02 22:28:12 +0000889 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000890 } else {
891 assert(0 && "Unknown identifier!");
892 }
Benjamin Kramerb1765912010-01-27 16:38:22 +0000893 CreateString(OS.str().data(), OS.str().size(), Tok, Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000894}
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000895
896void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
897 // If the 'used' status changed, and the macro requires 'unused' warning,
898 // remove its SourceLocation from the warn-for-unused-macro locations.
899 if (MI->isWarnIfUnused() && !MI->isUsed())
900 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
901 MI->setIsUsed(true);
902}