blob: 225a3fafd3c65ba961f4b927818399dbb24dc51d [file] [log] [blame]
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001//===--- MacroExpansion.cpp - Top level Macro Expansion -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
James Dennett32740042013-12-02 17:39:27 +000010// This file implements the top level handling of macro expansion for the
Joao Matosc0d4c1b2012-08-31 21:34:27 +000011// preprocessor.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Preprocessor.h"
Aaron Ballman2fbf9942014-03-31 13:14:44 +000016#include "clang/Basic/Attributes.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000017#include "clang/Basic/FileManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Basic/SourceManager.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000019#include "clang/Basic/TargetInfo.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000020#include "clang/Lex/CodeCompletionHandler.h"
21#include "clang/Lex/ExternalPreprocessorSource.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Lex/LexDiagnostic.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000023#include "clang/Lex/MacroArgs.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Lex/MacroInfo.h"
25#include "llvm/ADT/STLExtras.h"
Andy Gibbs58905d22012-11-17 19:15:38 +000026#include "llvm/ADT/SmallString.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000027#include "llvm/ADT/StringSwitch.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000028#include "llvm/Config/llvm-config.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000029#include "llvm/Support/ErrorHandling.h"
Dmitri Gribenkoae07f722012-09-24 20:56:28 +000030#include "llvm/Support/Format.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "llvm/Support/raw_ostream.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000032#include <cstdio>
33#include <ctime>
34using namespace clang;
35
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +000036MacroDirective *
37Preprocessor::getMacroDirectiveHistory(const IdentifierInfo *II) const {
Alexander Kornienko1d26c022012-09-25 17:18:14 +000038 assert(II->hadMacroDefinition() && "Identifier has not been not a macro!");
Joao Matosc0d4c1b2012-08-31 21:34:27 +000039
40 macro_iterator Pos = Macros.find(II);
Joao Matosc0d4c1b2012-08-31 21:34:27 +000041 assert(Pos != Macros.end() && "Identifier macro info is missing!");
Joao Matosc0d4c1b2012-08-31 21:34:27 +000042 return Pos->second;
43}
44
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000045void Preprocessor::appendMacroDirective(IdentifierInfo *II, MacroDirective *MD){
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000046 assert(MD && "MacroDirective should be non-zero!");
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000047 assert(!MD->getPrevious() && "Already attached to a MacroDirective history.");
Douglas Gregor5a4649b2012-10-11 00:46:49 +000048
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +000049 MacroDirective *&StoredMD = Macros[II];
50 MD->setPrevious(StoredMD);
51 StoredMD = MD;
Ben Langmuirc28ce3a2014-09-30 20:00:18 +000052 // Setup the identifier as having associated macro history.
53 II->setHasMacroDefinition(true);
54 if (!MD->isDefined())
55 II->setHasMacroDefinition(false);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000056 bool isImportedMacro = isa<DefMacroDirective>(MD) &&
57 cast<DefMacroDirective>(MD)->isImported();
58 if (II->isFromAST() && !isImportedMacro)
Joao Matosc0d4c1b2012-08-31 21:34:27 +000059 II->setChangedSinceDeserialization();
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000060}
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +000061
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000062void Preprocessor::setLoadedMacroDirective(IdentifierInfo *II,
63 MacroDirective *MD) {
64 assert(II && MD);
65 MacroDirective *&StoredMD = Macros[II];
66 assert(!StoredMD &&
67 "the macro history was modified before initializing it from a pch");
68 StoredMD = MD;
69 // Setup the identifier as having associated macro history.
70 II->setHasMacroDefinition(true);
71 if (!MD->isDefined())
72 II->setHasMacroDefinition(false);
Joao Matosc0d4c1b2012-08-31 21:34:27 +000073}
74
Joao Matosc0d4c1b2012-08-31 21:34:27 +000075/// RegisterBuiltinMacro - Register the specified identifier in the identifier
76/// table and mark it as a builtin macro to be expanded.
77static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
78 // Get the identifier.
79 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
80
81 // Mark it as being a macro that is builtin.
82 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
83 MI->setIsBuiltinMacro();
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000084 PP.appendDefMacroDirective(Id, MI);
Joao Matosc0d4c1b2012-08-31 21:34:27 +000085 return Id;
86}
87
88
89/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
90/// identifier table.
91void Preprocessor::RegisterBuiltinMacros() {
92 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
93 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
94 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
95 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
96 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
97 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
98
Aaron Ballmana0344c52014-11-14 13:44:02 +000099 // C++ Standing Document Extensions.
100 Ident__has_cpp_attribute = RegisterBuiltinMacro(*this, "__has_cpp_attribute");
101
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000102 // GCC Extensions.
103 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
104 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
105 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
106
Richard Smithae385082014-03-15 00:06:08 +0000107 // Microsoft Extensions.
108 if (LangOpts.MicrosoftExt) {
109 Ident__identifier = RegisterBuiltinMacro(*this, "__identifier");
110 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
111 } else {
Craig Topperd2d442c2014-05-17 23:10:59 +0000112 Ident__identifier = nullptr;
113 Ident__pragma = nullptr;
Richard Smithae385082014-03-15 00:06:08 +0000114 }
115
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000116 // Clang Extensions.
117 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
118 Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension");
119 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
120 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
121 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
122 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
123 Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning");
Yunzhong Gaoef309f42014-04-11 20:55:19 +0000124 Ident__is_identifier = RegisterBuiltinMacro(*this, "__is_identifier");
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000125
Douglas Gregorc83de302012-09-25 15:44:52 +0000126 // Modules.
127 if (LangOpts.Modules) {
128 Ident__building_module = RegisterBuiltinMacro(*this, "__building_module");
129
130 // __MODULE__
131 if (!LangOpts.CurrentModule.empty())
132 Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__");
133 else
Craig Topperd2d442c2014-05-17 23:10:59 +0000134 Ident__MODULE__ = nullptr;
Douglas Gregorc83de302012-09-25 15:44:52 +0000135 } else {
Craig Topperd2d442c2014-05-17 23:10:59 +0000136 Ident__building_module = nullptr;
137 Ident__MODULE__ = nullptr;
Douglas Gregorc83de302012-09-25 15:44:52 +0000138 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000139}
140
141/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
142/// in its expansion, currently expands to that token literally.
143static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
144 const IdentifierInfo *MacroIdent,
145 Preprocessor &PP) {
146 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
147
148 // If the token isn't an identifier, it's always literally expanded.
Craig Topperd2d442c2014-05-17 23:10:59 +0000149 if (!II) return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000150
151 // If the information about this identifier is out of date, update it from
152 // the external source.
153 if (II->isOutOfDate())
154 PP.getExternalSource()->updateOutOfDateIdentifier(*II);
155
156 // If the identifier is a macro, and if that macro is enabled, it may be
157 // expanded so it's not a trivial expansion.
158 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
159 // Fast expanding "#define X X" is ok, because X would be disabled.
160 II != MacroIdent)
161 return false;
162
163 // If this is an object-like macro invocation, it is safe to trivially expand
164 // it.
165 if (MI->isObjectLike()) return true;
166
167 // If this is a function-like macro invocation, it's safe to trivially expand
168 // as long as the identifier is not a macro argument.
169 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
170 I != E; ++I)
171 if (*I == II)
172 return false; // Identifier is a macro argument.
173
174 return true;
175}
176
177
178/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
179/// lexed is a '('. If so, consume the token and return true, if not, this
180/// method should have no observable side-effect on the lexed tokens.
181bool Preprocessor::isNextPPTokenLParen() {
182 // Do some quick tests for rejection cases.
183 unsigned Val;
184 if (CurLexer)
185 Val = CurLexer->isNextPPTokenLParen();
186 else if (CurPTHLexer)
187 Val = CurPTHLexer->isNextPPTokenLParen();
188 else
189 Val = CurTokenLexer->isNextTokenLParen();
190
191 if (Val == 2) {
192 // We have run off the end. If it's a source file we don't
193 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
194 // macro stack.
195 if (CurPPLexer)
196 return false;
197 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
198 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
199 if (Entry.TheLexer)
200 Val = Entry.TheLexer->isNextPPTokenLParen();
201 else if (Entry.ThePTHLexer)
202 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
203 else
204 Val = Entry.TheTokenLexer->isNextTokenLParen();
205
206 if (Val != 2)
207 break;
208
209 // Ran off the end of a source file?
210 if (Entry.ThePPLexer)
211 return false;
212 }
213 }
214
215 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
216 // have found something that isn't a '(' or we found the end of the
217 // translation unit. In either case, return false.
218 return Val == 1;
219}
220
221/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
222/// expanded as a macro, handle it and return the next token as 'Identifier'.
223bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000224 MacroDirective *MD) {
Argyrios Kyrtzidis09796b92013-03-27 01:25:19 +0000225 MacroDirective::DefInfo Def = MD->getDefinition();
226 assert(Def.isValid());
227 MacroInfo *MI = Def.getMacroInfo();
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000228
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000229 // If this is a macro expansion in the "#if !defined(x)" line for the file,
230 // then the macro could expand to different things in other contexts, we need
231 // to disable the optimization in this case.
232 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
233
234 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
235 if (MI->isBuiltinMacro()) {
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000236 if (Callbacks) Callbacks->MacroExpands(Identifier, MD,
Craig Topperd2d442c2014-05-17 23:10:59 +0000237 Identifier.getLocation(),
238 /*Args=*/nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000239 ExpandBuiltinMacro(Identifier);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000240 return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000241 }
242
243 /// Args - If this is a function-like macro expansion, this contains,
244 /// for each macro argument, the list of tokens that were provided to the
245 /// invocation.
Craig Topperd2d442c2014-05-17 23:10:59 +0000246 MacroArgs *Args = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000247
248 // Remember where the end of the expansion occurred. For an object-like
249 // macro, this is the identifier. For a function-like macro, this is the ')'.
250 SourceLocation ExpansionEnd = Identifier.getLocation();
251
252 // If this is a function-like macro, read the arguments.
253 if (MI->isFunctionLike()) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000254 // Remember that we are now parsing the arguments to a macro invocation.
255 // Preprocessor directives used inside macro arguments are not portable, and
256 // this enables the warning.
257 InMacroArgs = true;
258 Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd);
259
260 // Finished parsing args.
261 InMacroArgs = false;
262
263 // If there was an error parsing the arguments, bail out.
Craig Topperd2d442c2014-05-17 23:10:59 +0000264 if (!Args) return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000265
266 ++NumFnMacroExpanded;
267 } else {
268 ++NumMacroExpanded;
269 }
270
271 // Notice that this macro has been used.
272 markMacroAsUsed(MI);
273
274 // Remember where the token is expanded.
275 SourceLocation ExpandLoc = Identifier.getLocation();
276 SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
277
278 if (Callbacks) {
279 if (InMacroArgs) {
280 // We can have macro expansion inside a conditional directive while
281 // reading the function macro arguments. To ensure, in that case, that
282 // MacroExpands callbacks still happen in source order, queue this
283 // callback to have it happen after the function macro callback.
284 DelayedMacroExpandsCallbacks.push_back(
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000285 MacroExpandsInfo(Identifier, MD, ExpansionRange));
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000286 } else {
Argyrios Kyrtzidis37e48ff2013-05-03 22:31:32 +0000287 Callbacks->MacroExpands(Identifier, MD, ExpansionRange, Args);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000288 if (!DelayedMacroExpandsCallbacks.empty()) {
289 for (unsigned i=0, e = DelayedMacroExpandsCallbacks.size(); i!=e; ++i) {
290 MacroExpandsInfo &Info = DelayedMacroExpandsCallbacks[i];
Argyrios Kyrtzidis37e48ff2013-05-03 22:31:32 +0000291 // FIXME: We lose macro args info with delayed callback.
Craig Topperd2d442c2014-05-17 23:10:59 +0000292 Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range,
293 /*Args=*/nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000294 }
295 DelayedMacroExpandsCallbacks.clear();
296 }
297 }
298 }
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000299
300 // If the macro definition is ambiguous, complain.
Argyrios Kyrtzidis09796b92013-03-27 01:25:19 +0000301 if (Def.getDirective()->isAmbiguous()) {
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000302 Diag(Identifier, diag::warn_pp_ambiguous_macro)
303 << Identifier.getIdentifierInfo();
304 Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)
305 << Identifier.getIdentifierInfo();
Argyrios Kyrtzidis09796b92013-03-27 01:25:19 +0000306 for (MacroDirective::DefInfo PrevDef = Def.getPreviousDefinition();
307 PrevDef && !PrevDef.isUndefined();
308 PrevDef = PrevDef.getPreviousDefinition()) {
Richard Smith49f906a2014-03-01 00:08:04 +0000309 Diag(PrevDef.getMacroInfo()->getDefinitionLoc(),
310 diag::note_pp_ambiguous_macro_other)
311 << Identifier.getIdentifierInfo();
312 if (!PrevDef.getDirective()->isAmbiguous())
313 break;
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000314 }
315 }
316
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000317 // If we started lexing a macro, enter the macro expansion body.
318
319 // If this macro expands to no tokens, don't bother to push it onto the
320 // expansion stack, only to take it right back off.
321 if (MI->getNumTokens() == 0) {
322 // No need for arg info.
323 if (Args) Args->destroy(*this);
324
Eli Friedman0834a4b2013-09-19 00:41:32 +0000325 // Propagate whitespace info as if we had pushed, then popped,
326 // a macro context.
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000327 Identifier.setFlag(Token::LeadingEmptyMacro);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000328 PropagateLineStartLeadingSpaceInfo(Identifier);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000329 ++NumFastMacroExpanded;
330 return false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000331 } else if (MI->getNumTokens() == 1 &&
332 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
333 *this)) {
334 // Otherwise, if this macro expands into a single trivially-expanded
335 // token: expand it now. This handles common cases like
336 // "#define VAL 42".
337
338 // No need for arg info.
339 if (Args) Args->destroy(*this);
340
341 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
342 // identifier to the expanded token.
343 bool isAtStartOfLine = Identifier.isAtStartOfLine();
344 bool hasLeadingSpace = Identifier.hasLeadingSpace();
345
346 // Replace the result token.
347 Identifier = MI->getReplacementToken(0);
348
349 // Restore the StartOfLine/LeadingSpace markers.
350 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
351 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
352
353 // Update the tokens location to include both its expansion and physical
354 // locations.
355 SourceLocation Loc =
356 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
357 ExpansionEnd,Identifier.getLength());
358 Identifier.setLocation(Loc);
359
360 // If this is a disabled macro or #define X X, we must mark the result as
361 // unexpandable.
362 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
363 if (MacroInfo *NewMI = getMacroInfo(NewII))
364 if (!NewMI->isEnabled() || NewMI == MI) {
365 Identifier.setFlag(Token::DisableExpand);
Douglas Gregor1a347f72013-01-30 23:10:17 +0000366 // Don't warn for "#define X X" like "#define bool bool" from
367 // stdbool.h.
368 if (NewMI != MI || MI->isFunctionLike())
369 Diag(Identifier, diag::pp_disabled_macro_expansion);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000370 }
371 }
372
373 // Since this is not an identifier token, it can't be macro expanded, so
374 // we're done.
375 ++NumFastMacroExpanded;
Eli Friedman0834a4b2013-09-19 00:41:32 +0000376 return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000377 }
378
379 // Start expanding the macro.
380 EnterMacro(Identifier, ExpansionEnd, MI, Args);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000381 return false;
382}
383
Richard Trieu79b45382013-07-23 18:01:49 +0000384enum Bracket {
385 Brace,
386 Paren
387};
388
389/// CheckMatchedBrackets - Returns true if the braces and parentheses in the
390/// token vector are properly nested.
391static bool CheckMatchedBrackets(const SmallVectorImpl<Token> &Tokens) {
392 SmallVector<Bracket, 8> Brackets;
393 for (SmallVectorImpl<Token>::const_iterator I = Tokens.begin(),
394 E = Tokens.end();
395 I != E; ++I) {
396 if (I->is(tok::l_paren)) {
397 Brackets.push_back(Paren);
398 } else if (I->is(tok::r_paren)) {
399 if (Brackets.empty() || Brackets.back() == Brace)
400 return false;
401 Brackets.pop_back();
402 } else if (I->is(tok::l_brace)) {
403 Brackets.push_back(Brace);
404 } else if (I->is(tok::r_brace)) {
405 if (Brackets.empty() || Brackets.back() == Paren)
406 return false;
407 Brackets.pop_back();
408 }
409 }
410 if (!Brackets.empty())
411 return false;
412 return true;
413}
414
415/// GenerateNewArgTokens - Returns true if OldTokens can be converted to a new
416/// vector of tokens in NewTokens. The new number of arguments will be placed
417/// in NumArgs and the ranges which need to surrounded in parentheses will be
418/// in ParenHints.
419/// Returns false if the token stream cannot be changed. If this is because
420/// of an initializer list starting a macro argument, the range of those
421/// initializer lists will be place in InitLists.
422static bool GenerateNewArgTokens(Preprocessor &PP,
423 SmallVectorImpl<Token> &OldTokens,
424 SmallVectorImpl<Token> &NewTokens,
425 unsigned &NumArgs,
426 SmallVectorImpl<SourceRange> &ParenHints,
427 SmallVectorImpl<SourceRange> &InitLists) {
428 if (!CheckMatchedBrackets(OldTokens))
429 return false;
430
431 // Once it is known that the brackets are matched, only a simple count of the
432 // braces is needed.
433 unsigned Braces = 0;
434
435 // First token of a new macro argument.
436 SmallVectorImpl<Token>::iterator ArgStartIterator = OldTokens.begin();
437
438 // First closing brace in a new macro argument. Used to generate
439 // SourceRanges for InitLists.
440 SmallVectorImpl<Token>::iterator ClosingBrace = OldTokens.end();
441 NumArgs = 0;
442 Token TempToken;
443 // Set to true when a macro separator token is found inside a braced list.
444 // If true, the fixed argument spans multiple old arguments and ParenHints
445 // will be updated.
446 bool FoundSeparatorToken = false;
447 for (SmallVectorImpl<Token>::iterator I = OldTokens.begin(),
448 E = OldTokens.end();
449 I != E; ++I) {
450 if (I->is(tok::l_brace)) {
451 ++Braces;
452 } else if (I->is(tok::r_brace)) {
453 --Braces;
454 if (Braces == 0 && ClosingBrace == E && FoundSeparatorToken)
455 ClosingBrace = I;
456 } else if (I->is(tok::eof)) {
457 // EOF token is used to separate macro arguments
458 if (Braces != 0) {
459 // Assume comma separator is actually braced list separator and change
460 // it back to a comma.
461 FoundSeparatorToken = true;
462 I->setKind(tok::comma);
463 I->setLength(1);
464 } else { // Braces == 0
465 // Separator token still separates arguments.
466 ++NumArgs;
467
468 // If the argument starts with a brace, it can't be fixed with
469 // parentheses. A different diagnostic will be given.
470 if (FoundSeparatorToken && ArgStartIterator->is(tok::l_brace)) {
471 InitLists.push_back(
472 SourceRange(ArgStartIterator->getLocation(),
473 PP.getLocForEndOfToken(ClosingBrace->getLocation())));
474 ClosingBrace = E;
475 }
476
477 // Add left paren
478 if (FoundSeparatorToken) {
479 TempToken.startToken();
480 TempToken.setKind(tok::l_paren);
481 TempToken.setLocation(ArgStartIterator->getLocation());
482 TempToken.setLength(0);
483 NewTokens.push_back(TempToken);
484 }
485
486 // Copy over argument tokens
487 NewTokens.insert(NewTokens.end(), ArgStartIterator, I);
488
489 // Add right paren and store the paren locations in ParenHints
490 if (FoundSeparatorToken) {
491 SourceLocation Loc = PP.getLocForEndOfToken((I - 1)->getLocation());
492 TempToken.startToken();
493 TempToken.setKind(tok::r_paren);
494 TempToken.setLocation(Loc);
495 TempToken.setLength(0);
496 NewTokens.push_back(TempToken);
497 ParenHints.push_back(SourceRange(ArgStartIterator->getLocation(),
498 Loc));
499 }
500
501 // Copy separator token
502 NewTokens.push_back(*I);
503
504 // Reset values
505 ArgStartIterator = I + 1;
506 FoundSeparatorToken = false;
507 }
508 }
509 }
510
511 return !ParenHints.empty() && InitLists.empty();
512}
513
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000514/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
515/// token is the '(' of the macro, this method is invoked to read all of the
516/// actual arguments specified for the macro invocation. This returns null on
517/// error.
518MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
519 MacroInfo *MI,
520 SourceLocation &MacroEnd) {
521 // The number of fixed arguments to parse.
522 unsigned NumFixedArgsLeft = MI->getNumArgs();
523 bool isVariadic = MI->isVariadic();
524
525 // Outer loop, while there are more arguments, keep reading them.
526 Token Tok;
527
528 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
529 // an argument value in a macro could expand to ',' or '(' or ')'.
530 LexUnexpandedToken(Tok);
531 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
532
533 // ArgTokens - Build up a list of tokens that make up each argument. Each
534 // argument is separated by an EOF token. Use a SmallVector so we can avoid
535 // heap allocations in the common case.
536 SmallVector<Token, 64> ArgTokens;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000537 bool ContainsCodeCompletionTok = false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000538
Richard Trieu79b45382013-07-23 18:01:49 +0000539 SourceLocation TooManyArgsLoc;
540
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000541 unsigned NumActuals = 0;
542 while (Tok.isNot(tok::r_paren)) {
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000543 if (ContainsCodeCompletionTok && (Tok.is(tok::eof) || Tok.is(tok::eod)))
544 break;
545
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000546 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
547 "only expect argument separators here");
548
549 unsigned ArgTokenStart = ArgTokens.size();
550 SourceLocation ArgStartLoc = Tok.getLocation();
551
552 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
553 // that we already consumed the first one.
554 unsigned NumParens = 0;
555
556 while (1) {
557 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
558 // an argument value in a macro could expand to ',' or '(' or ')'.
559 LexUnexpandedToken(Tok);
560
561 if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n"
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000562 if (!ContainsCodeCompletionTok) {
563 Diag(MacroName, diag::err_unterm_macro_invoc);
564 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
565 << MacroName.getIdentifierInfo();
566 // Do not lose the EOF/EOD. Return it to the client.
567 MacroName = Tok;
Craig Topperd2d442c2014-05-17 23:10:59 +0000568 return nullptr;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000569 } else {
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000570 // Do not lose the EOF/EOD.
571 Token *Toks = new Token[1];
572 Toks[0] = Tok;
573 EnterTokenStream(Toks, 1, true, true);
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000574 break;
575 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000576 } else if (Tok.is(tok::r_paren)) {
577 // If we found the ) token, the macro arg list is done.
578 if (NumParens-- == 0) {
579 MacroEnd = Tok.getLocation();
580 break;
581 }
582 } else if (Tok.is(tok::l_paren)) {
583 ++NumParens;
Reid Kleckner596b85c2013-06-26 17:16:08 +0000584 } else if (Tok.is(tok::comma) && NumParens == 0 &&
585 !(Tok.getFlags() & Token::IgnoredComma)) {
586 // In Microsoft-compatibility mode, single commas from nested macro
587 // expansions should not be considered as argument separators. We test
588 // for this with the IgnoredComma token flag above.
589
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000590 // Comma ends this argument if there are more fixed arguments expected.
591 // However, if this is a variadic macro, and this is part of the
592 // variadic part, then the comma is just an argument token.
593 if (!isVariadic) break;
594 if (NumFixedArgsLeft > 1)
595 break;
596 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
597 // If this is a comment token in the argument list and we're just in
598 // -C mode (not -CC mode), discard the comment.
599 continue;
Craig Topperd2d442c2014-05-17 23:10:59 +0000600 } else if (Tok.getIdentifierInfo() != nullptr) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000601 // Reading macro arguments can cause macros that we are currently
602 // expanding from to be popped off the expansion stack. Doing so causes
603 // them to be reenabled for expansion. Here we record whether any
604 // identifiers we lex as macro arguments correspond to disabled macros.
605 // If so, we mark the token as noexpand. This is a subtle aspect of
606 // C99 6.10.3.4p2.
607 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
608 if (!MI->isEnabled())
609 Tok.setFlag(Token::DisableExpand);
610 } else if (Tok.is(tok::code_completion)) {
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000611 ContainsCodeCompletionTok = true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000612 if (CodeComplete)
613 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
614 MI, NumActuals);
615 // Don't mark that we reached the code-completion point because the
616 // parser is going to handle the token and there will be another
617 // code-completion callback.
618 }
619
620 ArgTokens.push_back(Tok);
621 }
622
623 // If this was an empty argument list foo(), don't add this as an empty
624 // argument.
625 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
626 break;
627
628 // If this is not a variadic macro, and too many args were specified, emit
629 // an error.
Richard Trieu79b45382013-07-23 18:01:49 +0000630 if (!isVariadic && NumFixedArgsLeft == 0 && TooManyArgsLoc.isInvalid()) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000631 if (ArgTokens.size() != ArgTokenStart)
Richard Trieu79b45382013-07-23 18:01:49 +0000632 TooManyArgsLoc = ArgTokens[ArgTokenStart].getLocation();
633 else
634 TooManyArgsLoc = ArgStartLoc;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000635 }
636
Richard Trieu79b45382013-07-23 18:01:49 +0000637 // Empty arguments are standard in C99 and C++0x, and are supported as an
638 // extension in other modes.
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000639 if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99)
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000640 Diag(Tok, LangOpts.CPlusPlus11 ?
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000641 diag::warn_cxx98_compat_empty_fnmacro_arg :
642 diag::ext_empty_fnmacro_arg);
643
644 // Add a marker EOF token to the end of the token list for this argument.
645 Token EOFTok;
646 EOFTok.startToken();
647 EOFTok.setKind(tok::eof);
648 EOFTok.setLocation(Tok.getLocation());
649 EOFTok.setLength(0);
650 ArgTokens.push_back(EOFTok);
651 ++NumActuals;
Richard Trieu79b45382013-07-23 18:01:49 +0000652 if (!ContainsCodeCompletionTok && NumFixedArgsLeft != 0)
Argyrios Kyrtzidisfb703802013-02-22 22:28:58 +0000653 --NumFixedArgsLeft;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000654 }
655
656 // Okay, we either found the r_paren. Check to see if we parsed too few
657 // arguments.
658 unsigned MinArgsExpected = MI->getNumArgs();
659
Richard Trieu79b45382013-07-23 18:01:49 +0000660 // If this is not a variadic macro, and too many args were specified, emit
661 // an error.
662 if (!isVariadic && NumActuals > MinArgsExpected &&
663 !ContainsCodeCompletionTok) {
664 // Emit the diagnostic at the macro name in case there is a missing ).
665 // Emitting it at the , could be far away from the macro name.
666 Diag(TooManyArgsLoc, diag::err_too_many_args_in_macro_invoc);
667 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
668 << MacroName.getIdentifierInfo();
669
670 // Commas from braced initializer lists will be treated as argument
671 // separators inside macros. Attempt to correct for this with parentheses.
672 // TODO: See if this can be generalized to angle brackets for templates
673 // inside macro arguments.
674
Bob Wilson57217352013-07-27 21:59:57 +0000675 SmallVector<Token, 4> FixedArgTokens;
Richard Trieu79b45382013-07-23 18:01:49 +0000676 unsigned FixedNumArgs = 0;
677 SmallVector<SourceRange, 4> ParenHints, InitLists;
678 if (!GenerateNewArgTokens(*this, ArgTokens, FixedArgTokens, FixedNumArgs,
679 ParenHints, InitLists)) {
680 if (!InitLists.empty()) {
681 DiagnosticBuilder DB =
682 Diag(MacroName,
683 diag::note_init_list_at_beginning_of_macro_argument);
Alexander Kornienkod3b4e082014-05-22 19:56:11 +0000684 for (const SourceRange &Range : InitLists)
685 DB << Range;
Richard Trieu79b45382013-07-23 18:01:49 +0000686 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000687 return nullptr;
Richard Trieu79b45382013-07-23 18:01:49 +0000688 }
689 if (FixedNumArgs != MinArgsExpected)
Craig Topperd2d442c2014-05-17 23:10:59 +0000690 return nullptr;
Richard Trieu79b45382013-07-23 18:01:49 +0000691
692 DiagnosticBuilder DB = Diag(MacroName, diag::note_suggest_parens_for_macro);
Alexander Kornienkod3b4e082014-05-22 19:56:11 +0000693 for (const SourceRange &ParenLocation : ParenHints) {
694 DB << FixItHint::CreateInsertion(ParenLocation.getBegin(), "(");
695 DB << FixItHint::CreateInsertion(ParenLocation.getEnd(), ")");
Richard Trieu79b45382013-07-23 18:01:49 +0000696 }
697 ArgTokens.swap(FixedArgTokens);
698 NumActuals = FixedNumArgs;
699 }
700
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000701 // See MacroArgs instance var for description of this.
702 bool isVarargsElided = false;
703
Argyrios Kyrtzidisd4635d42012-12-21 01:51:12 +0000704 if (ContainsCodeCompletionTok) {
705 // Recover from not-fully-formed macro invocation during code-completion.
706 Token EOFTok;
707 EOFTok.startToken();
708 EOFTok.setKind(tok::eof);
709 EOFTok.setLocation(Tok.getLocation());
710 EOFTok.setLength(0);
711 for (; NumActuals < MinArgsExpected; ++NumActuals)
712 ArgTokens.push_back(EOFTok);
713 }
714
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000715 if (NumActuals < MinArgsExpected) {
716 // There are several cases where too few arguments is ok, handle them now.
717 if (NumActuals == 0 && MinArgsExpected == 1) {
718 // #define A(X) or #define A(...) ---> A()
719
720 // If there is exactly one argument, and that argument is missing,
721 // then we have an empty "()" argument empty list. This is fine, even if
722 // the macro expects one argument (the argument is just empty).
723 isVarargsElided = MI->isVariadic();
724 } else if (MI->isVariadic() &&
725 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
726 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
727 // Varargs where the named vararg parameter is missing: OK as extension.
728 // #define A(x, ...)
729 // A("blah")
Eli Friedman14d3c792012-11-14 02:18:46 +0000730 //
731 // If the macro contains the comma pasting extension, the diagnostic
732 // is suppressed; we know we'll get another diagnostic later.
733 if (!MI->hasCommaPasting()) {
734 Diag(Tok, diag::ext_missing_varargs_arg);
735 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
736 << MacroName.getIdentifierInfo();
737 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000738
739 // Remember this occurred, allowing us to elide the comma when used for
740 // cases like:
741 // #define A(x, foo...) blah(a, ## foo)
742 // #define B(x, ...) blah(a, ## __VA_ARGS__)
743 // #define C(...) blah(a, ## __VA_ARGS__)
744 // A(x) B(x) C()
745 isVarargsElided = true;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000746 } else if (!ContainsCodeCompletionTok) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000747 // Otherwise, emit the error.
748 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Argyrios Kyrtzidis164fdb62012-12-14 18:53:47 +0000749 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
750 << MacroName.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000751 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000752 }
753
754 // Add a marker EOF token to the end of the token list for this argument.
755 SourceLocation EndLoc = Tok.getLocation();
756 Tok.startToken();
757 Tok.setKind(tok::eof);
758 Tok.setLocation(EndLoc);
759 Tok.setLength(0);
760 ArgTokens.push_back(Tok);
761
762 // If we expect two arguments, add both as empty.
763 if (NumActuals == 0 && MinArgsExpected == 2)
764 ArgTokens.push_back(Tok);
765
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000766 } else if (NumActuals > MinArgsExpected && !MI->isVariadic() &&
767 !ContainsCodeCompletionTok) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000768 // Emit the diagnostic at the macro name in case there is a missing ).
769 // Emitting it at the , could be far away from the macro name.
770 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Argyrios Kyrtzidis164fdb62012-12-14 18:53:47 +0000771 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
772 << MacroName.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000773 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000774 }
775
776 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
777}
778
779/// \brief Keeps macro expanded tokens for TokenLexers.
780//
781/// Works like a stack; a TokenLexer adds the macro expanded tokens that is
782/// going to lex in the cache and when it finishes the tokens are removed
783/// from the end of the cache.
784Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
785 ArrayRef<Token> tokens) {
786 assert(tokLexer);
787 if (tokens.empty())
Craig Topperd2d442c2014-05-17 23:10:59 +0000788 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000789
790 size_t newIndex = MacroExpandedTokens.size();
791 bool cacheNeedsToGrow = tokens.size() >
792 MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
793 MacroExpandedTokens.append(tokens.begin(), tokens.end());
794
795 if (cacheNeedsToGrow) {
796 // Go through all the TokenLexers whose 'Tokens' pointer points in the
797 // buffer and update the pointers to the (potential) new buffer array.
798 for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) {
799 TokenLexer *prevLexer;
800 size_t tokIndex;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000801 std::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i];
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000802 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
803 }
804 }
805
806 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
807 return MacroExpandedTokens.data() + newIndex;
808}
809
810void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
811 assert(!MacroExpandingLexersStack.empty());
812 size_t tokIndex = MacroExpandingLexersStack.back().second;
813 assert(tokIndex < MacroExpandedTokens.size());
814 // Pop the cached macro expanded tokens from the end.
815 MacroExpandedTokens.resize(tokIndex);
816 MacroExpandingLexersStack.pop_back();
817}
818
819/// ComputeDATE_TIME - Compute the current time, enter it into the specified
820/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
821/// the identifier tokens inserted.
822static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
823 Preprocessor &PP) {
Craig Topperd2d442c2014-05-17 23:10:59 +0000824 time_t TT = time(nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000825 struct tm *TM = localtime(&TT);
826
827 static const char * const Months[] = {
828 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
829 };
830
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000831 {
832 SmallString<32> TmpBuffer;
833 llvm::raw_svector_ostream TmpStream(TmpBuffer);
834 TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
835 TM->tm_mday, TM->tm_year + 1900);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000836 Token TmpTok;
837 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000838 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000839 DATELoc = TmpTok.getLocation();
840 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000841
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000842 {
843 SmallString<32> TmpBuffer;
844 llvm::raw_svector_ostream TmpStream(TmpBuffer);
845 TmpStream << llvm::format("\"%02d:%02d:%02d\"",
846 TM->tm_hour, TM->tm_min, TM->tm_sec);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000847 Token TmpTok;
848 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000849 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +0000850 TIMELoc = TmpTok.getLocation();
851 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000852}
853
854
855/// HasFeature - Return true if we recognize and implement the feature
856/// specified by the identifier as a standard language feature.
857static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
858 const LangOptions &LangOpts = PP.getLangOpts();
859 StringRef Feature = II->getName();
860
861 // Normalize the feature name, __foo__ becomes foo.
862 if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4)
863 Feature = Feature.substr(2, Feature.size() - 4);
864
865 return llvm::StringSwitch<bool>(Feature)
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000866 .Case("address_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Address))
867 .Case("attribute_analyzer_noreturn", true)
868 .Case("attribute_availability", true)
869 .Case("attribute_availability_with_message", true)
870 .Case("attribute_cf_returns_not_retained", true)
871 .Case("attribute_cf_returns_retained", true)
872 .Case("attribute_deprecated_with_message", true)
873 .Case("attribute_ext_vector_type", true)
874 .Case("attribute_ns_returns_not_retained", true)
875 .Case("attribute_ns_returns_retained", true)
876 .Case("attribute_ns_consumes_self", true)
877 .Case("attribute_ns_consumed", true)
878 .Case("attribute_cf_consumed", true)
879 .Case("attribute_objc_ivar_unused", true)
880 .Case("attribute_objc_method_family", true)
881 .Case("attribute_overloadable", true)
882 .Case("attribute_unavailable_with_message", true)
883 .Case("attribute_unused_on_fields", true)
884 .Case("blocks", LangOpts.Blocks)
885 .Case("c_thread_safety_attributes", true)
886 .Case("cxx_exceptions", LangOpts.CXXExceptions)
887 .Case("cxx_rtti", LangOpts.RTTI)
888 .Case("enumerator_attributes", true)
889 .Case("memory_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Memory))
890 .Case("thread_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Thread))
891 .Case("dataflow_sanitizer", LangOpts.Sanitize.has(SanitizerKind::DataFlow))
892 // Objective-C features
893 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
894 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
895 .Case("objc_arc_weak", LangOpts.ObjCARCWeak)
896 .Case("objc_default_synthesize_properties", LangOpts.ObjC2)
897 .Case("objc_fixed_enum", LangOpts.ObjC2)
898 .Case("objc_instancetype", LangOpts.ObjC2)
899 .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules)
900 .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile())
901 .Case("objc_property_explicit_atomic",
902 true) // Does clang support explicit "atomic" keyword?
903 .Case("objc_protocol_qualifier_mangling", true)
904 .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport())
905 .Case("ownership_holds", true)
906 .Case("ownership_returns", true)
907 .Case("ownership_takes", true)
908 .Case("objc_bool", true)
909 .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile())
910 .Case("objc_array_literals", LangOpts.ObjC2)
911 .Case("objc_dictionary_literals", LangOpts.ObjC2)
912 .Case("objc_boxed_expressions", LangOpts.ObjC2)
913 .Case("arc_cf_code_audited", true)
914 // C11 features
915 .Case("c_alignas", LangOpts.C11)
916 .Case("c_atomic", LangOpts.C11)
917 .Case("c_generic_selections", LangOpts.C11)
918 .Case("c_static_assert", LangOpts.C11)
919 .Case("c_thread_local",
920 LangOpts.C11 && PP.getTargetInfo().isTLSSupported())
921 // C++11 features
922 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus11)
923 .Case("cxx_alias_templates", LangOpts.CPlusPlus11)
924 .Case("cxx_alignas", LangOpts.CPlusPlus11)
925 .Case("cxx_atomic", LangOpts.CPlusPlus11)
926 .Case("cxx_attributes", LangOpts.CPlusPlus11)
927 .Case("cxx_auto_type", LangOpts.CPlusPlus11)
928 .Case("cxx_constexpr", LangOpts.CPlusPlus11)
929 .Case("cxx_decltype", LangOpts.CPlusPlus11)
930 .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus11)
931 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus11)
932 .Case("cxx_defaulted_functions", LangOpts.CPlusPlus11)
933 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus11)
934 .Case("cxx_deleted_functions", LangOpts.CPlusPlus11)
935 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus11)
936 .Case("cxx_generalized_initializers", LangOpts.CPlusPlus11)
937 .Case("cxx_implicit_moves", LangOpts.CPlusPlus11)
938 .Case("cxx_inheriting_constructors", LangOpts.CPlusPlus11)
939 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus11)
940 .Case("cxx_lambdas", LangOpts.CPlusPlus11)
941 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus11)
942 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus11)
943 .Case("cxx_noexcept", LangOpts.CPlusPlus11)
944 .Case("cxx_nullptr", LangOpts.CPlusPlus11)
945 .Case("cxx_override_control", LangOpts.CPlusPlus11)
946 .Case("cxx_range_for", LangOpts.CPlusPlus11)
947 .Case("cxx_raw_string_literals", LangOpts.CPlusPlus11)
948 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus11)
949 .Case("cxx_rvalue_references", LangOpts.CPlusPlus11)
950 .Case("cxx_strong_enums", LangOpts.CPlusPlus11)
951 .Case("cxx_static_assert", LangOpts.CPlusPlus11)
952 .Case("cxx_thread_local",
953 LangOpts.CPlusPlus11 && PP.getTargetInfo().isTLSSupported())
954 .Case("cxx_trailing_return", LangOpts.CPlusPlus11)
955 .Case("cxx_unicode_literals", LangOpts.CPlusPlus11)
956 .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus11)
957 .Case("cxx_user_literals", LangOpts.CPlusPlus11)
958 .Case("cxx_variadic_templates", LangOpts.CPlusPlus11)
959 // C++1y features
960 .Case("cxx_aggregate_nsdmi", LangOpts.CPlusPlus14)
961 .Case("cxx_binary_literals", LangOpts.CPlusPlus14)
962 .Case("cxx_contextual_conversions", LangOpts.CPlusPlus14)
963 .Case("cxx_decltype_auto", LangOpts.CPlusPlus14)
964 .Case("cxx_generic_lambdas", LangOpts.CPlusPlus14)
965 .Case("cxx_init_captures", LangOpts.CPlusPlus14)
966 .Case("cxx_relaxed_constexpr", LangOpts.CPlusPlus14)
967 .Case("cxx_return_type_deduction", LangOpts.CPlusPlus14)
968 .Case("cxx_variable_templates", LangOpts.CPlusPlus14)
969 // C++ TSes
970 //.Case("cxx_runtime_arrays", LangOpts.CPlusPlusTSArrays)
971 //.Case("cxx_concepts", LangOpts.CPlusPlusTSConcepts)
972 // FIXME: Should this be __has_feature or __has_extension?
973 //.Case("raw_invocation_type", LangOpts.CPlusPlus)
974 // Type traits
975 .Case("has_nothrow_assign", LangOpts.CPlusPlus)
976 .Case("has_nothrow_copy", LangOpts.CPlusPlus)
977 .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
978 .Case("has_trivial_assign", LangOpts.CPlusPlus)
979 .Case("has_trivial_copy", LangOpts.CPlusPlus)
980 .Case("has_trivial_constructor", LangOpts.CPlusPlus)
981 .Case("has_trivial_destructor", LangOpts.CPlusPlus)
982 .Case("has_virtual_destructor", LangOpts.CPlusPlus)
983 .Case("is_abstract", LangOpts.CPlusPlus)
984 .Case("is_base_of", LangOpts.CPlusPlus)
985 .Case("is_class", LangOpts.CPlusPlus)
986 .Case("is_constructible", LangOpts.CPlusPlus)
987 .Case("is_convertible_to", LangOpts.CPlusPlus)
988 .Case("is_empty", LangOpts.CPlusPlus)
989 .Case("is_enum", LangOpts.CPlusPlus)
990 .Case("is_final", LangOpts.CPlusPlus)
991 .Case("is_literal", LangOpts.CPlusPlus)
992 .Case("is_standard_layout", LangOpts.CPlusPlus)
993 .Case("is_pod", LangOpts.CPlusPlus)
994 .Case("is_polymorphic", LangOpts.CPlusPlus)
995 .Case("is_sealed", LangOpts.MicrosoftExt)
996 .Case("is_trivial", LangOpts.CPlusPlus)
997 .Case("is_trivially_assignable", LangOpts.CPlusPlus)
998 .Case("is_trivially_constructible", LangOpts.CPlusPlus)
999 .Case("is_trivially_copyable", LangOpts.CPlusPlus)
1000 .Case("is_union", LangOpts.CPlusPlus)
1001 .Case("modules", LangOpts.Modules)
1002 .Case("tls", PP.getTargetInfo().isTLSSupported())
1003 .Case("underlying_type", LangOpts.CPlusPlus)
1004 .Default(false);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001005}
1006
1007/// HasExtension - Return true if we recognize and implement the feature
1008/// specified by the identifier, either as an extension or a standard language
1009/// feature.
1010static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) {
1011 if (HasFeature(PP, II))
1012 return true;
1013
1014 // If the use of an extension results in an error diagnostic, extensions are
1015 // effectively unavailable, so just return false here.
Alp Tokerac4e8e52014-06-22 21:58:33 +00001016 if (PP.getDiagnostics().getExtensionHandlingBehavior() >=
1017 diag::Severity::Error)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001018 return false;
1019
1020 const LangOptions &LangOpts = PP.getLangOpts();
1021 StringRef Extension = II->getName();
1022
1023 // Normalize the extension name, __foo__ becomes foo.
1024 if (Extension.startswith("__") && Extension.endswith("__") &&
1025 Extension.size() >= 4)
1026 Extension = Extension.substr(2, Extension.size() - 4);
1027
1028 // Because we inherit the feature list from HasFeature, this string switch
1029 // must be less restrictive than HasFeature's.
1030 return llvm::StringSwitch<bool>(Extension)
1031 // C11 features supported by other languages as extensions.
1032 .Case("c_alignas", true)
1033 .Case("c_atomic", true)
1034 .Case("c_generic_selections", true)
1035 .Case("c_static_assert", true)
Ed Schouten401aeba2013-09-14 16:17:20 +00001036 .Case("c_thread_local", PP.getTargetInfo().isTLSSupported())
Richard Smith0a715422013-05-07 19:32:56 +00001037 // C++11 features supported by other languages as extensions.
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001038 .Case("cxx_atomic", LangOpts.CPlusPlus)
1039 .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
1040 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
1041 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
1042 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus)
1043 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
1044 .Case("cxx_override_control", LangOpts.CPlusPlus)
1045 .Case("cxx_range_for", LangOpts.CPlusPlus)
1046 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
1047 .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
Richard Smith0a715422013-05-07 19:32:56 +00001048 // C++1y features supported by other languages as extensions.
1049 .Case("cxx_binary_literals", true)
Richard Smithb438e622013-09-28 04:37:56 +00001050 .Case("cxx_init_captures", LangOpts.CPlusPlus11)
Alp Tokera8bb9c92014-01-15 04:11:24 +00001051 .Case("cxx_variable_templates", LangOpts.CPlusPlus)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001052 .Default(false);
1053}
1054
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001055/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
1056/// or '__has_include_next("path")' expression.
1057/// Returns true if successful.
1058static bool EvaluateHasIncludeCommon(Token &Tok,
1059 IdentifierInfo *II, Preprocessor &PP,
Richard Smith25d50752014-10-20 00:15:49 +00001060 const DirectoryLookup *LookupFrom,
1061 const FileEntry *LookupFromFile) {
Richard Trieuda031982012-10-22 20:28:48 +00001062 // Save the location of the current token. If a '(' is later found, use
Aaron Ballman5cb24112013-01-15 21:59:46 +00001063 // that location. If not, use the end of this location instead.
Richard Trieuda031982012-10-22 20:28:48 +00001064 SourceLocation LParenLoc = Tok.getLocation();
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001065
Aaron Ballman6ce00002013-01-16 19:32:21 +00001066 // These expressions are only allowed within a preprocessor directive.
1067 if (!PP.isParsingIfOrElifDirective()) {
1068 PP.Diag(LParenLoc, diag::err_pp_directive_required) << II->getName();
1069 return false;
1070 }
1071
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001072 // Get '('.
1073 PP.LexNonComment(Tok);
1074
1075 // Ensure we have a '('.
1076 if (Tok.isNot(tok::l_paren)) {
Richard Trieuda031982012-10-22 20:28:48 +00001077 // No '(', use end of last token.
1078 LParenLoc = PP.getLocForEndOfToken(LParenLoc);
Alp Toker751d6352013-12-30 01:59:29 +00001079 PP.Diag(LParenLoc, diag::err_pp_expected_after) << II << tok::l_paren;
Richard Trieuda031982012-10-22 20:28:48 +00001080 // If the next token looks like a filename or the start of one,
1081 // assume it is and process it as such.
1082 if (!Tok.is(tok::angle_string_literal) && !Tok.is(tok::string_literal) &&
1083 !Tok.is(tok::less))
1084 return false;
1085 } else {
1086 // Save '(' location for possible missing ')' message.
1087 LParenLoc = Tok.getLocation();
1088
Eli Friedmanec94b612013-01-09 02:20:00 +00001089 if (PP.getCurrentLexer()) {
1090 // Get the file name.
1091 PP.getCurrentLexer()->LexIncludeFilename(Tok);
1092 } else {
1093 // We're in a macro, so we can't use LexIncludeFilename; just
1094 // grab the next token.
1095 PP.Lex(Tok);
1096 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001097 }
1098
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001099 // Reserve a buffer to get the spelling.
1100 SmallString<128> FilenameBuffer;
1101 StringRef Filename;
1102 SourceLocation EndLoc;
1103
1104 switch (Tok.getKind()) {
1105 case tok::eod:
1106 // If the token kind is EOD, the error has already been diagnosed.
1107 return false;
1108
1109 case tok::angle_string_literal:
1110 case tok::string_literal: {
1111 bool Invalid = false;
1112 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
1113 if (Invalid)
1114 return false;
1115 break;
1116 }
1117
1118 case tok::less:
1119 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1120 // case, glue the tokens together into FilenameBuffer and interpret those.
1121 FilenameBuffer.push_back('<');
Richard Trieuda031982012-10-22 20:28:48 +00001122 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc)) {
1123 // Let the caller know a <eod> was found by changing the Token kind.
1124 Tok.setKind(tok::eod);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001125 return false; // Found <eod> but no ">"? Diagnostic already emitted.
Richard Trieuda031982012-10-22 20:28:48 +00001126 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001127 Filename = FilenameBuffer.str();
1128 break;
1129 default:
1130 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
1131 return false;
1132 }
1133
Richard Trieuda031982012-10-22 20:28:48 +00001134 SourceLocation FilenameLoc = Tok.getLocation();
1135
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001136 // Get ')'.
1137 PP.LexNonComment(Tok);
1138
1139 // Ensure we have a trailing ).
1140 if (Tok.isNot(tok::r_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001141 PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after)
1142 << II << tok::r_paren;
Alp Tokerec543272013-12-24 09:48:30 +00001143 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001144 return false;
1145 }
1146
1147 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
1148 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1149 // error.
1150 if (Filename.empty())
1151 return false;
1152
1153 // Search include directories.
1154 const DirectoryLookup *CurDir;
1155 const FileEntry *File =
Richard Smith25d50752014-10-20 00:15:49 +00001156 PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, LookupFromFile,
1157 CurDir, nullptr, nullptr, nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001158
1159 // Get the result value. A result of true means the file exists.
Craig Topperd2d442c2014-05-17 23:10:59 +00001160 return File != nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001161}
1162
1163/// EvaluateHasInclude - Process a '__has_include("path")' expression.
1164/// Returns true if successful.
1165static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
1166 Preprocessor &PP) {
Richard Smith25d50752014-10-20 00:15:49 +00001167 return EvaluateHasIncludeCommon(Tok, II, PP, nullptr, nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001168}
1169
1170/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
1171/// Returns true if successful.
1172static bool EvaluateHasIncludeNext(Token &Tok,
1173 IdentifierInfo *II, Preprocessor &PP) {
1174 // __has_include_next is like __has_include, except that we start
1175 // searching after the current found directory. If we can't do this,
1176 // issue a diagnostic.
Richard Smith25d50752014-10-20 00:15:49 +00001177 // FIXME: Factor out duplication wiht
1178 // Preprocessor::HandleIncludeNextDirective.
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001179 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
Richard Smith25d50752014-10-20 00:15:49 +00001180 const FileEntry *LookupFromFile = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001181 if (PP.isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001182 Lookup = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001183 PP.Diag(Tok, diag::pp_include_next_in_primary);
Richard Smith25d50752014-10-20 00:15:49 +00001184 } else if (PP.getCurrentSubmodule()) {
1185 // Start looking up in the directory *after* the one in which the current
1186 // file would be found, if any.
1187 assert(PP.getCurrentLexer() && "#include_next directive in macro?");
1188 LookupFromFile = PP.getCurrentLexer()->getFileEntry();
1189 Lookup = nullptr;
Craig Topperd2d442c2014-05-17 23:10:59 +00001190 } else if (!Lookup) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001191 PP.Diag(Tok, diag::pp_include_next_absolute_path);
1192 } else {
1193 // Start looking up in the next directory.
1194 ++Lookup;
1195 }
1196
Richard Smith25d50752014-10-20 00:15:49 +00001197 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup, LookupFromFile);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001198}
1199
Douglas Gregorc83de302012-09-25 15:44:52 +00001200/// \brief Process __building_module(identifier) expression.
1201/// \returns true if we are building the named module, false otherwise.
1202static bool EvaluateBuildingModule(Token &Tok,
1203 IdentifierInfo *II, Preprocessor &PP) {
1204 // Get '('.
1205 PP.LexNonComment(Tok);
1206
1207 // Ensure we have a '('.
1208 if (Tok.isNot(tok::l_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001209 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1210 << tok::l_paren;
Douglas Gregorc83de302012-09-25 15:44:52 +00001211 return false;
1212 }
1213
1214 // Save '(' location for possible missing ')' message.
1215 SourceLocation LParenLoc = Tok.getLocation();
1216
1217 // Get the module name.
1218 PP.LexNonComment(Tok);
1219
1220 // Ensure that we have an identifier.
1221 if (Tok.isNot(tok::identifier)) {
1222 PP.Diag(Tok.getLocation(), diag::err_expected_id_building_module);
1223 return false;
1224 }
1225
1226 bool Result
1227 = Tok.getIdentifierInfo()->getName() == PP.getLangOpts().CurrentModule;
1228
1229 // Get ')'.
1230 PP.LexNonComment(Tok);
1231
1232 // Ensure we have a trailing ).
1233 if (Tok.isNot(tok::r_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001234 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1235 << tok::r_paren;
Alp Tokerec543272013-12-24 09:48:30 +00001236 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
Douglas Gregorc83de302012-09-25 15:44:52 +00001237 return false;
1238 }
1239
1240 return Result;
1241}
1242
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001243/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1244/// as a builtin macro, handle it and return the next token as 'Tok'.
1245void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
1246 // Figure out which token this is.
1247 IdentifierInfo *II = Tok.getIdentifierInfo();
1248 assert(II && "Can't be a macro without id info!");
1249
1250 // If this is an _Pragma or Microsoft __pragma directive, expand it,
1251 // invoke the pragma handler, then lex the token after it.
1252 if (II == Ident_Pragma)
1253 return Handle_Pragma(Tok);
1254 else if (II == Ident__pragma) // in non-MS mode this is null
1255 return HandleMicrosoft__pragma(Tok);
1256
1257 ++NumBuiltinMacroExpanded;
1258
1259 SmallString<128> TmpBuffer;
1260 llvm::raw_svector_ostream OS(TmpBuffer);
1261
1262 // Set up the return result.
Craig Topperd2d442c2014-05-17 23:10:59 +00001263 Tok.setIdentifierInfo(nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001264 Tok.clearFlag(Token::NeedsCleaning);
1265
1266 if (II == Ident__LINE__) {
1267 // C99 6.10.8: "__LINE__: The presumed line number (within the current
1268 // source file) of the current source line (an integer constant)". This can
1269 // be affected by #line.
1270 SourceLocation Loc = Tok.getLocation();
1271
1272 // Advance to the location of the first _, this might not be the first byte
1273 // of the token if it starts with an escaped newline.
1274 Loc = AdvanceToTokenCharacter(Loc, 0);
1275
1276 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
1277 // a macro expansion. This doesn't matter for object-like macros, but
1278 // can matter for a function-like macro that expands to contain __LINE__.
1279 // Skip down through expansion points until we find a file loc for the
1280 // end of the expansion history.
1281 Loc = SourceMgr.getExpansionRange(Loc).second;
1282 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
1283
1284 // __LINE__ expands to a simple numeric value.
1285 OS << (PLoc.isValid()? PLoc.getLine() : 1);
1286 Tok.setKind(tok::numeric_constant);
1287 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
1288 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
1289 // character string literal)". This can be affected by #line.
1290 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1291
1292 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
1293 // #include stack instead of the current file.
1294 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
1295 SourceLocation NextLoc = PLoc.getIncludeLoc();
1296 while (NextLoc.isValid()) {
1297 PLoc = SourceMgr.getPresumedLoc(NextLoc);
1298 if (PLoc.isInvalid())
1299 break;
1300
1301 NextLoc = PLoc.getIncludeLoc();
1302 }
1303 }
1304
1305 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
1306 SmallString<128> FN;
1307 if (PLoc.isValid()) {
1308 FN += PLoc.getFilename();
1309 Lexer::Stringify(FN);
1310 OS << '"' << FN.str() << '"';
1311 }
1312 Tok.setKind(tok::string_literal);
1313 } else if (II == Ident__DATE__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001314 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001315 if (!DATELoc.isValid())
1316 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1317 Tok.setKind(tok::string_literal);
1318 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1319 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
1320 Tok.getLocation(),
1321 Tok.getLength()));
1322 return;
1323 } else if (II == Ident__TIME__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001324 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001325 if (!TIMELoc.isValid())
1326 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1327 Tok.setKind(tok::string_literal);
1328 Tok.setLength(strlen("\"hh:mm:ss\""));
1329 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
1330 Tok.getLocation(),
1331 Tok.getLength()));
1332 return;
1333 } else if (II == Ident__INCLUDE_LEVEL__) {
1334 // Compute the presumed include depth of this token. This can be affected
1335 // by GNU line markers.
1336 unsigned Depth = 0;
1337
1338 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1339 if (PLoc.isValid()) {
1340 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1341 for (; PLoc.isValid(); ++Depth)
1342 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1343 }
1344
1345 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1346 OS << Depth;
1347 Tok.setKind(tok::numeric_constant);
1348 } else if (II == Ident__TIMESTAMP__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001349 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001350 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1351 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1352
1353 // Get the file that we are lexing out of. If we're currently lexing from
1354 // a macro, dig into the include stack.
Craig Topperd2d442c2014-05-17 23:10:59 +00001355 const FileEntry *CurFile = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001356 PreprocessorLexer *TheLexer = getCurrentFileLexer();
1357
1358 if (TheLexer)
1359 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
1360
1361 const char *Result;
1362 if (CurFile) {
1363 time_t TT = CurFile->getModificationTime();
1364 struct tm *TM = localtime(&TT);
1365 Result = asctime(TM);
1366 } else {
1367 Result = "??? ??? ?? ??:??:?? ????\n";
1368 }
1369 // Surround the string with " and strip the trailing newline.
Alp Toker4f43e552014-06-10 06:08:51 +00001370 OS << '"' << StringRef(Result).drop_back() << '"';
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001371 Tok.setKind(tok::string_literal);
1372 } else if (II == Ident__COUNTER__) {
1373 // __COUNTER__ expands to a simple numeric value.
1374 OS << CounterValue++;
1375 Tok.setKind(tok::numeric_constant);
1376 } else if (II == Ident__has_feature ||
1377 II == Ident__has_extension ||
1378 II == Ident__has_builtin ||
Yunzhong Gaoef309f42014-04-11 20:55:19 +00001379 II == Ident__is_identifier ||
Aaron Ballmana0344c52014-11-14 13:44:02 +00001380 II == Ident__has_attribute ||
1381 II == Ident__has_cpp_attribute) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001382 // The argument to these builtins should be a parenthesized identifier.
1383 SourceLocation StartLoc = Tok.getLocation();
1384
1385 bool IsValid = false;
Craig Topperd2d442c2014-05-17 23:10:59 +00001386 IdentifierInfo *FeatureII = nullptr;
Aaron Ballmana0344c52014-11-14 13:44:02 +00001387 IdentifierInfo *ScopeII = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001388
1389 // Read the '('.
Andy Gibbsd41d0942012-11-17 19:18:27 +00001390 LexUnexpandedToken(Tok);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001391 if (Tok.is(tok::l_paren)) {
1392 // Read the identifier
Andy Gibbsd41d0942012-11-17 19:18:27 +00001393 LexUnexpandedToken(Tok);
Richard Smithbaf29122013-07-09 00:57:56 +00001394 if ((FeatureII = Tok.getIdentifierInfo())) {
Aaron Ballmana0344c52014-11-14 13:44:02 +00001395 // If we're checking __has_cpp_attribute, it is possible to receive a
1396 // scope token. Read the "::", if it's available.
Andy Gibbsd41d0942012-11-17 19:18:27 +00001397 LexUnexpandedToken(Tok);
Aaron Ballmana0344c52014-11-14 13:44:02 +00001398 bool IsScopeValid = true;
1399 if (II == Ident__has_cpp_attribute && Tok.is(tok::coloncolon)) {
1400 LexUnexpandedToken(Tok);
1401 // The first thing we read was not the feature, it was the scope.
1402 ScopeII = FeatureII;
1403 if (FeatureII = Tok.getIdentifierInfo())
1404 LexUnexpandedToken(Tok);
1405 else
1406 IsScopeValid = false;
1407 }
1408 // Read the closing paren.
1409 if (IsScopeValid && Tok.is(tok::r_paren))
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001410 IsValid = true;
1411 }
1412 }
1413
Aaron Ballmana0344c52014-11-14 13:44:02 +00001414 int Value = 0;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001415 if (!IsValid)
1416 Diag(StartLoc, diag::err_feature_check_malformed);
Yunzhong Gaoef309f42014-04-11 20:55:19 +00001417 else if (II == Ident__is_identifier)
1418 Value = FeatureII->getTokenID() == tok::identifier;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001419 else if (II == Ident__has_builtin) {
1420 // Check for a builtin is trivial.
1421 Value = FeatureII->getBuiltinID() != 0;
1422 } else if (II == Ident__has_attribute)
Aaron Ballman759c71d2014-03-31 15:26:40 +00001423 Value = hasAttribute(AttrSyntax::Generic, nullptr, FeatureII,
Aaron Ballman2fbf9942014-03-31 13:14:44 +00001424 getTargetInfo().getTriple(), getLangOpts());
Aaron Ballmana0344c52014-11-14 13:44:02 +00001425 else if (II == Ident__has_cpp_attribute)
1426 Value = hasAttribute(AttrSyntax::CXX, ScopeII, FeatureII,
1427 getTargetInfo().getTriple(), getLangOpts());
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001428 else if (II == Ident__has_extension)
1429 Value = HasExtension(*this, FeatureII);
1430 else {
1431 assert(II == Ident__has_feature && "Must be feature check");
1432 Value = HasFeature(*this, FeatureII);
1433 }
1434
Aaron Ballmana0344c52014-11-14 13:44:02 +00001435 OS << Value;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001436 if (IsValid)
1437 Tok.setKind(tok::numeric_constant);
1438 } else if (II == Ident__has_include ||
1439 II == Ident__has_include_next) {
1440 // The argument to these two builtins should be a parenthesized
1441 // file name string literal using angle brackets (<>) or
1442 // double-quotes ("").
1443 bool Value;
1444 if (II == Ident__has_include)
1445 Value = EvaluateHasInclude(Tok, II, *this);
1446 else
1447 Value = EvaluateHasIncludeNext(Tok, II, *this);
1448 OS << (int)Value;
Richard Trieuda031982012-10-22 20:28:48 +00001449 if (Tok.is(tok::r_paren))
1450 Tok.setKind(tok::numeric_constant);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001451 } else if (II == Ident__has_warning) {
1452 // The argument should be a parenthesized string literal.
1453 // The argument to these builtins should be a parenthesized identifier.
1454 SourceLocation StartLoc = Tok.getLocation();
1455 bool IsValid = false;
1456 bool Value = false;
1457 // Read the '('.
Andy Gibbs58905d22012-11-17 19:15:38 +00001458 LexUnexpandedToken(Tok);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001459 do {
Andy Gibbs58905d22012-11-17 19:15:38 +00001460 if (Tok.isNot(tok::l_paren)) {
1461 Diag(StartLoc, diag::err_warning_check_malformed);
1462 break;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001463 }
Andy Gibbs58905d22012-11-17 19:15:38 +00001464
1465 LexUnexpandedToken(Tok);
1466 std::string WarningName;
1467 SourceLocation StrStartLoc = Tok.getLocation();
Andy Gibbsa8df57a2012-11-17 19:16:52 +00001468 if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",
1469 /*MacroExpansion=*/false)) {
Andy Gibbs58905d22012-11-17 19:15:38 +00001470 // Eat tokens until ')'.
Andy Gibbsb5b30c42012-11-17 22:17:28 +00001471 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) &&
1472 Tok.isNot(tok::eof))
Andy Gibbs58905d22012-11-17 19:15:38 +00001473 LexUnexpandedToken(Tok);
1474 break;
1475 }
1476
1477 // Is the end a ')'?
1478 if (!(IsValid = Tok.is(tok::r_paren))) {
1479 Diag(StartLoc, diag::err_warning_check_malformed);
1480 break;
1481 }
1482
Richard Smith3be1cb22014-08-07 00:24:21 +00001483 // FIXME: Should we accept "-R..." flags here, or should that be handled
1484 // by a separate __has_remark?
Andy Gibbs58905d22012-11-17 19:15:38 +00001485 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1486 WarningName[1] != 'W') {
1487 Diag(StrStartLoc, diag::warn_has_warning_invalid_option);
1488 break;
1489 }
1490
1491 // Finally, check if the warning flags maps to a diagnostic group.
1492 // We construct a SmallVector here to talk to getDiagnosticIDs().
1493 // Although we don't use the result, this isn't a hot path, and not
1494 // worth special casing.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001495 SmallVector<diag::kind, 10> Diags;
Andy Gibbs58905d22012-11-17 19:15:38 +00001496 Value = !getDiagnostics().getDiagnosticIDs()->
Richard Smith3be1cb22014-08-07 00:24:21 +00001497 getDiagnosticsInGroup(diag::Flavor::WarningOrError,
1498 WarningName.substr(2), Diags);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001499 } while (false);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001500
1501 OS << (int)Value;
Andy Gibbsf591982b2012-11-17 19:14:53 +00001502 if (IsValid)
1503 Tok.setKind(tok::numeric_constant);
Douglas Gregorc83de302012-09-25 15:44:52 +00001504 } else if (II == Ident__building_module) {
1505 // The argument to this builtin should be an identifier. The
1506 // builtin evaluates to 1 when that identifier names the module we are
1507 // currently building.
1508 OS << (int)EvaluateBuildingModule(Tok, II, *this);
1509 Tok.setKind(tok::numeric_constant);
1510 } else if (II == Ident__MODULE__) {
1511 // The current module as an identifier.
1512 OS << getLangOpts().CurrentModule;
1513 IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);
1514 Tok.setIdentifierInfo(ModuleII);
1515 Tok.setKind(ModuleII->getTokenID());
Richard Smithae385082014-03-15 00:06:08 +00001516 } else if (II == Ident__identifier) {
1517 SourceLocation Loc = Tok.getLocation();
1518
1519 // We're expecting '__identifier' '(' identifier ')'. Try to recover
1520 // if the parens are missing.
1521 LexNonComment(Tok);
1522 if (Tok.isNot(tok::l_paren)) {
1523 // No '(', use end of last token.
1524 Diag(getLocForEndOfToken(Loc), diag::err_pp_expected_after)
1525 << II << tok::l_paren;
1526 // If the next token isn't valid as our argument, we can't recover.
1527 if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1528 Tok.setKind(tok::identifier);
1529 return;
1530 }
1531
1532 SourceLocation LParenLoc = Tok.getLocation();
1533 LexNonComment(Tok);
1534
1535 if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1536 Tok.setKind(tok::identifier);
1537 else {
1538 Diag(Tok.getLocation(), diag::err_pp_identifier_arg_not_identifier)
1539 << Tok.getKind();
1540 // Don't walk past anything that's not a real token.
1541 if (Tok.is(tok::eof) || Tok.is(tok::eod) || Tok.isAnnotation())
1542 return;
1543 }
1544
1545 // Discard the ')', preserving 'Tok' as our result.
1546 Token RParen;
1547 LexNonComment(RParen);
1548 if (RParen.isNot(tok::r_paren)) {
1549 Diag(getLocForEndOfToken(Tok.getLocation()), diag::err_pp_expected_after)
1550 << Tok.getKind() << tok::r_paren;
1551 Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1552 }
1553 return;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001554 } else {
1555 llvm_unreachable("Unknown identifier!");
1556 }
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00001557 CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation());
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001558}
1559
1560void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
1561 // If the 'used' status changed, and the macro requires 'unused' warning,
1562 // remove its SourceLocation from the warn-for-unused-macro locations.
1563 if (MI->isWarnIfUnused() && !MI->isUsed())
1564 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1565 MI->setIsUsed(true);
1566}