clang  6.0.0svn
DeclBase.cpp
Go to the documentation of this file.
1 //===--- DeclBase.cpp - Declaration AST Node Implementation ---------------===//
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 Decl and DeclContext classes.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/DeclBase.h"
15 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclFriend.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclOpenMP.h"
24 #include "clang/AST/DeclTemplate.h"
27 #include "clang/AST/Stmt.h"
28 #include "clang/AST/StmtCXX.h"
29 #include "clang/AST/Type.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include <algorithm>
33 using namespace clang;
34 
35 //===----------------------------------------------------------------------===//
36 // Statistics
37 //===----------------------------------------------------------------------===//
38 
39 #define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
40 #define ABSTRACT_DECL(DECL)
41 #include "clang/AST/DeclNodes.inc"
42 
45 }
46 
47 #define DECL(DERIVED, BASE) \
48  static_assert(alignof(Decl) >= alignof(DERIVED##Decl), \
49  "Alignment sufficient after objects prepended to " #DERIVED);
50 #define ABSTRACT_DECL(DECL)
51 #include "clang/AST/DeclNodes.inc"
52 
53 void *Decl::operator new(std::size_t Size, const ASTContext &Context,
54  unsigned ID, std::size_t Extra) {
55  // Allocate an extra 8 bytes worth of storage, which ensures that the
56  // resulting pointer will still be 8-byte aligned.
57  static_assert(sizeof(unsigned) * 2 >= alignof(Decl),
58  "Decl won't be misaligned");
59  void *Start = Context.Allocate(Size + Extra + 8);
60  void *Result = (char*)Start + 8;
61 
62  unsigned *PrefixPtr = (unsigned *)Result - 2;
63 
64  // Zero out the first 4 bytes; this is used to store the owning module ID.
65  PrefixPtr[0] = 0;
66 
67  // Store the global declaration ID in the second 4 bytes.
68  PrefixPtr[1] = ID;
69 
70  return Result;
71 }
72 
73 void *Decl::operator new(std::size_t Size, const ASTContext &Ctx,
74  DeclContext *Parent, std::size_t Extra) {
75  assert(!Parent || &Parent->getParentASTContext() == &Ctx);
76  // With local visibility enabled, we track the owning module even for local
77  // declarations. We create the TU decl early and may not yet know what the
78  // LangOpts are, so conservatively allocate the storage.
79  if (Ctx.getLangOpts().trackLocalOwningModule() || !Parent) {
80  // Ensure required alignment of the resulting object by adding extra
81  // padding at the start if required.
82  size_t ExtraAlign =
83  llvm::OffsetToAlignment(sizeof(Module *), alignof(Decl));
84  char *Buffer = reinterpret_cast<char *>(
85  ::operator new(ExtraAlign + sizeof(Module *) + Size + Extra, Ctx));
86  Buffer += ExtraAlign;
87  auto *ParentModule =
88  Parent ? cast<Decl>(Parent)->getOwningModule() : nullptr;
89  return new (Buffer) Module*(ParentModule) + 1;
90  }
91  return ::operator new(Size + Extra, Ctx);
92 }
93 
94 Module *Decl::getOwningModuleSlow() const {
95  assert(isFromASTFile() && "Not from AST file?");
97 }
98 
101 }
102 
103 const char *Decl::getDeclKindName() const {
104  switch (DeclKind) {
105  default: llvm_unreachable("Declaration not in DeclNodes.inc!");
106 #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
107 #define ABSTRACT_DECL(DECL)
108 #include "clang/AST/DeclNodes.inc"
109  }
110 }
111 
112 void Decl::setInvalidDecl(bool Invalid) {
113  InvalidDecl = Invalid;
114  assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
115  if (!Invalid) {
116  return;
117  }
118 
119  if (!isa<ParmVarDecl>(this)) {
120  // Defensive maneuver for ill-formed code: we're likely not to make it to
121  // a point where we set the access specifier, so default it to "public"
122  // to avoid triggering asserts elsewhere in the front end.
124  }
125 
126  // Marking a DecompositionDecl as invalid implies all the child BindingDecl's
127  // are invalid too.
128  if (DecompositionDecl *DD = dyn_cast<DecompositionDecl>(this)) {
129  for (BindingDecl *Binding : DD->bindings()) {
130  Binding->setInvalidDecl();
131  }
132  }
133 }
134 
135 const char *DeclContext::getDeclKindName() const {
136  switch (DeclKind) {
137  default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
138 #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
139 #define ABSTRACT_DECL(DECL)
140 #include "clang/AST/DeclNodes.inc"
141  }
142 }
143 
144 bool Decl::StatisticsEnabled = false;
146  StatisticsEnabled = true;
147 }
148 
150  llvm::errs() << "\n*** Decl Stats:\n";
151 
152  int totalDecls = 0;
153 #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
154 #define ABSTRACT_DECL(DECL)
155 #include "clang/AST/DeclNodes.inc"
156  llvm::errs() << " " << totalDecls << " decls total.\n";
157 
158  int totalBytes = 0;
159 #define DECL(DERIVED, BASE) \
160  if (n##DERIVED##s > 0) { \
161  totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
162  llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
163  << sizeof(DERIVED##Decl) << " each (" \
164  << n##DERIVED##s * sizeof(DERIVED##Decl) \
165  << " bytes)\n"; \
166  }
167 #define ABSTRACT_DECL(DECL)
168 #include "clang/AST/DeclNodes.inc"
169 
170  llvm::errs() << "Total bytes = " << totalBytes << "\n";
171 }
172 
173 void Decl::add(Kind k) {
174  switch (k) {
175 #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
176 #define ABSTRACT_DECL(DECL)
177 #include "clang/AST/DeclNodes.inc"
178  }
179 }
180 
182  if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
183  return TTP->isParameterPack();
184  if (const NonTypeTemplateParmDecl *NTTP
185  = dyn_cast<NonTypeTemplateParmDecl>(this))
186  return NTTP->isParameterPack();
187  if (const TemplateTemplateParmDecl *TTP
188  = dyn_cast<TemplateTemplateParmDecl>(this))
189  return TTP->isParameterPack();
190  return false;
191 }
192 
193 bool Decl::isParameterPack() const {
194  if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
195  return Parm->isParameterPack();
196 
197  return isTemplateParameterPack();
198 }
199 
201  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
202  return FD;
203  if (const FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(this))
204  return FTD->getTemplatedDecl();
205  return nullptr;
206 }
207 
208 bool Decl::isTemplateDecl() const {
209  return isa<TemplateDecl>(this);
210 }
211 
213  if (auto *FD = dyn_cast<FunctionDecl>(this))
214  return FD->getDescribedFunctionTemplate();
215  else if (auto *RD = dyn_cast<CXXRecordDecl>(this))
216  return RD->getDescribedClassTemplate();
217  else if (auto *VD = dyn_cast<VarDecl>(this))
218  return VD->getDescribedVarTemplate();
219 
220  return nullptr;
221 }
222 
224  for (const DeclContext *DC = getDeclContext();
225  DC && !DC->isTranslationUnit() && !DC->isNamespace();
226  DC = DC->getParent())
227  if (DC->isFunctionOrMethod())
228  return DC;
229 
230  return nullptr;
231 }
232 
233 
234 //===----------------------------------------------------------------------===//
235 // PrettyStackTraceDecl Implementation
236 //===----------------------------------------------------------------------===//
237 
238 void PrettyStackTraceDecl::print(raw_ostream &OS) const {
239  SourceLocation TheLoc = Loc;
240  if (TheLoc.isInvalid() && TheDecl)
241  TheLoc = TheDecl->getLocation();
242 
243  if (TheLoc.isValid()) {
244  TheLoc.print(OS, SM);
245  OS << ": ";
246  }
247 
248  OS << Message;
249 
250  if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
251  OS << " '";
252  DN->printQualifiedName(OS);
253  OS << '\'';
254  }
255  OS << '\n';
256 }
257 
258 //===----------------------------------------------------------------------===//
259 // Decl Implementation
260 //===----------------------------------------------------------------------===//
261 
262 // Out-of-line virtual method providing a home for Decl.
264 
266  DeclCtx = DC;
267 }
268 
270  if (DC == getLexicalDeclContext())
271  return;
272 
273  if (isInSemaDC()) {
274  setDeclContextsImpl(getDeclContext(), DC, getASTContext());
275  } else {
276  getMultipleDC()->LexicalDC = DC;
277  }
278 
279  // FIXME: We shouldn't be changing the lexical context of declarations
280  // imported from AST files.
281  if (!isFromASTFile()) {
282  setModuleOwnershipKind(getModuleOwnershipKindForChildOf(DC));
283  if (hasOwningModule())
284  setLocalOwningModule(cast<Decl>(DC)->getOwningModule());
285  }
286 
287  assert(
289  getOwningModule()) &&
290  "hidden declaration has no owning module");
291 }
292 
293 void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
294  ASTContext &Ctx) {
295  if (SemaDC == LexicalDC) {
296  DeclCtx = SemaDC;
297  } else {
298  Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
299  MDC->SemanticDC = SemaDC;
300  MDC->LexicalDC = LexicalDC;
301  DeclCtx = MDC;
302  }
303 }
304 
306  const DeclContext *LDC = getLexicalDeclContext();
307  while (true) {
308  if (LDC->isFunctionOrMethod())
309  return true;
310  if (!isa<TagDecl>(LDC))
311  return false;
312  LDC = LDC->getLexicalParent();
313  }
314  return false;
315 }
316 
318  for (const DeclContext *DC = getDeclContext(); DC; DC = DC->getParent()) {
319  if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
320  if (ND->isAnonymousNamespace())
321  return true;
322  }
323 
324  return false;
325 }
326 
328  return getDeclContext()->isStdNamespace();
329 }
330 
332  if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
333  return TUD;
334 
335  DeclContext *DC = getDeclContext();
336  assert(DC && "This decl is not contained in a translation unit!");
337 
338  while (!DC->isTranslationUnit()) {
339  DC = DC->getParent();
340  assert(DC && "This decl is not contained in a translation unit!");
341  }
342 
343  return cast<TranslationUnitDecl>(DC);
344 }
345 
348 }
349 
352 }
353 
354 unsigned Decl::getMaxAlignment() const {
355  if (!hasAttrs())
356  return 0;
357 
358  unsigned Align = 0;
359  const AttrVec &V = getAttrs();
360  ASTContext &Ctx = getASTContext();
361  specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
362  for (; I != E; ++I)
363  Align = std::max(Align, I->getAlignment(Ctx));
364  return Align;
365 }
366 
367 bool Decl::isUsed(bool CheckUsedAttr) const {
368  const Decl *CanonD = getCanonicalDecl();
369  if (CanonD->Used)
370  return true;
371 
372  // Check for used attribute.
373  // Ask the most recent decl, since attributes accumulate in the redecl chain.
374  if (CheckUsedAttr && getMostRecentDecl()->hasAttr<UsedAttr>())
375  return true;
376 
377  // The information may have not been deserialized yet. Force deserialization
378  // to complete the needed information.
379  return getMostRecentDecl()->getCanonicalDecl()->Used;
380 }
381 
383  if (isUsed(false))
384  return;
385 
386  if (C.getASTMutationListener())
388 
389  setIsUsed();
390 }
391 
392 bool Decl::isReferenced() const {
393  if (Referenced)
394  return true;
395 
396  // Check redeclarations.
397  for (auto I : redecls())
398  if (I->Referenced)
399  return true;
400 
401  return false;
402 }
403 
404 bool Decl::isExported() const {
405  if (isModulePrivate())
406  return false;
407  // Namespaces are always exported.
408  if (isa<TranslationUnitDecl>(this) || isa<NamespaceDecl>(this))
409  return true;
410  // Otherwise, this is a strictly lexical check.
411  for (auto *DC = getLexicalDeclContext(); DC; DC = DC->getLexicalParent()) {
412  if (cast<Decl>(DC)->isModulePrivate())
413  return false;
414  if (isa<ExportDecl>(DC))
415  return true;
416  }
417  return false;
418 }
419 
420 ExternalSourceSymbolAttr *Decl::getExternalSourceSymbolAttr() const {
421  const Decl *Definition = nullptr;
422  if (auto ID = dyn_cast<ObjCInterfaceDecl>(this)) {
423  Definition = ID->getDefinition();
424  } else if (auto PD = dyn_cast<ObjCProtocolDecl>(this)) {
425  Definition = PD->getDefinition();
426  } else if (auto TD = dyn_cast<TagDecl>(this)) {
427  Definition = TD->getDefinition();
428  }
429  if (!Definition)
430  Definition = this;
431 
432  if (auto *attr = Definition->getAttr<ExternalSourceSymbolAttr>())
433  return attr;
434  if (auto *dcd = dyn_cast<Decl>(getDeclContext())) {
435  return dcd->getAttr<ExternalSourceSymbolAttr>();
436  }
437 
438  return nullptr;
439 }
440 
441 bool Decl::hasDefiningAttr() const {
442  return hasAttr<AliasAttr>() || hasAttr<IFuncAttr>();
443 }
444 
445 const Attr *Decl::getDefiningAttr() const {
446  if (AliasAttr *AA = getAttr<AliasAttr>())
447  return AA;
448  if (IFuncAttr *IFA = getAttr<IFuncAttr>())
449  return IFA;
450  return nullptr;
451 }
452 
453 static StringRef getRealizedPlatform(const AvailabilityAttr *A,
454  const ASTContext &Context) {
455  // Check if this is an App Extension "platform", and if so chop off
456  // the suffix for matching with the actual platform.
457  StringRef RealizedPlatform = A->getPlatform()->getName();
458  if (!Context.getLangOpts().AppExt)
459  return RealizedPlatform;
460  size_t suffix = RealizedPlatform.rfind("_app_extension");
461  if (suffix != StringRef::npos)
462  return RealizedPlatform.slice(0, suffix);
463  return RealizedPlatform;
464 }
465 
466 /// \brief Determine the availability of the given declaration based on
467 /// the target platform.
468 ///
469 /// When it returns an availability result other than \c AR_Available,
470 /// if the \p Message parameter is non-NULL, it will be set to a
471 /// string describing why the entity is unavailable.
472 ///
473 /// FIXME: Make these strings localizable, since they end up in
474 /// diagnostics.
476  const AvailabilityAttr *A,
477  std::string *Message,
478  VersionTuple EnclosingVersion) {
479  if (EnclosingVersion.empty())
480  EnclosingVersion = Context.getTargetInfo().getPlatformMinVersion();
481 
482  if (EnclosingVersion.empty())
483  return AR_Available;
484 
485  StringRef ActualPlatform = A->getPlatform()->getName();
486  StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
487 
488  // Match the platform name.
489  if (getRealizedPlatform(A, Context) != TargetPlatform)
490  return AR_Available;
491 
492  StringRef PrettyPlatformName
493  = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
494 
495  if (PrettyPlatformName.empty())
496  PrettyPlatformName = ActualPlatform;
497 
498  std::string HintMessage;
499  if (!A->getMessage().empty()) {
500  HintMessage = " - ";
501  HintMessage += A->getMessage();
502  }
503 
504  // Make sure that this declaration has not been marked 'unavailable'.
505  if (A->getUnavailable()) {
506  if (Message) {
507  Message->clear();
508  llvm::raw_string_ostream Out(*Message);
509  Out << "not available on " << PrettyPlatformName
510  << HintMessage;
511  }
512 
513  return AR_Unavailable;
514  }
515 
516  // Make sure that this declaration has already been introduced.
517  if (!A->getIntroduced().empty() &&
518  EnclosingVersion < A->getIntroduced()) {
519  if (Message) {
520  Message->clear();
521  llvm::raw_string_ostream Out(*Message);
522  VersionTuple VTI(A->getIntroduced());
523  VTI.UseDotAsSeparator();
524  Out << "introduced in " << PrettyPlatformName << ' '
525  << VTI << HintMessage;
526  }
527 
528  return A->getStrict() ? AR_Unavailable : AR_NotYetIntroduced;
529  }
530 
531  // Make sure that this declaration hasn't been obsoleted.
532  if (!A->getObsoleted().empty() && EnclosingVersion >= A->getObsoleted()) {
533  if (Message) {
534  Message->clear();
535  llvm::raw_string_ostream Out(*Message);
536  VersionTuple VTO(A->getObsoleted());
537  VTO.UseDotAsSeparator();
538  Out << "obsoleted in " << PrettyPlatformName << ' '
539  << VTO << HintMessage;
540  }
541 
542  return AR_Unavailable;
543  }
544 
545  // Make sure that this declaration hasn't been deprecated.
546  if (!A->getDeprecated().empty() && EnclosingVersion >= A->getDeprecated()) {
547  if (Message) {
548  Message->clear();
549  llvm::raw_string_ostream Out(*Message);
550  VersionTuple VTD(A->getDeprecated());
551  VTD.UseDotAsSeparator();
552  Out << "first deprecated in " << PrettyPlatformName << ' '
553  << VTD << HintMessage;
554  }
555 
556  return AR_Deprecated;
557  }
558 
559  return AR_Available;
560 }
561 
563  VersionTuple EnclosingVersion) const {
564  if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
565  return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion);
566 
568  std::string ResultMessage;
569 
570  for (const auto *A : attrs()) {
571  if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
572  if (Result >= AR_Deprecated)
573  continue;
574 
575  if (Message)
576  ResultMessage = Deprecated->getMessage();
577 
578  Result = AR_Deprecated;
579  continue;
580  }
581 
582  if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
583  if (Message)
584  *Message = Unavailable->getMessage();
585  return AR_Unavailable;
586  }
587 
588  if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
590  Message, EnclosingVersion);
591 
592  if (AR == AR_Unavailable)
593  return AR_Unavailable;
594 
595  if (AR > Result) {
596  Result = AR;
597  if (Message)
598  ResultMessage.swap(*Message);
599  }
600  continue;
601  }
602  }
603 
604  if (Message)
605  Message->swap(ResultMessage);
606  return Result;
607 }
608 
610  const ASTContext &Context = getASTContext();
611  StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
612  for (const auto *A : attrs()) {
613  if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
614  if (getRealizedPlatform(Availability, Context) != TargetPlatform)
615  continue;
616  if (!Availability->getIntroduced().empty())
617  return Availability->getIntroduced();
618  }
619  }
620  return VersionTuple();
621 }
622 
623 bool Decl::canBeWeakImported(bool &IsDefinition) const {
624  IsDefinition = false;
625 
626  // Variables, if they aren't definitions.
627  if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
628  if (Var->isThisDeclarationADefinition()) {
629  IsDefinition = true;
630  return false;
631  }
632  return true;
633 
634  // Functions, if they aren't definitions.
635  } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
636  if (FD->hasBody()) {
637  IsDefinition = true;
638  return false;
639  }
640  return true;
641 
642  // Objective-C classes, if this is the non-fragile runtime.
643  } else if (isa<ObjCInterfaceDecl>(this) &&
645  return true;
646 
647  // Nothing else.
648  } else {
649  return false;
650  }
651 }
652 
653 bool Decl::isWeakImported() const {
654  bool IsDefinition;
655  if (!canBeWeakImported(IsDefinition))
656  return false;
657 
658  for (const auto *A : attrs()) {
659  if (isa<WeakImportAttr>(A))
660  return true;
661 
662  if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
663  if (CheckAvailability(getASTContext(), Availability, nullptr,
665  return true;
666  }
667  }
668 
669  return false;
670 }
671 
673  switch (DeclKind) {
674  case Function:
675  case CXXDeductionGuide:
676  case CXXMethod:
677  case CXXConstructor:
678  case ConstructorUsingShadow:
679  case CXXDestructor:
680  case CXXConversion:
681  case EnumConstant:
682  case Var:
683  case ImplicitParam:
684  case ParmVar:
685  case ObjCMethod:
686  case ObjCProperty:
687  case MSProperty:
688  return IDNS_Ordinary;
689  case Label:
690  return IDNS_Label;
691  case IndirectField:
692  return IDNS_Ordinary | IDNS_Member;
693 
694  case Binding:
695  case NonTypeTemplateParm:
696  case VarTemplate:
697  // These (C++-only) declarations are found by redeclaration lookup for
698  // tag types, so we include them in the tag namespace.
699  return IDNS_Ordinary | IDNS_Tag;
700 
701  case ObjCCompatibleAlias:
702  case ObjCInterface:
703  return IDNS_Ordinary | IDNS_Type;
704 
705  case Typedef:
706  case TypeAlias:
707  case TemplateTypeParm:
708  case ObjCTypeParam:
709  return IDNS_Ordinary | IDNS_Type;
710 
711  case UnresolvedUsingTypename:
713 
714  case UsingShadow:
715  return 0; // we'll actually overwrite this later
716 
717  case UnresolvedUsingValue:
718  return IDNS_Ordinary | IDNS_Using;
719 
720  case Using:
721  case UsingPack:
722  return IDNS_Using;
723 
724  case ObjCProtocol:
725  return IDNS_ObjCProtocol;
726 
727  case Field:
728  case ObjCAtDefsField:
729  case ObjCIvar:
730  return IDNS_Member;
731 
732  case Record:
733  case CXXRecord:
734  case Enum:
735  return IDNS_Tag | IDNS_Type;
736 
737  case Namespace:
738  case NamespaceAlias:
739  return IDNS_Namespace;
740 
741  case FunctionTemplate:
742  return IDNS_Ordinary;
743 
744  case ClassTemplate:
745  case TemplateTemplateParm:
746  case TypeAliasTemplate:
747  return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
748 
749  case OMPDeclareReduction:
750  return IDNS_OMPReduction;
751 
752  // Never have names.
753  case Friend:
754  case FriendTemplate:
755  case AccessSpec:
756  case LinkageSpec:
757  case Export:
758  case FileScopeAsm:
759  case StaticAssert:
760  case ObjCPropertyImpl:
761  case PragmaComment:
762  case PragmaDetectMismatch:
763  case Block:
764  case Captured:
765  case TranslationUnit:
766  case ExternCContext:
767  case Decomposition:
768 
769  case UsingDirective:
770  case BuiltinTemplate:
771  case ClassTemplateSpecialization:
772  case ClassTemplatePartialSpecialization:
773  case ClassScopeFunctionSpecialization:
774  case VarTemplateSpecialization:
775  case VarTemplatePartialSpecialization:
776  case ObjCImplementation:
777  case ObjCCategory:
778  case ObjCCategoryImpl:
779  case Import:
780  case OMPThreadPrivate:
781  case OMPCapturedExpr:
782  case Empty:
783  // Never looked up by name.
784  return 0;
785  }
786 
787  llvm_unreachable("Invalid DeclKind!");
788 }
789 
790 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
791  assert(!HasAttrs && "Decl already contains attrs.");
792 
793  AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
794  assert(AttrBlank.empty() && "HasAttrs was wrong?");
795 
796  AttrBlank = attrs;
797  HasAttrs = true;
798 }
799 
801  if (!HasAttrs) return;
802 
803  HasAttrs = false;
805 }
806 
807 const AttrVec &Decl::getAttrs() const {
808  assert(HasAttrs && "No attrs to get!");
809  return getASTContext().getDeclAttrs(this);
810 }
811 
813  Decl::Kind DK = D->getDeclKind();
814  switch(DK) {
815 #define DECL(NAME, BASE)
816 #define DECL_CONTEXT(NAME) \
817  case Decl::NAME: \
818  return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
819 #define DECL_CONTEXT_BASE(NAME)
820 #include "clang/AST/DeclNodes.inc"
821  default:
822 #define DECL(NAME, BASE)
823 #define DECL_CONTEXT_BASE(NAME) \
824  if (DK >= first##NAME && DK <= last##NAME) \
825  return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
826 #include "clang/AST/DeclNodes.inc"
827  llvm_unreachable("a decl that inherits DeclContext isn't handled");
828  }
829 }
830 
832  Decl::Kind DK = D->getKind();
833  switch(DK) {
834 #define DECL(NAME, BASE)
835 #define DECL_CONTEXT(NAME) \
836  case Decl::NAME: \
837  return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
838 #define DECL_CONTEXT_BASE(NAME)
839 #include "clang/AST/DeclNodes.inc"
840  default:
841 #define DECL(NAME, BASE)
842 #define DECL_CONTEXT_BASE(NAME) \
843  if (DK >= first##NAME && DK <= last##NAME) \
844  return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
845 #include "clang/AST/DeclNodes.inc"
846  llvm_unreachable("a decl that inherits DeclContext isn't handled");
847  }
848 }
849 
851  // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
852  // FunctionDecl stores EndRangeLoc for this purpose.
853  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
854  const FunctionDecl *Definition;
855  if (FD->hasBody(Definition))
856  return Definition->getSourceRange().getEnd();
857  return SourceLocation();
858  }
859 
860  if (Stmt *Body = getBody())
861  return Body->getSourceRange().getEnd();
862 
863  return SourceLocation();
864 }
865 
866 bool Decl::AccessDeclContextSanity() const {
867 #ifndef NDEBUG
868  // Suppress this check if any of the following hold:
869  // 1. this is the translation unit (and thus has no parent)
870  // 2. this is a template parameter (and thus doesn't belong to its context)
871  // 3. this is a non-type template parameter
872  // 4. the context is not a record
873  // 5. it's invalid
874  // 6. it's a C++0x static_assert.
875  if (isa<TranslationUnitDecl>(this) ||
876  isa<TemplateTypeParmDecl>(this) ||
877  isa<NonTypeTemplateParmDecl>(this) ||
878  !isa<CXXRecordDecl>(getDeclContext()) ||
879  isInvalidDecl() ||
880  isa<StaticAssertDecl>(this) ||
881  // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
882  // as DeclContext (?).
883  isa<ParmVarDecl>(this) ||
884  // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
885  // AS_none as access specifier.
886  isa<CXXRecordDecl>(this) ||
887  isa<ClassScopeFunctionSpecializationDecl>(this))
888  return true;
889 
890  assert(Access != AS_none &&
891  "Access specifier is AS_none inside a record decl");
892 #endif
893  return true;
894 }
895 
896 static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
897 static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
898 
899 const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
900  QualType Ty;
901  if (const ValueDecl *D = dyn_cast<ValueDecl>(this))
902  Ty = D->getType();
903  else if (const TypedefNameDecl *D = dyn_cast<TypedefNameDecl>(this))
904  Ty = D->getUnderlyingType();
905  else
906  return nullptr;
907 
908  if (Ty->isFunctionPointerType())
909  Ty = Ty->getAs<PointerType>()->getPointeeType();
910  else if (BlocksToo && Ty->isBlockPointerType())
911  Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
912 
913  return Ty->getAs<FunctionType>();
914 }
915 
916 
917 /// Starting at a given context (a Decl or DeclContext), look for a
918 /// code context that is not a closure (a lambda, block, etc.).
919 template <class T> static Decl *getNonClosureContext(T *D) {
920  if (getKind(D) == Decl::CXXMethod) {
921  CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
922  if (MD->getOverloadedOperator() == OO_Call &&
923  MD->getParent()->isLambda())
924  return getNonClosureContext(MD->getParent()->getParent());
925  return MD;
926  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
927  return FD;
928  } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
929  return MD;
930  } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
931  return getNonClosureContext(BD->getParent());
932  } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
933  return getNonClosureContext(CD->getParent());
934  } else {
935  return nullptr;
936  }
937 }
938 
941 }
942 
945 }
946 
947 //===----------------------------------------------------------------------===//
948 // DeclContext Implementation
949 //===----------------------------------------------------------------------===//
950 
951 bool DeclContext::classof(const Decl *D) {
952  switch (D->getKind()) {
953 #define DECL(NAME, BASE)
954 #define DECL_CONTEXT(NAME) case Decl::NAME:
955 #define DECL_CONTEXT_BASE(NAME)
956 #include "clang/AST/DeclNodes.inc"
957  return true;
958  default:
959 #define DECL(NAME, BASE)
960 #define DECL_CONTEXT_BASE(NAME) \
961  if (D->getKind() >= Decl::first##NAME && \
962  D->getKind() <= Decl::last##NAME) \
963  return true;
964 #include "clang/AST/DeclNodes.inc"
965  return false;
966  }
967 }
968 
970 
971 /// \brief Find the parent context of this context that will be
972 /// used for unqualified name lookup.
973 ///
974 /// Generally, the parent lookup context is the semantic context. However, for
975 /// a friend function the parent lookup context is the lexical context, which
976 /// is the class in which the friend is declared.
978  // FIXME: Find a better way to identify friends
979  if (isa<FunctionDecl>(this))
980  if (getParent()->getRedeclContext()->isFileContext() &&
981  getLexicalParent()->getRedeclContext()->isRecord())
982  return getLexicalParent();
983 
984  return getParent();
985 }
986 
988  return isNamespace() &&
989  cast<NamespaceDecl>(this)->isInline();
990 }
991 
993  if (!isNamespace())
994  return false;
995 
996  const NamespaceDecl *ND = cast<NamespaceDecl>(this);
997  if (ND->isInline()) {
998  return ND->getParent()->isStdNamespace();
999  }
1000 
1001  if (!getParent()->getRedeclContext()->isTranslationUnit())
1002  return false;
1003 
1004  const IdentifierInfo *II = ND->getIdentifier();
1005  return II && II->isStr("std");
1006 }
1007 
1009  if (isFileContext())
1010  return false;
1011 
1012  if (isa<ClassTemplatePartialSpecializationDecl>(this))
1013  return true;
1014 
1015  if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
1016  if (Record->getDescribedClassTemplate())
1017  return true;
1018 
1019  if (Record->isDependentLambda())
1020  return true;
1021  }
1022 
1023  if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
1024  if (Function->getDescribedFunctionTemplate())
1025  return true;
1026 
1027  // Friend function declarations are dependent if their *lexical*
1028  // context is dependent.
1029  if (cast<Decl>(this)->getFriendObjectKind())
1030  return getLexicalParent()->isDependentContext();
1031  }
1032 
1033  // FIXME: A variable template is a dependent context, but is not a
1034  // DeclContext. A context within it (such as a lambda-expression)
1035  // should be considered dependent.
1036 
1037  return getParent() && getParent()->isDependentContext();
1038 }
1039 
1041  if (DeclKind == Decl::Enum)
1042  return !cast<EnumDecl>(this)->isScoped();
1043  else if (DeclKind == Decl::LinkageSpec || DeclKind == Decl::Export)
1044  return true;
1045 
1046  return false;
1047 }
1048 
1049 static bool isLinkageSpecContext(const DeclContext *DC,
1051  while (DC->getDeclKind() != Decl::TranslationUnit) {
1052  if (DC->getDeclKind() == Decl::LinkageSpec)
1053  return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
1054  DC = DC->getLexicalParent();
1055  }
1056  return false;
1057 }
1058 
1061 }
1062 
1064  const DeclContext *DC = this;
1065  while (DC->getDeclKind() != Decl::TranslationUnit) {
1066  if (DC->getDeclKind() == Decl::LinkageSpec &&
1067  cast<LinkageSpecDecl>(DC)->getLanguage() ==
1069  return cast<LinkageSpecDecl>(DC);
1070  DC = DC->getLexicalParent();
1071  }
1072  return nullptr;
1073 }
1074 
1077 }
1078 
1079 bool DeclContext::Encloses(const DeclContext *DC) const {
1080  if (getPrimaryContext() != this)
1081  return getPrimaryContext()->Encloses(DC);
1082 
1083  for (; DC; DC = DC->getParent())
1084  if (DC->getPrimaryContext() == this)
1085  return true;
1086  return false;
1087 }
1088 
1090  switch (DeclKind) {
1091  case Decl::TranslationUnit:
1092  case Decl::ExternCContext:
1093  case Decl::LinkageSpec:
1094  case Decl::Export:
1095  case Decl::Block:
1096  case Decl::Captured:
1097  case Decl::OMPDeclareReduction:
1098  // There is only one DeclContext for these entities.
1099  return this;
1100 
1101  case Decl::Namespace:
1102  // The original namespace is our primary context.
1103  return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
1104 
1105  case Decl::ObjCMethod:
1106  return this;
1107 
1108  case Decl::ObjCInterface:
1109  if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
1110  return Def;
1111 
1112  return this;
1113 
1114  case Decl::ObjCProtocol:
1115  if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
1116  return Def;
1117 
1118  return this;
1119 
1120  case Decl::ObjCCategory:
1121  return this;
1122 
1123  case Decl::ObjCImplementation:
1124  case Decl::ObjCCategoryImpl:
1125  return this;
1126 
1127  default:
1128  if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
1129  // If this is a tag type that has a definition or is currently
1130  // being defined, that definition is our primary context.
1131  TagDecl *Tag = cast<TagDecl>(this);
1132 
1133  if (TagDecl *Def = Tag->getDefinition())
1134  return Def;
1135 
1136  if (const TagType *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
1137  // Note, TagType::getDecl returns the (partial) definition one exists.
1138  TagDecl *PossiblePartialDef = TagTy->getDecl();
1139  if (PossiblePartialDef->isBeingDefined())
1140  return PossiblePartialDef;
1141  } else {
1142  assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
1143  }
1144 
1145  return Tag;
1146  }
1147 
1148  assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
1149  "Unknown DeclContext kind");
1150  return this;
1151  }
1152 }
1153 
1154 void
1156  Contexts.clear();
1157 
1158  if (DeclKind != Decl::Namespace) {
1159  Contexts.push_back(this);
1160  return;
1161  }
1162 
1163  NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
1164  for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
1165  N = N->getPreviousDecl())
1166  Contexts.push_back(N);
1167 
1168  std::reverse(Contexts.begin(), Contexts.end());
1169 }
1170 
1171 std::pair<Decl *, Decl *>
1173  bool FieldsAlreadyLoaded) {
1174  // Build up a chain of declarations via the Decl::NextInContextAndBits field.
1175  Decl *FirstNewDecl = nullptr;
1176  Decl *PrevDecl = nullptr;
1177  for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1178  if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
1179  continue;
1180 
1181  Decl *D = Decls[I];
1182  if (PrevDecl)
1183  PrevDecl->NextInContextAndBits.setPointer(D);
1184  else
1185  FirstNewDecl = D;
1186 
1187  PrevDecl = D;
1188  }
1189 
1190  return std::make_pair(FirstNewDecl, PrevDecl);
1191 }
1192 
1193 /// \brief We have just acquired external visible storage, and we already have
1194 /// built a lookup map. For every name in the map, pull in the new names from
1195 /// the external storage.
1196 void DeclContext::reconcileExternalVisibleStorage() const {
1197  assert(NeedToReconcileExternalVisibleStorage && LookupPtr);
1198  NeedToReconcileExternalVisibleStorage = false;
1199 
1200  for (auto &Lookup : *LookupPtr)
1201  Lookup.second.setHasExternalDecls();
1202 }
1203 
1204 /// \brief Load the declarations within this lexical storage from an
1205 /// external source.
1206 /// \return \c true if any declarations were added.
1207 bool
1208 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1209  ExternalASTSource *Source = getParentASTContext().getExternalSource();
1210  assert(hasExternalLexicalStorage() && Source && "No external storage?");
1211 
1212  // Notify that we have a DeclContext that is initializing.
1213  ExternalASTSource::Deserializing ADeclContext(Source);
1214 
1215  // Load the external declarations, if any.
1216  SmallVector<Decl*, 64> Decls;
1217  ExternalLexicalStorage = false;
1218  Source->FindExternalLexicalDecls(this, Decls);
1219 
1220  if (Decls.empty())
1221  return false;
1222 
1223  // We may have already loaded just the fields of this record, in which case
1224  // we need to ignore them.
1225  bool FieldsAlreadyLoaded = false;
1226  if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
1227  FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
1228 
1229  // Splice the newly-read declarations into the beginning of the list
1230  // of declarations.
1231  Decl *ExternalFirst, *ExternalLast;
1232  std::tie(ExternalFirst, ExternalLast) =
1233  BuildDeclChain(Decls, FieldsAlreadyLoaded);
1234  ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1235  FirstDecl = ExternalFirst;
1236  if (!LastDecl)
1237  LastDecl = ExternalLast;
1238  return true;
1239 }
1240 
1243  DeclarationName Name) {
1244  ASTContext &Context = DC->getParentASTContext();
1245  StoredDeclsMap *Map;
1246  if (!(Map = DC->LookupPtr))
1247  Map = DC->CreateStoredDeclsMap(Context);
1248  if (DC->NeedToReconcileExternalVisibleStorage)
1249  DC->reconcileExternalVisibleStorage();
1250 
1251  (*Map)[Name].removeExternalDecls();
1252 
1253  return DeclContext::lookup_result();
1254 }
1255 
1258  DeclarationName Name,
1259  ArrayRef<NamedDecl*> Decls) {
1260  ASTContext &Context = DC->getParentASTContext();
1261  StoredDeclsMap *Map;
1262  if (!(Map = DC->LookupPtr))
1263  Map = DC->CreateStoredDeclsMap(Context);
1264  if (DC->NeedToReconcileExternalVisibleStorage)
1265  DC->reconcileExternalVisibleStorage();
1266 
1267  StoredDeclsList &List = (*Map)[Name];
1268 
1269  // Clear out any old external visible declarations, to avoid quadratic
1270  // performance in the redeclaration checks below.
1271  List.removeExternalDecls();
1272 
1273  if (!List.isNull()) {
1274  // We have both existing declarations and new declarations for this name.
1275  // Some of the declarations may simply replace existing ones. Handle those
1276  // first.
1278  for (unsigned I = 0, N = Decls.size(); I != N; ++I)
1279  if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
1280  Skip.push_back(I);
1281  Skip.push_back(Decls.size());
1282 
1283  // Add in any new declarations.
1284  unsigned SkipPos = 0;
1285  for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1286  if (I == Skip[SkipPos])
1287  ++SkipPos;
1288  else
1289  List.AddSubsequentDecl(Decls[I]);
1290  }
1291  } else {
1292  // Convert the array to a StoredDeclsList.
1294  I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1295  if (List.isNull())
1296  List.setOnlyValue(*I);
1297  else
1298  List.AddSubsequentDecl(*I);
1299  }
1300  }
1301 
1302  return List.getLookupResult();
1303 }
1304 
1306  if (hasExternalLexicalStorage())
1307  LoadLexicalDeclsFromExternalStorage();
1308  return decl_iterator(FirstDecl);
1309 }
1310 
1312  if (hasExternalLexicalStorage())
1313  LoadLexicalDeclsFromExternalStorage();
1314 
1315  return !FirstDecl;
1316 }
1317 
1319  return (D->getLexicalDeclContext() == this &&
1320  (D->NextInContextAndBits.getPointer() || D == LastDecl));
1321 }
1322 
1324  assert(D->getLexicalDeclContext() == this &&
1325  "decl being removed from non-lexical context");
1326  assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1327  "decl is not in decls list");
1328 
1329  // Remove D from the decl chain. This is O(n) but hopefully rare.
1330  if (D == FirstDecl) {
1331  if (D == LastDecl)
1332  FirstDecl = LastDecl = nullptr;
1333  else
1334  FirstDecl = D->NextInContextAndBits.getPointer();
1335  } else {
1336  for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1337  assert(I && "decl not found in linked list");
1338  if (I->NextInContextAndBits.getPointer() == D) {
1339  I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1340  if (D == LastDecl) LastDecl = I;
1341  break;
1342  }
1343  }
1344  }
1345 
1346  // Mark that D is no longer in the decl chain.
1347  D->NextInContextAndBits.setPointer(nullptr);
1348 
1349  // Remove D from the lookup table if necessary.
1350  if (isa<NamedDecl>(D)) {
1351  NamedDecl *ND = cast<NamedDecl>(D);
1352 
1353  // Remove only decls that have a name
1354  if (!ND->getDeclName()) return;
1355 
1356  auto *DC = D->getDeclContext();
1357  do {
1358  StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1359  if (Map) {
1360  StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1361  assert(Pos != Map->end() && "no lookup entry for decl");
1362  if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1363  Pos->second.remove(ND);
1364  }
1365  } while (DC->isTransparentContext() && (DC = DC->getParent()));
1366  }
1367 }
1368 
1370  assert(D->getLexicalDeclContext() == this &&
1371  "Decl inserted into wrong lexical context");
1372  assert(!D->getNextDeclInContext() && D != LastDecl &&
1373  "Decl already inserted into a DeclContext");
1374 
1375  if (FirstDecl) {
1376  LastDecl->NextInContextAndBits.setPointer(D);
1377  LastDecl = D;
1378  } else {
1379  FirstDecl = LastDecl = D;
1380  }
1381 
1382  // Notify a C++ record declaration that we've added a member, so it can
1383  // update its class-specific state.
1384  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1385  Record->addedMember(D);
1386 
1387  // If this is a newly-created (not de-serialized) import declaration, wire
1388  // it in to the list of local import declarations.
1389  if (!D->isFromASTFile()) {
1390  if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1391  D->getASTContext().addedLocalImportDecl(Import);
1392  }
1393 }
1394 
1396  addHiddenDecl(D);
1397 
1398  if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1400  makeDeclVisibleInContextWithFlags(ND, false, true);
1401 }
1402 
1404  addHiddenDecl(D);
1405 
1406  if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1408  makeDeclVisibleInContextWithFlags(ND, true, true);
1409 }
1410 
1411 /// shouldBeHidden - Determine whether a declaration which was declared
1412 /// within its semantic context should be invisible to qualified name lookup.
1413 static bool shouldBeHidden(NamedDecl *D) {
1414  // Skip unnamed declarations.
1415  if (!D->getDeclName())
1416  return true;
1417 
1418  // Skip entities that can't be found by name lookup into a particular
1419  // context.
1420  if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1421  D->isTemplateParameter())
1422  return true;
1423 
1424  // Skip template specializations.
1425  // FIXME: This feels like a hack. Should DeclarationName support
1426  // template-ids, or is there a better way to keep specializations
1427  // from being visible?
1428  if (isa<ClassTemplateSpecializationDecl>(D))
1429  return true;
1430  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1431  if (FD->isFunctionTemplateSpecialization())
1432  return true;
1433 
1434  return false;
1435 }
1436 
1437 /// buildLookup - Build the lookup data structure with all of the
1438 /// declarations in this DeclContext (and any other contexts linked
1439 /// to it or transparent contexts nested within it) and return it.
1440 ///
1441 /// Note that the produced map may miss out declarations from an
1442 /// external source. If it does, those entries will be marked with
1443 /// the 'hasExternalDecls' flag.
1445  assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1446 
1447  if (!HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups)
1448  return LookupPtr;
1449 
1451  collectAllContexts(Contexts);
1452 
1453  if (HasLazyExternalLexicalLookups) {
1454  HasLazyExternalLexicalLookups = false;
1455  for (auto *DC : Contexts) {
1456  if (DC->hasExternalLexicalStorage())
1457  HasLazyLocalLexicalLookups |=
1458  DC->LoadLexicalDeclsFromExternalStorage();
1459  }
1460 
1461  if (!HasLazyLocalLexicalLookups)
1462  return LookupPtr;
1463  }
1464 
1465  for (auto *DC : Contexts)
1466  buildLookupImpl(DC, hasExternalVisibleStorage());
1467 
1468  // We no longer have any lazy decls.
1469  HasLazyLocalLexicalLookups = false;
1470  return LookupPtr;
1471 }
1472 
1473 /// buildLookupImpl - Build part of the lookup data structure for the
1474 /// declarations contained within DCtx, which will either be this
1475 /// DeclContext, a DeclContext linked to it, or a transparent context
1476 /// nested within it.
1477 void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
1478  for (Decl *D : DCtx->noload_decls()) {
1479  // Insert this declaration into the lookup structure, but only if
1480  // it's semantically within its decl context. Any other decls which
1481  // should be found in this context are added eagerly.
1482  //
1483  // If it's from an AST file, don't add it now. It'll get handled by
1484  // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1485  // in C++, we do not track external visible decls for the TU, so in
1486  // that case we need to collect them all here.
1487  if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1488  if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1489  (!ND->isFromASTFile() ||
1490  (isTranslationUnit() &&
1491  !getParentASTContext().getLangOpts().CPlusPlus)))
1492  makeDeclVisibleInContextImpl(ND, Internal);
1493 
1494  // If this declaration is itself a transparent declaration context
1495  // or inline namespace, add the members of this declaration of that
1496  // context (recursively).
1497  if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1498  if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1499  buildLookupImpl(InnerCtx, Internal);
1500  }
1501 }
1502 
1503 NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1504 
1507  assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1508  "should not perform lookups into transparent contexts");
1509 
1510  const DeclContext *PrimaryContext = getPrimaryContext();
1511  if (PrimaryContext != this)
1512  return PrimaryContext->lookup(Name);
1513 
1514  // If we have an external source, ensure that any later redeclarations of this
1515  // context have been loaded, since they may add names to the result of this
1516  // lookup (or add external visible storage).
1517  ExternalASTSource *Source = getParentASTContext().getExternalSource();
1518  if (Source)
1519  (void)cast<Decl>(this)->getMostRecentDecl();
1520 
1521  if (hasExternalVisibleStorage()) {
1522  assert(Source && "external visible storage but no external source?");
1523 
1524  if (NeedToReconcileExternalVisibleStorage)
1525  reconcileExternalVisibleStorage();
1526 
1527  StoredDeclsMap *Map = LookupPtr;
1528 
1529  if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1530  // FIXME: Make buildLookup const?
1531  Map = const_cast<DeclContext*>(this)->buildLookup();
1532 
1533  if (!Map)
1534  Map = CreateStoredDeclsMap(getParentASTContext());
1535 
1536  // If we have a lookup result with no external decls, we are done.
1537  std::pair<StoredDeclsMap::iterator, bool> R =
1538  Map->insert(std::make_pair(Name, StoredDeclsList()));
1539  if (!R.second && !R.first->second.hasExternalDecls())
1540  return R.first->second.getLookupResult();
1541 
1542  if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
1543  if (StoredDeclsMap *Map = LookupPtr) {
1544  StoredDeclsMap::iterator I = Map->find(Name);
1545  if (I != Map->end())
1546  return I->second.getLookupResult();
1547  }
1548  }
1549 
1550  return lookup_result();
1551  }
1552 
1553  StoredDeclsMap *Map = LookupPtr;
1554  if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1555  Map = const_cast<DeclContext*>(this)->buildLookup();
1556 
1557  if (!Map)
1558  return lookup_result();
1559 
1560  StoredDeclsMap::iterator I = Map->find(Name);
1561  if (I == Map->end())
1562  return lookup_result();
1563 
1564  return I->second.getLookupResult();
1565 }
1566 
1569  assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1570  "should not perform lookups into transparent contexts");
1571 
1572  DeclContext *PrimaryContext = getPrimaryContext();
1573  if (PrimaryContext != this)
1574  return PrimaryContext->noload_lookup(Name);
1575 
1576  // If we have any lazy lexical declarations not in our lookup map, add them
1577  // now. Don't import any external declarations, not even if we know we have
1578  // some missing from the external visible lookups.
1579  if (HasLazyLocalLexicalLookups) {
1581  collectAllContexts(Contexts);
1582  for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1583  buildLookupImpl(Contexts[I], hasExternalVisibleStorage());
1584  HasLazyLocalLexicalLookups = false;
1585  }
1586 
1587  StoredDeclsMap *Map = LookupPtr;
1588  if (!Map)
1589  return lookup_result();
1590 
1591  StoredDeclsMap::iterator I = Map->find(Name);
1592  return I != Map->end() ? I->second.getLookupResult()
1593  : lookup_result();
1594 }
1595 
1597  SmallVectorImpl<NamedDecl *> &Results) {
1598  Results.clear();
1599 
1600  // If there's no external storage, just perform a normal lookup and copy
1601  // the results.
1602  if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1603  lookup_result LookupResults = lookup(Name);
1604  Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1605  return;
1606  }
1607 
1608  // If we have a lookup table, check there first. Maybe we'll get lucky.
1609  // FIXME: Should we be checking these flags on the primary context?
1610  if (Name && !HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups) {
1611  if (StoredDeclsMap *Map = LookupPtr) {
1612  StoredDeclsMap::iterator Pos = Map->find(Name);
1613  if (Pos != Map->end()) {
1614  Results.insert(Results.end(),
1615  Pos->second.getLookupResult().begin(),
1616  Pos->second.getLookupResult().end());
1617  return;
1618  }
1619  }
1620  }
1621 
1622  // Slow case: grovel through the declarations in our chain looking for
1623  // matches.
1624  // FIXME: If we have lazy external declarations, this will not find them!
1625  // FIXME: Should we CollectAllContexts and walk them all here?
1626  for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1627  if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1628  if (ND->getDeclName() == Name)
1629  Results.push_back(ND);
1630  }
1631 }
1632 
1634  DeclContext *Ctx = this;
1635  // Skip through transparent contexts.
1636  while (Ctx->isTransparentContext())
1637  Ctx = Ctx->getParent();
1638  return Ctx;
1639 }
1640 
1642  DeclContext *Ctx = this;
1643  // Skip through non-namespace, non-translation-unit contexts.
1644  while (!Ctx->isFileContext())
1645  Ctx = Ctx->getParent();
1646  return Ctx->getPrimaryContext();
1647 }
1648 
1650  // Loop until we find a non-record context.
1651  RecordDecl *OutermostRD = nullptr;
1652  DeclContext *DC = this;
1653  while (DC->isRecord()) {
1654  OutermostRD = cast<RecordDecl>(DC);
1655  DC = DC->getLexicalParent();
1656  }
1657  return OutermostRD;
1658 }
1659 
1661  // For non-file contexts, this is equivalent to Equals.
1662  if (!isFileContext())
1663  return O->Equals(this);
1664 
1665  do {
1666  if (O->Equals(this))
1667  return true;
1668 
1669  const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1670  if (!NS || !NS->isInline())
1671  break;
1672  O = NS->getParent();
1673  } while (O);
1674 
1675  return false;
1676 }
1677 
1679  DeclContext *PrimaryDC = this->getPrimaryContext();
1680  DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1681  // If the decl is being added outside of its semantic decl context, we
1682  // need to ensure that we eagerly build the lookup information for it.
1683  PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1684 }
1685 
1686 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1687  bool Recoverable) {
1688  assert(this == getPrimaryContext() && "expected a primary DC");
1689 
1690  if (!isLookupContext()) {
1691  if (isTransparentContext())
1692  getParent()->getPrimaryContext()
1693  ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1694  return;
1695  }
1696 
1697  // Skip declarations which should be invisible to name lookup.
1698  if (shouldBeHidden(D))
1699  return;
1700 
1701  // If we already have a lookup data structure, perform the insertion into
1702  // it. If we might have externally-stored decls with this name, look them
1703  // up and perform the insertion. If this decl was declared outside its
1704  // semantic context, buildLookup won't add it, so add it now.
1705  //
1706  // FIXME: As a performance hack, don't add such decls into the translation
1707  // unit unless we're in C++, since qualified lookup into the TU is never
1708  // performed.
1709  if (LookupPtr || hasExternalVisibleStorage() ||
1710  ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1711  (getParentASTContext().getLangOpts().CPlusPlus ||
1712  !isTranslationUnit()))) {
1713  // If we have lazily omitted any decls, they might have the same name as
1714  // the decl which we are adding, so build a full lookup table before adding
1715  // this decl.
1716  buildLookup();
1717  makeDeclVisibleInContextImpl(D, Internal);
1718  } else {
1719  HasLazyLocalLexicalLookups = true;
1720  }
1721 
1722  // If we are a transparent context or inline namespace, insert into our
1723  // parent context, too. This operation is recursive.
1724  if (isTransparentContext() || isInlineNamespace())
1725  getParent()->getPrimaryContext()->
1726  makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1727 
1728  Decl *DCAsDecl = cast<Decl>(this);
1729  // Notify that a decl was made visible unless we are a Tag being defined.
1730  if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1731  if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1732  L->AddedVisibleDecl(this, D);
1733 }
1734 
1735 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1736  // Find or create the stored declaration map.
1737  StoredDeclsMap *Map = LookupPtr;
1738  if (!Map) {
1739  ASTContext *C = &getParentASTContext();
1740  Map = CreateStoredDeclsMap(*C);
1741  }
1742 
1743  // If there is an external AST source, load any declarations it knows about
1744  // with this declaration's name.
1745  // If the lookup table contains an entry about this name it means that we
1746  // have already checked the external source.
1747  if (!Internal)
1748  if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1749  if (hasExternalVisibleStorage() &&
1750  Map->find(D->getDeclName()) == Map->end())
1751  Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1752 
1753  // Insert this declaration into the map.
1754  StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1755 
1756  if (Internal) {
1757  // If this is being added as part of loading an external declaration,
1758  // this may not be the only external declaration with this name.
1759  // In this case, we never try to replace an existing declaration; we'll
1760  // handle that when we finalize the list of declarations for this name.
1761  DeclNameEntries.setHasExternalDecls();
1762  DeclNameEntries.AddSubsequentDecl(D);
1763  return;
1764  }
1765 
1766  if (DeclNameEntries.isNull()) {
1767  DeclNameEntries.setOnlyValue(D);
1768  return;
1769  }
1770 
1771  if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
1772  // This declaration has replaced an existing one for which
1773  // declarationReplaces returns true.
1774  return;
1775  }
1776 
1777  // Put this declaration into the appropriate slot.
1778  DeclNameEntries.AddSubsequentDecl(D);
1779 }
1780 
1782  return cast<UsingDirectiveDecl>(*I);
1783 }
1784 
1785 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1786 /// this context.
1788  // FIXME: Use something more efficient than normal lookup for using
1789  // directives. In C++, using directives are looked up more than anything else.
1790  lookup_result Result = lookup(UsingDirectiveDecl::getName());
1791  return udir_range(Result.begin(), Result.end());
1792 }
1793 
1794 //===----------------------------------------------------------------------===//
1795 // Creation and Destruction of StoredDeclsMaps. //
1796 //===----------------------------------------------------------------------===//
1797 
1798 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1799  assert(!LookupPtr && "context already has a decls map");
1800  assert(getPrimaryContext() == this &&
1801  "creating decls map on non-primary context");
1802 
1803  StoredDeclsMap *M;
1804  bool Dependent = isDependentContext();
1805  if (Dependent)
1806  M = new DependentStoredDeclsMap();
1807  else
1808  M = new StoredDeclsMap();
1809  M->Previous = C.LastSDM;
1810  C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1811  LookupPtr = M;
1812  return M;
1813 }
1814 
1815 void ASTContext::ReleaseDeclContextMaps() {
1816  // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1817  // pointer because the subclass doesn't add anything that needs to
1818  // be deleted.
1819  StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1820 }
1821 
1822 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1823  while (Map) {
1824  // Advance the iteration before we invalidate memory.
1825  llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1826 
1827  if (Dependent)
1828  delete static_cast<DependentStoredDeclsMap*>(Map);
1829  else
1830  delete Map;
1831 
1832  Map = Next.getPointer();
1833  Dependent = Next.getInt();
1834  }
1835 }
1836 
1839  const PartialDiagnostic &PDiag) {
1840  assert(Parent->isDependentContext()
1841  && "cannot iterate dependent diagnostics of non-dependent context");
1842  Parent = Parent->getPrimaryContext();
1843  if (!Parent->LookupPtr)
1844  Parent->CreateStoredDeclsMap(C);
1845 
1847  static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
1848 
1849  // Allocate the copy of the PartialDiagnostic via the ASTContext's
1850  // BumpPtrAllocator, rather than the ASTContext itself.
1851  PartialDiagnostic::Storage *DiagStorage = nullptr;
1852  if (PDiag.hasStorage())
1853  DiagStorage = new (C) PartialDiagnostic::Storage;
1854 
1855  DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1856 
1857  // TODO: Maybe we shouldn't reverse the order during insertion.
1858  DD->NextDiagnostic = Map->FirstDiagnostic;
1859  Map->FirstDiagnostic = DD;
1860 
1861  return DD;
1862 }
static StringRef getRealizedPlatform(const AvailabilityAttr *A, const ASTContext &Context)
Definition: DeclBase.cpp:453
Defines the clang::ASTContext interface.
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1631
AttrVec & getDeclAttrs(const Decl *D)
Retrieve the attributes for the given declaration.
void localUncachedLookup(DeclarationName Name, SmallVectorImpl< NamedDecl *> &Results)
A simplistic name lookup mechanism that performs name lookup into this declaration context without co...
Definition: DeclBase.cpp:1596
VersionTuple getPlatformMinVersion() const
Retrieve the minimum desired version of the platform, to which the program should be compiled...
Definition: TargetInfo.h:988
static DeclContext * castToDeclContext(const Decl *)
Definition: DeclBase.cpp:831
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:737
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2222
QualType getPointeeType() const
Definition: Type.h:2236
static bool shouldBeHidden(NamedDecl *D)
shouldBeHidden - Determine whether a declaration which was declared within its semantic context shoul...
Definition: DeclBase.cpp:1413
A (possibly-)qualified type.
Definition: Type.h:614
bool isBlockPointerType() const
Definition: Type.h:5772
TagDecl * getDefinition() const
getDefinition - Returns the TagDecl that actually defines this struct/union/class/enum.
Definition: Decl.cpp:3689
const char * getDeclKindName() const
Definition: DeclBase.cpp:103
llvm::PointerIntPair< Decl *, 2, ModuleOwnershipKind > NextInContextAndBits
The next declaration within the same lexical DeclContext.
Definition: DeclBase.h:231
Represents a version number in the form major[.minor[.subminor[.build]]].
Definition: VersionTuple.h:26
void AddSubsequentDecl(NamedDecl *D)
AddSubsequentDecl - This is called on the second and later decl when it is not a redeclaration to mer...
virtual void FindExternalLexicalDecls(const DeclContext *DC, llvm::function_ref< bool(Decl::Kind)> IsKindWeWant, SmallVectorImpl< Decl *> &Result)
Finds all declarations lexically contained within the given DeclContext, after applying an optional f...
RAII class for safely pairing a StartedDeserializing call with FinishedDeserializing.
__SIZE_TYPE__ size_t
The unsigned integer type of the result of the sizeof operator.
Definition: opencl-c.h:60
static Decl * castFromDeclContext(const DeclContext *)
Definition: DeclBase.cpp:812
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition: DeclBase.h:955
static bool isLinkageSpecContext(const DeclContext *DC, LinkageSpecDecl::LanguageIDs ID)
Definition: DeclBase.cpp:1049
Stmt - This represents one statement.
Definition: Stmt.h:60
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:2964
C Language Family Type Representation.
const char * getDeclKindName() const
Definition: DeclBase.cpp:135
const Type * getTypeForDecl() const
Definition: Decl.h:2693
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:81
specific_attr_iterator - Iterates over a subrange of an AttrVec, only providing attributes that are o...
Definition: AttrIterator.h:47
static void add(Kind k)
Definition: DeclBase.cpp:173
Defines the C++ template declaration subclasses.
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration, or NULL if there is no previous declaration.
Definition: DeclBase.h:929
NamespaceDecl - Represent a C++ namespace.
Definition: Decl.h:474
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:645
unsigned getIdentifierNamespace() const
Definition: DeclBase.h:777
static Decl * getNonClosureContext(T *D)
Starting at a given context (a Decl or DeclContext), look for a code context that is not a closure (a...
Definition: DeclBase.cpp:919
const DeclContext * getParentFunctionOrMethod() const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext...
Definition: DeclBase.cpp:223
unsigned Access
Access - Used by C++ decls for the access specifier.
Definition: DeclBase.h:303
bool HandleRedeclaration(NamedDecl *D, bool IsKnownNewer)
HandleRedeclaration - If this is a redeclaration of an existing decl, replace the old one with D and ...
bool hasOwningModule() const
Is this declaration owned by some module?
Definition: DeclBase.h:732
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:771
ASTMutationListener * getASTMutationListener() const
Definition: DeclBase.cpp:350
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6099
bool hasLocalOwningModuleStorage() const
Definition: DeclBase.cpp:99
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1059
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:113
bool isInvalidDecl() const
Definition: DeclBase.h:532
ExternalSourceSymbolAttr * getExternalSourceSymbolAttr() const
Looks on this and related declarations for an applicable external source symbol attribute.
Definition: DeclBase.cpp:420
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:193
ParmVarDecl - Represents a parameter to a function.
Definition: Decl.h:1447
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1323
bool hasWeakClassImport() const
Does this runtime support weakly importing classes?
Definition: ObjCRuntime.h:271
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
Definition: Decl.h:232
Types, declared with &#39;struct foo&#39;, typedefs, etc.
Definition: DeclBase.h:125
bool isLexicallyWithinFunctionOrMethod() const
Returns true if this declaration lexically is inside a function.
Definition: DeclBase.cpp:305
RecordDecl - Represents a struct/union/class.
Definition: Decl.h:3384
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
Definition: Decl.h:258
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1079
One of these records is kept for each identifier that is lexed.
bool isInAnonymousNamespace() const
Definition: DeclBase.cpp:317
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
static DeclContextLookupResult SetExternalVisibleDeclsForName(const DeclContext *DC, DeclarationName Name, ArrayRef< NamedDecl *> Decls)
Definition: DeclBase.cpp:1257
QualType getPointeeType() const
Definition: Type.h:2339
void print(raw_ostream &OS, const SourceManager &SM) const
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:128
bool isInline() const
Returns true if this is an inline namespace declaration.
Definition: Decl.h:529
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1155
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC...
Definition: DeclBase.h:1423
Describes a module or submodule.
Definition: Module.h:57
virtual void updateOutOfDateIdentifier(IdentifierInfo &II)
Update an out-of-date identifier.
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:1641
virtual bool FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name)
Find all declarations with the given name in the given context, and add them to the context by callin...
Namespaces, declared with &#39;namespace foo {}&#39;.
Definition: DeclBase.h:135
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition: DeclBase.cpp:392
ModuleOwnershipKind getModuleOwnershipKind() const
Get the kind of module ownership for this declaration.
Definition: DeclBase.h:764
StoredDeclsMap * buildLookup()
Ensure the lookup structure is fully-built and return it.
Definition: DeclBase.cpp:1444
static DeclContextLookupResult SetNoExternalVisibleDeclsForName(const DeclContext *DC, DeclarationName Name)
Definition: DeclBase.cpp:1242
ASTContext & getASTContext() const
Definition: Decl.h:90
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1113
ObjCProtocolDecl * getDefinition()
Retrieve the definition of this protocol, if any.
Definition: DeclObjC.h:2115
void eraseDeclAttrs(const Decl *D)
Erase the attributes corresponding to the given declaration.
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:1985
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC)...
Definition: DeclBase.h:803
Labels, declared with &#39;x:&#39; and referenced with &#39;goto x&#39;.
Definition: DeclBase.h:112
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:724
This represents the body of a CapturedStmt, and serves as its DeclContext.
Definition: Decl.h:3756
Represents an ObjC class declaration.
Definition: DeclObjC.h:1108
Represents a linkage specification.
Definition: DeclCXX.h:2687
A binding in a decomposition declaration.
Definition: DeclCXX.h:3645
bool isExported() const
Whether this declaration is exported (by virtue of being lexically within an ExportDecl or by being a...
Definition: DeclBase.cpp:404
Ordinary names.
Definition: DeclBase.h:139
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:848
void addDeclInternal(Decl *D)
Add the declaration D into this context, but suppress searches for external declarations with the sam...
Definition: DeclBase.cpp:1403
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1506
AvailabilityResult
Captures the result of checking the availability of a declaration.
Definition: DeclBase.h:67
NodeId Parent
Definition: ASTDiff.cpp:192
Decl * getNextDeclInContext()
Definition: DeclBase.h:413
bool canBeWeakImported(bool &IsDefinition) const
Determines whether this symbol can be weak-imported, e.g., whether it would be well-formed to add the...
Definition: DeclBase.cpp:623
udir_range using_directives() const
Returns iterator range [First, Last) of UsingDirectiveDecls stored within this context.
Definition: DeclBase.cpp:1787
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any...
Definition: Decl.cpp:3138
Objective C @protocol.
Definition: DeclBase.h:142
decl_range noload_decls() const
noload_decls_begin/end - Iterate over the declarations stored in this context that are currently load...
Definition: DeclBase.h:1554
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl&#39;s underlying type to extract a FunctionType when possible. ...
Definition: DeclBase.cpp:899
void removeExternalDecls()
Remove any declarations which were imported from an external AST source.
bool isInlineNamespace() const
Definition: DeclBase.cpp:987
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:1319
BlockDecl - This represents a block literal declaration, which is like an unnamed FunctionDecl...
Definition: Decl.h:3587
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
Definition: Decl.h:593
const Attr * getDefiningAttr() const
Return this declaration&#39;s defining attribute if it has one.
Definition: DeclBase.cpp:445
std::string Label
static unsigned getIdentifierNamespaceForKind(Kind DK)
Definition: DeclBase.cpp:672
llvm::iterator_range< udir_iterator > udir_range
Definition: DeclBase.h:1816
const FunctionProtoType * T
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1318
Declaration of a template type parameter.
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:112
This declaration is an OpenMP user defined reduction construction.
Definition: DeclBase.h:173
bool InEnclosingNamespaceSetOf(const DeclContext *NS) const
Test if this context is part of the enclosing namespace set of the context NS, as defined in C++0x [n...
Definition: DeclBase.cpp:1660
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition: DeclBase.h:944
bool isFileContext() const
Definition: DeclBase.h:1369
DeclContext * getDeclContext()
Definition: DeclBase.h:416
lookup_result noload_lookup(DeclarationName Name)
Find the declarations with the given name that are visible within this context; don&#39;t attempt to retr...
Definition: DeclBase.cpp:1568
Decl * getNonClosureAncestor()
Find the nearest non-closure ancestor of this context, i.e.
Definition: DeclBase.cpp:943
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:1915
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack...
Definition: DeclBase.cpp:181
bool isFunctionOrMethod() const
Definition: DeclBase.h:1352
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:116
This declaration has an owning module, and is visible when that module is imported.
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl, 0 if there are none.
Definition: DeclBase.cpp:354
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1303
void collectAllContexts(SmallVectorImpl< DeclContext *> &Contexts)
Collects all of the declaration contexts that are semantically connected to this declaration context...
Definition: DeclBase.cpp:1155
SourceLocation getEnd() const
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1008
The result type of a method or function.
const SourceManager & SM
Definition: Format.cpp:1308
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:265
virtual void DeclarationMarkedUsed(const Decl *D)
A declaration is marked used which was not previously marked used.
bool decls_empty() const
Definition: DeclBase.cpp:1311
AttrVec & getAttrs()
Definition: DeclBase.h:466
bool hasAttrs() const
Definition: DeclBase.h:462
Abstract interface for external sources of AST nodes.
bool isTemplateDecl() const
returns true if this declaration is a template
Definition: DeclBase.cpp:208
bool empty() const
Determine whether this version information is empty (e.g., all version components are zero)...
Definition: VersionTuple.h:69
Decl::Kind getDeclKind() const
Definition: DeclBase.h:1297
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:1678
DeclContext::lookup_result getLookupResult()
getLookupResult - Return an array of all the decls that this list represents.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:200
StringRef getPlatformName() const
Retrieve the name of the platform as it is used in the availability attribute.
Definition: TargetInfo.h:984
VersionTuple getVersionIntroduced() const
Retrieve the version of the target platform in which this declaration was introduced.
Definition: DeclBase.cpp:609
Encodes a location in the source.
Members, declared with object declarations within tag definitions.
Definition: DeclBase.h:131
void setModuleOwnershipKind(ModuleOwnershipKind MOK)
Set whether this declaration is hidden from name lookup.
Definition: DeclBase.h:769
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1305
TagDecl - Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:2846
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:346
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1918
bool isStdNamespace() const
Definition: DeclBase.cpp:992
This file defines OpenMP nodes for declarative directives.
void print(raw_ostream &OS) const override
Definition: DeclBase.cpp:238
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition: DeclBase.h:681
UsingDirectiveDecl * operator*() const
Definition: DeclBase.cpp:1781
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required...
Definition: DeclBase.cpp:367
DeclContextLookupResult lookup_result
Definition: DeclBase.h:1745
An array of decls optimized for the common case of only containing one entry.
void dropAttrs()
Definition: DeclBase.cpp:800
bool isWeakImported() const
Determine whether this is a weak-imported symbol.
Definition: DeclBase.cpp:653
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition: Decl.h:3859
void * Allocate(size_t Size, unsigned Align=8) const
Definition: ASTContext.h:625
decl_iterator - Iterates through the declarations stored within this context.
Definition: DeclBase.h:1505
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:2712
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:918
Dataflow Directional Tag Classes.
void updateOutOfDate(IdentifierInfo &II) const
Update a potentially out-of-date declaration.
Definition: DeclBase.cpp:43
bool isValid() const
Return true if this is a valid SourceLocation object.
virtual Module * getModule(unsigned ID)
Retrieve the module that corresponds to the given module ID.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1224
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:378
bool isRecord() const
Definition: DeclBase.h:1377
attr_range attrs() const
Definition: DeclBase.h:482
ObjCInterfaceDecl * getDefinition()
Retrieve the definition of this class, or NULL if this class has been forward-declared (with @class) ...
Definition: DeclObjC.h:1471
A decomposition declaration.
Definition: DeclCXX.h:3693
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:1649
DeclarationName - The name of a declaration.
const CXXRecordDecl * getParent() const
Returns the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:2033
Kind getKind() const
Definition: DeclBase.h:410
Decl * getNonClosureContext()
Find the innermost non-closure ancestor of this declaration, walking up through blocks, lambdas, etc.
Definition: DeclBase.cpp:939
Tags, declared with &#39;struct foo;&#39; and referenced with &#39;struct foo&#39;.
Definition: DeclBase.h:120
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any...
Definition: ASTContext.h:1017
A dependently-generated diagnostic.
Pointer to a block type.
Definition: Type.h:2325
static DependentDiagnostic * Create(ASTContext &Context, DeclContext *Parent, AccessNonce _, SourceLocation Loc, bool IsMemberAccess, AccessSpecifier AS, NamedDecl *TargetDecl, CXXRecordDecl *NamingClass, QualType BaseObjectType, const PartialDiagnostic &PDiag)
void setIsUsed()
Set whether the declaration is used, in the sense of odr-use.
Definition: DeclBase.h:552
LanguageIDs
Represents the language in a linkage specification.
Definition: DeclCXX.h:2696
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple()) const
Determine the availability of the given declaration.
Definition: DeclBase.cpp:562
T * getAttr() const
Definition: DeclBase.h:518
unsigned getOwningModuleID() const
Retrieve the global ID of the module that owns this particular declaration.
Definition: DeclBase.h:693
virtual ~Decl()
Definition: DeclBase.cpp:263
void setOnlyValue(NamedDecl *ND)
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1633
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
Definition: DeclBase.cpp:1063
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1395
char __ovld __cnfn max(char x, char y)
Returns y if x < y, otherwise it returns x.
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:382
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any...
Definition: ASTContext.h:1032
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
Represents a C++ struct/union/class.
Definition: DeclCXX.h:266
void addHiddenDecl(Decl *D)
Add the declaration D to this context without modifying any lookup tables.
Definition: DeclBase.cpp:1369
static std::pair< Decl *, Decl * > BuildDeclChain(ArrayRef< Decl *> Decls, bool FieldsAlreadyLoaded)
Build up a chain of declarations.
Definition: DeclBase.cpp:1172
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:977
static bool classof(const Decl *D)
Definition: DeclBase.cpp:951
Defines the clang::TargetInfo interface.
ASTContext & getParentASTContext() const
Definition: DeclBase.h:1332
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:3470
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:84
TranslationUnitDecl - The top declaration context.
Definition: Decl.h:80
static void DestroyAll(StoredDeclsMap *Map, bool Dependent)
Definition: DeclBase.cpp:1822
static void PrintStats()
Definition: DeclBase.cpp:149
NamedDecl * getMostRecentDecl()
Definition: Decl.h:404
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1089
bool trackLocalOwningModule() const
Do we need to track the owning module for a local declaration?
Definition: LangOptions.h:171
static void EnableStatistics()
Definition: DeclBase.cpp:145
bool isModulePrivate() const
Whether this declaration was marked as being private to the module in which it was defined...
Definition: DeclBase.h:586
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:269
NamedDecl - This represents a decl with a name.
Definition: Decl.h:213
bool isTranslationUnit() const
Definition: DeclBase.h:1373
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:446
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration...
Definition: DeclBase.cpp:212
Represents C++ using-directive.
Definition: DeclCXX.h:2779
bool hasDefiningAttr() const
Return true if this declaration has an attribute which acts as definition of the entity, such as &#39;alias&#39; or &#39;ifunc&#39;.
Definition: DeclBase.cpp:441
bool isFunctionPointerType() const
Definition: Type.h:5784
void addedLocalImportDecl(ImportDecl *Import)
Notify the AST context that a new import declaration has been parsed or implicitly created within thi...
bool isInStdNamespace() const
Definition: DeclBase.cpp:327
TranslationUnitDecl * getTranslationUnitDecl()
Definition: DeclBase.cpp:331
const LangOptions & getLangOpts() const
Definition: ASTContext.h:661
bool isExternCXXContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1075
SourceLocation getBodyRBrace() const
getBodyRBrace - Gets the right brace of the body, if a body exists.
Definition: DeclBase.cpp:850
Declaration of a template function.
Definition: DeclTemplate.h:939
Attr - This represents one attribute.
Definition: Attr.h:43
static AvailabilityResult CheckAvailability(ASTContext &Context, const AvailabilityAttr *A, std::string *Message, VersionTuple EnclosingVersion)
Determine the availability of the given declaration based on the target platform. ...
Definition: DeclBase.cpp:475
bool isBeingDefined() const
isBeingDefined - Return true if this decl is currently being defined.
Definition: Decl.h:3001
This declaration is a using declaration.
Definition: DeclBase.h:158
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context, meaning that the members declared in this context are semantically declared in the nearest enclosing non-transparent (opaque) context but are lexically declared in this context.
Definition: DeclBase.cpp:1040