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