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