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