]> CyberLeo.Net >> Repos - FreeBSD/releng/9.2.git/blob - contrib/llvm/tools/clang/lib/Lex/PPMacroExpansion.cpp
- Copy stable/9 to releng/9.2 as part of the 9.2-RELEASE cycle.
[FreeBSD/releng/9.2.git] / contrib / llvm / tools / clang / lib / Lex / PPMacroExpansion.cpp
1 //===--- 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 "clang/Lex/MacroArgs.h"
17 #include "clang/Basic/FileManager.h"
18 #include "clang/Basic/SourceManager.h"
19 #include "clang/Basic/TargetInfo.h"
20 #include "clang/Lex/CodeCompletionHandler.h"
21 #include "clang/Lex/ExternalPreprocessorSource.h"
22 #include "clang/Lex/LexDiagnostic.h"
23 #include "clang/Lex/MacroInfo.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/Config/llvm-config.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/Format.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include <cstdio>
32 #include <ctime>
33 using namespace clang;
34
35 MacroDirective *
36 Preprocessor::getMacroDirectiveHistory(const IdentifierInfo *II) const {
37   assert(II->hadMacroDefinition() && "Identifier has not been not a macro!");
38
39   macro_iterator Pos = Macros.find(II);
40   assert(Pos != Macros.end() && "Identifier macro info is missing!");
41   return Pos->second;
42 }
43
44 void Preprocessor::appendMacroDirective(IdentifierInfo *II, MacroDirective *MD){
45   assert(MD && "MacroDirective should be non-zero!");
46   assert(!MD->getPrevious() && "Already attached to a MacroDirective history.");
47
48   MacroDirective *&StoredMD = Macros[II];
49   MD->setPrevious(StoredMD);
50   StoredMD = MD;
51   II->setHasMacroDefinition(MD->isDefined());
52   bool isImportedMacro = isa<DefMacroDirective>(MD) &&
53                          cast<DefMacroDirective>(MD)->isImported();
54   if (II->isFromAST() && !isImportedMacro)
55     II->setChangedSinceDeserialization();
56 }
57
58 void Preprocessor::setLoadedMacroDirective(IdentifierInfo *II,
59                                            MacroDirective *MD) {
60   assert(II && MD);
61   MacroDirective *&StoredMD = Macros[II];
62   assert(!StoredMD &&
63          "the macro history was modified before initializing it from a pch");
64   StoredMD = MD;
65   // Setup the identifier as having associated macro history.
66   II->setHasMacroDefinition(true);
67   if (!MD->isDefined())
68     II->setHasMacroDefinition(false);
69 }
70
71 /// RegisterBuiltinMacro - Register the specified identifier in the identifier
72 /// table and mark it as a builtin macro to be expanded.
73 static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
74   // Get the identifier.
75   IdentifierInfo *Id = PP.getIdentifierInfo(Name);
76
77   // Mark it as being a macro that is builtin.
78   MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
79   MI->setIsBuiltinMacro();
80   PP.appendDefMacroDirective(Id, MI);
81   return Id;
82 }
83
84
85 /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
86 /// identifier table.
87 void Preprocessor::RegisterBuiltinMacros() {
88   Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
89   Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
90   Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
91   Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
92   Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
93   Ident_Pragma  = RegisterBuiltinMacro(*this, "_Pragma");
94
95   // GCC Extensions.
96   Ident__BASE_FILE__     = RegisterBuiltinMacro(*this, "__BASE_FILE__");
97   Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
98   Ident__TIMESTAMP__     = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
99
100   // Clang Extensions.
101   Ident__has_feature      = RegisterBuiltinMacro(*this, "__has_feature");
102   Ident__has_extension    = RegisterBuiltinMacro(*this, "__has_extension");
103   Ident__has_builtin      = RegisterBuiltinMacro(*this, "__has_builtin");
104   Ident__has_attribute    = RegisterBuiltinMacro(*this, "__has_attribute");
105   Ident__has_include      = RegisterBuiltinMacro(*this, "__has_include");
106   Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
107   Ident__has_warning      = RegisterBuiltinMacro(*this, "__has_warning");
108
109   // Modules.
110   if (LangOpts.Modules) {
111     Ident__building_module  = RegisterBuiltinMacro(*this, "__building_module");
112
113     // __MODULE__
114     if (!LangOpts.CurrentModule.empty())
115       Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__");
116     else
117       Ident__MODULE__ = 0;
118   } else {
119     Ident__building_module = 0;
120     Ident__MODULE__ = 0;
121   }
122   
123   // Microsoft Extensions.
124   if (LangOpts.MicrosoftExt) 
125     Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
126   else
127     Ident__pragma = 0;
128 }
129
130 /// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
131 /// in its expansion, currently expands to that token literally.
132 static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
133                                           const IdentifierInfo *MacroIdent,
134                                           Preprocessor &PP) {
135   IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
136
137   // If the token isn't an identifier, it's always literally expanded.
138   if (II == 0) return true;
139
140   // If the information about this identifier is out of date, update it from
141   // the external source.
142   if (II->isOutOfDate())
143     PP.getExternalSource()->updateOutOfDateIdentifier(*II);
144
145   // If the identifier is a macro, and if that macro is enabled, it may be
146   // expanded so it's not a trivial expansion.
147   if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
148       // Fast expanding "#define X X" is ok, because X would be disabled.
149       II != MacroIdent)
150     return false;
151
152   // If this is an object-like macro invocation, it is safe to trivially expand
153   // it.
154   if (MI->isObjectLike()) return true;
155
156   // If this is a function-like macro invocation, it's safe to trivially expand
157   // as long as the identifier is not a macro argument.
158   for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
159        I != E; ++I)
160     if (*I == II)
161       return false;   // Identifier is a macro argument.
162
163   return true;
164 }
165
166
167 /// isNextPPTokenLParen - Determine whether the next preprocessor token to be
168 /// lexed is a '('.  If so, consume the token and return true, if not, this
169 /// method should have no observable side-effect on the lexed tokens.
170 bool Preprocessor::isNextPPTokenLParen() {
171   // Do some quick tests for rejection cases.
172   unsigned Val;
173   if (CurLexer)
174     Val = CurLexer->isNextPPTokenLParen();
175   else if (CurPTHLexer)
176     Val = CurPTHLexer->isNextPPTokenLParen();
177   else
178     Val = CurTokenLexer->isNextTokenLParen();
179
180   if (Val == 2) {
181     // We have run off the end.  If it's a source file we don't
182     // examine enclosing ones (C99 5.1.1.2p4).  Otherwise walk up the
183     // macro stack.
184     if (CurPPLexer)
185       return false;
186     for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
187       IncludeStackInfo &Entry = IncludeMacroStack[i-1];
188       if (Entry.TheLexer)
189         Val = Entry.TheLexer->isNextPPTokenLParen();
190       else if (Entry.ThePTHLexer)
191         Val = Entry.ThePTHLexer->isNextPPTokenLParen();
192       else
193         Val = Entry.TheTokenLexer->isNextTokenLParen();
194
195       if (Val != 2)
196         break;
197
198       // Ran off the end of a source file?
199       if (Entry.ThePPLexer)
200         return false;
201     }
202   }
203
204   // Okay, if we know that the token is a '(', lex it and return.  Otherwise we
205   // have found something that isn't a '(' or we found the end of the
206   // translation unit.  In either case, return false.
207   return Val == 1;
208 }
209
210 /// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
211 /// expanded as a macro, handle it and return the next token as 'Identifier'.
212 bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
213                                                  MacroDirective *MD) {
214   MacroDirective::DefInfo Def = MD->getDefinition();
215   assert(Def.isValid());
216   MacroInfo *MI = Def.getMacroInfo();
217
218   // If this is a macro expansion in the "#if !defined(x)" line for the file,
219   // then the macro could expand to different things in other contexts, we need
220   // to disable the optimization in this case.
221   if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
222
223   // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
224   if (MI->isBuiltinMacro()) {
225     if (Callbacks) Callbacks->MacroExpands(Identifier, MD,
226                                            Identifier.getLocation(),/*Args=*/0);
227     ExpandBuiltinMacro(Identifier);
228     return false;
229   }
230
231   /// Args - If this is a function-like macro expansion, this contains,
232   /// for each macro argument, the list of tokens that were provided to the
233   /// invocation.
234   MacroArgs *Args = 0;
235
236   // Remember where the end of the expansion occurred.  For an object-like
237   // macro, this is the identifier.  For a function-like macro, this is the ')'.
238   SourceLocation ExpansionEnd = Identifier.getLocation();
239
240   // If this is a function-like macro, read the arguments.
241   if (MI->isFunctionLike()) {
242     // C99 6.10.3p10: If the preprocessing token immediately after the macro
243     // name isn't a '(', this macro should not be expanded.
244     if (!isNextPPTokenLParen())
245       return true;
246
247     // Remember that we are now parsing the arguments to a macro invocation.
248     // Preprocessor directives used inside macro arguments are not portable, and
249     // this enables the warning.
250     InMacroArgs = true;
251     Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd);
252
253     // Finished parsing args.
254     InMacroArgs = false;
255
256     // If there was an error parsing the arguments, bail out.
257     if (Args == 0) return false;
258
259     ++NumFnMacroExpanded;
260   } else {
261     ++NumMacroExpanded;
262   }
263
264   // Notice that this macro has been used.
265   markMacroAsUsed(MI);
266
267   // Remember where the token is expanded.
268   SourceLocation ExpandLoc = Identifier.getLocation();
269   SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
270
271   if (Callbacks) {
272     if (InMacroArgs) {
273       // We can have macro expansion inside a conditional directive while
274       // reading the function macro arguments. To ensure, in that case, that
275       // MacroExpands callbacks still happen in source order, queue this
276       // callback to have it happen after the function macro callback.
277       DelayedMacroExpandsCallbacks.push_back(
278                               MacroExpandsInfo(Identifier, MD, ExpansionRange));
279     } else {
280       Callbacks->MacroExpands(Identifier, MD, ExpansionRange, Args);
281       if (!DelayedMacroExpandsCallbacks.empty()) {
282         for (unsigned i=0, e = DelayedMacroExpandsCallbacks.size(); i!=e; ++i) {
283           MacroExpandsInfo &Info = DelayedMacroExpandsCallbacks[i];
284           // FIXME: We lose macro args info with delayed callback.
285           Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range, /*Args=*/0);
286         }
287         DelayedMacroExpandsCallbacks.clear();
288       }
289     }
290   }
291
292   // If the macro definition is ambiguous, complain.
293   if (Def.getDirective()->isAmbiguous()) {
294     Diag(Identifier, diag::warn_pp_ambiguous_macro)
295       << Identifier.getIdentifierInfo();
296     Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)
297       << Identifier.getIdentifierInfo();
298     for (MacroDirective::DefInfo PrevDef = Def.getPreviousDefinition();
299          PrevDef && !PrevDef.isUndefined();
300          PrevDef = PrevDef.getPreviousDefinition()) {
301       if (PrevDef.getDirective()->isAmbiguous()) {
302         Diag(PrevDef.getMacroInfo()->getDefinitionLoc(),
303              diag::note_pp_ambiguous_macro_other)
304           << Identifier.getIdentifierInfo();
305       }
306     }
307   }
308
309   // If we started lexing a macro, enter the macro expansion body.
310
311   // If this macro expands to no tokens, don't bother to push it onto the
312   // expansion stack, only to take it right back off.
313   if (MI->getNumTokens() == 0) {
314     // No need for arg info.
315     if (Args) Args->destroy(*this);
316
317     // Ignore this macro use, just return the next token in the current
318     // buffer.
319     bool HadLeadingSpace = Identifier.hasLeadingSpace();
320     bool IsAtStartOfLine = Identifier.isAtStartOfLine();
321
322     Lex(Identifier);
323
324     // If the identifier isn't on some OTHER line, inherit the leading
325     // whitespace/first-on-a-line property of this token.  This handles
326     // stuff like "! XX," -> "! ," and "   XX," -> "    ,", when XX is
327     // empty.
328     if (!Identifier.isAtStartOfLine()) {
329       if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine);
330       if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace);
331     }
332     Identifier.setFlag(Token::LeadingEmptyMacro);
333     ++NumFastMacroExpanded;
334     return false;
335
336   } else if (MI->getNumTokens() == 1 &&
337              isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
338                                            *this)) {
339     // Otherwise, if this macro expands into a single trivially-expanded
340     // token: expand it now.  This handles common cases like
341     // "#define VAL 42".
342
343     // No need for arg info.
344     if (Args) Args->destroy(*this);
345
346     // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
347     // identifier to the expanded token.
348     bool isAtStartOfLine = Identifier.isAtStartOfLine();
349     bool hasLeadingSpace = Identifier.hasLeadingSpace();
350
351     // Replace the result token.
352     Identifier = MI->getReplacementToken(0);
353
354     // Restore the StartOfLine/LeadingSpace markers.
355     Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
356     Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
357
358     // Update the tokens location to include both its expansion and physical
359     // locations.
360     SourceLocation Loc =
361       SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
362                                    ExpansionEnd,Identifier.getLength());
363     Identifier.setLocation(Loc);
364
365     // If this is a disabled macro or #define X X, we must mark the result as
366     // unexpandable.
367     if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
368       if (MacroInfo *NewMI = getMacroInfo(NewII))
369         if (!NewMI->isEnabled() || NewMI == MI) {
370           Identifier.setFlag(Token::DisableExpand);
371           // Don't warn for "#define X X" like "#define bool bool" from
372           // stdbool.h.
373           if (NewMI != MI || MI->isFunctionLike())
374             Diag(Identifier, diag::pp_disabled_macro_expansion);
375         }
376     }
377
378     // Since this is not an identifier token, it can't be macro expanded, so
379     // we're done.
380     ++NumFastMacroExpanded;
381     return false;
382   }
383
384   // Start expanding the macro.
385   EnterMacro(Identifier, ExpansionEnd, MI, Args);
386
387   // Now that the macro is at the top of the include stack, ask the
388   // preprocessor to read the next token from it.
389   Lex(Identifier);
390   return false;
391 }
392
393 /// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
394 /// token is the '(' of the macro, this method is invoked to read all of the
395 /// actual arguments specified for the macro invocation.  This returns null on
396 /// error.
397 MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
398                                                    MacroInfo *MI,
399                                                    SourceLocation &MacroEnd) {
400   // The number of fixed arguments to parse.
401   unsigned NumFixedArgsLeft = MI->getNumArgs();
402   bool isVariadic = MI->isVariadic();
403
404   // Outer loop, while there are more arguments, keep reading them.
405   Token Tok;
406
407   // Read arguments as unexpanded tokens.  This avoids issues, e.g., where
408   // an argument value in a macro could expand to ',' or '(' or ')'.
409   LexUnexpandedToken(Tok);
410   assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
411
412   // ArgTokens - Build up a list of tokens that make up each argument.  Each
413   // argument is separated by an EOF token.  Use a SmallVector so we can avoid
414   // heap allocations in the common case.
415   SmallVector<Token, 64> ArgTokens;
416   bool ContainsCodeCompletionTok = false;
417
418   unsigned NumActuals = 0;
419   while (Tok.isNot(tok::r_paren)) {
420     if (ContainsCodeCompletionTok && (Tok.is(tok::eof) || Tok.is(tok::eod)))
421       break;
422
423     assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
424            "only expect argument separators here");
425
426     unsigned ArgTokenStart = ArgTokens.size();
427     SourceLocation ArgStartLoc = Tok.getLocation();
428
429     // C99 6.10.3p11: Keep track of the number of l_parens we have seen.  Note
430     // that we already consumed the first one.
431     unsigned NumParens = 0;
432
433     while (1) {
434       // Read arguments as unexpanded tokens.  This avoids issues, e.g., where
435       // an argument value in a macro could expand to ',' or '(' or ')'.
436       LexUnexpandedToken(Tok);
437
438       if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n"
439         if (!ContainsCodeCompletionTok) {
440           Diag(MacroName, diag::err_unterm_macro_invoc);
441           Diag(MI->getDefinitionLoc(), diag::note_macro_here)
442             << MacroName.getIdentifierInfo();
443           // Do not lose the EOF/EOD.  Return it to the client.
444           MacroName = Tok;
445           return 0;
446         } else {
447           // Do not lose the EOF/EOD.
448           Token *Toks = new Token[1];
449           Toks[0] = Tok;
450           EnterTokenStream(Toks, 1, true, true);
451           break;
452         }
453       } else if (Tok.is(tok::r_paren)) {
454         // If we found the ) token, the macro arg list is done.
455         if (NumParens-- == 0) {
456           MacroEnd = Tok.getLocation();
457           break;
458         }
459       } else if (Tok.is(tok::l_paren)) {
460         ++NumParens;
461       } else if (Tok.is(tok::comma) && NumParens == 0) {
462         // Comma ends this argument if there are more fixed arguments expected.
463         // However, if this is a variadic macro, and this is part of the
464         // variadic part, then the comma is just an argument token.
465         if (!isVariadic) break;
466         if (NumFixedArgsLeft > 1)
467           break;
468       } else if (Tok.is(tok::comment) && !KeepMacroComments) {
469         // If this is a comment token in the argument list and we're just in
470         // -C mode (not -CC mode), discard the comment.
471         continue;
472       } else if (Tok.getIdentifierInfo() != 0) {
473         // Reading macro arguments can cause macros that we are currently
474         // expanding from to be popped off the expansion stack.  Doing so causes
475         // them to be reenabled for expansion.  Here we record whether any
476         // identifiers we lex as macro arguments correspond to disabled macros.
477         // If so, we mark the token as noexpand.  This is a subtle aspect of
478         // C99 6.10.3.4p2.
479         if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
480           if (!MI->isEnabled())
481             Tok.setFlag(Token::DisableExpand);
482       } else if (Tok.is(tok::code_completion)) {
483         ContainsCodeCompletionTok = true;
484         if (CodeComplete)
485           CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
486                                                   MI, NumActuals);
487         // Don't mark that we reached the code-completion point because the
488         // parser is going to handle the token and there will be another
489         // code-completion callback.
490       }
491
492       ArgTokens.push_back(Tok);
493     }
494
495     // If this was an empty argument list foo(), don't add this as an empty
496     // argument.
497     if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
498       break;
499
500     // If this is not a variadic macro, and too many args were specified, emit
501     // an error.
502     if (!isVariadic && NumFixedArgsLeft == 0) {
503       if (ArgTokens.size() != ArgTokenStart)
504         ArgStartLoc = ArgTokens[ArgTokenStart].getLocation();
505
506       if (!ContainsCodeCompletionTok) {
507         // Emit the diagnostic at the macro name in case there is a missing ).
508         // Emitting it at the , could be far away from the macro name.
509         Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc);
510         Diag(MI->getDefinitionLoc(), diag::note_macro_here)
511           << MacroName.getIdentifierInfo();
512         return 0;
513       }
514     }
515
516     // Empty arguments are standard in C99 and C++0x, and are supported as an extension in
517     // other modes.
518     if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99)
519       Diag(Tok, LangOpts.CPlusPlus11 ?
520            diag::warn_cxx98_compat_empty_fnmacro_arg :
521            diag::ext_empty_fnmacro_arg);
522
523     // Add a marker EOF token to the end of the token list for this argument.
524     Token EOFTok;
525     EOFTok.startToken();
526     EOFTok.setKind(tok::eof);
527     EOFTok.setLocation(Tok.getLocation());
528     EOFTok.setLength(0);
529     ArgTokens.push_back(EOFTok);
530     ++NumActuals;
531     if (!ContainsCodeCompletionTok || NumFixedArgsLeft != 0) {
532       assert(NumFixedArgsLeft != 0 && "Too many arguments parsed");
533       --NumFixedArgsLeft;
534     }
535   }
536
537   // Okay, we either found the r_paren.  Check to see if we parsed too few
538   // arguments.
539   unsigned MinArgsExpected = MI->getNumArgs();
540
541   // See MacroArgs instance var for description of this.
542   bool isVarargsElided = false;
543
544   if (ContainsCodeCompletionTok) {
545     // Recover from not-fully-formed macro invocation during code-completion.
546     Token EOFTok;
547     EOFTok.startToken();
548     EOFTok.setKind(tok::eof);
549     EOFTok.setLocation(Tok.getLocation());
550     EOFTok.setLength(0);
551     for (; NumActuals < MinArgsExpected; ++NumActuals)
552       ArgTokens.push_back(EOFTok);
553   }
554
555   if (NumActuals < MinArgsExpected) {
556     // There are several cases where too few arguments is ok, handle them now.
557     if (NumActuals == 0 && MinArgsExpected == 1) {
558       // #define A(X)  or  #define A(...)   ---> A()
559
560       // If there is exactly one argument, and that argument is missing,
561       // then we have an empty "()" argument empty list.  This is fine, even if
562       // the macro expects one argument (the argument is just empty).
563       isVarargsElided = MI->isVariadic();
564     } else if (MI->isVariadic() &&
565                (NumActuals+1 == MinArgsExpected ||  // A(x, ...) -> A(X)
566                 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
567       // Varargs where the named vararg parameter is missing: OK as extension.
568       //   #define A(x, ...)
569       //   A("blah")
570       //
571       // If the macro contains the comma pasting extension, the diagnostic
572       // is suppressed; we know we'll get another diagnostic later.
573       if (!MI->hasCommaPasting()) {
574         Diag(Tok, diag::ext_missing_varargs_arg);
575         Diag(MI->getDefinitionLoc(), diag::note_macro_here)
576           << MacroName.getIdentifierInfo();
577       }
578
579       // Remember this occurred, allowing us to elide the comma when used for
580       // cases like:
581       //   #define A(x, foo...) blah(a, ## foo)
582       //   #define B(x, ...) blah(a, ## __VA_ARGS__)
583       //   #define C(...) blah(a, ## __VA_ARGS__)
584       //  A(x) B(x) C()
585       isVarargsElided = true;
586     } else if (!ContainsCodeCompletionTok) {
587       // Otherwise, emit the error.
588       Diag(Tok, diag::err_too_few_args_in_macro_invoc);
589       Diag(MI->getDefinitionLoc(), diag::note_macro_here)
590         << MacroName.getIdentifierInfo();
591       return 0;
592     }
593
594     // Add a marker EOF token to the end of the token list for this argument.
595     SourceLocation EndLoc = Tok.getLocation();
596     Tok.startToken();
597     Tok.setKind(tok::eof);
598     Tok.setLocation(EndLoc);
599     Tok.setLength(0);
600     ArgTokens.push_back(Tok);
601
602     // If we expect two arguments, add both as empty.
603     if (NumActuals == 0 && MinArgsExpected == 2)
604       ArgTokens.push_back(Tok);
605
606   } else if (NumActuals > MinArgsExpected && !MI->isVariadic() &&
607              !ContainsCodeCompletionTok) {
608     // Emit the diagnostic at the macro name in case there is a missing ).
609     // Emitting it at the , could be far away from the macro name.
610     Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
611     Diag(MI->getDefinitionLoc(), diag::note_macro_here)
612       << MacroName.getIdentifierInfo();
613     return 0;
614   }
615
616   return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
617 }
618
619 /// \brief Keeps macro expanded tokens for TokenLexers.
620 //
621 /// Works like a stack; a TokenLexer adds the macro expanded tokens that is
622 /// going to lex in the cache and when it finishes the tokens are removed
623 /// from the end of the cache.
624 Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
625                                               ArrayRef<Token> tokens) {
626   assert(tokLexer);
627   if (tokens.empty())
628     return 0;
629
630   size_t newIndex = MacroExpandedTokens.size();
631   bool cacheNeedsToGrow = tokens.size() >
632                       MacroExpandedTokens.capacity()-MacroExpandedTokens.size(); 
633   MacroExpandedTokens.append(tokens.begin(), tokens.end());
634
635   if (cacheNeedsToGrow) {
636     // Go through all the TokenLexers whose 'Tokens' pointer points in the
637     // buffer and update the pointers to the (potential) new buffer array.
638     for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) {
639       TokenLexer *prevLexer;
640       size_t tokIndex;
641       llvm::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i];
642       prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
643     }
644   }
645
646   MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
647   return MacroExpandedTokens.data() + newIndex;
648 }
649
650 void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
651   assert(!MacroExpandingLexersStack.empty());
652   size_t tokIndex = MacroExpandingLexersStack.back().second;
653   assert(tokIndex < MacroExpandedTokens.size());
654   // Pop the cached macro expanded tokens from the end.
655   MacroExpandedTokens.resize(tokIndex);
656   MacroExpandingLexersStack.pop_back();
657 }
658
659 /// ComputeDATE_TIME - Compute the current time, enter it into the specified
660 /// scratch buffer, then return DATELoc/TIMELoc locations with the position of
661 /// the identifier tokens inserted.
662 static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
663                              Preprocessor &PP) {
664   time_t TT = time(0);
665   struct tm *TM = localtime(&TT);
666
667   static const char * const Months[] = {
668     "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
669   };
670
671   {
672     SmallString<32> TmpBuffer;
673     llvm::raw_svector_ostream TmpStream(TmpBuffer);
674     TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
675                               TM->tm_mday, TM->tm_year + 1900);
676     Token TmpTok;
677     TmpTok.startToken();
678     PP.CreateString(TmpStream.str(), TmpTok);
679     DATELoc = TmpTok.getLocation();
680   }
681
682   {
683     SmallString<32> TmpBuffer;
684     llvm::raw_svector_ostream TmpStream(TmpBuffer);
685     TmpStream << llvm::format("\"%02d:%02d:%02d\"",
686                               TM->tm_hour, TM->tm_min, TM->tm_sec);
687     Token TmpTok;
688     TmpTok.startToken();
689     PP.CreateString(TmpStream.str(), TmpTok);
690     TIMELoc = TmpTok.getLocation();
691   }
692 }
693
694
695 /// HasFeature - Return true if we recognize and implement the feature
696 /// specified by the identifier as a standard language feature.
697 static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
698   const LangOptions &LangOpts = PP.getLangOpts();
699   StringRef Feature = II->getName();
700
701   // Normalize the feature name, __foo__ becomes foo.
702   if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4)
703     Feature = Feature.substr(2, Feature.size() - 4);
704
705   return llvm::StringSwitch<bool>(Feature)
706            .Case("address_sanitizer", LangOpts.Sanitize.Address)
707            .Case("attribute_analyzer_noreturn", true)
708            .Case("attribute_availability", true)
709            .Case("attribute_availability_with_message", true)
710            .Case("attribute_cf_returns_not_retained", true)
711            .Case("attribute_cf_returns_retained", true)
712            .Case("attribute_deprecated_with_message", true)
713            .Case("attribute_ext_vector_type", true)
714            .Case("attribute_ns_returns_not_retained", true)
715            .Case("attribute_ns_returns_retained", true)
716            .Case("attribute_ns_consumes_self", true)
717            .Case("attribute_ns_consumed", true)
718            .Case("attribute_cf_consumed", true)
719            .Case("attribute_objc_ivar_unused", true)
720            .Case("attribute_objc_method_family", true)
721            .Case("attribute_overloadable", true)
722            .Case("attribute_unavailable_with_message", true)
723            .Case("attribute_unused_on_fields", true)
724            .Case("blocks", LangOpts.Blocks)
725            .Case("cxx_exceptions", LangOpts.Exceptions)
726            .Case("cxx_rtti", LangOpts.RTTI)
727            .Case("enumerator_attributes", true)
728            .Case("memory_sanitizer", LangOpts.Sanitize.Memory)
729            .Case("thread_sanitizer", LangOpts.Sanitize.Thread)
730            // Objective-C features
731            .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
732            .Case("objc_arc", LangOpts.ObjCAutoRefCount)
733            .Case("objc_arc_weak", LangOpts.ObjCARCWeak)
734            .Case("objc_default_synthesize_properties", LangOpts.ObjC2)
735            .Case("objc_fixed_enum", LangOpts.ObjC2)
736            .Case("objc_instancetype", LangOpts.ObjC2)
737            .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules)
738            .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile())
739            .Case("objc_property_explicit_atomic", true) // Does clang support explicit "atomic" keyword?
740            .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport())
741            .Case("ownership_holds", true)
742            .Case("ownership_returns", true)
743            .Case("ownership_takes", true)
744            .Case("objc_bool", true)
745            .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile())
746            .Case("objc_array_literals", LangOpts.ObjC2)
747            .Case("objc_dictionary_literals", LangOpts.ObjC2)
748            .Case("objc_boxed_expressions", LangOpts.ObjC2)
749            .Case("arc_cf_code_audited", true)
750            // C11 features
751            .Case("c_alignas", LangOpts.C11)
752            .Case("c_atomic", LangOpts.C11)
753            .Case("c_generic_selections", LangOpts.C11)
754            .Case("c_static_assert", LangOpts.C11)
755            .Case("c_thread_local", 
756                  LangOpts.C11 && PP.getTargetInfo().isTLSSupported())
757            // C++11 features
758            .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus11)
759            .Case("cxx_alias_templates", LangOpts.CPlusPlus11)
760            .Case("cxx_alignas", LangOpts.CPlusPlus11)
761            .Case("cxx_atomic", LangOpts.CPlusPlus11)
762            .Case("cxx_attributes", LangOpts.CPlusPlus11)
763            .Case("cxx_auto_type", LangOpts.CPlusPlus11)
764            .Case("cxx_constexpr", LangOpts.CPlusPlus11)
765            .Case("cxx_decltype", LangOpts.CPlusPlus11)
766            .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus11)
767            .Case("cxx_default_function_template_args", LangOpts.CPlusPlus11)
768            .Case("cxx_defaulted_functions", LangOpts.CPlusPlus11)
769            .Case("cxx_delegating_constructors", LangOpts.CPlusPlus11)
770            .Case("cxx_deleted_functions", LangOpts.CPlusPlus11)
771            .Case("cxx_explicit_conversions", LangOpts.CPlusPlus11)
772            .Case("cxx_generalized_initializers", LangOpts.CPlusPlus11)
773            .Case("cxx_implicit_moves", LangOpts.CPlusPlus11)
774            .Case("cxx_inheriting_constructors", LangOpts.CPlusPlus11)
775            .Case("cxx_inline_namespaces", LangOpts.CPlusPlus11)
776            .Case("cxx_lambdas", LangOpts.CPlusPlus11)
777            .Case("cxx_local_type_template_args", LangOpts.CPlusPlus11)
778            .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus11)
779            .Case("cxx_noexcept", LangOpts.CPlusPlus11)
780            .Case("cxx_nullptr", LangOpts.CPlusPlus11)
781            .Case("cxx_override_control", LangOpts.CPlusPlus11)
782            .Case("cxx_range_for", LangOpts.CPlusPlus11)
783            .Case("cxx_raw_string_literals", LangOpts.CPlusPlus11)
784            .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus11)
785            .Case("cxx_rvalue_references", LangOpts.CPlusPlus11)
786            .Case("cxx_strong_enums", LangOpts.CPlusPlus11)
787            .Case("cxx_static_assert", LangOpts.CPlusPlus11)
788            .Case("cxx_thread_local", 
789                  LangOpts.CPlusPlus11 && PP.getTargetInfo().isTLSSupported())
790            .Case("cxx_trailing_return", LangOpts.CPlusPlus11)
791            .Case("cxx_unicode_literals", LangOpts.CPlusPlus11)
792            .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus11)
793            .Case("cxx_user_literals", LangOpts.CPlusPlus11)
794            .Case("cxx_variadic_templates", LangOpts.CPlusPlus11)
795            // C++1y features
796            .Case("cxx_binary_literals", LangOpts.CPlusPlus1y)
797            //.Case("cxx_contextual_conversions", LangOpts.CPlusPlus1y)
798            //.Case("cxx_generalized_capture", LangOpts.CPlusPlus1y)
799            //.Case("cxx_generic_lambda", LangOpts.CPlusPlus1y)
800            //.Case("cxx_relaxed_constexpr", LangOpts.CPlusPlus1y)
801            //.Case("cxx_return_type_deduction", LangOpts.CPlusPlus1y)
802            //.Case("cxx_runtime_array", LangOpts.CPlusPlus1y)
803            .Case("cxx_aggregate_nsdmi", LangOpts.CPlusPlus1y)
804            //.Case("cxx_variable_templates", LangOpts.CPlusPlus1y)
805            // Type traits
806            .Case("has_nothrow_assign", LangOpts.CPlusPlus)
807            .Case("has_nothrow_copy", LangOpts.CPlusPlus)
808            .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
809            .Case("has_trivial_assign", LangOpts.CPlusPlus)
810            .Case("has_trivial_copy", LangOpts.CPlusPlus)
811            .Case("has_trivial_constructor", LangOpts.CPlusPlus)
812            .Case("has_trivial_destructor", LangOpts.CPlusPlus)
813            .Case("has_virtual_destructor", LangOpts.CPlusPlus)
814            .Case("is_abstract", LangOpts.CPlusPlus)
815            .Case("is_base_of", LangOpts.CPlusPlus)
816            .Case("is_class", LangOpts.CPlusPlus)
817            .Case("is_convertible_to", LangOpts.CPlusPlus)
818            .Case("is_empty", LangOpts.CPlusPlus)
819            .Case("is_enum", LangOpts.CPlusPlus)
820            .Case("is_final", LangOpts.CPlusPlus)
821            .Case("is_literal", LangOpts.CPlusPlus)
822            .Case("is_standard_layout", LangOpts.CPlusPlus)
823            .Case("is_pod", LangOpts.CPlusPlus)
824            .Case("is_polymorphic", LangOpts.CPlusPlus)
825            .Case("is_trivial", LangOpts.CPlusPlus)
826            .Case("is_trivially_assignable", LangOpts.CPlusPlus)
827            .Case("is_trivially_constructible", LangOpts.CPlusPlus)
828            .Case("is_trivially_copyable", LangOpts.CPlusPlus)
829            .Case("is_union", LangOpts.CPlusPlus)
830            .Case("modules", LangOpts.Modules)
831            .Case("tls", PP.getTargetInfo().isTLSSupported())
832            .Case("underlying_type", LangOpts.CPlusPlus)
833            .Default(false);
834 }
835
836 /// HasExtension - Return true if we recognize and implement the feature
837 /// specified by the identifier, either as an extension or a standard language
838 /// feature.
839 static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) {
840   if (HasFeature(PP, II))
841     return true;
842
843   // If the use of an extension results in an error diagnostic, extensions are
844   // effectively unavailable, so just return false here.
845   if (PP.getDiagnostics().getExtensionHandlingBehavior() ==
846       DiagnosticsEngine::Ext_Error)
847     return false;
848
849   const LangOptions &LangOpts = PP.getLangOpts();
850   StringRef Extension = II->getName();
851
852   // Normalize the extension name, __foo__ becomes foo.
853   if (Extension.startswith("__") && Extension.endswith("__") &&
854       Extension.size() >= 4)
855     Extension = Extension.substr(2, Extension.size() - 4);
856
857   // Because we inherit the feature list from HasFeature, this string switch
858   // must be less restrictive than HasFeature's.
859   return llvm::StringSwitch<bool>(Extension)
860            // C11 features supported by other languages as extensions.
861            .Case("c_alignas", true)
862            .Case("c_atomic", true)
863            .Case("c_generic_selections", true)
864            .Case("c_static_assert", true)
865            // C++11 features supported by other languages as extensions.
866            .Case("cxx_atomic", LangOpts.CPlusPlus)
867            .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
868            .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
869            .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
870            .Case("cxx_local_type_template_args", LangOpts.CPlusPlus)
871            .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
872            .Case("cxx_override_control", LangOpts.CPlusPlus)
873            .Case("cxx_range_for", LangOpts.CPlusPlus)
874            .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
875            .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
876            // C++1y features supported by other languages as extensions.
877            .Case("cxx_binary_literals", true)
878            .Default(false);
879 }
880
881 /// HasAttribute -  Return true if we recognize and implement the attribute
882 /// specified by the given identifier.
883 static bool HasAttribute(const IdentifierInfo *II) {
884   StringRef Name = II->getName();
885   // Normalize the attribute name, __foo__ becomes foo.
886   if (Name.startswith("__") && Name.endswith("__") && Name.size() >= 4)
887     Name = Name.substr(2, Name.size() - 4);
888
889   // FIXME: Do we need to handle namespaces here?
890   return llvm::StringSwitch<bool>(Name)
891 #include "clang/Lex/AttrSpellings.inc"
892         .Default(false);
893 }
894
895 /// EvaluateHasIncludeCommon - Process a '__has_include("path")'
896 /// or '__has_include_next("path")' expression.
897 /// Returns true if successful.
898 static bool EvaluateHasIncludeCommon(Token &Tok,
899                                      IdentifierInfo *II, Preprocessor &PP,
900                                      const DirectoryLookup *LookupFrom) {
901   // Save the location of the current token.  If a '(' is later found, use
902   // that location.  If not, use the end of this location instead.
903   SourceLocation LParenLoc = Tok.getLocation();
904
905   // These expressions are only allowed within a preprocessor directive.
906   if (!PP.isParsingIfOrElifDirective()) {
907     PP.Diag(LParenLoc, diag::err_pp_directive_required) << II->getName();
908     return false;
909   }
910
911   // Get '('.
912   PP.LexNonComment(Tok);
913
914   // Ensure we have a '('.
915   if (Tok.isNot(tok::l_paren)) {
916     // No '(', use end of last token.
917     LParenLoc = PP.getLocForEndOfToken(LParenLoc);
918     PP.Diag(LParenLoc, diag::err_pp_missing_lparen) << II->getName();
919     // If the next token looks like a filename or the start of one,
920     // assume it is and process it as such.
921     if (!Tok.is(tok::angle_string_literal) && !Tok.is(tok::string_literal) &&
922         !Tok.is(tok::less))
923       return false;
924   } else {
925     // Save '(' location for possible missing ')' message.
926     LParenLoc = Tok.getLocation();
927
928     if (PP.getCurrentLexer()) {
929       // Get the file name.
930       PP.getCurrentLexer()->LexIncludeFilename(Tok);
931     } else {
932       // We're in a macro, so we can't use LexIncludeFilename; just
933       // grab the next token.
934       PP.Lex(Tok);
935     }
936   }
937
938   // Reserve a buffer to get the spelling.
939   SmallString<128> FilenameBuffer;
940   StringRef Filename;
941   SourceLocation EndLoc;
942   
943   switch (Tok.getKind()) {
944   case tok::eod:
945     // If the token kind is EOD, the error has already been diagnosed.
946     return false;
947
948   case tok::angle_string_literal:
949   case tok::string_literal: {
950     bool Invalid = false;
951     Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
952     if (Invalid)
953       return false;
954     break;
955   }
956
957   case tok::less:
958     // This could be a <foo/bar.h> file coming from a macro expansion.  In this
959     // case, glue the tokens together into FilenameBuffer and interpret those.
960     FilenameBuffer.push_back('<');
961     if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc)) {
962       // Let the caller know a <eod> was found by changing the Token kind.
963       Tok.setKind(tok::eod);
964       return false;   // Found <eod> but no ">"?  Diagnostic already emitted.
965     }
966     Filename = FilenameBuffer.str();
967     break;
968   default:
969     PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
970     return false;
971   }
972
973   SourceLocation FilenameLoc = Tok.getLocation();
974
975   // Get ')'.
976   PP.LexNonComment(Tok);
977
978   // Ensure we have a trailing ).
979   if (Tok.isNot(tok::r_paren)) {
980     PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_missing_rparen)
981         << II->getName();
982     PP.Diag(LParenLoc, diag::note_matching) << "(";
983     return false;
984   }
985
986   bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
987   // If GetIncludeFilenameSpelling set the start ptr to null, there was an
988   // error.
989   if (Filename.empty())
990     return false;
991
992   // Search include directories.
993   const DirectoryLookup *CurDir;
994   const FileEntry *File =
995       PP.LookupFile(Filename, isAngled, LookupFrom, CurDir, NULL, NULL, NULL);
996
997   // Get the result value.  A result of true means the file exists.
998   return File != 0;
999 }
1000
1001 /// EvaluateHasInclude - Process a '__has_include("path")' expression.
1002 /// Returns true if successful.
1003 static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
1004                                Preprocessor &PP) {
1005   return EvaluateHasIncludeCommon(Tok, II, PP, NULL);
1006 }
1007
1008 /// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
1009 /// Returns true if successful.
1010 static bool EvaluateHasIncludeNext(Token &Tok,
1011                                    IdentifierInfo *II, Preprocessor &PP) {
1012   // __has_include_next is like __has_include, except that we start
1013   // searching after the current found directory.  If we can't do this,
1014   // issue a diagnostic.
1015   const DirectoryLookup *Lookup = PP.GetCurDirLookup();
1016   if (PP.isInPrimaryFile()) {
1017     Lookup = 0;
1018     PP.Diag(Tok, diag::pp_include_next_in_primary);
1019   } else if (Lookup == 0) {
1020     PP.Diag(Tok, diag::pp_include_next_absolute_path);
1021   } else {
1022     // Start looking up in the next directory.
1023     ++Lookup;
1024   }
1025
1026   return EvaluateHasIncludeCommon(Tok, II, PP, Lookup);
1027 }
1028
1029 /// \brief Process __building_module(identifier) expression.
1030 /// \returns true if we are building the named module, false otherwise.
1031 static bool EvaluateBuildingModule(Token &Tok,
1032                                    IdentifierInfo *II, Preprocessor &PP) {
1033   // Get '('.
1034   PP.LexNonComment(Tok);
1035
1036   // Ensure we have a '('.
1037   if (Tok.isNot(tok::l_paren)) {
1038     PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName();
1039     return false;
1040   }
1041
1042   // Save '(' location for possible missing ')' message.
1043   SourceLocation LParenLoc = Tok.getLocation();
1044
1045   // Get the module name.
1046   PP.LexNonComment(Tok);
1047
1048   // Ensure that we have an identifier.
1049   if (Tok.isNot(tok::identifier)) {
1050     PP.Diag(Tok.getLocation(), diag::err_expected_id_building_module);
1051     return false;
1052   }
1053
1054   bool Result
1055     = Tok.getIdentifierInfo()->getName() == PP.getLangOpts().CurrentModule;
1056
1057   // Get ')'.
1058   PP.LexNonComment(Tok);
1059
1060   // Ensure we have a trailing ).
1061   if (Tok.isNot(tok::r_paren)) {
1062     PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName();
1063     PP.Diag(LParenLoc, diag::note_matching) << "(";
1064     return false;
1065   }
1066
1067   return Result;
1068 }
1069
1070 /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1071 /// as a builtin macro, handle it and return the next token as 'Tok'.
1072 void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
1073   // Figure out which token this is.
1074   IdentifierInfo *II = Tok.getIdentifierInfo();
1075   assert(II && "Can't be a macro without id info!");
1076
1077   // If this is an _Pragma or Microsoft __pragma directive, expand it,
1078   // invoke the pragma handler, then lex the token after it.
1079   if (II == Ident_Pragma)
1080     return Handle_Pragma(Tok);
1081   else if (II == Ident__pragma) // in non-MS mode this is null
1082     return HandleMicrosoft__pragma(Tok);
1083
1084   ++NumBuiltinMacroExpanded;
1085
1086   SmallString<128> TmpBuffer;
1087   llvm::raw_svector_ostream OS(TmpBuffer);
1088
1089   // Set up the return result.
1090   Tok.setIdentifierInfo(0);
1091   Tok.clearFlag(Token::NeedsCleaning);
1092
1093   if (II == Ident__LINE__) {
1094     // C99 6.10.8: "__LINE__: The presumed line number (within the current
1095     // source file) of the current source line (an integer constant)".  This can
1096     // be affected by #line.
1097     SourceLocation Loc = Tok.getLocation();
1098
1099     // Advance to the location of the first _, this might not be the first byte
1100     // of the token if it starts with an escaped newline.
1101     Loc = AdvanceToTokenCharacter(Loc, 0);
1102
1103     // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
1104     // a macro expansion.  This doesn't matter for object-like macros, but
1105     // can matter for a function-like macro that expands to contain __LINE__.
1106     // Skip down through expansion points until we find a file loc for the
1107     // end of the expansion history.
1108     Loc = SourceMgr.getExpansionRange(Loc).second;
1109     PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
1110
1111     // __LINE__ expands to a simple numeric value.
1112     OS << (PLoc.isValid()? PLoc.getLine() : 1);
1113     Tok.setKind(tok::numeric_constant);
1114   } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
1115     // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
1116     // character string literal)". This can be affected by #line.
1117     PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1118
1119     // __BASE_FILE__ is a GNU extension that returns the top of the presumed
1120     // #include stack instead of the current file.
1121     if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
1122       SourceLocation NextLoc = PLoc.getIncludeLoc();
1123       while (NextLoc.isValid()) {
1124         PLoc = SourceMgr.getPresumedLoc(NextLoc);
1125         if (PLoc.isInvalid())
1126           break;
1127         
1128         NextLoc = PLoc.getIncludeLoc();
1129       }
1130     }
1131
1132     // Escape this filename.  Turn '\' -> '\\' '"' -> '\"'
1133     SmallString<128> FN;
1134     if (PLoc.isValid()) {
1135       FN += PLoc.getFilename();
1136       Lexer::Stringify(FN);
1137       OS << '"' << FN.str() << '"';
1138     }
1139     Tok.setKind(tok::string_literal);
1140   } else if (II == Ident__DATE__) {
1141     if (!DATELoc.isValid())
1142       ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1143     Tok.setKind(tok::string_literal);
1144     Tok.setLength(strlen("\"Mmm dd yyyy\""));
1145     Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
1146                                                  Tok.getLocation(),
1147                                                  Tok.getLength()));
1148     return;
1149   } else if (II == Ident__TIME__) {
1150     if (!TIMELoc.isValid())
1151       ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1152     Tok.setKind(tok::string_literal);
1153     Tok.setLength(strlen("\"hh:mm:ss\""));
1154     Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
1155                                                  Tok.getLocation(),
1156                                                  Tok.getLength()));
1157     return;
1158   } else if (II == Ident__INCLUDE_LEVEL__) {
1159     // Compute the presumed include depth of this token.  This can be affected
1160     // by GNU line markers.
1161     unsigned Depth = 0;
1162
1163     PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1164     if (PLoc.isValid()) {
1165       PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1166       for (; PLoc.isValid(); ++Depth)
1167         PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1168     }
1169
1170     // __INCLUDE_LEVEL__ expands to a simple numeric value.
1171     OS << Depth;
1172     Tok.setKind(tok::numeric_constant);
1173   } else if (II == Ident__TIMESTAMP__) {
1174     // MSVC, ICC, GCC, VisualAge C++ extension.  The generated string should be
1175     // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1176
1177     // Get the file that we are lexing out of.  If we're currently lexing from
1178     // a macro, dig into the include stack.
1179     const FileEntry *CurFile = 0;
1180     PreprocessorLexer *TheLexer = getCurrentFileLexer();
1181
1182     if (TheLexer)
1183       CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
1184
1185     const char *Result;
1186     if (CurFile) {
1187       time_t TT = CurFile->getModificationTime();
1188       struct tm *TM = localtime(&TT);
1189       Result = asctime(TM);
1190     } else {
1191       Result = "??? ??? ?? ??:??:?? ????\n";
1192     }
1193     // Surround the string with " and strip the trailing newline.
1194     OS << '"' << StringRef(Result, strlen(Result)-1) << '"';
1195     Tok.setKind(tok::string_literal);
1196   } else if (II == Ident__COUNTER__) {
1197     // __COUNTER__ expands to a simple numeric value.
1198     OS << CounterValue++;
1199     Tok.setKind(tok::numeric_constant);
1200   } else if (II == Ident__has_feature   ||
1201              II == Ident__has_extension ||
1202              II == Ident__has_builtin   ||
1203              II == Ident__has_attribute) {
1204     // The argument to these builtins should be a parenthesized identifier.
1205     SourceLocation StartLoc = Tok.getLocation();
1206
1207     bool IsValid = false;
1208     IdentifierInfo *FeatureII = 0;
1209
1210     // Read the '('.
1211     LexUnexpandedToken(Tok);
1212     if (Tok.is(tok::l_paren)) {
1213       // Read the identifier
1214       LexUnexpandedToken(Tok);
1215       if (Tok.is(tok::identifier) || Tok.is(tok::kw_const)) {
1216         FeatureII = Tok.getIdentifierInfo();
1217
1218         // Read the ')'.
1219         LexUnexpandedToken(Tok);
1220         if (Tok.is(tok::r_paren))
1221           IsValid = true;
1222       }
1223     }
1224
1225     bool Value = false;
1226     if (!IsValid)
1227       Diag(StartLoc, diag::err_feature_check_malformed);
1228     else if (II == Ident__has_builtin) {
1229       // Check for a builtin is trivial.
1230       Value = FeatureII->getBuiltinID() != 0;
1231     } else if (II == Ident__has_attribute)
1232       Value = HasAttribute(FeatureII);
1233     else if (II == Ident__has_extension)
1234       Value = HasExtension(*this, FeatureII);
1235     else {
1236       assert(II == Ident__has_feature && "Must be feature check");
1237       Value = HasFeature(*this, FeatureII);
1238     }
1239
1240     OS << (int)Value;
1241     if (IsValid)
1242       Tok.setKind(tok::numeric_constant);
1243   } else if (II == Ident__has_include ||
1244              II == Ident__has_include_next) {
1245     // The argument to these two builtins should be a parenthesized
1246     // file name string literal using angle brackets (<>) or
1247     // double-quotes ("").
1248     bool Value;
1249     if (II == Ident__has_include)
1250       Value = EvaluateHasInclude(Tok, II, *this);
1251     else
1252       Value = EvaluateHasIncludeNext(Tok, II, *this);
1253     OS << (int)Value;
1254     if (Tok.is(tok::r_paren))
1255       Tok.setKind(tok::numeric_constant);
1256   } else if (II == Ident__has_warning) {
1257     // The argument should be a parenthesized string literal.
1258     // The argument to these builtins should be a parenthesized identifier.
1259     SourceLocation StartLoc = Tok.getLocation();    
1260     bool IsValid = false;
1261     bool Value = false;
1262     // Read the '('.
1263     LexUnexpandedToken(Tok);
1264     do {
1265       if (Tok.isNot(tok::l_paren)) {
1266         Diag(StartLoc, diag::err_warning_check_malformed);
1267         break;
1268       }
1269
1270       LexUnexpandedToken(Tok);
1271       std::string WarningName;
1272       SourceLocation StrStartLoc = Tok.getLocation();
1273       if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",
1274                                   /*MacroExpansion=*/false)) {
1275         // Eat tokens until ')'.
1276         while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) &&
1277                Tok.isNot(tok::eof))
1278           LexUnexpandedToken(Tok);
1279         break;
1280       }
1281
1282       // Is the end a ')'?
1283       if (!(IsValid = Tok.is(tok::r_paren))) {
1284         Diag(StartLoc, diag::err_warning_check_malformed);
1285         break;
1286       }
1287
1288       if (WarningName.size() < 3 || WarningName[0] != '-' ||
1289           WarningName[1] != 'W') {
1290         Diag(StrStartLoc, diag::warn_has_warning_invalid_option);
1291         break;
1292       }
1293
1294       // Finally, check if the warning flags maps to a diagnostic group.
1295       // We construct a SmallVector here to talk to getDiagnosticIDs().
1296       // Although we don't use the result, this isn't a hot path, and not
1297       // worth special casing.
1298       SmallVector<diag::kind, 10> Diags;
1299       Value = !getDiagnostics().getDiagnosticIDs()->
1300         getDiagnosticsInGroup(WarningName.substr(2), Diags);
1301     } while (false);
1302
1303     OS << (int)Value;
1304     if (IsValid)
1305       Tok.setKind(tok::numeric_constant);
1306   } else if (II == Ident__building_module) {
1307     // The argument to this builtin should be an identifier. The
1308     // builtin evaluates to 1 when that identifier names the module we are
1309     // currently building.
1310     OS << (int)EvaluateBuildingModule(Tok, II, *this);
1311     Tok.setKind(tok::numeric_constant);
1312   } else if (II == Ident__MODULE__) {
1313     // The current module as an identifier.
1314     OS << getLangOpts().CurrentModule;
1315     IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);
1316     Tok.setIdentifierInfo(ModuleII);
1317     Tok.setKind(ModuleII->getTokenID());
1318   } else {
1319     llvm_unreachable("Unknown identifier!");
1320   }
1321   CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation());
1322 }
1323
1324 void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
1325   // If the 'used' status changed, and the macro requires 'unused' warning,
1326   // remove its SourceLocation from the warn-for-unused-macro locations.
1327   if (MI->isWarnIfUnused() && !MI->isUsed())
1328     WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1329   MI->setIsUsed(true);
1330 }