blob: c6aabde03e0a657bb34c63edb493111510de7969 [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"
Ted Kremenekd7681502011-10-12 19:46:30 +000024#include "clang/Lex/LiteralSupport.h"
Benjamin Kramer32592e82010-01-09 18:53:11 +000025#include "llvm/ADT/StringSwitch.h"
Argyrios Kyrtzidis5b3284a2011-06-29 22:20:11 +000026#include "llvm/ADT/STLExtras.h"
Dylan Noblesmith1770e0d2011-12-22 22:49:47 +000027#include "llvm/Config/llvm-config.h"
Benjamin Kramerb1765912010-01-27 16:38:22 +000028#include "llvm/Support/raw_ostream.h"
David Blaikie9fe8c742011-09-23 05:35:21 +000029#include "llvm/Support/ErrorHandling.h"
Chris Lattner3daed522009-03-02 22:20:04 +000030#include <cstdio>
Chris Lattnerf90a2482008-03-18 05:59:11 +000031#include <ctime>
Chris Lattnera3b605e2008-03-09 03:13:06 +000032using namespace clang;
33
Douglas Gregor295a2a62010-10-30 00:23:06 +000034MacroInfo *Preprocessor::getInfoForMacro(IdentifierInfo *II) const {
35 assert(II->hasMacroDefinition() && "Identifier is not a macro!");
36
37 llvm::DenseMap<IdentifierInfo*, MacroInfo*>::const_iterator Pos
38 = Macros.find(II);
39 if (Pos == Macros.end()) {
40 // Load this macro from the external source.
41 getExternalSource()->LoadMacroDefinition(II);
42 Pos = Macros.find(II);
43 }
44 assert(Pos != Macros.end() && "Identifier macro info is missing!");
45 return Pos->second;
46}
47
Chris Lattnera3b605e2008-03-09 03:13:06 +000048/// setMacroInfo - Specify a macro for this identifier.
49///
Douglas Gregor5d5051f2012-01-24 15:24:38 +000050void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI,
51 bool LoadedFromAST) {
Chris Lattner555589d2009-04-10 21:17:07 +000052 if (MI) {
Chris Lattnera3b605e2008-03-09 03:13:06 +000053 Macros[II] = MI;
54 II->setHasMacroDefinition(true);
Douglas Gregor5d5051f2012-01-24 15:24:38 +000055 if (II->isFromAST() && !LoadedFromAST)
Douglas Gregoreee242f2011-10-27 09:33:13 +000056 II->setChangedSinceDeserialization();
Chris Lattner555589d2009-04-10 21:17:07 +000057 } else if (II->hasMacroDefinition()) {
58 Macros.erase(II);
59 II->setHasMacroDefinition(false);
Douglas Gregor5d5051f2012-01-24 15:24:38 +000060 if (II->isFromAST() && !LoadedFromAST)
Douglas Gregoreee242f2011-10-27 09:33:13 +000061 II->setChangedSinceDeserialization();
Chris Lattnera3b605e2008-03-09 03:13:06 +000062 }
63}
64
65/// RegisterBuiltinMacro - Register the specified identifier in the identifier
66/// table and mark it as a builtin macro to be expanded.
Chris Lattner148772a2009-06-13 07:13:28 +000067static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
Chris Lattnera3b605e2008-03-09 03:13:06 +000068 // Get the identifier.
Chris Lattner148772a2009-06-13 07:13:28 +000069 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
Mike Stump1eb44332009-09-09 15:08:12 +000070
Chris Lattnera3b605e2008-03-09 03:13:06 +000071 // Mark it as being a macro that is builtin.
Chris Lattner148772a2009-06-13 07:13:28 +000072 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +000073 MI->setIsBuiltinMacro();
Chris Lattner148772a2009-06-13 07:13:28 +000074 PP.setMacroInfo(Id, MI);
Chris Lattnera3b605e2008-03-09 03:13:06 +000075 return Id;
76}
77
78
79/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
80/// identifier table.
81void Preprocessor::RegisterBuiltinMacros() {
Chris Lattner148772a2009-06-13 07:13:28 +000082 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
83 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
84 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
85 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
86 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
87 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
Mike Stump1eb44332009-09-09 15:08:12 +000088
Chris Lattnera3b605e2008-03-09 03:13:06 +000089 // GCC Extensions.
Chris Lattner148772a2009-06-13 07:13:28 +000090 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
91 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
92 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
Mike Stump1eb44332009-09-09 15:08:12 +000093
Chris Lattner148772a2009-06-13 07:13:28 +000094 // Clang Extensions.
John Thompson92bd8c72009-11-02 22:28:12 +000095 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
Peter Collingbournec1b5fa42011-05-13 20:54:45 +000096 Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension");
John Thompson92bd8c72009-11-02 22:28:12 +000097 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
Anders Carlssoncae50952010-10-20 02:31:43 +000098 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
John Thompson92bd8c72009-11-02 22:28:12 +000099 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
100 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
Ted Kremenekd7681502011-10-12 19:46:30 +0000101 Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning");
John McCall1ef8a2e2010-08-28 22:34:47 +0000102
103 // Microsoft Extensions.
David Blaikie4e4d0842012-03-11 07:00:24 +0000104 if (LangOpts.MicrosoftExt)
John McCall1ef8a2e2010-08-28 22:34:47 +0000105 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
106 else
107 Ident__pragma = 0;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000108}
109
110/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
111/// in its expansion, currently expands to that token literally.
112static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
113 const IdentifierInfo *MacroIdent,
114 Preprocessor &PP) {
115 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
116
117 // If the token isn't an identifier, it's always literally expanded.
118 if (II == 0) return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Argyrios Kyrtzidis373cb782011-12-17 04:13:31 +0000120 // If the information about this identifier is out of date, update it from
121 // the external source.
122 if (II->isOutOfDate())
123 PP.getExternalSource()->updateOutOfDateIdentifier(*II);
124
Chris Lattnera3b605e2008-03-09 03:13:06 +0000125 // If the identifier is a macro, and if that macro is enabled, it may be
126 // expanded so it's not a trivial expansion.
127 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
128 // Fast expanding "#define X X" is ok, because X would be disabled.
129 II != MacroIdent)
130 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000131
Chris Lattnera3b605e2008-03-09 03:13:06 +0000132 // If this is an object-like macro invocation, it is safe to trivially expand
133 // it.
134 if (MI->isObjectLike()) return true;
135
136 // If this is a function-like macro invocation, it's safe to trivially expand
137 // as long as the identifier is not a macro argument.
138 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
139 I != E; ++I)
140 if (*I == II)
141 return false; // Identifier is a macro argument.
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Chris Lattnera3b605e2008-03-09 03:13:06 +0000143 return true;
144}
145
146
147/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
148/// lexed is a '('. If so, consume the token and return true, if not, this
149/// method should have no observable side-effect on the lexed tokens.
150bool Preprocessor::isNextPPTokenLParen() {
151 // Do some quick tests for rejection cases.
152 unsigned Val;
153 if (CurLexer)
154 Val = CurLexer->isNextPPTokenLParen();
Ted Kremenek1a531572008-11-19 22:43:49 +0000155 else if (CurPTHLexer)
156 Val = CurPTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000157 else
158 Val = CurTokenLexer->isNextTokenLParen();
Mike Stump1eb44332009-09-09 15:08:12 +0000159
Chris Lattnera3b605e2008-03-09 03:13:06 +0000160 if (Val == 2) {
161 // We have run off the end. If it's a source file we don't
162 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
163 // macro stack.
Ted Kremenek17ff58a2008-11-19 22:21:33 +0000164 if (CurPPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000165 return false;
166 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
167 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
168 if (Entry.TheLexer)
169 Val = Entry.TheLexer->isNextPPTokenLParen();
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000170 else if (Entry.ThePTHLexer)
171 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000172 else
173 Val = Entry.TheTokenLexer->isNextTokenLParen();
Mike Stump1eb44332009-09-09 15:08:12 +0000174
Chris Lattnera3b605e2008-03-09 03:13:06 +0000175 if (Val != 2)
176 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000177
Chris Lattnera3b605e2008-03-09 03:13:06 +0000178 // Ran off the end of a source file?
Ted Kremenekdd95d6c2008-11-20 16:46:54 +0000179 if (Entry.ThePPLexer)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000180 return false;
181 }
182 }
183
184 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
185 // have found something that isn't a '(' or we found the end of the
186 // translation unit. In either case, return false.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000187 return Val == 1;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000188}
189
190/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
191/// expanded as a macro, handle it and return the next token as 'Identifier'.
Mike Stump1eb44332009-09-09 15:08:12 +0000192bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000193 MacroInfo *MI) {
Douglas Gregor13678972010-01-26 19:43:43 +0000194 // If this is a macro expansion in the "#if !defined(x)" line for the file,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000195 // then the macro could expand to different things in other contexts, we need
196 // to disable the optimization in this case.
Ted Kremenek68a91d52008-11-18 01:12:54 +0000197 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
Mike Stump1eb44332009-09-09 15:08:12 +0000198
Chris Lattnera3b605e2008-03-09 03:13:06 +0000199 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
200 if (MI->isBuiltinMacro()) {
Argyrios Kyrtzidis1b2d5362011-08-18 01:05:45 +0000201 if (Callbacks) Callbacks->MacroExpands(Identifier, MI,
202 Identifier.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000203 ExpandBuiltinMacro(Identifier);
204 return false;
205 }
Mike Stump1eb44332009-09-09 15:08:12 +0000206
Chris Lattnera3b605e2008-03-09 03:13:06 +0000207 /// Args - If this is a function-like macro expansion, this contains,
208 /// for each macro argument, the list of tokens that were provided to the
209 /// invocation.
210 MacroArgs *Args = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000211
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000212 // Remember where the end of the expansion occurred. For an object-like
Chris Lattnere7fb4842009-02-15 20:52:18 +0000213 // macro, this is the identifier. For a function-like macro, this is the ')'.
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000214 SourceLocation ExpansionEnd = Identifier.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000215
Chris Lattnera3b605e2008-03-09 03:13:06 +0000216 // If this is a function-like macro, read the arguments.
217 if (MI->isFunctionLike()) {
218 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000219 // name isn't a '(', this macro should not be expanded.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000220 if (!isNextPPTokenLParen())
221 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000222
Chris Lattnera3b605e2008-03-09 03:13:06 +0000223 // Remember that we are now parsing the arguments to a macro invocation.
224 // Preprocessor directives used inside macro arguments are not portable, and
225 // this enables the warning.
226 InMacroArgs = true;
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000227 Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000228
Chris Lattnera3b605e2008-03-09 03:13:06 +0000229 // Finished parsing args.
230 InMacroArgs = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000231
Chris Lattnera3b605e2008-03-09 03:13:06 +0000232 // If there was an error parsing the arguments, bail out.
233 if (Args == 0) return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000234
Chris Lattnera3b605e2008-03-09 03:13:06 +0000235 ++NumFnMacroExpanded;
236 } else {
237 ++NumMacroExpanded;
238 }
Mike Stump1eb44332009-09-09 15:08:12 +0000239
Chris Lattnera3b605e2008-03-09 03:13:06 +0000240 // Notice that this macro has been used.
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000241 markMacroAsUsed(MI);
Mike Stump1eb44332009-09-09 15:08:12 +0000242
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000243 // Remember where the token is expanded.
244 SourceLocation ExpandLoc = Identifier.getLocation();
Argyrios Kyrtzidis66c44e72012-05-10 18:57:19 +0000245 SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
Argyrios Kyrtzidisb7d98d32011-04-27 05:04:02 +0000246
Argyrios Kyrtzidis66c44e72012-05-10 18:57:19 +0000247 if (Callbacks) {
248 if (InMacroArgs) {
249 // We can have macro expansion inside a conditional directive while
250 // reading the function macro arguments. To ensure, in that case, that
251 // MacroExpands callbacks still happen in source order, queue this
252 // callback to have it happen after the function macro callback.
253 DelayedMacroExpandsCallbacks.push_back(
254 MacroExpandsInfo(Identifier, MI, ExpansionRange));
255 } else {
256 Callbacks->MacroExpands(Identifier, MI, ExpansionRange);
257 if (!DelayedMacroExpandsCallbacks.empty()) {
258 for (unsigned i=0, e = DelayedMacroExpandsCallbacks.size(); i!=e; ++i) {
259 MacroExpandsInfo &Info = DelayedMacroExpandsCallbacks[i];
260 Callbacks->MacroExpands(Info.Tok, Info.MI, Info.Range);
261 }
262 DelayedMacroExpandsCallbacks.clear();
263 }
264 }
265 }
Argyrios Kyrtzidis1b2d5362011-08-18 01:05:45 +0000266
267 // If we started lexing a macro, enter the macro expansion body.
268
Chris Lattnera3b605e2008-03-09 03:13:06 +0000269 // If this macro expands to no tokens, don't bother to push it onto the
270 // expansion stack, only to take it right back off.
271 if (MI->getNumTokens() == 0) {
272 // No need for arg info.
Chris Lattner561395b2009-12-14 22:12:52 +0000273 if (Args) Args->destroy(*this);
Mike Stump1eb44332009-09-09 15:08:12 +0000274
Chris Lattnera3b605e2008-03-09 03:13:06 +0000275 // Ignore this macro use, just return the next token in the current
276 // buffer.
277 bool HadLeadingSpace = Identifier.hasLeadingSpace();
278 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Chris Lattnera3b605e2008-03-09 03:13:06 +0000280 Lex(Identifier);
Mike Stump1eb44332009-09-09 15:08:12 +0000281
Chris Lattnera3b605e2008-03-09 03:13:06 +0000282 // If the identifier isn't on some OTHER line, inherit the leading
283 // whitespace/first-on-a-line property of this token. This handles
284 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
285 // empty.
286 if (!Identifier.isAtStartOfLine()) {
287 if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
288 if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
289 }
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000290 Identifier.setFlag(Token::LeadingEmptyMacro);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000291 ++NumFastMacroExpanded;
292 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000293
Chris Lattnera3b605e2008-03-09 03:13:06 +0000294 } else if (MI->getNumTokens() == 1 &&
295 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000296 *this)) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000297 // Otherwise, if this macro expands into a single trivially-expanded
Mike Stump1eb44332009-09-09 15:08:12 +0000298 // token: expand it now. This handles common cases like
Chris Lattnera3b605e2008-03-09 03:13:06 +0000299 // "#define VAL 42".
Sam Bishop9a4939f2008-03-21 07:13:02 +0000300
301 // No need for arg info.
Chris Lattner561395b2009-12-14 22:12:52 +0000302 if (Args) Args->destroy(*this);
Sam Bishop9a4939f2008-03-21 07:13:02 +0000303
Chris Lattnera3b605e2008-03-09 03:13:06 +0000304 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
305 // identifier to the expanded token.
306 bool isAtStartOfLine = Identifier.isAtStartOfLine();
307 bool hasLeadingSpace = Identifier.hasLeadingSpace();
Mike Stump1eb44332009-09-09 15:08:12 +0000308
Chris Lattnera3b605e2008-03-09 03:13:06 +0000309 // Replace the result token.
310 Identifier = MI->getReplacementToken(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000311
Chris Lattnera3b605e2008-03-09 03:13:06 +0000312 // Restore the StartOfLine/LeadingSpace markers.
313 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
314 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +0000315
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000316 // Update the tokens location to include both its expansion and physical
Chris Lattnera3b605e2008-03-09 03:13:06 +0000317 // locations.
318 SourceLocation Loc =
Chandler Carruthbf340e42011-07-26 03:03:05 +0000319 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
320 ExpansionEnd,Identifier.getLength());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000321 Identifier.setLocation(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000322
Chris Lattner8ff66de2010-03-26 17:49:16 +0000323 // If this is a disabled macro or #define X X, we must mark the result as
324 // unexpandable.
325 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
326 if (MacroInfo *NewMI = getMacroInfo(NewII))
Abramo Bagnara1e8a0672012-01-02 10:08:26 +0000327 if (!NewMI->isEnabled() || NewMI == MI) {
Chris Lattner8ff66de2010-03-26 17:49:16 +0000328 Identifier.setFlag(Token::DisableExpand);
Abramo Bagnara1e8a0672012-01-02 10:08:26 +0000329 Diag(Identifier, diag::pp_disabled_macro_expansion);
330 }
Chris Lattner8ff66de2010-03-26 17:49:16 +0000331 }
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Chris Lattnera3b605e2008-03-09 03:13:06 +0000333 // Since this is not an identifier token, it can't be macro expanded, so
334 // we're done.
335 ++NumFastMacroExpanded;
336 return false;
337 }
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Chris Lattnera3b605e2008-03-09 03:13:06 +0000339 // Start expanding the macro.
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000340 EnterMacro(Identifier, ExpansionEnd, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Chris Lattnera3b605e2008-03-09 03:13:06 +0000342 // Now that the macro is at the top of the include stack, ask the
343 // preprocessor to read the next token from it.
344 Lex(Identifier);
345 return false;
346}
347
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000348/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
349/// token is the '(' of the macro, this method is invoked to read all of the
350/// actual arguments specified for the macro invocation. This returns null on
351/// error.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000352MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000353 MacroInfo *MI,
354 SourceLocation &MacroEnd) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000355 // The number of fixed arguments to parse.
356 unsigned NumFixedArgsLeft = MI->getNumArgs();
357 bool isVariadic = MI->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Chris Lattnera3b605e2008-03-09 03:13:06 +0000359 // Outer loop, while there are more arguments, keep reading them.
360 Token Tok;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000361
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000362 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
363 // an argument value in a macro could expand to ',' or '(' or ')'.
364 LexUnexpandedToken(Tok);
365 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Chris Lattnera3b605e2008-03-09 03:13:06 +0000367 // ArgTokens - Build up a list of tokens that make up each argument. Each
368 // argument is separated by an EOF token. Use a SmallVector so we can avoid
369 // heap allocations in the common case.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000370 SmallVector<Token, 64> ArgTokens;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000371
372 unsigned NumActuals = 0;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000373 while (Tok.isNot(tok::r_paren)) {
374 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
375 "only expect argument separators here");
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000377 unsigned ArgTokenStart = ArgTokens.size();
378 SourceLocation ArgStartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Chris Lattnera3b605e2008-03-09 03:13:06 +0000380 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
381 // that we already consumed the first one.
382 unsigned NumParens = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Chris Lattnera3b605e2008-03-09 03:13:06 +0000384 while (1) {
385 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
386 // an argument value in a macro could expand to ',' or '(' or ')'.
387 LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Peter Collingbourne84021552011-02-28 02:37:51 +0000389 if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n"
Chris Lattnera3b605e2008-03-09 03:13:06 +0000390 Diag(MacroName, diag::err_unterm_macro_invoc);
Peter Collingbourne84021552011-02-28 02:37:51 +0000391 // Do not lose the EOF/EOD. Return it to the client.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000392 MacroName = Tok;
393 return 0;
394 } else if (Tok.is(tok::r_paren)) {
395 // If we found the ) token, the macro arg list is done.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000396 if (NumParens-- == 0) {
397 MacroEnd = Tok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000398 break;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000399 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000400 } else if (Tok.is(tok::l_paren)) {
401 ++NumParens;
402 } else if (Tok.is(tok::comma) && NumParens == 0) {
403 // Comma ends this argument if there are more fixed arguments expected.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000404 // However, if this is a variadic macro, and this is part of the
Mike Stump1eb44332009-09-09 15:08:12 +0000405 // variadic part, then the comma is just an argument token.
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000406 if (!isVariadic) break;
407 if (NumFixedArgsLeft > 1)
Chris Lattnera3b605e2008-03-09 03:13:06 +0000408 break;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000409 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
410 // If this is a comment token in the argument list and we're just in
411 // -C mode (not -CC mode), discard the comment.
412 continue;
Chris Lattner5c497a82009-04-18 06:44:18 +0000413 } else if (Tok.getIdentifierInfo() != 0) {
Chris Lattnera3b605e2008-03-09 03:13:06 +0000414 // Reading macro arguments can cause macros that we are currently
415 // expanding from to be popped off the expansion stack. Doing so causes
416 // them to be reenabled for expansion. Here we record whether any
417 // identifiers we lex as macro arguments correspond to disabled macros.
Mike Stump1eb44332009-09-09 15:08:12 +0000418 // If so, we mark the token as noexpand. This is a subtle aspect of
Chris Lattnera3b605e2008-03-09 03:13:06 +0000419 // C99 6.10.3.4p2.
420 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
421 if (!MI->isEnabled())
422 Tok.setFlag(Token::DisableExpand);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000423 } else if (Tok.is(tok::code_completion)) {
424 if (CodeComplete)
425 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
426 MI, NumActuals);
427 // Don't mark that we reached the code-completion point because the
428 // parser is going to handle the token and there will be another
429 // code-completion callback.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000430 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000431
Chris Lattnera3b605e2008-03-09 03:13:06 +0000432 ArgTokens.push_back(Tok);
433 }
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000435 // If this was an empty argument list foo(), don't add this as an empty
436 // argument.
437 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
438 break;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000439
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000440 // If this is not a variadic macro, and too many args were specified, emit
441 // an error.
442 if (!isVariadic && NumFixedArgsLeft == 0) {
443 if (ArgTokens.size() != ArgTokenStart)
444 ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000445
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000446 // Emit the diagnostic at the macro name in case there is a missing ).
447 // Emitting it at the , could be far away from the macro name.
448 Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
449 return 0;
450 }
Mike Stump1eb44332009-09-09 15:08:12 +0000451
Chris Lattner32c13882011-04-22 23:25:09 +0000452 // Empty arguments are standard in C99 and C++0x, and are supported as an extension in
Chris Lattnera3b605e2008-03-09 03:13:06 +0000453 // other modes.
David Blaikie4e4d0842012-03-11 07:00:24 +0000454 if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99)
455 Diag(Tok, LangOpts.CPlusPlus0x ?
Richard Smith661a9962011-10-15 01:18:56 +0000456 diag::warn_cxx98_compat_empty_fnmacro_arg :
457 diag::ext_empty_fnmacro_arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Chris Lattnera3b605e2008-03-09 03:13:06 +0000459 // Add a marker EOF token to the end of the token list for this argument.
460 Token EOFTok;
461 EOFTok.startToken();
462 EOFTok.setKind(tok::eof);
Chris Lattnere7689882009-01-26 20:24:53 +0000463 EOFTok.setLocation(Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +0000464 EOFTok.setLength(0);
465 ArgTokens.push_back(EOFTok);
466 ++NumActuals;
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000467 assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
Chris Lattnera3b605e2008-03-09 03:13:06 +0000468 --NumFixedArgsLeft;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000469 }
Mike Stump1eb44332009-09-09 15:08:12 +0000470
Chris Lattnera3b605e2008-03-09 03:13:06 +0000471 // Okay, we either found the r_paren. Check to see if we parsed too few
472 // arguments.
473 unsigned MinArgsExpected = MI->getNumArgs();
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Chris Lattnera3b605e2008-03-09 03:13:06 +0000475 // See MacroArgs instance var for description of this.
476 bool isVarargsElided = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000477
Chris Lattnera3b605e2008-03-09 03:13:06 +0000478 if (NumActuals < MinArgsExpected) {
479 // There are several cases where too few arguments is ok, handle them now.
Chris Lattner97e2de12009-04-20 21:08:10 +0000480 if (NumActuals == 0 && MinArgsExpected == 1) {
481 // #define A(X) or #define A(...) ---> A()
Mike Stump1eb44332009-09-09 15:08:12 +0000482
Chris Lattner97e2de12009-04-20 21:08:10 +0000483 // If there is exactly one argument, and that argument is missing,
484 // then we have an empty "()" argument empty list. This is fine, even if
485 // the macro expects one argument (the argument is just empty).
486 isVarargsElided = MI->isVariadic();
487 } else if (MI->isVariadic() &&
488 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
489 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
Richard Smith9f728cd2012-06-22 23:59:08 +0000490 // Varargs where the named vararg parameter is missing: OK as extension.
491 // #define A(x, ...)
492 // A("blah")
Chris Lattnera3b605e2008-03-09 03:13:06 +0000493 Diag(Tok, diag::ext_missing_varargs_arg);
Richard Smith9f728cd2012-06-22 23:59:08 +0000494 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
495 << MacroName.getIdentifierInfo();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000496
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000497 // Remember this occurred, allowing us to elide the comma when used for
Chris Lattner63bc0352008-05-08 05:10:33 +0000498 // cases like:
Mike Stump1eb44332009-09-09 15:08:12 +0000499 // #define A(x, foo...) blah(a, ## foo)
500 // #define B(x, ...) blah(a, ## __VA_ARGS__)
501 // #define C(...) blah(a, ## __VA_ARGS__)
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000502 // A(x) B(x) C()
Chris Lattner97e2de12009-04-20 21:08:10 +0000503 isVarargsElided = true;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000504 } else {
505 // Otherwise, emit the error.
506 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
507 return 0;
508 }
Mike Stump1eb44332009-09-09 15:08:12 +0000509
Chris Lattnera3b605e2008-03-09 03:13:06 +0000510 // Add a marker EOF token to the end of the token list for this argument.
511 SourceLocation EndLoc = Tok.getLocation();
512 Tok.startToken();
513 Tok.setKind(tok::eof);
514 Tok.setLocation(EndLoc);
515 Tok.setLength(0);
516 ArgTokens.push_back(Tok);
Chris Lattner9fc9e772009-05-13 00:55:26 +0000517
518 // If we expect two arguments, add both as empty.
519 if (NumActuals == 0 && MinArgsExpected == 2)
520 ArgTokens.push_back(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000521
Chris Lattner0a4f1b92009-04-18 01:13:56 +0000522 } else if (NumActuals > MinArgsExpected && !MI->isVariadic()) {
523 // Emit the diagnostic at the macro name in case there is a missing ).
524 // Emitting it at the , could be far away from the macro name.
525 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
526 return 0;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000527 }
Mike Stump1eb44332009-09-09 15:08:12 +0000528
David Blaikied7bb6a02011-09-22 02:03:12 +0000529 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000530}
531
Argyrios Kyrtzidis5b3284a2011-06-29 22:20:11 +0000532/// \brief Keeps macro expanded tokens for TokenLexers.
533//
534/// Works like a stack; a TokenLexer adds the macro expanded tokens that is
535/// going to lex in the cache and when it finishes the tokens are removed
536/// from the end of the cache.
537Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
Chris Lattner2d3ba4f2011-07-23 17:14:25 +0000538 ArrayRef<Token> tokens) {
Argyrios Kyrtzidis5b3284a2011-06-29 22:20:11 +0000539 assert(tokLexer);
540 if (tokens.empty())
541 return 0;
542
543 size_t newIndex = MacroExpandedTokens.size();
544 bool cacheNeedsToGrow = tokens.size() >
545 MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
546 MacroExpandedTokens.append(tokens.begin(), tokens.end());
547
548 if (cacheNeedsToGrow) {
549 // Go through all the TokenLexers whose 'Tokens' pointer points in the
550 // buffer and update the pointers to the (potential) new buffer array.
551 for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) {
552 TokenLexer *prevLexer;
553 size_t tokIndex;
554 llvm::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i];
555 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
556 }
557 }
558
559 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
560 return MacroExpandedTokens.data() + newIndex;
561}
562
563void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
564 assert(!MacroExpandingLexersStack.empty());
565 size_t tokIndex = MacroExpandingLexersStack.back().second;
566 assert(tokIndex < MacroExpandedTokens.size());
567 // Pop the cached macro expanded tokens from the end.
568 MacroExpandedTokens.resize(tokIndex);
569 MacroExpandingLexersStack.pop_back();
570}
571
Chris Lattnera3b605e2008-03-09 03:13:06 +0000572/// ComputeDATE_TIME - Compute the current time, enter it into the specified
573/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
574/// the identifier tokens inserted.
575static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
576 Preprocessor &PP) {
577 time_t TT = time(0);
578 struct tm *TM = localtime(&TT);
Mike Stump1eb44332009-09-09 15:08:12 +0000579
Chris Lattnera3b605e2008-03-09 03:13:06 +0000580 static const char * const Months[] = {
581 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
582 };
Mike Stump1eb44332009-09-09 15:08:12 +0000583
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000584 char TmpBuffer[32];
Douglas Gregorb87b29e2010-11-09 04:38:09 +0000585#ifdef LLVM_ON_WIN32
586 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
587 TM->tm_year+1900);
588#else
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000589 snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
Chris Lattnera3b605e2008-03-09 03:13:06 +0000590 TM->tm_year+1900);
Douglas Gregorb87b29e2010-11-09 04:38:09 +0000591#endif
Mike Stump1eb44332009-09-09 15:08:12 +0000592
Chris Lattner47246be2009-01-26 19:29:26 +0000593 Token TmpTok;
594 TmpTok.startToken();
595 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
596 DATELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000597
NAKAMURA Takumi513038d2010-11-09 06:27:32 +0000598#ifdef LLVM_ON_WIN32
599 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
600#else
Douglas Gregor5e0fb352010-11-09 03:20:07 +0000601 snprintf(TmpBuffer, sizeof(TmpBuffer), "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
NAKAMURA Takumi513038d2010-11-09 06:27:32 +0000602#endif
Chris Lattner47246be2009-01-26 19:29:26 +0000603 PP.CreateString(TmpBuffer, strlen(TmpBuffer), TmpTok);
604 TIMELoc = TmpTok.getLocation();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000605}
606
Chris Lattner148772a2009-06-13 07:13:28 +0000607
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000608/// HasFeature - Return true if we recognize and implement the feature
609/// specified by the identifier as a standard language feature.
Chris Lattner148772a2009-06-13 07:13:28 +0000610static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000611 const LangOptions &LangOpts = PP.getLangOpts();
Richard Smith5297d712012-02-25 10:41:10 +0000612 StringRef Feature = II->getName();
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Richard Smith5297d712012-02-25 10:41:10 +0000614 // Normalize the feature name, __foo__ becomes foo.
615 if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4)
616 Feature = Feature.substr(2, Feature.size() - 4);
617
618 return llvm::StringSwitch<bool>(Feature)
Kostya Serebryanyb6196882011-11-22 01:28:36 +0000619 .Case("address_sanitizer", LangOpts.AddressSanitizer)
Benjamin Kramer32592e82010-01-09 18:53:11 +0000620 .Case("attribute_analyzer_noreturn", true)
Douglas Gregordceb5312011-03-26 12:16:15 +0000621 .Case("attribute_availability", true)
Ted Kremenek13593002010-02-18 00:06:04 +0000622 .Case("attribute_cf_returns_not_retained", true)
Benjamin Kramer32592e82010-01-09 18:53:11 +0000623 .Case("attribute_cf_returns_retained", true)
John McCall48209082010-11-08 19:48:17 +0000624 .Case("attribute_deprecated_with_message", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000625 .Case("attribute_ext_vector_type", true)
Ted Kremenek13593002010-02-18 00:06:04 +0000626 .Case("attribute_ns_returns_not_retained", true)
627 .Case("attribute_ns_returns_retained", true)
Ted Kremenek12b94342011-01-27 06:54:14 +0000628 .Case("attribute_ns_consumes_self", true)
Ted Kremenek11fe1752011-01-27 18:43:03 +0000629 .Case("attribute_ns_consumed", true)
630 .Case("attribute_cf_consumed", true)
Ted Kremenek444b0352010-03-05 22:43:32 +0000631 .Case("attribute_objc_ivar_unused", true)
John McCalld5313b02011-03-02 11:33:24 +0000632 .Case("attribute_objc_method_family", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000633 .Case("attribute_overloadable", true)
John McCall48209082010-11-08 19:48:17 +0000634 .Case("attribute_unavailable_with_message", true)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000635 .Case("blocks", LangOpts.Blocks)
Ted Kremenek6d9afd92010-04-29 02:06:42 +0000636 .Case("cxx_exceptions", LangOpts.Exceptions)
637 .Case("cxx_rtti", LangOpts.RTTI)
John McCall48209082010-11-08 19:48:17 +0000638 .Case("enumerator_attributes", true)
John McCallf85e1932011-06-15 23:02:42 +0000639 // Objective-C features
640 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
641 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
642 .Case("objc_arc_weak", LangOpts.ObjCAutoRefCount &&
John McCall9f084a32011-07-06 00:26:06 +0000643 LangOpts.ObjCRuntimeHasWeak)
Fariborz Jahanianf83a6152012-02-02 00:15:51 +0000644 .Case("objc_default_synthesize_properties", LangOpts.ObjC2)
Douglas Gregor5471bc82011-09-08 17:18:35 +0000645 .Case("objc_fixed_enum", LangOpts.ObjC2)
Douglas Gregore97179c2011-09-08 01:46:34 +0000646 .Case("objc_instancetype", LangOpts.ObjC2)
Douglas Gregorbd507c52012-01-04 21:16:09 +0000647 .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules)
John McCall260611a2012-06-20 06:18:46 +0000648 .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile())
John McCall0b92fcb2012-06-20 21:58:02 +0000649 .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport())
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000650 .Case("ownership_holds", true)
651 .Case("ownership_returns", true)
652 .Case("ownership_takes", true)
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000653 .Case("objc_bool", true)
John McCall260611a2012-06-20 06:18:46 +0000654 .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile())
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000655 .Case("objc_array_literals", LangOpts.ObjC2)
656 .Case("objc_dictionary_literals", LangOpts.ObjC2)
Patrick Beardeb382ec2012-04-19 00:25:12 +0000657 .Case("objc_boxed_expressions", LangOpts.ObjC2)
John McCalleb2ac8b2011-10-18 21:18:53 +0000658 .Case("arc_cf_code_audited", true)
Benjamin Kramerffbe9b92011-12-23 17:00:35 +0000659 // C11 features
660 .Case("c_alignas", LangOpts.C11)
David Chisnall7a7ee302012-01-16 17:27:18 +0000661 .Case("c_atomic", LangOpts.C11)
Benjamin Kramerffbe9b92011-12-23 17:00:35 +0000662 .Case("c_generic_selections", LangOpts.C11)
663 .Case("c_static_assert", LangOpts.C11)
Richard Smith9c1dda72012-03-09 08:41:27 +0000664 // C++11 features
Douglas Gregor7822ee32011-05-11 23:45:11 +0000665 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus0x)
Richard Smith3e4c6c42011-05-05 21:57:07 +0000666 .Case("cxx_alias_templates", LangOpts.CPlusPlus0x)
Peter Collingbournefd5f6862011-10-14 23:44:46 +0000667 .Case("cxx_alignas", LangOpts.CPlusPlus0x)
David Chisnall7a7ee302012-01-16 17:27:18 +0000668 .Case("cxx_atomic", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000669 .Case("cxx_attributes", LangOpts.CPlusPlus0x)
Richard Smith738291e2011-02-20 12:13:05 +0000670 .Case("cxx_auto_type", LangOpts.CPlusPlus0x)
Richard Smithb5216aa2012-02-14 22:56:17 +0000671 .Case("cxx_constexpr", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000672 .Case("cxx_decltype", LangOpts.CPlusPlus0x)
Douglas Gregor316551f2012-04-10 20:00:33 +0000673 .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus0x)
Douglas Gregor07508002011-02-05 20:35:30 +0000674 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus0x)
Douglas Gregorf695a692011-11-01 01:19:34 +0000675 .Case("cxx_defaulted_functions", LangOpts.CPlusPlus0x)
Sean Hunt059ce0d2011-05-01 07:04:31 +0000676 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000677 .Case("cxx_deleted_functions", LangOpts.CPlusPlus0x)
Douglas Gregorece38942011-08-29 17:28:38 +0000678 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus0x)
Sebastian Redld1dc3aa2012-02-25 20:51:27 +0000679 .Case("cxx_generalized_initializers", LangOpts.CPlusPlus0x)
Sebastian Redl74e611a2011-09-04 18:14:28 +0000680 .Case("cxx_implicit_moves", LangOpts.CPlusPlus0x)
Douglas Gregorece38942011-08-29 17:28:38 +0000681 //.Case("cxx_inheriting_constructors", false)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000682 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus0x)
Douglas Gregor7c07e962012-02-23 03:02:32 +0000683 .Case("cxx_lambdas", LangOpts.CPlusPlus0x)
Douglas Gregor7b156dd2012-04-04 00:48:39 +0000684 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus0x)
Douglas Gregorece38942011-08-29 17:28:38 +0000685 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus0x)
Sebastian Redl4561ecd2011-03-15 21:17:12 +0000686 .Case("cxx_noexcept", LangOpts.CPlusPlus0x)
Douglas Gregor84ee2ee2011-05-21 23:15:46 +0000687 .Case("cxx_nullptr", LangOpts.CPlusPlus0x)
Anders Carlssonc8b9f792011-03-25 15:04:23 +0000688 .Case("cxx_override_control", LangOpts.CPlusPlus0x)
Richard Smitha391a462011-04-15 15:14:40 +0000689 .Case("cxx_range_for", LangOpts.CPlusPlus0x)
Douglas Gregor172b2212011-11-01 01:23:44 +0000690 .Case("cxx_raw_string_literals", LangOpts.CPlusPlus0x)
Douglas Gregor56209ff2011-01-26 21:25:54 +0000691 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000692 .Case("cxx_rvalue_references", LangOpts.CPlusPlus0x)
693 .Case("cxx_strong_enums", LangOpts.CPlusPlus0x)
694 .Case("cxx_static_assert", LangOpts.CPlusPlus0x)
695 .Case("cxx_trailing_return", LangOpts.CPlusPlus0x)
Douglas Gregor172b2212011-11-01 01:23:44 +0000696 .Case("cxx_unicode_literals", LangOpts.CPlusPlus0x)
Richard Smithec92bc72012-03-03 23:51:05 +0000697 .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus0x)
Richard Smith9c1dda72012-03-09 08:41:27 +0000698 .Case("cxx_user_literals", LangOpts.CPlusPlus0x)
Douglas Gregorc78e2592011-01-26 15:36:03 +0000699 .Case("cxx_variadic_templates", LangOpts.CPlusPlus0x)
Douglas Gregorafdf1372011-02-03 21:57:35 +0000700 // Type traits
701 .Case("has_nothrow_assign", LangOpts.CPlusPlus)
702 .Case("has_nothrow_copy", LangOpts.CPlusPlus)
703 .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
704 .Case("has_trivial_assign", LangOpts.CPlusPlus)
705 .Case("has_trivial_copy", LangOpts.CPlusPlus)
706 .Case("has_trivial_constructor", LangOpts.CPlusPlus)
707 .Case("has_trivial_destructor", LangOpts.CPlusPlus)
708 .Case("has_virtual_destructor", LangOpts.CPlusPlus)
709 .Case("is_abstract", LangOpts.CPlusPlus)
710 .Case("is_base_of", LangOpts.CPlusPlus)
711 .Case("is_class", LangOpts.CPlusPlus)
712 .Case("is_convertible_to", LangOpts.CPlusPlus)
Douglas Gregorb3f8c242011-08-03 17:01:05 +0000713 // __is_empty is available only if the horrible
714 // "struct __is_empty" parsing hack hasn't been needed in this
715 // translation unit. If it has, __is_empty reverts to a normal
716 // identifier and __has_feature(is_empty) evaluates false.
Douglas Gregor68876142011-07-30 07:01:49 +0000717 .Case("is_empty",
Douglas Gregor9a14ecb2011-07-30 07:08:19 +0000718 LangOpts.CPlusPlus &&
719 PP.getIdentifierInfo("__is_empty")->getTokenID()
720 != tok::identifier)
Douglas Gregorafdf1372011-02-03 21:57:35 +0000721 .Case("is_enum", LangOpts.CPlusPlus)
Douglas Gregor5e9392b2011-12-03 18:14:24 +0000722 .Case("is_final", LangOpts.CPlusPlus)
Chandler Carruth4e61ddd2011-04-23 10:47:20 +0000723 .Case("is_literal", LangOpts.CPlusPlus)
Howard Hinnanta55e68b2011-05-12 19:52:14 +0000724 .Case("is_standard_layout", LangOpts.CPlusPlus)
Douglas Gregorb3f8c242011-08-03 17:01:05 +0000725 // __is_pod is available only if the horrible
726 // "struct __is_pod" parsing hack hasn't been needed in this
727 // translation unit. If it has, __is_pod reverts to a normal
728 // identifier and __has_feature(is_pod) evaluates false.
Douglas Gregor68876142011-07-30 07:01:49 +0000729 .Case("is_pod",
Douglas Gregor9a14ecb2011-07-30 07:08:19 +0000730 LangOpts.CPlusPlus &&
731 PP.getIdentifierInfo("__is_pod")->getTokenID()
732 != tok::identifier)
Douglas Gregorafdf1372011-02-03 21:57:35 +0000733 .Case("is_polymorphic", LangOpts.CPlusPlus)
Chandler Carruthb7e95892011-04-23 10:47:28 +0000734 .Case("is_trivial", LangOpts.CPlusPlus)
Douglas Gregor25d0a0f2012-02-23 07:33:15 +0000735 .Case("is_trivially_assignable", LangOpts.CPlusPlus)
Douglas Gregor4ca8ac22012-02-24 07:38:34 +0000736 .Case("is_trivially_constructible", LangOpts.CPlusPlus)
Sean Huntfeb375d2011-05-13 00:31:07 +0000737 .Case("is_trivially_copyable", LangOpts.CPlusPlus)
Douglas Gregorafdf1372011-02-03 21:57:35 +0000738 .Case("is_union", LangOpts.CPlusPlus)
Douglas Gregorbd507c52012-01-04 21:16:09 +0000739 .Case("modules", LangOpts.Modules)
Eric Christopher1f84f8d2010-06-24 02:02:00 +0000740 .Case("tls", PP.getTargetInfo().isTLSSupported())
Sean Hunt858a3252011-07-18 17:08:00 +0000741 .Case("underlying_type", LangOpts.CPlusPlus)
Benjamin Kramer32592e82010-01-09 18:53:11 +0000742 .Default(false);
Chris Lattner148772a2009-06-13 07:13:28 +0000743}
744
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000745/// HasExtension - Return true if we recognize and implement the feature
746/// specified by the identifier, either as an extension or a standard language
747/// feature.
748static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) {
749 if (HasFeature(PP, II))
750 return true;
751
752 // If the use of an extension results in an error diagnostic, extensions are
753 // effectively unavailable, so just return false here.
David Blaikied6471f72011-09-25 23:23:43 +0000754 if (PP.getDiagnostics().getExtensionHandlingBehavior() ==
755 DiagnosticsEngine::Ext_Error)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000756 return false;
757
David Blaikie4e4d0842012-03-11 07:00:24 +0000758 const LangOptions &LangOpts = PP.getLangOpts();
Richard Smith5297d712012-02-25 10:41:10 +0000759 StringRef Extension = II->getName();
760
761 // Normalize the extension name, __foo__ becomes foo.
762 if (Extension.startswith("__") && Extension.endswith("__") &&
763 Extension.size() >= 4)
764 Extension = Extension.substr(2, Extension.size() - 4);
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000765
766 // Because we inherit the feature list from HasFeature, this string switch
767 // must be less restrictive than HasFeature's.
Richard Smith5297d712012-02-25 10:41:10 +0000768 return llvm::StringSwitch<bool>(Extension)
Benjamin Kramerffbe9b92011-12-23 17:00:35 +0000769 // C11 features supported by other languages as extensions.
Peter Collingbournefd5f6862011-10-14 23:44:46 +0000770 .Case("c_alignas", true)
David Chisnall7a7ee302012-01-16 17:27:18 +0000771 .Case("c_atomic", true)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000772 .Case("c_generic_selections", true)
773 .Case("c_static_assert", true)
774 // C++0x features supported by other languages as extensions.
David Chisnall7a7ee302012-01-16 17:27:18 +0000775 .Case("cxx_atomic", LangOpts.CPlusPlus)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000776 .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
Douglas Gregorece38942011-08-29 17:28:38 +0000777 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000778 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
Douglas Gregor7b156dd2012-04-04 00:48:39 +0000779 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus)
Douglas Gregorece38942011-08-29 17:28:38 +0000780 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000781 .Case("cxx_override_control", LangOpts.CPlusPlus)
Richard Smith7640c002011-09-06 18:03:41 +0000782 .Case("cxx_range_for", LangOpts.CPlusPlus)
Peter Collingbournec1b5fa42011-05-13 20:54:45 +0000783 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
784 .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
785 .Default(false);
786}
787
Anders Carlssoncae50952010-10-20 02:31:43 +0000788/// HasAttribute - Return true if we recognize and implement the attribute
789/// specified by the given identifier.
790static bool HasAttribute(const IdentifierInfo *II) {
Jean-Daniel Dupas8a5e7fd2012-03-01 14:53:16 +0000791 StringRef Name = II->getName();
792 // Normalize the attribute name, __foo__ becomes foo.
793 if (Name.startswith("__") && Name.endswith("__") && Name.size() >= 4)
794 Name = Name.substr(2, Name.size() - 4);
795
Sean Hunt8e083e72012-06-19 23:57:03 +0000796 // FIXME: Do we need to handle namespaces here?
Jean-Daniel Dupas8a5e7fd2012-03-01 14:53:16 +0000797 return llvm::StringSwitch<bool>(Name)
Anders Carlssoncae50952010-10-20 02:31:43 +0000798#include "clang/Lex/AttrSpellings.inc"
799 .Default(false);
800}
801
John Thompson92bd8c72009-11-02 22:28:12 +0000802/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
803/// or '__has_include_next("path")' expression.
804/// Returns true if successful.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000805static bool EvaluateHasIncludeCommon(Token &Tok,
806 IdentifierInfo *II, Preprocessor &PP,
807 const DirectoryLookup *LookupFrom) {
John Thompson92bd8c72009-11-02 22:28:12 +0000808 SourceLocation LParenLoc;
809
810 // Get '('.
811 PP.LexNonComment(Tok);
812
813 // Ensure we have a '('.
814 if (Tok.isNot(tok::l_paren)) {
815 PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
816 return false;
817 }
818
819 // Save '(' location for possible missing ')' message.
820 LParenLoc = Tok.getLocation();
821
822 // Get the file name.
823 PP.getCurrentLexer()->LexIncludeFilename(Tok);
824
825 // Reserve a buffer to get the spelling.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000826 SmallString<128> FilenameBuffer;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000827 StringRef Filename;
Douglas Gregorecdcb882010-10-20 22:00:55 +0000828 SourceLocation EndLoc;
829
John Thompson92bd8c72009-11-02 22:28:12 +0000830 switch (Tok.getKind()) {
Peter Collingbourne84021552011-02-28 02:37:51 +0000831 case tok::eod:
832 // If the token kind is EOD, the error has already been diagnosed.
John Thompson92bd8c72009-11-02 22:28:12 +0000833 return false;
834
835 case tok::angle_string_literal:
Douglas Gregor453091c2010-03-16 22:30:13 +0000836 case tok::string_literal: {
837 bool Invalid = false;
838 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
839 if (Invalid)
840 return false;
John Thompson92bd8c72009-11-02 22:28:12 +0000841 break;
Douglas Gregor453091c2010-03-16 22:30:13 +0000842 }
John Thompson92bd8c72009-11-02 22:28:12 +0000843
844 case tok::less:
845 // This could be a <foo/bar.h> file coming from a macro expansion. In this
846 // case, glue the tokens together into FilenameBuffer and interpret those.
847 FilenameBuffer.push_back('<');
Douglas Gregorecdcb882010-10-20 22:00:55 +0000848 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc))
Peter Collingbourne84021552011-02-28 02:37:51 +0000849 return false; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnera1394812010-01-10 01:35:12 +0000850 Filename = FilenameBuffer.str();
John Thompson92bd8c72009-11-02 22:28:12 +0000851 break;
852 default:
853 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
854 return false;
855 }
856
Richard Smith99831e42012-03-06 03:21:47 +0000857 // Get ')'.
858 PP.LexNonComment(Tok);
859
860 // Ensure we have a trailing ).
861 if (Tok.isNot(tok::r_paren)) {
862 PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
863 PP.Diag(LParenLoc, diag::note_matching) << "(";
864 return false;
865 }
866
Chris Lattnera1394812010-01-10 01:35:12 +0000867 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
John Thompson92bd8c72009-11-02 22:28:12 +0000868 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
869 // error.
Chris Lattnera1394812010-01-10 01:35:12 +0000870 if (Filename.empty())
John Thompson92bd8c72009-11-02 22:28:12 +0000871 return false;
John Thompson92bd8c72009-11-02 22:28:12 +0000872
873 // Search include directories.
874 const DirectoryLookup *CurDir;
Chandler Carruthb5142bb2011-03-16 18:34:36 +0000875 const FileEntry *File =
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000876 PP.LookupFile(Filename, isAngled, LookupFrom, CurDir, NULL, NULL, NULL);
John Thompson92bd8c72009-11-02 22:28:12 +0000877
Richard Smith99831e42012-03-06 03:21:47 +0000878 // Get the result value. A result of true means the file exists.
879 return File != 0;
John Thompson92bd8c72009-11-02 22:28:12 +0000880}
881
882/// EvaluateHasInclude - Process a '__has_include("path")' expression.
883/// Returns true if successful.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000884static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
John Thompson92bd8c72009-11-02 22:28:12 +0000885 Preprocessor &PP) {
Chris Lattner3ed572e2011-01-15 06:57:04 +0000886 return EvaluateHasIncludeCommon(Tok, II, PP, NULL);
John Thompson92bd8c72009-11-02 22:28:12 +0000887}
888
889/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
890/// Returns true if successful.
Chris Lattner3ed572e2011-01-15 06:57:04 +0000891static bool EvaluateHasIncludeNext(Token &Tok,
John Thompson92bd8c72009-11-02 22:28:12 +0000892 IdentifierInfo *II, Preprocessor &PP) {
893 // __has_include_next is like __has_include, except that we start
894 // searching after the current found directory. If we can't do this,
895 // issue a diagnostic.
896 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
897 if (PP.isInPrimaryFile()) {
898 Lookup = 0;
899 PP.Diag(Tok, diag::pp_include_next_in_primary);
900 } else if (Lookup == 0) {
901 PP.Diag(Tok, diag::pp_include_next_absolute_path);
902 } else {
903 // Start looking up in the next directory.
904 ++Lookup;
905 }
906
Chris Lattner3ed572e2011-01-15 06:57:04 +0000907 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup);
John Thompson92bd8c72009-11-02 22:28:12 +0000908}
Chris Lattner148772a2009-06-13 07:13:28 +0000909
Chris Lattnera3b605e2008-03-09 03:13:06 +0000910/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
911/// as a builtin macro, handle it and return the next token as 'Tok'.
912void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
913 // Figure out which token this is.
914 IdentifierInfo *II = Tok.getIdentifierInfo();
915 assert(II && "Can't be a macro without id info!");
Mike Stump1eb44332009-09-09 15:08:12 +0000916
John McCall1ef8a2e2010-08-28 22:34:47 +0000917 // If this is an _Pragma or Microsoft __pragma directive, expand it,
918 // invoke the pragma handler, then lex the token after it.
Chris Lattnera3b605e2008-03-09 03:13:06 +0000919 if (II == Ident_Pragma)
920 return Handle_Pragma(Tok);
John McCall1ef8a2e2010-08-28 22:34:47 +0000921 else if (II == Ident__pragma) // in non-MS mode this is null
922 return HandleMicrosoft__pragma(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000923
Chris Lattnera3b605e2008-03-09 03:13:06 +0000924 ++NumBuiltinMacroExpanded;
925
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000926 SmallString<128> TmpBuffer;
Benjamin Kramerb1765912010-01-27 16:38:22 +0000927 llvm::raw_svector_ostream OS(TmpBuffer);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000928
929 // Set up the return result.
930 Tok.setIdentifierInfo(0);
931 Tok.clearFlag(Token::NeedsCleaning);
Mike Stump1eb44332009-09-09 15:08:12 +0000932
Chris Lattnera3b605e2008-03-09 03:13:06 +0000933 if (II == Ident__LINE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000934 // C99 6.10.8: "__LINE__: The presumed line number (within the current
935 // source file) of the current source line (an integer constant)". This can
936 // be affected by #line.
Chris Lattner081927b2009-02-15 21:06:39 +0000937 SourceLocation Loc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000938
Chris Lattnerdff070f2009-04-18 22:29:33 +0000939 // Advance to the location of the first _, this might not be the first byte
940 // of the token if it starts with an escaped newline.
941 Loc = AdvanceToTokenCharacter(Loc, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000942
Chris Lattner081927b2009-02-15 21:06:39 +0000943 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000944 // a macro expansion. This doesn't matter for object-like macros, but
Chris Lattner081927b2009-02-15 21:06:39 +0000945 // can matter for a function-like macro that expands to contain __LINE__.
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000946 // Skip down through expansion points until we find a file loc for the
947 // end of the expansion history.
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000948 Loc = SourceMgr.getExpansionRange(Loc).second;
Chris Lattner081927b2009-02-15 21:06:39 +0000949 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000950
Chris Lattner1fa49532009-03-08 08:08:45 +0000951 // __LINE__ expands to a simple numeric value.
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000952 OS << (PLoc.isValid()? PLoc.getLine() : 1);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000953 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000954 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000955 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
956 // character string literal)". This can be affected by #line.
957 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
958
959 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
960 // #include stack instead of the current file.
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000961 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000962 SourceLocation NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000963 while (NextLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000964 PLoc = SourceMgr.getPresumedLoc(NextLoc);
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000965 if (PLoc.isInvalid())
966 break;
967
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000968 NextLoc = PLoc.getIncludeLoc();
Chris Lattnera3b605e2008-03-09 03:13:06 +0000969 }
970 }
Mike Stump1eb44332009-09-09 15:08:12 +0000971
Chris Lattnera3b605e2008-03-09 03:13:06 +0000972 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000973 SmallString<128> FN;
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000974 if (PLoc.isValid()) {
975 FN += PLoc.getFilename();
976 Lexer::Stringify(FN);
977 OS << '"' << FN.str() << '"';
978 }
Chris Lattnera3b605e2008-03-09 03:13:06 +0000979 Tok.setKind(tok::string_literal);
Chris Lattnera3b605e2008-03-09 03:13:06 +0000980 } else if (II == Ident__DATE__) {
981 if (!DATELoc.isValid())
982 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
983 Tok.setKind(tok::string_literal);
984 Tok.setLength(strlen("\"Mmm dd yyyy\""));
Chandler Carruthbf340e42011-07-26 03:03:05 +0000985 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
986 Tok.getLocation(),
987 Tok.getLength()));
Benjamin Kramerb1765912010-01-27 16:38:22 +0000988 return;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000989 } else if (II == Ident__TIME__) {
990 if (!TIMELoc.isValid())
991 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
992 Tok.setKind(tok::string_literal);
993 Tok.setLength(strlen("\"hh:mm:ss\""));
Chandler Carruthbf340e42011-07-26 03:03:05 +0000994 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
995 Tok.getLocation(),
996 Tok.getLength()));
Benjamin Kramerb1765912010-01-27 16:38:22 +0000997 return;
Chris Lattnera3b605e2008-03-09 03:13:06 +0000998 } else if (II == Ident__INCLUDE_LEVEL__) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000999 // Compute the presumed include depth of this token. This can be affected
1000 // by GNU line markers.
Chris Lattnera3b605e2008-03-09 03:13:06 +00001001 unsigned Depth = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001002
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001003 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +00001004 if (PLoc.isValid()) {
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001005 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +00001006 for (; PLoc.isValid(); ++Depth)
1007 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1008 }
Mike Stump1eb44332009-09-09 15:08:12 +00001009
Chris Lattner1fa49532009-03-08 08:08:45 +00001010 // __INCLUDE_LEVEL__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +00001011 OS << Depth;
Chris Lattnera3b605e2008-03-09 03:13:06 +00001012 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +00001013 } else if (II == Ident__TIMESTAMP__) {
1014 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1015 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
Chris Lattnera3b605e2008-03-09 03:13:06 +00001016
1017 // Get the file that we are lexing out of. If we're currently lexing from
1018 // a macro, dig into the include stack.
1019 const FileEntry *CurFile = 0;
Ted Kremeneka275a192008-11-20 01:35:24 +00001020 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Mike Stump1eb44332009-09-09 15:08:12 +00001021
Chris Lattnera3b605e2008-03-09 03:13:06 +00001022 if (TheLexer)
Ted Kremenekac80c6e2008-11-19 22:55:25 +00001023 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
Mike Stump1eb44332009-09-09 15:08:12 +00001024
Chris Lattnera3b605e2008-03-09 03:13:06 +00001025 const char *Result;
1026 if (CurFile) {
1027 time_t TT = CurFile->getModificationTime();
1028 struct tm *TM = localtime(&TT);
1029 Result = asctime(TM);
1030 } else {
1031 Result = "??? ??? ?? ??:??:?? ????\n";
1032 }
Benjamin Kramerb1765912010-01-27 16:38:22 +00001033 // Surround the string with " and strip the trailing newline.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001034 OS << '"' << StringRef(Result, strlen(Result)-1) << '"';
Chris Lattnera3b605e2008-03-09 03:13:06 +00001035 Tok.setKind(tok::string_literal);
Chris Lattnerc1f9d822009-04-13 01:29:17 +00001036 } else if (II == Ident__COUNTER__) {
Chris Lattnerc1f9d822009-04-13 01:29:17 +00001037 // __COUNTER__ expands to a simple numeric value.
Benjamin Kramerb1765912010-01-27 16:38:22 +00001038 OS << CounterValue++;
Chris Lattnerc1f9d822009-04-13 01:29:17 +00001039 Tok.setKind(tok::numeric_constant);
Peter Collingbournec1b5fa42011-05-13 20:54:45 +00001040 } else if (II == Ident__has_feature ||
1041 II == Ident__has_extension ||
1042 II == Ident__has_builtin ||
Anders Carlssoncae50952010-10-20 02:31:43 +00001043 II == Ident__has_attribute) {
Peter Collingbournec1b5fa42011-05-13 20:54:45 +00001044 // The argument to these builtins should be a parenthesized identifier.
Chris Lattner148772a2009-06-13 07:13:28 +00001045 SourceLocation StartLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001046
Chris Lattner148772a2009-06-13 07:13:28 +00001047 bool IsValid = false;
1048 IdentifierInfo *FeatureII = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001049
Chris Lattner148772a2009-06-13 07:13:28 +00001050 // Read the '('.
1051 Lex(Tok);
1052 if (Tok.is(tok::l_paren)) {
1053 // Read the identifier
1054 Lex(Tok);
1055 if (Tok.is(tok::identifier)) {
1056 FeatureII = Tok.getIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00001057
Chris Lattner148772a2009-06-13 07:13:28 +00001058 // Read the ')'.
1059 Lex(Tok);
1060 if (Tok.is(tok::r_paren))
1061 IsValid = true;
1062 }
1063 }
Mike Stump1eb44332009-09-09 15:08:12 +00001064
Chris Lattner148772a2009-06-13 07:13:28 +00001065 bool Value = false;
1066 if (!IsValid)
1067 Diag(StartLoc, diag::err_feature_check_malformed);
1068 else if (II == Ident__has_builtin) {
Mike Stump1eb44332009-09-09 15:08:12 +00001069 // Check for a builtin is trivial.
Chris Lattner148772a2009-06-13 07:13:28 +00001070 Value = FeatureII->getBuiltinID() != 0;
Anders Carlssoncae50952010-10-20 02:31:43 +00001071 } else if (II == Ident__has_attribute)
1072 Value = HasAttribute(FeatureII);
Peter Collingbournec1b5fa42011-05-13 20:54:45 +00001073 else if (II == Ident__has_extension)
1074 Value = HasExtension(*this, FeatureII);
Anders Carlssoncae50952010-10-20 02:31:43 +00001075 else {
Chris Lattner148772a2009-06-13 07:13:28 +00001076 assert(II == Ident__has_feature && "Must be feature check");
1077 Value = HasFeature(*this, FeatureII);
1078 }
Mike Stump1eb44332009-09-09 15:08:12 +00001079
Benjamin Kramerb1765912010-01-27 16:38:22 +00001080 OS << (int)Value;
Chris Lattner28310922012-01-31 18:53:44 +00001081 if (IsValid)
1082 Tok.setKind(tok::numeric_constant);
John Thompson92bd8c72009-11-02 22:28:12 +00001083 } else if (II == Ident__has_include ||
1084 II == Ident__has_include_next) {
1085 // The argument to these two builtins should be a parenthesized
1086 // file name string literal using angle brackets (<>) or
1087 // double-quotes ("").
Chris Lattner3ed572e2011-01-15 06:57:04 +00001088 bool Value;
John Thompson92bd8c72009-11-02 22:28:12 +00001089 if (II == Ident__has_include)
Chris Lattner3ed572e2011-01-15 06:57:04 +00001090 Value = EvaluateHasInclude(Tok, II, *this);
John Thompson92bd8c72009-11-02 22:28:12 +00001091 else
Chris Lattner3ed572e2011-01-15 06:57:04 +00001092 Value = EvaluateHasIncludeNext(Tok, II, *this);
Benjamin Kramerb1765912010-01-27 16:38:22 +00001093 OS << (int)Value;
John Thompson92bd8c72009-11-02 22:28:12 +00001094 Tok.setKind(tok::numeric_constant);
Ted Kremenekd7681502011-10-12 19:46:30 +00001095 } else if (II == Ident__has_warning) {
1096 // The argument should be a parenthesized string literal.
1097 // The argument to these builtins should be a parenthesized identifier.
1098 SourceLocation StartLoc = Tok.getLocation();
1099 bool IsValid = false;
1100 bool Value = false;
1101 // Read the '('.
1102 Lex(Tok);
1103 do {
1104 if (Tok.is(tok::l_paren)) {
1105 // Read the string.
1106 Lex(Tok);
1107
1108 // We need at least one string literal.
1109 if (!Tok.is(tok::string_literal)) {
1110 StartLoc = Tok.getLocation();
1111 IsValid = false;
1112 // Eat tokens until ')'.
1113 do Lex(Tok); while (!(Tok.is(tok::r_paren) || Tok.is(tok::eod)));
1114 break;
1115 }
1116
1117 // String concatenation allows multiple strings, which can even come
1118 // from macro expansion.
1119 SmallVector<Token, 4> StrToks;
1120 while (Tok.is(tok::string_literal)) {
Richard Smith99831e42012-03-06 03:21:47 +00001121 // Complain about, and drop, any ud-suffix.
1122 if (Tok.hasUDSuffix())
1123 Diag(Tok, diag::err_invalid_string_udl);
Ted Kremenekd7681502011-10-12 19:46:30 +00001124 StrToks.push_back(Tok);
1125 LexUnexpandedToken(Tok);
1126 }
1127
1128 // Is the end a ')'?
1129 if (!(IsValid = Tok.is(tok::r_paren)))
1130 break;
1131
1132 // Concatenate and parse the strings.
1133 StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this);
1134 assert(Literal.isAscii() && "Didn't allow wide strings in");
1135 if (Literal.hadError)
1136 break;
1137 if (Literal.Pascal) {
1138 Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1139 break;
1140 }
1141
1142 StringRef WarningName(Literal.GetString());
1143
1144 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1145 WarningName[1] != 'W') {
1146 Diag(StrToks[0].getLocation(), diag::warn_has_warning_invalid_option);
1147 break;
1148 }
1149
1150 // Finally, check if the warning flags maps to a diagnostic group.
1151 // We construct a SmallVector here to talk to getDiagnosticIDs().
1152 // Although we don't use the result, this isn't a hot path, and not
1153 // worth special casing.
1154 llvm::SmallVector<diag::kind, 10> Diags;
1155 Value = !getDiagnostics().getDiagnosticIDs()->
1156 getDiagnosticsInGroup(WarningName.substr(2), Diags);
1157 }
1158 } while (false);
1159
1160 if (!IsValid)
1161 Diag(StartLoc, diag::err_warning_check_malformed);
1162
1163 OS << (int)Value;
1164 Tok.setKind(tok::numeric_constant);
Chris Lattnera3b605e2008-03-09 03:13:06 +00001165 } else {
David Blaikieb219cfc2011-09-23 05:06:16 +00001166 llvm_unreachable("Unknown identifier!");
Chris Lattnera3b605e2008-03-09 03:13:06 +00001167 }
Abramo Bagnaraa08529c2011-10-03 18:39:03 +00001168 CreateString(OS.str().data(), OS.str().size(), Tok,
1169 Tok.getLocation(), Tok.getLocation());
Chris Lattnera3b605e2008-03-09 03:13:06 +00001170}
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001171
1172void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
1173 // If the 'used' status changed, and the macro requires 'unused' warning,
1174 // remove its SourceLocation from the warn-for-unused-macro locations.
1175 if (MI->isWarnIfUnused() && !MI->isUsed())
1176 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1177 MI->setIsUsed(true);
1178}