clang  9.0.0svn
PPMacroExpansion.cpp
Go to the documentation of this file.
1 //===--- MacroExpansion.cpp - Top level Macro Expansion -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the top level handling of macro expansion for the
10 // preprocessor.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Basic/Attributes.h"
17 #include "clang/Basic/LLVM.h"
21 #include "clang/Basic/TargetInfo.h"
25 #include "clang/Lex/HeaderSearch.h"
27 #include "clang/Lex/MacroArgs.h"
28 #include "clang/Lex/MacroInfo.h"
29 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Lex/Token.h"
32 #include "llvm/ADT/ArrayRef.h"
33 #include "llvm/ADT/DenseMap.h"
34 #include "llvm/ADT/DenseSet.h"
35 #include "llvm/ADT/FoldingSet.h"
36 #include "llvm/ADT/None.h"
37 #include "llvm/ADT/Optional.h"
38 #include "llvm/ADT/SmallString.h"
39 #include "llvm/ADT/SmallVector.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/ADT/StringRef.h"
42 #include "llvm/ADT/StringSwitch.h"
43 #include "llvm/Support/Casting.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/Format.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include <algorithm>
48 #include <cassert>
49 #include <cstddef>
50 #include <cstring>
51 #include <ctime>
52 #include <string>
53 #include <tuple>
54 #include <utility>
55 
56 using namespace clang;
57 
60  if (!II->hadMacroDefinition())
61  return nullptr;
62  auto Pos = CurSubmoduleState->Macros.find(II);
63  return Pos == CurSubmoduleState->Macros.end() ? nullptr
64  : Pos->second.getLatest();
65 }
66 
68  assert(MD && "MacroDirective should be non-zero!");
69  assert(!MD->getPrevious() && "Already attached to a MacroDirective history.");
70 
71  MacroState &StoredMD = CurSubmoduleState->Macros[II];
72  auto *OldMD = StoredMD.getLatest();
73  MD->setPrevious(OldMD);
74  StoredMD.setLatest(MD);
75  StoredMD.overrideActiveModuleMacros(*this, II);
76 
77  if (needModuleMacros()) {
78  // Track that we created a new macro directive, so we know we should
79  // consider building a ModuleMacro for it when we get to the end of
80  // the module.
81  PendingModuleMacroNames.push_back(II);
82  }
83 
84  // Set up the identifier as having associated macro history.
85  II->setHasMacroDefinition(true);
86  if (!MD->isDefined() && LeafModuleMacros.find(II) == LeafModuleMacros.end())
87  II->setHasMacroDefinition(false);
88  if (II->isFromAST())
90 }
91 
93  MacroDirective *ED,
94  MacroDirective *MD) {
95  // Normally, when a macro is defined, it goes through appendMacroDirective()
96  // above, which chains a macro to previous defines, undefs, etc.
97  // However, in a pch, the whole macro history up to the end of the pch is
98  // stored, so ASTReader goes through this function instead.
99  // However, built-in macros are already registered in the Preprocessor
100  // ctor, and ASTWriter stops writing the macro chain at built-in macros,
101  // so in that case the chain from the pch needs to be spliced to the existing
102  // built-in.
103 
104  assert(II && MD);
105  MacroState &StoredMD = CurSubmoduleState->Macros[II];
106 
107  if (auto *OldMD = StoredMD.getLatest()) {
108  // shouldIgnoreMacro() in ASTWriter also stops at macros from the
109  // predefines buffer in module builds. However, in module builds, modules
110  // are loaded completely before predefines are processed, so StoredMD
111  // will be nullptr for them when they're loaded. StoredMD should only be
112  // non-nullptr for builtins read from a pch file.
113  assert(OldMD->getMacroInfo()->isBuiltinMacro() &&
114  "only built-ins should have an entry here");
115  assert(!OldMD->getPrevious() && "builtin should only have a single entry");
116  ED->setPrevious(OldMD);
117  StoredMD.setLatest(MD);
118  } else {
119  StoredMD = MD;
120  }
121 
122  // Setup the identifier as having associated macro history.
123  II->setHasMacroDefinition(true);
124  if (!MD->isDefined() && LeafModuleMacros.find(II) == LeafModuleMacros.end())
125  II->setHasMacroDefinition(false);
126 }
127 
129  MacroInfo *Macro,
130  ArrayRef<ModuleMacro *> Overrides,
131  bool &New) {
132  llvm::FoldingSetNodeID ID;
133  ModuleMacro::Profile(ID, Mod, II);
134 
135  void *InsertPos;
136  if (auto *MM = ModuleMacros.FindNodeOrInsertPos(ID, InsertPos)) {
137  New = false;
138  return MM;
139  }
140 
141  auto *MM = ModuleMacro::create(*this, Mod, II, Macro, Overrides);
142  ModuleMacros.InsertNode(MM, InsertPos);
143 
144  // Each overridden macro is now overridden by one more macro.
145  bool HidAny = false;
146  for (auto *O : Overrides) {
147  HidAny |= (O->NumOverriddenBy == 0);
148  ++O->NumOverriddenBy;
149  }
150 
151  // If we were the first overrider for any macro, it's no longer a leaf.
152  auto &LeafMacros = LeafModuleMacros[II];
153  if (HidAny) {
154  LeafMacros.erase(std::remove_if(LeafMacros.begin(), LeafMacros.end(),
155  [](ModuleMacro *MM) {
156  return MM->NumOverriddenBy != 0;
157  }),
158  LeafMacros.end());
159  }
160 
161  // The new macro is always a leaf macro.
162  LeafMacros.push_back(MM);
163  // The identifier now has defined macros (that may or may not be visible).
164  II->setHasMacroDefinition(true);
165 
166  New = true;
167  return MM;
168 }
169 
171  llvm::FoldingSetNodeID ID;
172  ModuleMacro::Profile(ID, Mod, II);
173 
174  void *InsertPos;
175  return ModuleMacros.FindNodeOrInsertPos(ID, InsertPos);
176 }
177 
178 void Preprocessor::updateModuleMacroInfo(const IdentifierInfo *II,
179  ModuleMacroInfo &Info) {
180  assert(Info.ActiveModuleMacrosGeneration !=
181  CurSubmoduleState->VisibleModules.getGeneration() &&
182  "don't need to update this macro name info");
183  Info.ActiveModuleMacrosGeneration =
184  CurSubmoduleState->VisibleModules.getGeneration();
185 
186  auto Leaf = LeafModuleMacros.find(II);
187  if (Leaf == LeafModuleMacros.end()) {
188  // No imported macros at all: nothing to do.
189  return;
190  }
191 
192  Info.ActiveModuleMacros.clear();
193 
194  // Every macro that's locally overridden is overridden by a visible macro.
195  llvm::DenseMap<ModuleMacro *, int> NumHiddenOverrides;
196  for (auto *O : Info.OverriddenMacros)
197  NumHiddenOverrides[O] = -1;
198 
199  // Collect all macros that are not overridden by a visible macro.
201  for (auto *LeafMM : Leaf->second) {
202  assert(LeafMM->getNumOverridingMacros() == 0 && "leaf macro overridden");
203  if (NumHiddenOverrides.lookup(LeafMM) == 0)
204  Worklist.push_back(LeafMM);
205  }
206  while (!Worklist.empty()) {
207  auto *MM = Worklist.pop_back_val();
208  if (CurSubmoduleState->VisibleModules.isVisible(MM->getOwningModule())) {
209  // We only care about collecting definitions; undefinitions only act
210  // to override other definitions.
211  if (MM->getMacroInfo())
212  Info.ActiveModuleMacros.push_back(MM);
213  } else {
214  for (auto *O : MM->overrides())
215  if ((unsigned)++NumHiddenOverrides[O] == O->getNumOverridingMacros())
216  Worklist.push_back(O);
217  }
218  }
219  // Our reverse postorder walk found the macros in reverse order.
220  std::reverse(Info.ActiveModuleMacros.begin(), Info.ActiveModuleMacros.end());
221 
222  // Determine whether the macro name is ambiguous.
223  MacroInfo *MI = nullptr;
224  bool IsSystemMacro = true;
225  bool IsAmbiguous = false;
226  if (auto *MD = Info.MD) {
227  while (MD && isa<VisibilityMacroDirective>(MD))
228  MD = MD->getPrevious();
229  if (auto *DMD = dyn_cast_or_null<DefMacroDirective>(MD)) {
230  MI = DMD->getInfo();
231  IsSystemMacro &= SourceMgr.isInSystemHeader(DMD->getLocation());
232  }
233  }
234  for (auto *Active : Info.ActiveModuleMacros) {
235  auto *NewMI = Active->getMacroInfo();
236 
237  // Before marking the macro as ambiguous, check if this is a case where
238  // both macros are in system headers. If so, we trust that the system
239  // did not get it wrong. This also handles cases where Clang's own
240  // headers have a different spelling of certain system macros:
241  // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
242  // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
243  //
244  // FIXME: Remove the defined-in-system-headers check. clang's limits.h
245  // overrides the system limits.h's macros, so there's no conflict here.
246  if (MI && NewMI != MI &&
247  !MI->isIdenticalTo(*NewMI, *this, /*Syntactically=*/true))
248  IsAmbiguous = true;
249  IsSystemMacro &= Active->getOwningModule()->IsSystem ||
250  SourceMgr.isInSystemHeader(NewMI->getDefinitionLoc());
251  MI = NewMI;
252  }
253  Info.IsAmbiguous = IsAmbiguous && !IsSystemMacro;
254 }
255 
258  auto LeafIt = LeafModuleMacros.find(II);
259  if (LeafIt != LeafModuleMacros.end())
260  Leaf = LeafIt->second;
261  const MacroState *State = nullptr;
262  auto Pos = CurSubmoduleState->Macros.find(II);
263  if (Pos != CurSubmoduleState->Macros.end())
264  State = &Pos->second;
265 
266  llvm::errs() << "MacroState " << State << " " << II->getNameStart();
267  if (State && State->isAmbiguous(*this, II))
268  llvm::errs() << " ambiguous";
269  if (State && !State->getOverriddenMacros().empty()) {
270  llvm::errs() << " overrides";
271  for (auto *O : State->getOverriddenMacros())
272  llvm::errs() << " " << O->getOwningModule()->getFullModuleName();
273  }
274  llvm::errs() << "\n";
275 
276  // Dump local macro directives.
277  for (auto *MD = State ? State->getLatest() : nullptr; MD;
278  MD = MD->getPrevious()) {
279  llvm::errs() << " ";
280  MD->dump();
281  }
282 
283  // Dump module macros.
285  for (auto *MM : State ? State->getActiveModuleMacros(*this, II) : None)
286  Active.insert(MM);
288  llvm::SmallVector<ModuleMacro *, 16> Worklist(Leaf.begin(), Leaf.end());
289  while (!Worklist.empty()) {
290  auto *MM = Worklist.pop_back_val();
291  llvm::errs() << " ModuleMacro " << MM << " "
292  << MM->getOwningModule()->getFullModuleName();
293  if (!MM->getMacroInfo())
294  llvm::errs() << " undef";
295 
296  if (Active.count(MM))
297  llvm::errs() << " active";
298  else if (!CurSubmoduleState->VisibleModules.isVisible(
299  MM->getOwningModule()))
300  llvm::errs() << " hidden";
301  else if (MM->getMacroInfo())
302  llvm::errs() << " overridden";
303 
304  if (!MM->overrides().empty()) {
305  llvm::errs() << " overrides";
306  for (auto *O : MM->overrides()) {
307  llvm::errs() << " " << O->getOwningModule()->getFullModuleName();
308  if (Visited.insert(O).second)
309  Worklist.push_back(O);
310  }
311  }
312  llvm::errs() << "\n";
313  if (auto *MI = MM->getMacroInfo()) {
314  llvm::errs() << " ";
315  MI->dump();
316  llvm::errs() << "\n";
317  }
318  }
319 }
320 
321 /// RegisterBuiltinMacro - Register the specified identifier in the identifier
322 /// table and mark it as a builtin macro to be expanded.
323 static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
324  // Get the identifier.
325  IdentifierInfo *Id = PP.getIdentifierInfo(Name);
326 
327  // Mark it as being a macro that is builtin.
329  MI->setIsBuiltinMacro();
330  PP.appendDefMacroDirective(Id, MI);
331  return Id;
332 }
333 
334 /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
335 /// identifier table.
336 void Preprocessor::RegisterBuiltinMacros() {
337  Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
338  Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
339  Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
340  Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
341  Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
342  Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
343 
344  // C++ Standing Document Extensions.
345  if (LangOpts.CPlusPlus)
346  Ident__has_cpp_attribute =
347  RegisterBuiltinMacro(*this, "__has_cpp_attribute");
348  else
349  Ident__has_cpp_attribute = nullptr;
350 
351  // GCC Extensions.
352  Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
353  Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
354  Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
355 
356  // Microsoft Extensions.
357  if (LangOpts.MicrosoftExt) {
358  Ident__identifier = RegisterBuiltinMacro(*this, "__identifier");
359  Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
360  } else {
361  Ident__identifier = nullptr;
362  Ident__pragma = nullptr;
363  }
364 
365  // Clang Extensions.
366  Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
367  Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension");
368  Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
369  Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
370  Ident__has_c_attribute = RegisterBuiltinMacro(*this, "__has_c_attribute");
371  Ident__has_declspec = RegisterBuiltinMacro(*this, "__has_declspec_attribute");
372  Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
373  Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
374  Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning");
375  Ident__is_identifier = RegisterBuiltinMacro(*this, "__is_identifier");
376  Ident__is_target_arch = RegisterBuiltinMacro(*this, "__is_target_arch");
377  Ident__is_target_vendor = RegisterBuiltinMacro(*this, "__is_target_vendor");
378  Ident__is_target_os = RegisterBuiltinMacro(*this, "__is_target_os");
379  Ident__is_target_environment =
380  RegisterBuiltinMacro(*this, "__is_target_environment");
381 
382  // Modules.
383  Ident__building_module = RegisterBuiltinMacro(*this, "__building_module");
384  if (!LangOpts.CurrentModule.empty())
385  Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__");
386  else
387  Ident__MODULE__ = nullptr;
388 }
389 
390 /// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
391 /// in its expansion, currently expands to that token literally.
393  const IdentifierInfo *MacroIdent,
394  Preprocessor &PP) {
396 
397  // If the token isn't an identifier, it's always literally expanded.
398  if (!II) return true;
399 
400  // If the information about this identifier is out of date, update it from
401  // the external source.
402  if (II->isOutOfDate())
404 
405  // If the identifier is a macro, and if that macro is enabled, it may be
406  // expanded so it's not a trivial expansion.
407  if (auto *ExpansionMI = PP.getMacroInfo(II))
408  if (ExpansionMI->isEnabled() &&
409  // Fast expanding "#define X X" is ok, because X would be disabled.
410  II != MacroIdent)
411  return false;
412 
413  // If this is an object-like macro invocation, it is safe to trivially expand
414  // it.
415  if (MI->isObjectLike()) return true;
416 
417  // If this is a function-like macro invocation, it's safe to trivially expand
418  // as long as the identifier is not a macro argument.
419  return std::find(MI->param_begin(), MI->param_end(), II) == MI->param_end();
420 }
421 
422 /// isNextPPTokenLParen - Determine whether the next preprocessor token to be
423 /// lexed is a '('. If so, consume the token and return true, if not, this
424 /// method should have no observable side-effect on the lexed tokens.
425 bool Preprocessor::isNextPPTokenLParen() {
426  // Do some quick tests for rejection cases.
427  unsigned Val;
428  if (CurLexer)
429  Val = CurLexer->isNextPPTokenLParen();
430  else
431  Val = CurTokenLexer->isNextTokenLParen();
432 
433  if (Val == 2) {
434  // We have run off the end. If it's a source file we don't
435  // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
436  // macro stack.
437  if (CurPPLexer)
438  return false;
439  for (const IncludeStackInfo &Entry : llvm::reverse(IncludeMacroStack)) {
440  if (Entry.TheLexer)
441  Val = Entry.TheLexer->isNextPPTokenLParen();
442  else
443  Val = Entry.TheTokenLexer->isNextTokenLParen();
444 
445  if (Val != 2)
446  break;
447 
448  // Ran off the end of a source file?
449  if (Entry.ThePPLexer)
450  return false;
451  }
452  }
453 
454  // Okay, if we know that the token is a '(', lex it and return. Otherwise we
455  // have found something that isn't a '(' or we found the end of the
456  // translation unit. In either case, return false.
457  return Val == 1;
458 }
459 
460 /// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
461 /// expanded as a macro, handle it and return the next token as 'Identifier'.
462 bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
463  const MacroDefinition &M) {
464  MacroInfo *MI = M.getMacroInfo();
465 
466  // If this is a macro expansion in the "#if !defined(x)" line for the file,
467  // then the macro could expand to different things in other contexts, we need
468  // to disable the optimization in this case.
469  if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
470 
471  // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
472  if (MI->isBuiltinMacro()) {
473  if (Callbacks)
474  Callbacks->MacroExpands(Identifier, M, Identifier.getLocation(),
475  /*Args=*/nullptr);
476  ExpandBuiltinMacro(Identifier);
477  return true;
478  }
479 
480  /// Args - If this is a function-like macro expansion, this contains,
481  /// for each macro argument, the list of tokens that were provided to the
482  /// invocation.
483  MacroArgs *Args = nullptr;
484 
485  // Remember where the end of the expansion occurred. For an object-like
486  // macro, this is the identifier. For a function-like macro, this is the ')'.
487  SourceLocation ExpansionEnd = Identifier.getLocation();
488 
489  // If this is a function-like macro, read the arguments.
490  if (MI->isFunctionLike()) {
491  // Remember that we are now parsing the arguments to a macro invocation.
492  // Preprocessor directives used inside macro arguments are not portable, and
493  // this enables the warning.
494  InMacroArgs = true;
495  ArgMacro = &Identifier;
496 
497  Args = ReadMacroCallArgumentList(Identifier, MI, ExpansionEnd);
498 
499  // Finished parsing args.
500  InMacroArgs = false;
501  ArgMacro = nullptr;
502 
503  // If there was an error parsing the arguments, bail out.
504  if (!Args) return true;
505 
506  ++NumFnMacroExpanded;
507  } else {
508  ++NumMacroExpanded;
509  }
510 
511  // Notice that this macro has been used.
512  markMacroAsUsed(MI);
513 
514  // Remember where the token is expanded.
515  SourceLocation ExpandLoc = Identifier.getLocation();
516  SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
517 
518  if (Callbacks) {
519  if (InMacroArgs) {
520  // We can have macro expansion inside a conditional directive while
521  // reading the function macro arguments. To ensure, in that case, that
522  // MacroExpands callbacks still happen in source order, queue this
523  // callback to have it happen after the function macro callback.
524  DelayedMacroExpandsCallbacks.push_back(
525  MacroExpandsInfo(Identifier, M, ExpansionRange));
526  } else {
527  Callbacks->MacroExpands(Identifier, M, ExpansionRange, Args);
528  if (!DelayedMacroExpandsCallbacks.empty()) {
529  for (const MacroExpandsInfo &Info : DelayedMacroExpandsCallbacks) {
530  // FIXME: We lose macro args info with delayed callback.
531  Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range,
532  /*Args=*/nullptr);
533  }
534  DelayedMacroExpandsCallbacks.clear();
535  }
536  }
537  }
538 
539  // If the macro definition is ambiguous, complain.
540  if (M.isAmbiguous()) {
541  Diag(Identifier, diag::warn_pp_ambiguous_macro)
542  << Identifier.getIdentifierInfo();
543  Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)
544  << Identifier.getIdentifierInfo();
545  M.forAllDefinitions([&](const MacroInfo *OtherMI) {
546  if (OtherMI != MI)
547  Diag(OtherMI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_other)
548  << Identifier.getIdentifierInfo();
549  });
550  }
551 
552  // If we started lexing a macro, enter the macro expansion body.
553 
554  // If this macro expands to no tokens, don't bother to push it onto the
555  // expansion stack, only to take it right back off.
556  if (MI->getNumTokens() == 0) {
557  // No need for arg info.
558  if (Args) Args->destroy(*this);
559 
560  // Propagate whitespace info as if we had pushed, then popped,
561  // a macro context.
562  Identifier.setFlag(Token::LeadingEmptyMacro);
563  PropagateLineStartLeadingSpaceInfo(Identifier);
564  ++NumFastMacroExpanded;
565  return false;
566  } else if (MI->getNumTokens() == 1 &&
568  *this)) {
569  // Otherwise, if this macro expands into a single trivially-expanded
570  // token: expand it now. This handles common cases like
571  // "#define VAL 42".
572 
573  // No need for arg info.
574  if (Args) Args->destroy(*this);
575 
576  // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
577  // identifier to the expanded token.
578  bool isAtStartOfLine = Identifier.isAtStartOfLine();
579  bool hasLeadingSpace = Identifier.hasLeadingSpace();
580 
581  // Replace the result token.
582  Identifier = MI->getReplacementToken(0);
583 
584  // Restore the StartOfLine/LeadingSpace markers.
585  Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
586  Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
587 
588  // Update the tokens location to include both its expansion and physical
589  // locations.
590  SourceLocation Loc =
591  SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
592  ExpansionEnd,Identifier.getLength());
593  Identifier.setLocation(Loc);
594 
595  // If this is a disabled macro or #define X X, we must mark the result as
596  // unexpandable.
597  if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
598  if (MacroInfo *NewMI = getMacroInfo(NewII))
599  if (!NewMI->isEnabled() || NewMI == MI) {
600  Identifier.setFlag(Token::DisableExpand);
601  // Don't warn for "#define X X" like "#define bool bool" from
602  // stdbool.h.
603  if (NewMI != MI || MI->isFunctionLike())
604  Diag(Identifier, diag::pp_disabled_macro_expansion);
605  }
606  }
607 
608  // Since this is not an identifier token, it can't be macro expanded, so
609  // we're done.
610  ++NumFastMacroExpanded;
611  return true;
612  }
613 
614  // Start expanding the macro.
615  EnterMacro(Identifier, ExpansionEnd, MI, Args);
616  return false;
617 }
618 
619 enum Bracket {
622 };
623 
624 /// CheckMatchedBrackets - Returns true if the braces and parentheses in the
625 /// token vector are properly nested.
626 static bool CheckMatchedBrackets(const SmallVectorImpl<Token> &Tokens) {
627  SmallVector<Bracket, 8> Brackets;
628  for (SmallVectorImpl<Token>::const_iterator I = Tokens.begin(),
629  E = Tokens.end();
630  I != E; ++I) {
631  if (I->is(tok::l_paren)) {
632  Brackets.push_back(Paren);
633  } else if (I->is(tok::r_paren)) {
634  if (Brackets.empty() || Brackets.back() == Brace)
635  return false;
636  Brackets.pop_back();
637  } else if (I->is(tok::l_brace)) {
638  Brackets.push_back(Brace);
639  } else if (I->is(tok::r_brace)) {
640  if (Brackets.empty() || Brackets.back() == Paren)
641  return false;
642  Brackets.pop_back();
643  }
644  }
645  return Brackets.empty();
646 }
647 
648 /// GenerateNewArgTokens - Returns true if OldTokens can be converted to a new
649 /// vector of tokens in NewTokens. The new number of arguments will be placed
650 /// in NumArgs and the ranges which need to surrounded in parentheses will be
651 /// in ParenHints.
652 /// Returns false if the token stream cannot be changed. If this is because
653 /// of an initializer list starting a macro argument, the range of those
654 /// initializer lists will be place in InitLists.
656  SmallVectorImpl<Token> &OldTokens,
657  SmallVectorImpl<Token> &NewTokens,
658  unsigned &NumArgs,
659  SmallVectorImpl<SourceRange> &ParenHints,
660  SmallVectorImpl<SourceRange> &InitLists) {
661  if (!CheckMatchedBrackets(OldTokens))
662  return false;
663 
664  // Once it is known that the brackets are matched, only a simple count of the
665  // braces is needed.
666  unsigned Braces = 0;
667 
668  // First token of a new macro argument.
669  SmallVectorImpl<Token>::iterator ArgStartIterator = OldTokens.begin();
670 
671  // First closing brace in a new macro argument. Used to generate
672  // SourceRanges for InitLists.
673  SmallVectorImpl<Token>::iterator ClosingBrace = OldTokens.end();
674  NumArgs = 0;
675  Token TempToken;
676  // Set to true when a macro separator token is found inside a braced list.
677  // If true, the fixed argument spans multiple old arguments and ParenHints
678  // will be updated.
679  bool FoundSeparatorToken = false;
680  for (SmallVectorImpl<Token>::iterator I = OldTokens.begin(),
681  E = OldTokens.end();
682  I != E; ++I) {
683  if (I->is(tok::l_brace)) {
684  ++Braces;
685  } else if (I->is(tok::r_brace)) {
686  --Braces;
687  if (Braces == 0 && ClosingBrace == E && FoundSeparatorToken)
688  ClosingBrace = I;
689  } else if (I->is(tok::eof)) {
690  // EOF token is used to separate macro arguments
691  if (Braces != 0) {
692  // Assume comma separator is actually braced list separator and change
693  // it back to a comma.
694  FoundSeparatorToken = true;
695  I->setKind(tok::comma);
696  I->setLength(1);
697  } else { // Braces == 0
698  // Separator token still separates arguments.
699  ++NumArgs;
700 
701  // If the argument starts with a brace, it can't be fixed with
702  // parentheses. A different diagnostic will be given.
703  if (FoundSeparatorToken && ArgStartIterator->is(tok::l_brace)) {
704  InitLists.push_back(
705  SourceRange(ArgStartIterator->getLocation(),
706  PP.getLocForEndOfToken(ClosingBrace->getLocation())));
707  ClosingBrace = E;
708  }
709 
710  // Add left paren
711  if (FoundSeparatorToken) {
712  TempToken.startToken();
713  TempToken.setKind(tok::l_paren);
714  TempToken.setLocation(ArgStartIterator->getLocation());
715  TempToken.setLength(0);
716  NewTokens.push_back(TempToken);
717  }
718 
719  // Copy over argument tokens
720  NewTokens.insert(NewTokens.end(), ArgStartIterator, I);
721 
722  // Add right paren and store the paren locations in ParenHints
723  if (FoundSeparatorToken) {
724  SourceLocation Loc = PP.getLocForEndOfToken((I - 1)->getLocation());
725  TempToken.startToken();
726  TempToken.setKind(tok::r_paren);
727  TempToken.setLocation(Loc);
728  TempToken.setLength(0);
729  NewTokens.push_back(TempToken);
730  ParenHints.push_back(SourceRange(ArgStartIterator->getLocation(),
731  Loc));
732  }
733 
734  // Copy separator token
735  NewTokens.push_back(*I);
736 
737  // Reset values
738  ArgStartIterator = I + 1;
739  FoundSeparatorToken = false;
740  }
741  }
742  }
743 
744  return !ParenHints.empty() && InitLists.empty();
745 }
746 
747 /// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
748 /// token is the '(' of the macro, this method is invoked to read all of the
749 /// actual arguments specified for the macro invocation. This returns null on
750 /// error.
751 MacroArgs *Preprocessor::ReadMacroCallArgumentList(Token &MacroName,
752  MacroInfo *MI,
753  SourceLocation &MacroEnd) {
754  // The number of fixed arguments to parse.
755  unsigned NumFixedArgsLeft = MI->getNumParams();
756  bool isVariadic = MI->isVariadic();
757 
758  // Outer loop, while there are more arguments, keep reading them.
759  Token Tok;
760 
761  // Read arguments as unexpanded tokens. This avoids issues, e.g., where
762  // an argument value in a macro could expand to ',' or '(' or ')'.
763  LexUnexpandedToken(Tok);
764  assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
765 
766  // ArgTokens - Build up a list of tokens that make up each argument. Each
767  // argument is separated by an EOF token. Use a SmallVector so we can avoid
768  // heap allocations in the common case.
769  SmallVector<Token, 64> ArgTokens;
770  bool ContainsCodeCompletionTok = false;
771  bool FoundElidedComma = false;
772 
773  SourceLocation TooManyArgsLoc;
774 
775  unsigned NumActuals = 0;
776  while (Tok.isNot(tok::r_paren)) {
777  if (ContainsCodeCompletionTok && Tok.isOneOf(tok::eof, tok::eod))
778  break;
779 
780  assert(Tok.isOneOf(tok::l_paren, tok::comma) &&
781  "only expect argument separators here");
782 
783  size_t ArgTokenStart = ArgTokens.size();
784  SourceLocation ArgStartLoc = Tok.getLocation();
785 
786  // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
787  // that we already consumed the first one.
788  unsigned NumParens = 0;
789 
790  while (true) {
791  // Read arguments as unexpanded tokens. This avoids issues, e.g., where
792  // an argument value in a macro could expand to ',' or '(' or ')'.
793  LexUnexpandedToken(Tok);
794 
795  if (Tok.isOneOf(tok::eof, tok::eod)) { // "#if f(<eof>" & "#if f(\n"
796  if (!ContainsCodeCompletionTok) {
797  Diag(MacroName, diag::err_unterm_macro_invoc);
798  Diag(MI->getDefinitionLoc(), diag::note_macro_here)
799  << MacroName.getIdentifierInfo();
800  // Do not lose the EOF/EOD. Return it to the client.
801  MacroName = Tok;
802  return nullptr;
803  }
804  // Do not lose the EOF/EOD.
805  auto Toks = llvm::make_unique<Token[]>(1);
806  Toks[0] = Tok;
807  EnterTokenStream(std::move(Toks), 1, true);
808  break;
809  } else if (Tok.is(tok::r_paren)) {
810  // If we found the ) token, the macro arg list is done.
811  if (NumParens-- == 0) {
812  MacroEnd = Tok.getLocation();
813  if (!ArgTokens.empty() &&
814  ArgTokens.back().commaAfterElided()) {
815  FoundElidedComma = true;
816  }
817  break;
818  }
819  } else if (Tok.is(tok::l_paren)) {
820  ++NumParens;
821  } else if (Tok.is(tok::comma) && NumParens == 0 &&
822  !(Tok.getFlags() & Token::IgnoredComma)) {
823  // In Microsoft-compatibility mode, single commas from nested macro
824  // expansions should not be considered as argument separators. We test
825  // for this with the IgnoredComma token flag above.
826 
827  // Comma ends this argument if there are more fixed arguments expected.
828  // However, if this is a variadic macro, and this is part of the
829  // variadic part, then the comma is just an argument token.
830  if (!isVariadic) break;
831  if (NumFixedArgsLeft > 1)
832  break;
833  } else if (Tok.is(tok::comment) && !KeepMacroComments) {
834  // If this is a comment token in the argument list and we're just in
835  // -C mode (not -CC mode), discard the comment.
836  continue;
837  } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo() != nullptr) {
838  // Reading macro arguments can cause macros that we are currently
839  // expanding from to be popped off the expansion stack. Doing so causes
840  // them to be reenabled for expansion. Here we record whether any
841  // identifiers we lex as macro arguments correspond to disabled macros.
842  // If so, we mark the token as noexpand. This is a subtle aspect of
843  // C99 6.10.3.4p2.
844  if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
845  if (!MI->isEnabled())
847  } else if (Tok.is(tok::code_completion)) {
848  ContainsCodeCompletionTok = true;
849  if (CodeComplete)
850  CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
851  MI, NumActuals);
852  // Don't mark that we reached the code-completion point because the
853  // parser is going to handle the token and there will be another
854  // code-completion callback.
855  }
856 
857  ArgTokens.push_back(Tok);
858  }
859 
860  // If this was an empty argument list foo(), don't add this as an empty
861  // argument.
862  if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
863  break;
864 
865  // If this is not a variadic macro, and too many args were specified, emit
866  // an error.
867  if (!isVariadic && NumFixedArgsLeft == 0 && TooManyArgsLoc.isInvalid()) {
868  if (ArgTokens.size() != ArgTokenStart)
869  TooManyArgsLoc = ArgTokens[ArgTokenStart].getLocation();
870  else
871  TooManyArgsLoc = ArgStartLoc;
872  }
873 
874  // Empty arguments are standard in C99 and C++0x, and are supported as an
875  // extension in other modes.
876  if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99)
877  Diag(Tok, LangOpts.CPlusPlus11 ?
878  diag::warn_cxx98_compat_empty_fnmacro_arg :
879  diag::ext_empty_fnmacro_arg);
880 
881  // Add a marker EOF token to the end of the token list for this argument.
882  Token EOFTok;
883  EOFTok.startToken();
884  EOFTok.setKind(tok::eof);
885  EOFTok.setLocation(Tok.getLocation());
886  EOFTok.setLength(0);
887  ArgTokens.push_back(EOFTok);
888  ++NumActuals;
889  if (!ContainsCodeCompletionTok && NumFixedArgsLeft != 0)
890  --NumFixedArgsLeft;
891  }
892 
893  // Okay, we either found the r_paren. Check to see if we parsed too few
894  // arguments.
895  unsigned MinArgsExpected = MI->getNumParams();
896 
897  // If this is not a variadic macro, and too many args were specified, emit
898  // an error.
899  if (!isVariadic && NumActuals > MinArgsExpected &&
900  !ContainsCodeCompletionTok) {
901  // Emit the diagnostic at the macro name in case there is a missing ).
902  // Emitting it at the , could be far away from the macro name.
903  Diag(TooManyArgsLoc, diag::err_too_many_args_in_macro_invoc);
904  Diag(MI->getDefinitionLoc(), diag::note_macro_here)
905  << MacroName.getIdentifierInfo();
906 
907  // Commas from braced initializer lists will be treated as argument
908  // separators inside macros. Attempt to correct for this with parentheses.
909  // TODO: See if this can be generalized to angle brackets for templates
910  // inside macro arguments.
911 
912  SmallVector<Token, 4> FixedArgTokens;
913  unsigned FixedNumArgs = 0;
914  SmallVector<SourceRange, 4> ParenHints, InitLists;
915  if (!GenerateNewArgTokens(*this, ArgTokens, FixedArgTokens, FixedNumArgs,
916  ParenHints, InitLists)) {
917  if (!InitLists.empty()) {
918  DiagnosticBuilder DB =
919  Diag(MacroName,
920  diag::note_init_list_at_beginning_of_macro_argument);
921  for (SourceRange Range : InitLists)
922  DB << Range;
923  }
924  return nullptr;
925  }
926  if (FixedNumArgs != MinArgsExpected)
927  return nullptr;
928 
929  DiagnosticBuilder DB = Diag(MacroName, diag::note_suggest_parens_for_macro);
930  for (SourceRange ParenLocation : ParenHints) {
931  DB << FixItHint::CreateInsertion(ParenLocation.getBegin(), "(");
932  DB << FixItHint::CreateInsertion(ParenLocation.getEnd(), ")");
933  }
934  ArgTokens.swap(FixedArgTokens);
935  NumActuals = FixedNumArgs;
936  }
937 
938  // See MacroArgs instance var for description of this.
939  bool isVarargsElided = false;
940 
941  if (ContainsCodeCompletionTok) {
942  // Recover from not-fully-formed macro invocation during code-completion.
943  Token EOFTok;
944  EOFTok.startToken();
945  EOFTok.setKind(tok::eof);
946  EOFTok.setLocation(Tok.getLocation());
947  EOFTok.setLength(0);
948  for (; NumActuals < MinArgsExpected; ++NumActuals)
949  ArgTokens.push_back(EOFTok);
950  }
951 
952  if (NumActuals < MinArgsExpected) {
953  // There are several cases where too few arguments is ok, handle them now.
954  if (NumActuals == 0 && MinArgsExpected == 1) {
955  // #define A(X) or #define A(...) ---> A()
956 
957  // If there is exactly one argument, and that argument is missing,
958  // then we have an empty "()" argument empty list. This is fine, even if
959  // the macro expects one argument (the argument is just empty).
960  isVarargsElided = MI->isVariadic();
961  } else if ((FoundElidedComma || MI->isVariadic()) &&
962  (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
963  (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
964  // Varargs where the named vararg parameter is missing: OK as extension.
965  // #define A(x, ...)
966  // A("blah")
967  //
968  // If the macro contains the comma pasting extension, the diagnostic
969  // is suppressed; we know we'll get another diagnostic later.
970  if (!MI->hasCommaPasting()) {
971  Diag(Tok, diag::ext_missing_varargs_arg);
972  Diag(MI->getDefinitionLoc(), diag::note_macro_here)
973  << MacroName.getIdentifierInfo();
974  }
975 
976  // Remember this occurred, allowing us to elide the comma when used for
977  // cases like:
978  // #define A(x, foo...) blah(a, ## foo)
979  // #define B(x, ...) blah(a, ## __VA_ARGS__)
980  // #define C(...) blah(a, ## __VA_ARGS__)
981  // A(x) B(x) C()
982  isVarargsElided = true;
983  } else if (!ContainsCodeCompletionTok) {
984  // Otherwise, emit the error.
985  Diag(Tok, diag::err_too_few_args_in_macro_invoc);
986  Diag(MI->getDefinitionLoc(), diag::note_macro_here)
987  << MacroName.getIdentifierInfo();
988  return nullptr;
989  }
990 
991  // Add a marker EOF token to the end of the token list for this argument.
992  SourceLocation EndLoc = Tok.getLocation();
993  Tok.startToken();
994  Tok.setKind(tok::eof);
995  Tok.setLocation(EndLoc);
996  Tok.setLength(0);
997  ArgTokens.push_back(Tok);
998 
999  // If we expect two arguments, add both as empty.
1000  if (NumActuals == 0 && MinArgsExpected == 2)
1001  ArgTokens.push_back(Tok);
1002 
1003  } else if (NumActuals > MinArgsExpected && !MI->isVariadic() &&
1004  !ContainsCodeCompletionTok) {
1005  // Emit the diagnostic at the macro name in case there is a missing ).
1006  // Emitting it at the , could be far away from the macro name.
1007  Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
1008  Diag(MI->getDefinitionLoc(), diag::note_macro_here)
1009  << MacroName.getIdentifierInfo();
1010  return nullptr;
1011  }
1012 
1013  return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
1014 }
1015 
1016 /// Keeps macro expanded tokens for TokenLexers.
1017 //
1018 /// Works like a stack; a TokenLexer adds the macro expanded tokens that is
1019 /// going to lex in the cache and when it finishes the tokens are removed
1020 /// from the end of the cache.
1021 Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
1022  ArrayRef<Token> tokens) {
1023  assert(tokLexer);
1024  if (tokens.empty())
1025  return nullptr;
1026 
1027  size_t newIndex = MacroExpandedTokens.size();
1028  bool cacheNeedsToGrow = tokens.size() >
1029  MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
1030  MacroExpandedTokens.append(tokens.begin(), tokens.end());
1031 
1032  if (cacheNeedsToGrow) {
1033  // Go through all the TokenLexers whose 'Tokens' pointer points in the
1034  // buffer and update the pointers to the (potential) new buffer array.
1035  for (const auto &Lexer : MacroExpandingLexersStack) {
1036  TokenLexer *prevLexer;
1037  size_t tokIndex;
1038  std::tie(prevLexer, tokIndex) = Lexer;
1039  prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
1040  }
1041  }
1042 
1043  MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
1044  return MacroExpandedTokens.data() + newIndex;
1045 }
1046 
1047 void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
1048  assert(!MacroExpandingLexersStack.empty());
1049  size_t tokIndex = MacroExpandingLexersStack.back().second;
1050  assert(tokIndex < MacroExpandedTokens.size());
1051  // Pop the cached macro expanded tokens from the end.
1052  MacroExpandedTokens.resize(tokIndex);
1053  MacroExpandingLexersStack.pop_back();
1054 }
1055 
1056 /// ComputeDATE_TIME - Compute the current time, enter it into the specified
1057 /// scratch buffer, then return DATELoc/TIMELoc locations with the position of
1058 /// the identifier tokens inserted.
1059 static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
1060  Preprocessor &PP) {
1061  time_t TT = time(nullptr);
1062  struct tm *TM = localtime(&TT);
1063 
1064  static const char * const Months[] = {
1065  "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
1066  };
1067 
1068  {
1069  SmallString<32> TmpBuffer;
1070  llvm::raw_svector_ostream TmpStream(TmpBuffer);
1071  TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
1072  TM->tm_mday, TM->tm_year + 1900);
1073  Token TmpTok;
1074  TmpTok.startToken();
1075  PP.CreateString(TmpStream.str(), TmpTok);
1076  DATELoc = TmpTok.getLocation();
1077  }
1078 
1079  {
1080  SmallString<32> TmpBuffer;
1081  llvm::raw_svector_ostream TmpStream(TmpBuffer);
1082  TmpStream << llvm::format("\"%02d:%02d:%02d\"",
1083  TM->tm_hour, TM->tm_min, TM->tm_sec);
1084  Token TmpTok;
1085  TmpTok.startToken();
1086  PP.CreateString(TmpStream.str(), TmpTok);
1087  TIMELoc = TmpTok.getLocation();
1088  }
1089 }
1090 
1091 /// HasFeature - Return true if we recognize and implement the feature
1092 /// specified by the identifier as a standard language feature.
1093 static bool HasFeature(const Preprocessor &PP, StringRef Feature) {
1094  const LangOptions &LangOpts = PP.getLangOpts();
1095 
1096  // Normalize the feature name, __foo__ becomes foo.
1097  if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4)
1098  Feature = Feature.substr(2, Feature.size() - 4);
1099 
1100 #define FEATURE(Name, Predicate) .Case(#Name, Predicate)
1101  return llvm::StringSwitch<bool>(Feature)
1102 #include "clang/Basic/Features.def"
1103  .Default(false);
1104 #undef FEATURE
1105 }
1106 
1107 /// HasExtension - Return true if we recognize and implement the feature
1108 /// specified by the identifier, either as an extension or a standard language
1109 /// feature.
1110 static bool HasExtension(const Preprocessor &PP, StringRef Extension) {
1111  if (HasFeature(PP, Extension))
1112  return true;
1113 
1114  // If the use of an extension results in an error diagnostic, extensions are
1115  // effectively unavailable, so just return false here.
1118  return false;
1119 
1120  const LangOptions &LangOpts = PP.getLangOpts();
1121 
1122  // Normalize the extension name, __foo__ becomes foo.
1123  if (Extension.startswith("__") && Extension.endswith("__") &&
1124  Extension.size() >= 4)
1125  Extension = Extension.substr(2, Extension.size() - 4);
1126 
1127  // Because we inherit the feature list from HasFeature, this string switch
1128  // must be less restrictive than HasFeature's.
1129 #define EXTENSION(Name, Predicate) .Case(#Name, Predicate)
1130  return llvm::StringSwitch<bool>(Extension)
1131 #include "clang/Basic/Features.def"
1132  .Default(false);
1133 #undef EXTENSION
1134 }
1135 
1136 /// EvaluateHasIncludeCommon - Process a '__has_include("path")'
1137 /// or '__has_include_next("path")' expression.
1138 /// Returns true if successful.
1140  IdentifierInfo *II, Preprocessor &PP,
1141  const DirectoryLookup *LookupFrom,
1142  const FileEntry *LookupFromFile) {
1143  // Save the location of the current token. If a '(' is later found, use
1144  // that location. If not, use the end of this location instead.
1145  SourceLocation LParenLoc = Tok.getLocation();
1146 
1147  // These expressions are only allowed within a preprocessor directive.
1148  if (!PP.isParsingIfOrElifDirective()) {
1149  PP.Diag(LParenLoc, diag::err_pp_directive_required) << II;
1150  // Return a valid identifier token.
1151  assert(Tok.is(tok::identifier));
1152  Tok.setIdentifierInfo(II);
1153  return false;
1154  }
1155 
1156  // Get '('.
1157  PP.LexNonComment(Tok);
1158 
1159  // Ensure we have a '('.
1160  if (Tok.isNot(tok::l_paren)) {
1161  // No '(', use end of last token.
1162  LParenLoc = PP.getLocForEndOfToken(LParenLoc);
1163  PP.Diag(LParenLoc, diag::err_pp_expected_after) << II << tok::l_paren;
1164  // If the next token looks like a filename or the start of one,
1165  // assume it is and process it as such.
1166  if (!Tok.is(tok::angle_string_literal) && !Tok.is(tok::string_literal) &&
1167  !Tok.is(tok::less))
1168  return false;
1169  } else {
1170  // Save '(' location for possible missing ')' message.
1171  LParenLoc = Tok.getLocation();
1172 
1173  if (PP.getCurrentLexer()) {
1174  // Get the file name.
1176  } else {
1177  // We're in a macro, so we can't use LexIncludeFilename; just
1178  // grab the next token.
1179  PP.Lex(Tok);
1180  }
1181  }
1182 
1183  // Reserve a buffer to get the spelling.
1184  SmallString<128> FilenameBuffer;
1185  StringRef Filename;
1186  SourceLocation EndLoc;
1187 
1188  switch (Tok.getKind()) {
1189  case tok::eod:
1190  // If the token kind is EOD, the error has already been diagnosed.
1191  return false;
1192 
1193  case tok::angle_string_literal:
1194  case tok::string_literal: {
1195  bool Invalid = false;
1196  Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
1197  if (Invalid)
1198  return false;
1199  break;
1200  }
1201 
1202  case tok::less:
1203  // This could be a <foo/bar.h> file coming from a macro expansion. In this
1204  // case, glue the tokens together into FilenameBuffer and interpret those.
1205  FilenameBuffer.push_back('<');
1206  if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc)) {
1207  // Let the caller know a <eod> was found by changing the Token kind.
1208  Tok.setKind(tok::eod);
1209  return false; // Found <eod> but no ">"? Diagnostic already emitted.
1210  }
1211  Filename = FilenameBuffer;
1212  break;
1213  default:
1214  PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
1215  return false;
1216  }
1217 
1218  SourceLocation FilenameLoc = Tok.getLocation();
1219 
1220  // Get ')'.
1221  PP.LexNonComment(Tok);
1222 
1223  // Ensure we have a trailing ).
1224  if (Tok.isNot(tok::r_paren)) {
1225  PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after)
1226  << II << tok::r_paren;
1227  PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1228  return false;
1229  }
1230 
1231  bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
1232  // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1233  // error.
1234  if (Filename.empty())
1235  return false;
1236 
1237  // Search include directories.
1238  const DirectoryLookup *CurDir;
1239  const FileEntry *File =
1240  PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, LookupFromFile,
1241  CurDir, nullptr, nullptr, nullptr, nullptr, nullptr);
1242 
1243  if (PPCallbacks *Callbacks = PP.getPPCallbacks()) {
1245  if (File)
1246  FileType = PP.getHeaderSearchInfo().getFileDirFlavor(File);
1247  Callbacks->HasInclude(FilenameLoc, Filename, isAngled, File, FileType);
1248  }
1249 
1250  // Get the result value. A result of true means the file exists.
1251  return File != nullptr;
1252 }
1253 
1254 /// EvaluateHasInclude - Process a '__has_include("path")' expression.
1255 /// Returns true if successful.
1257  Preprocessor &PP) {
1258  return EvaluateHasIncludeCommon(Tok, II, PP, nullptr, nullptr);
1259 }
1260 
1261 /// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
1262 /// Returns true if successful.
1264  IdentifierInfo *II, Preprocessor &PP) {
1265  // __has_include_next is like __has_include, except that we start
1266  // searching after the current found directory. If we can't do this,
1267  // issue a diagnostic.
1268  // FIXME: Factor out duplication with
1269  // Preprocessor::HandleIncludeNextDirective.
1270  const DirectoryLookup *Lookup = PP.GetCurDirLookup();
1271  const FileEntry *LookupFromFile = nullptr;
1272  if (PP.isInPrimaryFile() && PP.getLangOpts().IsHeaderFile) {
1273  // If the main file is a header, then it's either for PCH/AST generation,
1274  // or libclang opened it. Either way, handle it as a normal include below
1275  // and do not complain about __has_include_next.
1276  } else if (PP.isInPrimaryFile()) {
1277  Lookup = nullptr;
1278  PP.Diag(Tok, diag::pp_include_next_in_primary);
1279  } else if (PP.getCurrentLexerSubmodule()) {
1280  // Start looking up in the directory *after* the one in which the current
1281  // file would be found, if any.
1282  assert(PP.getCurrentLexer() && "#include_next directive in macro?");
1283  LookupFromFile = PP.getCurrentLexer()->getFileEntry();
1284  Lookup = nullptr;
1285  } else if (!Lookup) {
1286  PP.Diag(Tok, diag::pp_include_next_absolute_path);
1287  } else {
1288  // Start looking up in the next directory.
1289  ++Lookup;
1290  }
1291 
1292  return EvaluateHasIncludeCommon(Tok, II, PP, Lookup, LookupFromFile);
1293 }
1294 
1295 /// Process single-argument builtin feature-like macros that return
1296 /// integer values.
1297 static void EvaluateFeatureLikeBuiltinMacro(llvm::raw_svector_ostream& OS,
1298  Token &Tok, IdentifierInfo *II,
1299  Preprocessor &PP,
1300  llvm::function_ref<
1301  int(Token &Tok,
1302  bool &HasLexedNextTok)> Op) {
1303  // Parse the initial '('.
1304  PP.LexUnexpandedToken(Tok);
1305  if (Tok.isNot(tok::l_paren)) {
1306  PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1307  << tok::l_paren;
1308 
1309  // Provide a dummy '0' value on output stream to elide further errors.
1310  if (!Tok.isOneOf(tok::eof, tok::eod)) {
1311  OS << 0;
1312  Tok.setKind(tok::numeric_constant);
1313  }
1314  return;
1315  }
1316 
1317  unsigned ParenDepth = 1;
1318  SourceLocation LParenLoc = Tok.getLocation();
1320 
1321  Token ResultTok;
1322  bool SuppressDiagnostic = false;
1323  while (true) {
1324  // Parse next token.
1325  PP.LexUnexpandedToken(Tok);
1326 
1327 already_lexed:
1328  switch (Tok.getKind()) {
1329  case tok::eof:
1330  case tok::eod:
1331  // Don't provide even a dummy value if the eod or eof marker is
1332  // reached. Simply provide a diagnostic.
1333  PP.Diag(Tok.getLocation(), diag::err_unterm_macro_invoc);
1334  return;
1335 
1336  case tok::comma:
1337  if (!SuppressDiagnostic) {
1338  PP.Diag(Tok.getLocation(), diag::err_too_many_args_in_macro_invoc);
1339  SuppressDiagnostic = true;
1340  }
1341  continue;
1342 
1343  case tok::l_paren:
1344  ++ParenDepth;
1345  if (Result.hasValue())
1346  break;
1347  if (!SuppressDiagnostic) {
1348  PP.Diag(Tok.getLocation(), diag::err_pp_nested_paren) << II;
1349  SuppressDiagnostic = true;
1350  }
1351  continue;
1352 
1353  case tok::r_paren:
1354  if (--ParenDepth > 0)
1355  continue;
1356 
1357  // The last ')' has been reached; return the value if one found or
1358  // a diagnostic and a dummy value.
1359  if (Result.hasValue())
1360  OS << Result.getValue();
1361  else {
1362  OS << 0;
1363  if (!SuppressDiagnostic)
1364  PP.Diag(Tok.getLocation(), diag::err_too_few_args_in_macro_invoc);
1365  }
1366  Tok.setKind(tok::numeric_constant);
1367  return;
1368 
1369  default: {
1370  // Parse the macro argument, if one not found so far.
1371  if (Result.hasValue())
1372  break;
1373 
1374  bool HasLexedNextToken = false;
1375  Result = Op(Tok, HasLexedNextToken);
1376  ResultTok = Tok;
1377  if (HasLexedNextToken)
1378  goto already_lexed;
1379  continue;
1380  }
1381  }
1382 
1383  // Diagnose missing ')'.
1384  if (!SuppressDiagnostic) {
1385  if (auto Diag = PP.Diag(Tok.getLocation(), diag::err_pp_expected_after)) {
1386  if (IdentifierInfo *LastII = ResultTok.getIdentifierInfo())
1387  Diag << LastII;
1388  else
1389  Diag << ResultTok.getKind();
1390  Diag << tok::r_paren << ResultTok.getLocation();
1391  }
1392  PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1393  SuppressDiagnostic = true;
1394  }
1395  }
1396 }
1397 
1398 /// Helper function to return the IdentifierInfo structure of a Token
1399 /// or generate a diagnostic if none available.
1401  Preprocessor &PP,
1402  signed DiagID) {
1403  IdentifierInfo *II;
1404  if (!Tok.isAnnotation() && (II = Tok.getIdentifierInfo()))
1405  return II;
1406 
1407  PP.Diag(Tok.getLocation(), DiagID);
1408  return nullptr;
1409 }
1410 
1411 /// Implements the __is_target_arch builtin macro.
1412 static bool isTargetArch(const TargetInfo &TI, const IdentifierInfo *II) {
1413  std::string ArchName = II->getName().lower() + "--";
1414  llvm::Triple Arch(ArchName);
1415  const llvm::Triple &TT = TI.getTriple();
1416  if (TT.isThumb()) {
1417  // arm matches thumb or thumbv7. armv7 matches thumbv7.
1418  if ((Arch.getSubArch() == llvm::Triple::NoSubArch ||
1419  Arch.getSubArch() == TT.getSubArch()) &&
1420  ((TT.getArch() == llvm::Triple::thumb &&
1421  Arch.getArch() == llvm::Triple::arm) ||
1422  (TT.getArch() == llvm::Triple::thumbeb &&
1423  Arch.getArch() == llvm::Triple::armeb)))
1424  return true;
1425  }
1426  // Check the parsed arch when it has no sub arch to allow Clang to
1427  // match thumb to thumbv7 but to prohibit matching thumbv6 to thumbv7.
1428  return (Arch.getSubArch() == llvm::Triple::NoSubArch ||
1429  Arch.getSubArch() == TT.getSubArch()) &&
1430  Arch.getArch() == TT.getArch();
1431 }
1432 
1433 /// Implements the __is_target_vendor builtin macro.
1434 static bool isTargetVendor(const TargetInfo &TI, const IdentifierInfo *II) {
1435  StringRef VendorName = TI.getTriple().getVendorName();
1436  if (VendorName.empty())
1437  VendorName = "unknown";
1438  return VendorName.equals_lower(II->getName());
1439 }
1440 
1441 /// Implements the __is_target_os builtin macro.
1442 static bool isTargetOS(const TargetInfo &TI, const IdentifierInfo *II) {
1443  std::string OSName =
1444  (llvm::Twine("unknown-unknown-") + II->getName().lower()).str();
1445  llvm::Triple OS(OSName);
1446  if (OS.getOS() == llvm::Triple::Darwin) {
1447  // Darwin matches macos, ios, etc.
1448  return TI.getTriple().isOSDarwin();
1449  }
1450  return TI.getTriple().getOS() == OS.getOS();
1451 }
1452 
1453 /// Implements the __is_target_environment builtin macro.
1454 static bool isTargetEnvironment(const TargetInfo &TI,
1455  const IdentifierInfo *II) {
1456  std::string EnvName = (llvm::Twine("---") + II->getName().lower()).str();
1457  llvm::Triple Env(EnvName);
1458  return TI.getTriple().getEnvironment() == Env.getEnvironment();
1459 }
1460 
1461 /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1462 /// as a builtin macro, handle it and return the next token as 'Tok'.
1463 void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
1464  // Figure out which token this is.
1465  IdentifierInfo *II = Tok.getIdentifierInfo();
1466  assert(II && "Can't be a macro without id info!");
1467 
1468  // If this is an _Pragma or Microsoft __pragma directive, expand it,
1469  // invoke the pragma handler, then lex the token after it.
1470  if (II == Ident_Pragma)
1471  return Handle_Pragma(Tok);
1472  else if (II == Ident__pragma) // in non-MS mode this is null
1473  return HandleMicrosoft__pragma(Tok);
1474 
1475  ++NumBuiltinMacroExpanded;
1476 
1477  SmallString<128> TmpBuffer;
1478  llvm::raw_svector_ostream OS(TmpBuffer);
1479 
1480  // Set up the return result.
1481  Tok.setIdentifierInfo(nullptr);
1483 
1484  if (II == Ident__LINE__) {
1485  // C99 6.10.8: "__LINE__: The presumed line number (within the current
1486  // source file) of the current source line (an integer constant)". This can
1487  // be affected by #line.
1488  SourceLocation Loc = Tok.getLocation();
1489 
1490  // Advance to the location of the first _, this might not be the first byte
1491  // of the token if it starts with an escaped newline.
1492  Loc = AdvanceToTokenCharacter(Loc, 0);
1493 
1494  // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
1495  // a macro expansion. This doesn't matter for object-like macros, but
1496  // can matter for a function-like macro that expands to contain __LINE__.
1497  // Skip down through expansion points until we find a file loc for the
1498  // end of the expansion history.
1499  Loc = SourceMgr.getExpansionRange(Loc).getEnd();
1500  PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
1501 
1502  // __LINE__ expands to a simple numeric value.
1503  OS << (PLoc.isValid()? PLoc.getLine() : 1);
1504  Tok.setKind(tok::numeric_constant);
1505  } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
1506  // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
1507  // character string literal)". This can be affected by #line.
1508  PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1509 
1510  // __BASE_FILE__ is a GNU extension that returns the top of the presumed
1511  // #include stack instead of the current file.
1512  if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
1513  SourceLocation NextLoc = PLoc.getIncludeLoc();
1514  while (NextLoc.isValid()) {
1515  PLoc = SourceMgr.getPresumedLoc(NextLoc);
1516  if (PLoc.isInvalid())
1517  break;
1518 
1519  NextLoc = PLoc.getIncludeLoc();
1520  }
1521  }
1522 
1523  // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
1524  SmallString<128> FN;
1525  if (PLoc.isValid()) {
1526  FN += PLoc.getFilename();
1527  Lexer::Stringify(FN);
1528  OS << '"' << FN << '"';
1529  }
1530  Tok.setKind(tok::string_literal);
1531  } else if (II == Ident__DATE__) {
1532  Diag(Tok.getLocation(), diag::warn_pp_date_time);
1533  if (!DATELoc.isValid())
1534  ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1535  Tok.setKind(tok::string_literal);
1536  Tok.setLength(strlen("\"Mmm dd yyyy\""));
1537  Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
1538  Tok.getLocation(),
1539  Tok.getLength()));
1540  return;
1541  } else if (II == Ident__TIME__) {
1542  Diag(Tok.getLocation(), diag::warn_pp_date_time);
1543  if (!TIMELoc.isValid())
1544  ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1545  Tok.setKind(tok::string_literal);
1546  Tok.setLength(strlen("\"hh:mm:ss\""));
1547  Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
1548  Tok.getLocation(),
1549  Tok.getLength()));
1550  return;
1551  } else if (II == Ident__INCLUDE_LEVEL__) {
1552  // Compute the presumed include depth of this token. This can be affected
1553  // by GNU line markers.
1554  unsigned Depth = 0;
1555 
1556  PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1557  if (PLoc.isValid()) {
1558  PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1559  for (; PLoc.isValid(); ++Depth)
1560  PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1561  }
1562 
1563  // __INCLUDE_LEVEL__ expands to a simple numeric value.
1564  OS << Depth;
1565  Tok.setKind(tok::numeric_constant);
1566  } else if (II == Ident__TIMESTAMP__) {
1567  Diag(Tok.getLocation(), diag::warn_pp_date_time);
1568  // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1569  // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1570 
1571  // Get the file that we are lexing out of. If we're currently lexing from
1572  // a macro, dig into the include stack.
1573  const FileEntry *CurFile = nullptr;
1574  PreprocessorLexer *TheLexer = getCurrentFileLexer();
1575 
1576  if (TheLexer)
1577  CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
1578 
1579  const char *Result;
1580  if (CurFile) {
1581  time_t TT = CurFile->getModificationTime();
1582  struct tm *TM = localtime(&TT);
1583  Result = asctime(TM);
1584  } else {
1585  Result = "??? ??? ?? ??:??:?? ????\n";
1586  }
1587  // Surround the string with " and strip the trailing newline.
1588  OS << '"' << StringRef(Result).drop_back() << '"';
1589  Tok.setKind(tok::string_literal);
1590  } else if (II == Ident__COUNTER__) {
1591  // __COUNTER__ expands to a simple numeric value.
1592  OS << CounterValue++;
1593  Tok.setKind(tok::numeric_constant);
1594  } else if (II == Ident__has_feature) {
1595  EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1596  [this](Token &Tok, bool &HasLexedNextToken) -> int {
1598  diag::err_feature_check_malformed);
1599  return II && HasFeature(*this, II->getName());
1600  });
1601  } else if (II == Ident__has_extension) {
1602  EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1603  [this](Token &Tok, bool &HasLexedNextToken) -> int {
1605  diag::err_feature_check_malformed);
1606  return II && HasExtension(*this, II->getName());
1607  });
1608  } else if (II == Ident__has_builtin) {
1609  EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1610  [this](Token &Tok, bool &HasLexedNextToken) -> int {
1612  diag::err_feature_check_malformed);
1613  const LangOptions &LangOpts = getLangOpts();
1614  if (!II)
1615  return false;
1616  else if (II->getBuiltinID() != 0) {
1617  switch (II->getBuiltinID()) {
1618  case Builtin::BI__builtin_operator_new:
1619  case Builtin::BI__builtin_operator_delete:
1620  // denotes date of behavior change to support calling arbitrary
1621  // usual allocation and deallocation functions. Required by libc++
1622  return 201802;
1623  default:
1624  return true;
1625  }
1626  return true;
1627  } else {
1628  return llvm::StringSwitch<bool>(II->getName())
1629  .Case("__make_integer_seq", LangOpts.CPlusPlus)
1630  .Case("__type_pack_element", LangOpts.CPlusPlus)
1631  .Case("__builtin_available", true)
1632  .Case("__is_target_arch", true)
1633  .Case("__is_target_vendor", true)
1634  .Case("__is_target_os", true)
1635  .Case("__is_target_environment", true)
1636  .Default(false);
1637  }
1638  });
1639  } else if (II == Ident__is_identifier) {
1640  EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1641  [](Token &Tok, bool &HasLexedNextToken) -> int {
1642  return Tok.is(tok::identifier);
1643  });
1644  } else if (II == Ident__has_attribute) {
1645  EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1646  [this](Token &Tok, bool &HasLexedNextToken) -> int {
1648  diag::err_feature_check_malformed);
1649  return II ? hasAttribute(AttrSyntax::GNU, nullptr, II,
1650  getTargetInfo(), getLangOpts()) : 0;
1651  });
1652  } else if (II == Ident__has_declspec) {
1653  EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1654  [this](Token &Tok, bool &HasLexedNextToken) -> int {
1656  diag::err_feature_check_malformed);
1657  return II ? hasAttribute(AttrSyntax::Declspec, nullptr, II,
1658  getTargetInfo(), getLangOpts()) : 0;
1659  });
1660  } else if (II == Ident__has_cpp_attribute ||
1661  II == Ident__has_c_attribute) {
1662  bool IsCXX = II == Ident__has_cpp_attribute;
1664  OS, Tok, II, *this, [&](Token &Tok, bool &HasLexedNextToken) -> int {
1665  IdentifierInfo *ScopeII = nullptr;
1667  Tok, *this, diag::err_feature_check_malformed);
1668  if (!II)
1669  return false;
1670 
1671  // It is possible to receive a scope token. Read the "::", if it is
1672  // available, and the subsequent identifier.
1673  LexUnexpandedToken(Tok);
1674  if (Tok.isNot(tok::coloncolon))
1675  HasLexedNextToken = true;
1676  else {
1677  ScopeII = II;
1678  LexUnexpandedToken(Tok);
1679  II = ExpectFeatureIdentifierInfo(Tok, *this,
1680  diag::err_feature_check_malformed);
1681  }
1682 
1683  AttrSyntax Syntax = IsCXX ? AttrSyntax::CXX : AttrSyntax::C;
1684  return II ? hasAttribute(Syntax, ScopeII, II, getTargetInfo(),
1685  getLangOpts())
1686  : 0;
1687  });
1688  } else if (II == Ident__has_include ||
1689  II == Ident__has_include_next) {
1690  // The argument to these two builtins should be a parenthesized
1691  // file name string literal using angle brackets (<>) or
1692  // double-quotes ("").
1693  bool Value;
1694  if (II == Ident__has_include)
1695  Value = EvaluateHasInclude(Tok, II, *this);
1696  else
1697  Value = EvaluateHasIncludeNext(Tok, II, *this);
1698 
1699  if (Tok.isNot(tok::r_paren))
1700  return;
1701  OS << (int)Value;
1702  Tok.setKind(tok::numeric_constant);
1703  } else if (II == Ident__has_warning) {
1704  // The argument should be a parenthesized string literal.
1705  EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1706  [this](Token &Tok, bool &HasLexedNextToken) -> int {
1707  std::string WarningName;
1708  SourceLocation StrStartLoc = Tok.getLocation();
1709 
1710  HasLexedNextToken = Tok.is(tok::string_literal);
1711  if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",
1712  /*MacroExpansion=*/false))
1713  return false;
1714 
1715  // FIXME: Should we accept "-R..." flags here, or should that be
1716  // handled by a separate __has_remark?
1717  if (WarningName.size() < 3 || WarningName[0] != '-' ||
1718  WarningName[1] != 'W') {
1719  Diag(StrStartLoc, diag::warn_has_warning_invalid_option);
1720  return false;
1721  }
1722 
1723  // Finally, check if the warning flags maps to a diagnostic group.
1724  // We construct a SmallVector here to talk to getDiagnosticIDs().
1725  // Although we don't use the result, this isn't a hot path, and not
1726  // worth special casing.
1728  return !getDiagnostics().getDiagnosticIDs()->
1730  WarningName.substr(2), Diags);
1731  });
1732  } else if (II == Ident__building_module) {
1733  // The argument to this builtin should be an identifier. The
1734  // builtin evaluates to 1 when that identifier names the module we are
1735  // currently building.
1736  EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1737  [this](Token &Tok, bool &HasLexedNextToken) -> int {
1739  diag::err_expected_id_building_module);
1740  return getLangOpts().isCompilingModule() && II &&
1741  (II->getName() == getLangOpts().CurrentModule);
1742  });
1743  } else if (II == Ident__MODULE__) {
1744  // The current module as an identifier.
1745  OS << getLangOpts().CurrentModule;
1746  IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);
1747  Tok.setIdentifierInfo(ModuleII);
1748  Tok.setKind(ModuleII->getTokenID());
1749  } else if (II == Ident__identifier) {
1750  SourceLocation Loc = Tok.getLocation();
1751 
1752  // We're expecting '__identifier' '(' identifier ')'. Try to recover
1753  // if the parens are missing.
1754  LexNonComment(Tok);
1755  if (Tok.isNot(tok::l_paren)) {
1756  // No '(', use end of last token.
1757  Diag(getLocForEndOfToken(Loc), diag::err_pp_expected_after)
1758  << II << tok::l_paren;
1759  // If the next token isn't valid as our argument, we can't recover.
1760  if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1761  Tok.setKind(tok::identifier);
1762  return;
1763  }
1764 
1765  SourceLocation LParenLoc = Tok.getLocation();
1766  LexNonComment(Tok);
1767 
1768  if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1769  Tok.setKind(tok::identifier);
1770  else {
1771  Diag(Tok.getLocation(), diag::err_pp_identifier_arg_not_identifier)
1772  << Tok.getKind();
1773  // Don't walk past anything that's not a real token.
1774  if (Tok.isOneOf(tok::eof, tok::eod) || Tok.isAnnotation())
1775  return;
1776  }
1777 
1778  // Discard the ')', preserving 'Tok' as our result.
1779  Token RParen;
1780  LexNonComment(RParen);
1781  if (RParen.isNot(tok::r_paren)) {
1782  Diag(getLocForEndOfToken(Tok.getLocation()), diag::err_pp_expected_after)
1783  << Tok.getKind() << tok::r_paren;
1784  Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1785  }
1786  return;
1787  } else if (II == Ident__is_target_arch) {
1789  OS, Tok, II, *this, [this](Token &Tok, bool &HasLexedNextToken) -> int {
1791  Tok, *this, diag::err_feature_check_malformed);
1792  return II && isTargetArch(getTargetInfo(), II);
1793  });
1794  } else if (II == Ident__is_target_vendor) {
1796  OS, Tok, II, *this, [this](Token &Tok, bool &HasLexedNextToken) -> int {
1798  Tok, *this, diag::err_feature_check_malformed);
1799  return II && isTargetVendor(getTargetInfo(), II);
1800  });
1801  } else if (II == Ident__is_target_os) {
1803  OS, Tok, II, *this, [this](Token &Tok, bool &HasLexedNextToken) -> int {
1805  Tok, *this, diag::err_feature_check_malformed);
1806  return II && isTargetOS(getTargetInfo(), II);
1807  });
1808  } else if (II == Ident__is_target_environment) {
1810  OS, Tok, II, *this, [this](Token &Tok, bool &HasLexedNextToken) -> int {
1812  Tok, *this, diag::err_feature_check_malformed);
1813  return II && isTargetEnvironment(getTargetInfo(), II);
1814  });
1815  } else {
1816  llvm_unreachable("Unknown identifier!");
1817  }
1818  CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation());
1819 }
1820 
1822  // If the 'used' status changed, and the macro requires 'unused' warning,
1823  // remove its SourceLocation from the warn-for-unused-macro locations.
1824  if (MI->isWarnIfUnused() && !MI->isUsed())
1825  WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1826  MI->setIsUsed(true);
1827 }
A diagnostic that indicates a problem or potential problem.
static IdentifierInfo * RegisterBuiltinMacro(Preprocessor &PP, const char *Name)
RegisterBuiltinMacro - Register the specified identifier in the identifier table and mark it as a bui...
StringRef Identifier
Definition: Format.cpp:1635
static bool CheckMatchedBrackets(const SmallVectorImpl< Token > &Tokens)
CheckMatchedBrackets - Returns true if the braces and parentheses in the token vector are properly ne...
Lexer - This provides a simple interface that turns a text buffer into a stream of tokens...
Definition: Lexer.h:76
MacroInfo * AllocateMacroInfo(SourceLocation L)
Allocate a new MacroInfo object with the provided SourceLocation.
param_iterator param_begin() const
Definition: MacroInfo.h:180
bool ConcatenateIncludeName(SmallString< 128 > &FilenameBuffer, SourceLocation &End)
Handle cases where the #include name is expanded from a macro as multiple tokens, which need to be gl...
void setChangedSinceDeserialization()
Note that this identifier has changed since it was loaded from an AST file.
void markMacroAsUsed(MacroInfo *MI)
A macro is used, update information about macros that need unused warnings.
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
void setFlagValue(TokenFlags Flag, bool Val)
Set a flag to either true or false.
Definition: Token.h:256
Defines the clang::FileManager interface and associated types.
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:962
ModuleMacro * addModuleMacro(Module *Mod, IdentifierInfo *II, MacroInfo *Macro, ArrayRef< ModuleMacro *> Overrides, bool &IsNew)
Register an exported macro for a module and identifier.
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {...
Definition: Token.h:94
void dumpMacroInfo(const IdentifierInfo *II)
bool isEnabled() const
Return true if this macro is enabled.
Definition: MacroInfo.h:258
Is the identifier known as a __declspec-style attribute?
bool isInPrimaryFile() const
Return true if we&#39;re in the top-level file, not in a #include.
static bool EvaluateHasIncludeCommon(Token &Tok, IdentifierInfo *II, Preprocessor &PP, const DirectoryLookup *LookupFrom, const FileEntry *LookupFromFile)
EvaluateHasIncludeCommon - Process a &#39;__has_include("path")&#39; or &#39;__has_include_next("path")&#39; expressi...
Defines the clang::MacroInfo and clang::MacroDirective classes.
Is the identifier known as a GNU-style attribute?
Defines types useful for describing an Objective-C runtime.
A description of the current definition of a macro.
Definition: MacroInfo.h:564
static bool GenerateNewArgTokens(Preprocessor &PP, SmallVectorImpl< Token > &OldTokens, SmallVectorImpl< Token > &NewTokens, unsigned &NumArgs, SmallVectorImpl< SourceRange > &ParenHints, SmallVectorImpl< SourceRange > &InitLists)
GenerateNewArgTokens - Returns true if OldTokens can be converted to a new vector of tokens in NewTok...
bool isOutOfDate() const
Determine whether the information for this identifier is out of date with respect to the external sou...
static bool isTargetEnvironment(const TargetInfo &TI, const IdentifierInfo *II)
Implements the __is_target_environment builtin macro.
void setFlag(TokenFlags Flag)
Set the specified flag.
Definition: Token.h:233
bool isCompilingModule() const
Are we compiling a module interface (.cppm or module map)?
Definition: LangOptions.h:262
bool isFromAST() const
Return true if the identifier in its current state was loaded from an AST file.
bool isVariadic() const
Definition: MacroInfo.h:207
diag::Severity getExtensionHandlingBehavior() const
Definition: Diagnostic.h:687
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
Definition: SourceManager.h:77
This interface provides a way to observe the actions of the preprocessor as it does its thing...
Definition: PPCallbacks.h:35
bool isAnnotation() const
Return true if this is any of tok::annot_* kind tokens.
Definition: Token.h:117
const MacroDirective * getPrevious() const
Get previous definition of the macro with the same name.
Definition: MacroInfo.h:328
tok::TokenKind getKind() const
Definition: Token.h:89
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
DefMacroDirective * appendDefMacroDirective(IdentifierInfo *II, MacroInfo *MI, SourceLocation Loc)
One of these records is kept for each identifier that is lexed.
Represents a macro directive exported by a module.
Definition: MacroInfo.h:488
static bool HasFeature(const Preprocessor &PP, StringRef Feature)
HasFeature - Return true if we recognize and implement the feature specified by the identifier as a s...
void setHasMacroDefinition(bool Val)
LineState State
static bool isTargetOS(const TargetInfo &TI, const IdentifierInfo *II)
Implements the __is_target_os builtin macro.
static bool getDiagnosticsInGroup(diag::Flavor Flavor, const WarningOption *Group, SmallVectorImpl< diag::kind > &Diags)
Return true if any diagnostics were found in this group, even if they were filtered out due to having...
bool hasCommaPasting() const
Definition: MacroInfo.h:217
const TargetInfo & getTargetInfo() const
Definition: Preprocessor.h:818
Token - This structure provides full information about a lexed token.
Definition: Token.h:34
void setKind(tok::TokenKind K)
Definition: Token.h:90
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:49
const LangOptions & getLangOpts() const
Definition: Preprocessor.h:817
AttrSyntax
Definition: Attributes.h:19
Describes a module or submodule.
Definition: Module.h:64
static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc, Preprocessor &PP)
ComputeDATE_TIME - Compute the current time, enter it into the specified scratch buffer, then return DATELoc/TIMELoc locations with the position of the identifier tokens inserted.
param_iterator param_end() const
Definition: MacroInfo.h:181
SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, unsigned Char) const
Given a location that specifies the start of a token, return a new location that specifies a characte...
Module * getCurrentLexerSubmodule() const
Return the submodule owning the file being lexed.
Definition: Preprocessor.h:899
static IdentifierInfo * ExpectFeatureIdentifierInfo(Token &Tok, Preprocessor &PP, signed DiagID)
Helper function to return the IdentifierInfo structure of a Token or generate a diagnostic if none av...
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the &#39;spelling&#39; of the token at the given location; does not go up to the spelling location or ...
HeaderSearch & getHeaderSearchInfo() const
Definition: Preprocessor.h:823
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
static void EvaluateFeatureLikeBuiltinMacro(llvm::raw_svector_ostream &OS, Token &Tok, IdentifierInfo *II, Preprocessor &PP, llvm::function_ref< int(Token &Tok, bool &HasLexedNextTok)> Op)
Process single-argument builtin feature-like macros that return integer values.
const Token & getReplacementToken(unsigned Tok) const
Definition: MacroInfo.h:235
const FormatToken & Tok
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
void LexNonComment(Token &Result)
Lex a token.
bool GetIncludeFilenameSpelling(SourceLocation Loc, StringRef &Buffer)
Turn the specified lexer token into a fully checked and spelled filename, e.g.
void ExpandedMacro()
ExpandedMacro - When a macro is expanded with this lexer as the current buffer, this method is called...
static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II, Preprocessor &PP)
EvaluateHasInclude - Process a &#39;__has_include("path")&#39; expression.
void destroy(Preprocessor &PP)
destroy - Destroy and deallocate the memory for this object.
Definition: MacroArgs.cpp:78
TokenLexer - This implements a lexer that returns tokens from a macro body or token stream instead of...
Definition: TokenLexer.h:30
Present this diagnostic as an error.
int hasAttribute(AttrSyntax Syntax, const IdentifierInfo *Scope, const IdentifierInfo *Attr, const TargetInfo &Target, const LangOptions &LangOpts)
Return the version number associated with the attribute if we recognize and implement the attribute s...
Definition: Attributes.cpp:7
bool isUsed() const
Return false if this macro is defined in the main file and has not yet been used. ...
Definition: MacroInfo.h:222
void appendMacroDirective(IdentifierInfo *II, MacroDirective *MD)
Add a directive to the macro directive history for this identifier.
void LexUnexpandedToken(Token &Result)
Just like Lex, but disables macro expansion of identifier tokens.
return Out str()
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:1042
std::string CurrentModule
The name of the current module, of which the main source file is a part.
Definition: LangOptions.h:226
StringRef Filename
Definition: Format.cpp:1628
unsigned getNumParams() const
Definition: MacroInfo.h:182
Exposes information about the current target.
Definition: TargetInfo.h:161
bool isValid() const
Defines the clang::LangOptions interface.
bool isInvalid() const
Return true if this object is invalid or uninitialized.
int Id
Definition: ASTDiff.cpp:190
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
static bool isTargetVendor(const TargetInfo &TI, const IdentifierInfo *II)
Implements the __is_target_vendor builtin macro.
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
bool isDefined() const
Definition: MacroInfo.h:384
MacroArgs - An instance of this class captures information about the formal arguments specified to a ...
Definition: MacroArgs.h:29
unsigned getLine() const
Return the presumed line number of this location.
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file. ...
Definition: Token.h:123
Defines the clang::Preprocessor interface.
MultipleIncludeOpt MIOpt
A state machine that detects the #ifndef-wrapping a file idiom for the multiple-include optimization...
int Depth
Definition: ASTDiff.cpp:190
const MacroInfo * getMacroInfo(const IdentifierInfo *II) const
Definition: Preprocessor.h:983
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Represents an unpacked "presumed" location which can be presented to the user.
PPCallbacks * getPPCallbacks() const
Definition: Preprocessor.h:909
bool isObjectLike() const
Definition: MacroInfo.h:200
The result type of a method or function.
static bool HasExtension(const Preprocessor &PP, StringRef Extension)
HasExtension - Return true if we recognize and implement the feature specified by the identifier...
DirectoryLookup - This class represents one entry in the search list that specifies the search order ...
const DirectoryLookup * GetCurDirLookup()
Get the DirectoryLookup structure used to find the current FileEntry, if CurLexer is non-null and if ...
unsigned getBuiltinID() const
Return a value indicating whether this is a builtin function.
void setIsUsed(bool Val)
Set the value of the IsUsed flag.
Definition: MacroInfo.h:152
SrcMgr::CharacteristicKind getFileDirFlavor(const FileEntry *File)
Return whether the specified file is a normal header, a system header, or a C++ friendly system heade...
Definition: HeaderSearch.h:434
const char * getFilename() const
Return the presumed filename of this location.
ExternalPreprocessorSource * getExternalSource() const
Definition: Preprocessor.h:835
Encapsulates changes to the "macros namespace" (the location where the macro name became active...
Definition: MacroInfo.h:290
Encodes a location in the source.
static bool isTargetArch(const TargetInfo &TI, const IdentifierInfo *II)
Implements the __is_target_arch builtin macro.
static bool isTrivialSingleTokenExpansion(const MacroInfo *MI, const IdentifierInfo *MacroIdent, Preprocessor &PP)
isTrivialSingleTokenExpansion - Return true if MI, which has a single token in its expansion...
void setLength(unsigned Len)
Definition: Token.h:132
SourceLocation createExpansionLoc(SourceLocation Loc, SourceLocation ExpansionLocStart, SourceLocation ExpansionLocEnd, unsigned TokLength, bool ExpansionIsTokenRange=true, int LoadedID=0, unsigned LoadedOffset=0)
Return a new SourceLocation that encodes the fact that a token from SpellingLoc should actually be re...
MacroDirective * getLocalMacroDirectiveHistory(const IdentifierInfo *II) const
Given an identifier, return the latest non-imported macro directive for that identifier.
static bool EvaluateHasIncludeNext(Token &Tok, IdentifierInfo *II, Preprocessor &PP)
EvaluateHasIncludeNext - Process &#39;__has_include_next("path")&#39; expression.
IdentifierInfo * getIdentifierInfo() const
Definition: Token.h:176
Cached information about one file (either on disk or in the virtual file system). ...
Definition: FileManager.h:59
void setIdentifierInfo(IdentifierInfo *II)
Definition: Token.h:185
void setIsBuiltinMacro(bool Val=true)
Set or clear the isBuiltinMacro flag.
Definition: MacroInfo.h:149
void Lex(Token &Result)
Lex the next token for this preprocessor.
const char * getNameStart() const
Return the beginning of the actual null-terminated string for this identifier.
void setLoadedMacroDirective(IdentifierInfo *II, MacroDirective *ED, MacroDirective *MD)
Set a MacroDirective that was loaded from a PCH file.
bool isAtStartOfLine() const
isAtStartOfLine - Return true if this token is at the start of a line.
Definition: Token.h:265
PreprocessorLexer * getCurrentLexer() const
Return the current lexer being lexed from.
Definition: Preprocessor.h:889
const FileEntry * LookupFile(SourceLocation FilenameLoc, StringRef Filename, bool isAngled, const DirectoryLookup *FromDir, const FileEntry *FromFile, const DirectoryLookup *&CurDir, SmallVectorImpl< char > *SearchPath, SmallVectorImpl< char > *RelativePath, ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped, bool *IsFrameworkFound, bool SkipCache=false)
Given a "foo" or <foo> reference, look up the indicated file.
StringRef getName() const
Return the actual identifier string.
bool isNot(tok::TokenKind K) const
Definition: Token.h:95
bool hadMacroDefinition() const
Returns true if this identifier was #defined to some value at any moment.
Dataflow Directional Tag Classes.
bool isWarnIfUnused() const
Return true if we should emit a warning if the macro is unused.
Definition: MacroInfo.h:230
bool isValid() const
Return true if this is a valid SourceLocation object.
unsigned getNumTokens() const
Return the number of tokens that this macro expands to.
Definition: MacroInfo.h:233
bool isFunctionLike() const
Definition: MacroInfo.h:199
const FileEntry * getFileEntry() const
getFileEntry - Return the FileEntry corresponding to this FileID.
bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const
Definition: Token.h:96
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.
bool IsHeaderFile
Indicates whether the front-end is explicitly told that the input is a header file (i...
Definition: LangOptions.h:250
unsigned getLength() const
Definition: Token.h:126
Encapsulates the data about a macro definition (e.g.
Definition: MacroInfo.h:39
static ModuleMacro * create(Preprocessor &PP, Module *OwningModule, IdentifierInfo *II, MacroInfo *Macro, ArrayRef< ModuleMacro *> Overrides)
Definition: MacroInfo.cpp:241
bool FinishLexStringLiteral(Token &Result, std::string &String, const char *DiagnosticTag, bool AllowMacroExpansion)
Complete the lexing of a string literal where the first token has already been lexed (see LexStringLi...
virtual void updateOutOfDateIdentifier(IdentifierInfo &II)=0
Update an out-of-date identifier.
void CreateString(StringRef Str, Token &Tok, SourceLocation ExpansionLocStart=SourceLocation(), SourceLocation ExpansionLocEnd=SourceLocation())
Plop the specified string into a scratch buffer and set the specified token&#39;s location and length to ...
SourceLocation getEnd() const
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:91
SourceLocation getDefinitionLoc() const
Return the location that the macro was defined at.
Definition: MacroInfo.h:123
CharSourceRange getExpansionRange(SourceLocation Loc) const
Given a SourceLocation object, return the range of tokens covered by the expansion in the ultimate fi...
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition: Diagnostic.h:494
Defines the clang::SourceLocation class and associated facilities.
ModuleMacro * getModuleMacro(Module *Mod, IdentifierInfo *II)
DiagnosticsEngine & getDiagnostics() const
Definition: Preprocessor.h:814
bool isAmbiguous() const
true if the definition is ambiguous, false otherwise.
Definition: MacroInfo.h:589
static MacroArgs * create(const MacroInfo *MI, ArrayRef< Token > UnexpArgTokens, bool VarargsElided, Preprocessor &PP)
MacroArgs ctor function - Create a new MacroArgs object with the specified macro and argument info...
Definition: MacroArgs.cpp:24
bool isBuiltinMacro() const
Return true if this macro requires processing before expansion.
Definition: MacroInfo.h:215
Defines the clang::TargetInfo interface.
void setPrevious(MacroDirective *Prev)
Set previous definition of the macro with the same name.
Definition: MacroInfo.h:325
void forAllDefinitions(Fn F) const
Definition: MacroInfo.h:600
MacroInfo * getMacroInfo() const
Get the MacroInfo that should be used for this definition.
Definition: MacroInfo.h:580
void EnterMacro(Token &Tok, SourceLocation ILEnd, MacroInfo *Macro, MacroArgs *Args)
Add a Macro to the top of the include stack and start lexing tokens from it instead of the current bu...
void setLocation(SourceLocation L)
Definition: Token.h:131
bool isParsingIfOrElifDirective() const
True if we are currently preprocessing a if or #elif directive.
Definition: Preprocessor.h:847
A trivial tuple used to represent a source range.
PreprocessorLexer * getCurrentFileLexer() const
Return the current file lexer being lexed from.
unsigned getFlags() const
Return the internal represtation of the flags.
Definition: Token.h:251
void clearFlag(TokenFlags Flag)
Unset the specified flag.
Definition: Token.h:243
SourceLocation getIncludeLoc() const
Return the presumed include location of this location.
Defines the PreprocessorLexer interface.
void LexIncludeFilename(Token &FilenameTok)
After the preprocessor has parsed a #include, lex and (potentially) macro expand the filename...
virtual void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned ArgumentIndex)
Callback invoked when performing code completion inside a function-like macro argument.
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: MacroInfo.h:519
bool hasLeadingSpace() const
Return true if this token has whitespace before it.
Definition: Token.h:269
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
void startToken()
Reset all flags to cleared.
Definition: Token.h:168
static std::string Stringify(StringRef Str, bool Charify=false)
Stringify - Convert the specified string into a C string by i) escaping &#39;\&#39; and " characters and ii) ...
Definition: Lexer.cpp:246
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:124