clang  5.0.0
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.
78  if (Ctx.getLangOpts().trackLocalOwningModule()) {
79  // Ensure required alignment of the resulting object by adding extra
80  // padding at the start if required.
81  size_t ExtraAlign =
82  llvm::OffsetToAlignment(sizeof(Module *), alignof(Decl));
83  char *Buffer = reinterpret_cast<char *>(
84  ::operator new(ExtraAlign + sizeof(Module *) + Size + Extra, Ctx));
85  Buffer += ExtraAlign;
86  auto *ParentModule =
87  Parent ? cast<Decl>(Parent)->getOwningModule() : nullptr;
88  return new (Buffer) Module*(ParentModule) + 1;
89  }
90  return ::operator new(Size + Extra, Ctx);
91 }
92 
93 Module *Decl::getOwningModuleSlow() const {
94  assert(isFromASTFile() && "Not from AST file?");
96 }
97 
100 }
101 
102 const char *Decl::getDeclKindName() const {
103  switch (DeclKind) {
104  default: llvm_unreachable("Declaration not in DeclNodes.inc!");
105 #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
106 #define ABSTRACT_DECL(DECL)
107 #include "clang/AST/DeclNodes.inc"
108  }
109 }
110 
111 void Decl::setInvalidDecl(bool Invalid) {
112  InvalidDecl = Invalid;
113  assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
114  if (!Invalid) {
115  return;
116  }
117 
118  if (!isa<ParmVarDecl>(this)) {
119  // Defensive maneuver for ill-formed code: we're likely not to make it to
120  // a point where we set the access specifier, so default it to "public"
121  // to avoid triggering asserts elsewhere in the front end.
123  }
124 
125  // Marking a DecompositionDecl as invalid implies all the child BindingDecl's
126  // are invalid too.
127  if (DecompositionDecl *DD = dyn_cast<DecompositionDecl>(this)) {
128  for (BindingDecl *Binding : DD->bindings()) {
129  Binding->setInvalidDecl();
130  }
131  }
132 }
133 
134 const char *DeclContext::getDeclKindName() const {
135  switch (DeclKind) {
136  default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
137 #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
138 #define ABSTRACT_DECL(DECL)
139 #include "clang/AST/DeclNodes.inc"
140  }
141 }
142 
143 bool Decl::StatisticsEnabled = false;
145  StatisticsEnabled = true;
146 }
147 
149  llvm::errs() << "\n*** Decl Stats:\n";
150 
151  int totalDecls = 0;
152 #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
153 #define ABSTRACT_DECL(DECL)
154 #include "clang/AST/DeclNodes.inc"
155  llvm::errs() << " " << totalDecls << " decls total.\n";
156 
157  int totalBytes = 0;
158 #define DECL(DERIVED, BASE) \
159  if (n##DERIVED##s > 0) { \
160  totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
161  llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
162  << sizeof(DERIVED##Decl) << " each (" \
163  << n##DERIVED##s * sizeof(DERIVED##Decl) \
164  << " bytes)\n"; \
165  }
166 #define ABSTRACT_DECL(DECL)
167 #include "clang/AST/DeclNodes.inc"
168 
169  llvm::errs() << "Total bytes = " << totalBytes << "\n";
170 }
171 
172 void Decl::add(Kind k) {
173  switch (k) {
174 #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
175 #define ABSTRACT_DECL(DECL)
176 #include "clang/AST/DeclNodes.inc"
177  }
178 }
179 
181  if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
182  return TTP->isParameterPack();
183  if (const NonTypeTemplateParmDecl *NTTP
184  = dyn_cast<NonTypeTemplateParmDecl>(this))
185  return NTTP->isParameterPack();
186  if (const TemplateTemplateParmDecl *TTP
187  = dyn_cast<TemplateTemplateParmDecl>(this))
188  return TTP->isParameterPack();
189  return false;
190 }
191 
192 bool Decl::isParameterPack() const {
193  if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
194  return Parm->isParameterPack();
195 
196  return isTemplateParameterPack();
197 }
198 
200  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
201  return FD;
202  if (const FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(this))
203  return FTD->getTemplatedDecl();
204  return nullptr;
205 }
206 
207 bool Decl::isTemplateDecl() const {
208  return isa<TemplateDecl>(this);
209 }
210 
212  if (auto *FD = dyn_cast<FunctionDecl>(this))
213  return FD->getDescribedFunctionTemplate();
214  else if (auto *RD = dyn_cast<CXXRecordDecl>(this))
215  return RD->getDescribedClassTemplate();
216  else if (auto *VD = dyn_cast<VarDecl>(this))
217  return VD->getDescribedVarTemplate();
218 
219  return nullptr;
220 }
221 
223  for (const DeclContext *DC = getDeclContext();
224  DC && !DC->isTranslationUnit() && !DC->isNamespace();
225  DC = DC->getParent())
226  if (DC->isFunctionOrMethod())
227  return DC;
228 
229  return nullptr;
230 }
231 
232 
233 //===----------------------------------------------------------------------===//
234 // PrettyStackTraceDecl Implementation
235 //===----------------------------------------------------------------------===//
236 
237 void PrettyStackTraceDecl::print(raw_ostream &OS) const {
238  SourceLocation TheLoc = Loc;
239  if (TheLoc.isInvalid() && TheDecl)
240  TheLoc = TheDecl->getLocation();
241 
242  if (TheLoc.isValid()) {
243  TheLoc.print(OS, SM);
244  OS << ": ";
245  }
246 
247  OS << Message;
248 
249  if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
250  OS << " '";
251  DN->printQualifiedName(OS);
252  OS << '\'';
253  }
254  OS << '\n';
255 }
256 
257 //===----------------------------------------------------------------------===//
258 // Decl Implementation
259 //===----------------------------------------------------------------------===//
260 
261 // Out-of-line virtual method providing a home for Decl.
263 
265  DeclCtx = DC;
266 }
267 
269  if (DC == getLexicalDeclContext())
270  return;
271 
272  if (isInSemaDC()) {
273  setDeclContextsImpl(getDeclContext(), DC, getASTContext());
274  } else {
275  getMultipleDC()->LexicalDC = DC;
276  }
277 
278  // FIXME: We shouldn't be changing the lexical context of declarations
279  // imported from AST files.
280  if (!isFromASTFile()) {
281  setModuleOwnershipKind(getModuleOwnershipKindForChildOf(DC));
282  if (hasOwningModule())
283  setLocalOwningModule(cast<Decl>(DC)->getOwningModule());
284  }
285 
286  assert(
288  getOwningModule()) &&
289  "hidden declaration has no owning module");
290 }
291 
292 void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
293  ASTContext &Ctx) {
294  if (SemaDC == LexicalDC) {
295  DeclCtx = SemaDC;
296  } else {
297  Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
298  MDC->SemanticDC = SemaDC;
299  MDC->LexicalDC = LexicalDC;
300  DeclCtx = MDC;
301  }
302 }
303 
305  const DeclContext *LDC = getLexicalDeclContext();
306  while (true) {
307  if (LDC->isFunctionOrMethod())
308  return true;
309  if (!isa<TagDecl>(LDC))
310  return false;
311  LDC = LDC->getLexicalParent();
312  }
313  return false;
314 }
315 
317  const DeclContext *DC = getDeclContext();
318  do {
319  if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
320  if (ND->isAnonymousNamespace())
321  return true;
322  } while ((DC = DC->getParent()));
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 Binding:
684  case ImplicitParam:
685  case ParmVar:
686  case ObjCMethod:
687  case ObjCProperty:
688  case MSProperty:
689  return IDNS_Ordinary;
690  case Label:
691  return IDNS_Label;
692  case IndirectField:
693  return IDNS_Ordinary | IDNS_Member;
694 
695  case NonTypeTemplateParm:
696  // Non-type template parameters are not found by lookups that ignore
697  // non-types, but they are found by redeclaration lookups for tag types,
698  // 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 TypeAliasTemplate:
708  case TemplateTypeParm:
709  case ObjCTypeParam:
710  return IDNS_Ordinary | IDNS_Type;
711 
712  case UnresolvedUsingTypename:
714 
715  case UsingShadow:
716  return 0; // we'll actually overwrite this later
717 
718  case UnresolvedUsingValue:
719  return IDNS_Ordinary | IDNS_Using;
720 
721  case Using:
722  case UsingPack:
723  return IDNS_Using;
724 
725  case ObjCProtocol:
726  return IDNS_ObjCProtocol;
727 
728  case Field:
729  case ObjCAtDefsField:
730  case ObjCIvar:
731  return IDNS_Member;
732 
733  case Record:
734  case CXXRecord:
735  case Enum:
736  return IDNS_Tag | IDNS_Type;
737 
738  case Namespace:
739  case NamespaceAlias:
740  return IDNS_Namespace;
741 
742  case FunctionTemplate:
743  case VarTemplate:
744  return IDNS_Ordinary;
745 
746  case ClassTemplate:
747  case TemplateTemplateParm:
748  return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
749 
750  case OMPDeclareReduction:
751  return IDNS_OMPReduction;
752 
753  // Never have names.
754  case Friend:
755  case FriendTemplate:
756  case AccessSpec:
757  case LinkageSpec:
758  case Export:
759  case FileScopeAsm:
760  case StaticAssert:
761  case ObjCPropertyImpl:
762  case PragmaComment:
763  case PragmaDetectMismatch:
764  case Block:
765  case Captured:
766  case TranslationUnit:
767  case ExternCContext:
768  case Decomposition:
769 
770  case UsingDirective:
771  case BuiltinTemplate:
772  case ClassTemplateSpecialization:
773  case ClassTemplatePartialSpecialization:
774  case ClassScopeFunctionSpecialization:
775  case VarTemplateSpecialization:
776  case VarTemplatePartialSpecialization:
777  case ObjCImplementation:
778  case ObjCCategory:
779  case ObjCCategoryImpl:
780  case Import:
781  case OMPThreadPrivate:
782  case OMPCapturedExpr:
783  case Empty:
784  // Never looked up by name.
785  return 0;
786  }
787 
788  llvm_unreachable("Invalid DeclKind!");
789 }
790 
791 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
792  assert(!HasAttrs && "Decl already contains attrs.");
793 
794  AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
795  assert(AttrBlank.empty() && "HasAttrs was wrong?");
796 
797  AttrBlank = attrs;
798  HasAttrs = true;
799 }
800 
802  if (!HasAttrs) return;
803 
804  HasAttrs = false;
806 }
807 
808 const AttrVec &Decl::getAttrs() const {
809  assert(HasAttrs && "No attrs to get!");
810  return getASTContext().getDeclAttrs(this);
811 }
812 
814  Decl::Kind DK = D->getDeclKind();
815  switch(DK) {
816 #define DECL(NAME, BASE)
817 #define DECL_CONTEXT(NAME) \
818  case Decl::NAME: \
819  return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
820 #define DECL_CONTEXT_BASE(NAME)
821 #include "clang/AST/DeclNodes.inc"
822  default:
823 #define DECL(NAME, BASE)
824 #define DECL_CONTEXT_BASE(NAME) \
825  if (DK >= first##NAME && DK <= last##NAME) \
826  return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
827 #include "clang/AST/DeclNodes.inc"
828  llvm_unreachable("a decl that inherits DeclContext isn't handled");
829  }
830 }
831 
833  Decl::Kind DK = D->getKind();
834  switch(DK) {
835 #define DECL(NAME, BASE)
836 #define DECL_CONTEXT(NAME) \
837  case Decl::NAME: \
838  return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
839 #define DECL_CONTEXT_BASE(NAME)
840 #include "clang/AST/DeclNodes.inc"
841  default:
842 #define DECL(NAME, BASE)
843 #define DECL_CONTEXT_BASE(NAME) \
844  if (DK >= first##NAME && DK <= last##NAME) \
845  return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
846 #include "clang/AST/DeclNodes.inc"
847  llvm_unreachable("a decl that inherits DeclContext isn't handled");
848  }
849 }
850 
852  // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
853  // FunctionDecl stores EndRangeLoc for this purpose.
854  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
855  const FunctionDecl *Definition;
856  if (FD->hasBody(Definition))
857  return Definition->getSourceRange().getEnd();
858  return SourceLocation();
859  }
860 
861  if (Stmt *Body = getBody())
862  return Body->getSourceRange().getEnd();
863 
864  return SourceLocation();
865 }
866 
867 bool Decl::AccessDeclContextSanity() const {
868 #ifndef NDEBUG
869  // Suppress this check if any of the following hold:
870  // 1. this is the translation unit (and thus has no parent)
871  // 2. this is a template parameter (and thus doesn't belong to its context)
872  // 3. this is a non-type template parameter
873  // 4. the context is not a record
874  // 5. it's invalid
875  // 6. it's a C++0x static_assert.
876  if (isa<TranslationUnitDecl>(this) ||
877  isa<TemplateTypeParmDecl>(this) ||
878  isa<NonTypeTemplateParmDecl>(this) ||
879  !isa<CXXRecordDecl>(getDeclContext()) ||
880  isInvalidDecl() ||
881  isa<StaticAssertDecl>(this) ||
882  // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
883  // as DeclContext (?).
884  isa<ParmVarDecl>(this) ||
885  // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
886  // AS_none as access specifier.
887  isa<CXXRecordDecl>(this) ||
888  isa<ClassScopeFunctionSpecializationDecl>(this))
889  return true;
890 
891  assert(Access != AS_none &&
892  "Access specifier is AS_none inside a record decl");
893 #endif
894  return true;
895 }
896 
897 static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
898 static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
899 
900 const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
901  QualType Ty;
902  if (const ValueDecl *D = dyn_cast<ValueDecl>(this))
903  Ty = D->getType();
904  else if (const TypedefNameDecl *D = dyn_cast<TypedefNameDecl>(this))
905  Ty = D->getUnderlyingType();
906  else
907  return nullptr;
908 
909  if (Ty->isFunctionPointerType())
910  Ty = Ty->getAs<PointerType>()->getPointeeType();
911  else if (BlocksToo && Ty->isBlockPointerType())
912  Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
913 
914  return Ty->getAs<FunctionType>();
915 }
916 
917 
918 /// Starting at a given context (a Decl or DeclContext), look for a
919 /// code context that is not a closure (a lambda, block, etc.).
920 template <class T> static Decl *getNonClosureContext(T *D) {
921  if (getKind(D) == Decl::CXXMethod) {
922  CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
923  if (MD->getOverloadedOperator() == OO_Call &&
924  MD->getParent()->isLambda())
925  return getNonClosureContext(MD->getParent()->getParent());
926  return MD;
927  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
928  return FD;
929  } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
930  return MD;
931  } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
932  return getNonClosureContext(BD->getParent());
933  } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
934  return getNonClosureContext(CD->getParent());
935  } else {
936  return nullptr;
937  }
938 }
939 
942 }
943 
946 }
947 
948 //===----------------------------------------------------------------------===//
949 // DeclContext Implementation
950 //===----------------------------------------------------------------------===//
951 
952 bool DeclContext::classof(const Decl *D) {
953  switch (D->getKind()) {
954 #define DECL(NAME, BASE)
955 #define DECL_CONTEXT(NAME) case Decl::NAME:
956 #define DECL_CONTEXT_BASE(NAME)
957 #include "clang/AST/DeclNodes.inc"
958  return true;
959  default:
960 #define DECL(NAME, BASE)
961 #define DECL_CONTEXT_BASE(NAME) \
962  if (D->getKind() >= Decl::first##NAME && \
963  D->getKind() <= Decl::last##NAME) \
964  return true;
965 #include "clang/AST/DeclNodes.inc"
966  return false;
967  }
968 }
969 
971 
972 /// \brief Find the parent context of this context that will be
973 /// used for unqualified name lookup.
974 ///
975 /// Generally, the parent lookup context is the semantic context. However, for
976 /// a friend function the parent lookup context is the lexical context, which
977 /// is the class in which the friend is declared.
979  // FIXME: Find a better way to identify friends
980  if (isa<FunctionDecl>(this))
983  return getLexicalParent();
984 
985  return getParent();
986 }
987 
989  return isNamespace() &&
990  cast<NamespaceDecl>(this)->isInline();
991 }
992 
994  if (!isNamespace())
995  return false;
996 
997  const NamespaceDecl *ND = cast<NamespaceDecl>(this);
998  if (ND->isInline()) {
999  return ND->getParent()->isStdNamespace();
1000  }
1001 
1003  return false;
1004 
1005  const IdentifierInfo *II = ND->getIdentifier();
1006  return II && II->isStr("std");
1007 }
1008 
1010  if (isFileContext())
1011  return false;
1012 
1013  if (isa<ClassTemplatePartialSpecializationDecl>(this))
1014  return true;
1015 
1016  if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
1017  if (Record->getDescribedClassTemplate())
1018  return true;
1019 
1020  if (Record->isDependentLambda())
1021  return true;
1022  }
1023 
1024  if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
1025  if (Function->getDescribedFunctionTemplate())
1026  return true;
1027 
1028  // Friend function declarations are dependent if their *lexical*
1029  // context is dependent.
1030  if (cast<Decl>(this)->getFriendObjectKind())
1032  }
1033 
1034  // FIXME: A variable template is a dependent context, but is not a
1035  // DeclContext. A context within it (such as a lambda-expression)
1036  // should be considered dependent.
1037 
1038  return getParent() && getParent()->isDependentContext();
1039 }
1040 
1042  if (DeclKind == Decl::Enum)
1043  return !cast<EnumDecl>(this)->isScoped();
1044  else if (DeclKind == Decl::LinkageSpec || DeclKind == Decl::Export)
1045  return true;
1046 
1047  return false;
1048 }
1049 
1050 static bool isLinkageSpecContext(const DeclContext *DC,
1052  while (DC->getDeclKind() != Decl::TranslationUnit) {
1053  if (DC->getDeclKind() == Decl::LinkageSpec)
1054  return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
1055  DC = DC->getLexicalParent();
1056  }
1057  return false;
1058 }
1059 
1062 }
1063 
1065  const DeclContext *DC = this;
1066  while (DC->getDeclKind() != Decl::TranslationUnit) {
1067  if (DC->getDeclKind() == Decl::LinkageSpec &&
1068  cast<LinkageSpecDecl>(DC)->getLanguage() ==
1070  return cast<LinkageSpecDecl>(DC);
1071  DC = DC->getLexicalParent();
1072  }
1073  return nullptr;
1074 }
1075 
1078 }
1079 
1080 bool DeclContext::Encloses(const DeclContext *DC) const {
1081  if (getPrimaryContext() != this)
1082  return getPrimaryContext()->Encloses(DC);
1083 
1084  for (; DC; DC = DC->getParent())
1085  if (DC->getPrimaryContext() == this)
1086  return true;
1087  return false;
1088 }
1089 
1091  switch (DeclKind) {
1092  case Decl::TranslationUnit:
1093  case Decl::ExternCContext:
1094  case Decl::LinkageSpec:
1095  case Decl::Export:
1096  case Decl::Block:
1097  case Decl::Captured:
1098  case Decl::OMPDeclareReduction:
1099  // There is only one DeclContext for these entities.
1100  return this;
1101 
1102  case Decl::Namespace:
1103  // The original namespace is our primary context.
1104  return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
1105 
1106  case Decl::ObjCMethod:
1107  return this;
1108 
1109  case Decl::ObjCInterface:
1110  if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
1111  return Def;
1112 
1113  return this;
1114 
1115  case Decl::ObjCProtocol:
1116  if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
1117  return Def;
1118 
1119  return this;
1120 
1121  case Decl::ObjCCategory:
1122  return this;
1123 
1124  case Decl::ObjCImplementation:
1125  case Decl::ObjCCategoryImpl:
1126  return this;
1127 
1128  default:
1129  if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
1130  // If this is a tag type that has a definition or is currently
1131  // being defined, that definition is our primary context.
1132  TagDecl *Tag = cast<TagDecl>(this);
1133 
1134  if (TagDecl *Def = Tag->getDefinition())
1135  return Def;
1136 
1137  if (const TagType *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
1138  // Note, TagType::getDecl returns the (partial) definition one exists.
1139  TagDecl *PossiblePartialDef = TagTy->getDecl();
1140  if (PossiblePartialDef->isBeingDefined())
1141  return PossiblePartialDef;
1142  } else {
1143  assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
1144  }
1145 
1146  return Tag;
1147  }
1148 
1149  assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
1150  "Unknown DeclContext kind");
1151  return this;
1152  }
1153 }
1154 
1155 void
1157  Contexts.clear();
1158 
1159  if (DeclKind != Decl::Namespace) {
1160  Contexts.push_back(this);
1161  return;
1162  }
1163 
1164  NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
1165  for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
1166  N = N->getPreviousDecl())
1167  Contexts.push_back(N);
1168 
1169  std::reverse(Contexts.begin(), Contexts.end());
1170 }
1171 
1172 std::pair<Decl *, Decl *>
1174  bool FieldsAlreadyLoaded) {
1175  // Build up a chain of declarations via the Decl::NextInContextAndBits field.
1176  Decl *FirstNewDecl = nullptr;
1177  Decl *PrevDecl = nullptr;
1178  for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1179  if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
1180  continue;
1181 
1182  Decl *D = Decls[I];
1183  if (PrevDecl)
1184  PrevDecl->NextInContextAndBits.setPointer(D);
1185  else
1186  FirstNewDecl = D;
1187 
1188  PrevDecl = D;
1189  }
1190 
1191  return std::make_pair(FirstNewDecl, PrevDecl);
1192 }
1193 
1194 /// \brief We have just acquired external visible storage, and we already have
1195 /// built a lookup map. For every name in the map, pull in the new names from
1196 /// the external storage.
1197 void DeclContext::reconcileExternalVisibleStorage() const {
1198  assert(NeedToReconcileExternalVisibleStorage && LookupPtr);
1199  NeedToReconcileExternalVisibleStorage = false;
1200 
1201  for (auto &Lookup : *LookupPtr)
1202  Lookup.second.setHasExternalDecls();
1203 }
1204 
1205 /// \brief Load the declarations within this lexical storage from an
1206 /// external source.
1207 /// \return \c true if any declarations were added.
1208 bool
1209 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1211  assert(hasExternalLexicalStorage() && Source && "No external storage?");
1212 
1213  // Notify that we have a DeclContext that is initializing.
1214  ExternalASTSource::Deserializing ADeclContext(Source);
1215 
1216  // Load the external declarations, if any.
1217  SmallVector<Decl*, 64> Decls;
1218  ExternalLexicalStorage = false;
1219  Source->FindExternalLexicalDecls(this, Decls);
1220 
1221  if (Decls.empty())
1222  return false;
1223 
1224  // We may have already loaded just the fields of this record, in which case
1225  // we need to ignore them.
1226  bool FieldsAlreadyLoaded = false;
1227  if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
1228  FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
1229 
1230  // Splice the newly-read declarations into the beginning of the list
1231  // of declarations.
1232  Decl *ExternalFirst, *ExternalLast;
1233  std::tie(ExternalFirst, ExternalLast) =
1234  BuildDeclChain(Decls, FieldsAlreadyLoaded);
1235  ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1236  FirstDecl = ExternalFirst;
1237  if (!LastDecl)
1238  LastDecl = ExternalLast;
1239  return true;
1240 }
1241 
1247  if (!(Map = DC->LookupPtr))
1248  Map = DC->CreateStoredDeclsMap(Context);
1249  if (DC->NeedToReconcileExternalVisibleStorage)
1250  DC->reconcileExternalVisibleStorage();
1251 
1252  (*Map)[Name].removeExternalDecls();
1253 
1254  return DeclContext::lookup_result();
1255 }
1256 
1260  ArrayRef<NamedDecl*> Decls) {
1263  if (!(Map = DC->LookupPtr))
1264  Map = DC->CreateStoredDeclsMap(Context);
1265  if (DC->NeedToReconcileExternalVisibleStorage)
1266  DC->reconcileExternalVisibleStorage();
1267 
1268  StoredDeclsList &List = (*Map)[Name];
1269 
1270  // Clear out any old external visible declarations, to avoid quadratic
1271  // performance in the redeclaration checks below.
1272  List.removeExternalDecls();
1273 
1274  if (!List.isNull()) {
1275  // We have both existing declarations and new declarations for this name.
1276  // Some of the declarations may simply replace existing ones. Handle those
1277  // first.
1279  for (unsigned I = 0, N = Decls.size(); I != N; ++I)
1280  if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
1281  Skip.push_back(I);
1282  Skip.push_back(Decls.size());
1283 
1284  // Add in any new declarations.
1285  unsigned SkipPos = 0;
1286  for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1287  if (I == Skip[SkipPos])
1288  ++SkipPos;
1289  else
1290  List.AddSubsequentDecl(Decls[I]);
1291  }
1292  } else {
1293  // Convert the array to a StoredDeclsList.
1295  I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1296  if (List.isNull())
1297  List.setOnlyValue(*I);
1298  else
1299  List.AddSubsequentDecl(*I);
1300  }
1301  }
1302 
1303  return List.getLookupResult();
1304 }
1305 
1308  LoadLexicalDeclsFromExternalStorage();
1309  return decl_iterator(FirstDecl);
1310 }
1311 
1314  LoadLexicalDeclsFromExternalStorage();
1315 
1316  return !FirstDecl;
1317 }
1318 
1320  return (D->getLexicalDeclContext() == this &&
1321  (D->NextInContextAndBits.getPointer() || D == LastDecl));
1322 }
1323 
1325  assert(D->getLexicalDeclContext() == this &&
1326  "decl being removed from non-lexical context");
1327  assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1328  "decl is not in decls list");
1329 
1330  // Remove D from the decl chain. This is O(n) but hopefully rare.
1331  if (D == FirstDecl) {
1332  if (D == LastDecl)
1333  FirstDecl = LastDecl = nullptr;
1334  else
1335  FirstDecl = D->NextInContextAndBits.getPointer();
1336  } else {
1337  for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1338  assert(I && "decl not found in linked list");
1339  if (I->NextInContextAndBits.getPointer() == D) {
1340  I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1341  if (D == LastDecl) LastDecl = I;
1342  break;
1343  }
1344  }
1345  }
1346 
1347  // Mark that D is no longer in the decl chain.
1348  D->NextInContextAndBits.setPointer(nullptr);
1349 
1350  // Remove D from the lookup table if necessary.
1351  if (isa<NamedDecl>(D)) {
1352  NamedDecl *ND = cast<NamedDecl>(D);
1353 
1354  // Remove only decls that have a name
1355  if (!ND->getDeclName()) return;
1356 
1357  auto *DC = D->getDeclContext();
1358  do {
1359  StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1360  if (Map) {
1361  StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1362  assert(Pos != Map->end() && "no lookup entry for decl");
1363  if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1364  Pos->second.remove(ND);
1365  }
1366  } while (DC->isTransparentContext() && (DC = DC->getParent()));
1367  }
1368 }
1369 
1371  assert(D->getLexicalDeclContext() == this &&
1372  "Decl inserted into wrong lexical context");
1373  assert(!D->getNextDeclInContext() && D != LastDecl &&
1374  "Decl already inserted into a DeclContext");
1375 
1376  if (FirstDecl) {
1377  LastDecl->NextInContextAndBits.setPointer(D);
1378  LastDecl = D;
1379  } else {
1380  FirstDecl = LastDecl = D;
1381  }
1382 
1383  // Notify a C++ record declaration that we've added a member, so it can
1384  // update its class-specific state.
1385  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1386  Record->addedMember(D);
1387 
1388  // If this is a newly-created (not de-serialized) import declaration, wire
1389  // it in to the list of local import declarations.
1390  if (!D->isFromASTFile()) {
1391  if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1392  D->getASTContext().addedLocalImportDecl(Import);
1393  }
1394 }
1395 
1397  addHiddenDecl(D);
1398 
1399  if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1400  ND->getDeclContext()->getPrimaryContext()->
1401  makeDeclVisibleInContextWithFlags(ND, false, true);
1402 }
1403 
1405  addHiddenDecl(D);
1406 
1407  if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1408  ND->getDeclContext()->getPrimaryContext()->
1409  makeDeclVisibleInContextWithFlags(ND, true, true);
1410 }
1411 
1412 /// shouldBeHidden - Determine whether a declaration which was declared
1413 /// within its semantic context should be invisible to qualified name lookup.
1414 static bool shouldBeHidden(NamedDecl *D) {
1415  // Skip unnamed declarations.
1416  if (!D->getDeclName())
1417  return true;
1418 
1419  // Skip entities that can't be found by name lookup into a particular
1420  // context.
1421  if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1422  D->isTemplateParameter())
1423  return true;
1424 
1425  // Skip template specializations.
1426  // FIXME: This feels like a hack. Should DeclarationName support
1427  // template-ids, or is there a better way to keep specializations
1428  // from being visible?
1429  if (isa<ClassTemplateSpecializationDecl>(D))
1430  return true;
1431  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1432  if (FD->isFunctionTemplateSpecialization())
1433  return true;
1434 
1435  return false;
1436 }
1437 
1438 /// buildLookup - Build the lookup data structure with all of the
1439 /// declarations in this DeclContext (and any other contexts linked
1440 /// to it or transparent contexts nested within it) and return it.
1441 ///
1442 /// Note that the produced map may miss out declarations from an
1443 /// external source. If it does, those entries will be marked with
1444 /// the 'hasExternalDecls' flag.
1446  assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1447 
1448  if (!HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups)
1449  return LookupPtr;
1450 
1452  collectAllContexts(Contexts);
1453 
1454  if (HasLazyExternalLexicalLookups) {
1455  HasLazyExternalLexicalLookups = false;
1456  for (auto *DC : Contexts) {
1457  if (DC->hasExternalLexicalStorage())
1458  HasLazyLocalLexicalLookups |=
1459  DC->LoadLexicalDeclsFromExternalStorage();
1460  }
1461 
1462  if (!HasLazyLocalLexicalLookups)
1463  return LookupPtr;
1464  }
1465 
1466  for (auto *DC : Contexts)
1467  buildLookupImpl(DC, hasExternalVisibleStorage());
1468 
1469  // We no longer have any lazy decls.
1470  HasLazyLocalLexicalLookups = false;
1471  return LookupPtr;
1472 }
1473 
1474 /// buildLookupImpl - Build part of the lookup data structure for the
1475 /// declarations contained within DCtx, which will either be this
1476 /// DeclContext, a DeclContext linked to it, or a transparent context
1477 /// nested within it.
1478 void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
1479  for (Decl *D : DCtx->noload_decls()) {
1480  // Insert this declaration into the lookup structure, but only if
1481  // it's semantically within its decl context. Any other decls which
1482  // should be found in this context are added eagerly.
1483  //
1484  // If it's from an AST file, don't add it now. It'll get handled by
1485  // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1486  // in C++, we do not track external visible decls for the TU, so in
1487  // that case we need to collect them all here.
1488  if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1489  if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1490  (!ND->isFromASTFile() ||
1491  (isTranslationUnit() &&
1492  !getParentASTContext().getLangOpts().CPlusPlus)))
1493  makeDeclVisibleInContextImpl(ND, Internal);
1494 
1495  // If this declaration is itself a transparent declaration context
1496  // or inline namespace, add the members of this declaration of that
1497  // context (recursively).
1498  if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1499  if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1500  buildLookupImpl(InnerCtx, Internal);
1501  }
1502 }
1503 
1504 NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1505 
1508  assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1509  "should not perform lookups into transparent contexts");
1510 
1511  const DeclContext *PrimaryContext = getPrimaryContext();
1512  if (PrimaryContext != this)
1513  return PrimaryContext->lookup(Name);
1514 
1515  // If we have an external source, ensure that any later redeclarations of this
1516  // context have been loaded, since they may add names to the result of this
1517  // lookup (or add external visible storage).
1519  if (Source)
1520  (void)cast<Decl>(this)->getMostRecentDecl();
1521 
1522  if (hasExternalVisibleStorage()) {
1523  assert(Source && "external visible storage but no external source?");
1524 
1525  if (NeedToReconcileExternalVisibleStorage)
1526  reconcileExternalVisibleStorage();
1527 
1528  StoredDeclsMap *Map = LookupPtr;
1529 
1530  if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1531  // FIXME: Make buildLookup const?
1532  Map = const_cast<DeclContext*>(this)->buildLookup();
1533 
1534  if (!Map)
1535  Map = CreateStoredDeclsMap(getParentASTContext());
1536 
1537  // If we have a lookup result with no external decls, we are done.
1538  std::pair<StoredDeclsMap::iterator, bool> R =
1539  Map->insert(std::make_pair(Name, StoredDeclsList()));
1540  if (!R.second && !R.first->second.hasExternalDecls())
1541  return R.first->second.getLookupResult();
1542 
1543  if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
1544  if (StoredDeclsMap *Map = LookupPtr) {
1545  StoredDeclsMap::iterator I = Map->find(Name);
1546  if (I != Map->end())
1547  return I->second.getLookupResult();
1548  }
1549  }
1550 
1551  return lookup_result();
1552  }
1553 
1554  StoredDeclsMap *Map = LookupPtr;
1555  if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1556  Map = const_cast<DeclContext*>(this)->buildLookup();
1557 
1558  if (!Map)
1559  return lookup_result();
1560 
1561  StoredDeclsMap::iterator I = Map->find(Name);
1562  if (I == Map->end())
1563  return lookup_result();
1564 
1565  return I->second.getLookupResult();
1566 }
1567 
1570  assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1571  "should not perform lookups into transparent contexts");
1572 
1573  DeclContext *PrimaryContext = getPrimaryContext();
1574  if (PrimaryContext != this)
1575  return PrimaryContext->noload_lookup(Name);
1576 
1577  // If we have any lazy lexical declarations not in our lookup map, add them
1578  // now. Don't import any external declarations, not even if we know we have
1579  // some missing from the external visible lookups.
1580  if (HasLazyLocalLexicalLookups) {
1582  collectAllContexts(Contexts);
1583  for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1584  buildLookupImpl(Contexts[I], hasExternalVisibleStorage());
1585  HasLazyLocalLexicalLookups = false;
1586  }
1587 
1588  StoredDeclsMap *Map = LookupPtr;
1589  if (!Map)
1590  return lookup_result();
1591 
1592  StoredDeclsMap::iterator I = Map->find(Name);
1593  return I != Map->end() ? I->second.getLookupResult()
1594  : lookup_result();
1595 }
1596 
1598  SmallVectorImpl<NamedDecl *> &Results) {
1599  Results.clear();
1600 
1601  // If there's no external storage, just perform a normal lookup and copy
1602  // the results.
1604  lookup_result LookupResults = lookup(Name);
1605  Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1606  return;
1607  }
1608 
1609  // If we have a lookup table, check there first. Maybe we'll get lucky.
1610  // FIXME: Should we be checking these flags on the primary context?
1611  if (Name && !HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups) {
1612  if (StoredDeclsMap *Map = LookupPtr) {
1613  StoredDeclsMap::iterator Pos = Map->find(Name);
1614  if (Pos != Map->end()) {
1615  Results.insert(Results.end(),
1616  Pos->second.getLookupResult().begin(),
1617  Pos->second.getLookupResult().end());
1618  return;
1619  }
1620  }
1621  }
1622 
1623  // Slow case: grovel through the declarations in our chain looking for
1624  // matches.
1625  // FIXME: If we have lazy external declarations, this will not find them!
1626  // FIXME: Should we CollectAllContexts and walk them all here?
1627  for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1628  if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1629  if (ND->getDeclName() == Name)
1630  Results.push_back(ND);
1631  }
1632 }
1633 
1635  DeclContext *Ctx = this;
1636  // Skip through transparent contexts.
1637  while (Ctx->isTransparentContext())
1638  Ctx = Ctx->getParent();
1639  return Ctx;
1640 }
1641 
1643  DeclContext *Ctx = this;
1644  // Skip through non-namespace, non-translation-unit contexts.
1645  while (!Ctx->isFileContext())
1646  Ctx = Ctx->getParent();
1647  return Ctx->getPrimaryContext();
1648 }
1649 
1651  // Loop until we find a non-record context.
1652  RecordDecl *OutermostRD = nullptr;
1653  DeclContext *DC = this;
1654  while (DC->isRecord()) {
1655  OutermostRD = cast<RecordDecl>(DC);
1656  DC = DC->getLexicalParent();
1657  }
1658  return OutermostRD;
1659 }
1660 
1662  // For non-file contexts, this is equivalent to Equals.
1663  if (!isFileContext())
1664  return O->Equals(this);
1665 
1666  do {
1667  if (O->Equals(this))
1668  return true;
1669 
1670  const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1671  if (!NS || !NS->isInline())
1672  break;
1673  O = NS->getParent();
1674  } while (O);
1675 
1676  return false;
1677 }
1678 
1680  DeclContext *PrimaryDC = this->getPrimaryContext();
1681  DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1682  // If the decl is being added outside of its semantic decl context, we
1683  // need to ensure that we eagerly build the lookup information for it.
1684  PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1685 }
1686 
1687 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1688  bool Recoverable) {
1689  assert(this == getPrimaryContext() && "expected a primary DC");
1690 
1691  if (!isLookupContext()) {
1692  if (isTransparentContext())
1694  ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1695  return;
1696  }
1697 
1698  // Skip declarations which should be invisible to name lookup.
1699  if (shouldBeHidden(D))
1700  return;
1701 
1702  // If we already have a lookup data structure, perform the insertion into
1703  // it. If we might have externally-stored decls with this name, look them
1704  // up and perform the insertion. If this decl was declared outside its
1705  // semantic context, buildLookup won't add it, so add it now.
1706  //
1707  // FIXME: As a performance hack, don't add such decls into the translation
1708  // unit unless we're in C++, since qualified lookup into the TU is never
1709  // performed.
1710  if (LookupPtr || hasExternalVisibleStorage() ||
1711  ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1712  (getParentASTContext().getLangOpts().CPlusPlus ||
1713  !isTranslationUnit()))) {
1714  // If we have lazily omitted any decls, they might have the same name as
1715  // the decl which we are adding, so build a full lookup table before adding
1716  // this decl.
1717  buildLookup();
1718  makeDeclVisibleInContextImpl(D, Internal);
1719  } else {
1720  HasLazyLocalLexicalLookups = true;
1721  }
1722 
1723  // If we are a transparent context or inline namespace, insert into our
1724  // parent context, too. This operation is recursive.
1727  makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1728 
1729  Decl *DCAsDecl = cast<Decl>(this);
1730  // Notify that a decl was made visible unless we are a Tag being defined.
1731  if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1732  if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1733  L->AddedVisibleDecl(this, D);
1734 }
1735 
1736 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1737  // Find or create the stored declaration map.
1738  StoredDeclsMap *Map = LookupPtr;
1739  if (!Map) {
1741  Map = CreateStoredDeclsMap(*C);
1742  }
1743 
1744  // If there is an external AST source, load any declarations it knows about
1745  // with this declaration's name.
1746  // If the lookup table contains an entry about this name it means that we
1747  // have already checked the external source.
1748  if (!Internal)
1749  if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1750  if (hasExternalVisibleStorage() &&
1751  Map->find(D->getDeclName()) == Map->end())
1752  Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1753 
1754  // Insert this declaration into the map.
1755  StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1756 
1757  if (Internal) {
1758  // If this is being added as part of loading an external declaration,
1759  // this may not be the only external declaration with this name.
1760  // In this case, we never try to replace an existing declaration; we'll
1761  // handle that when we finalize the list of declarations for this name.
1762  DeclNameEntries.setHasExternalDecls();
1763  DeclNameEntries.AddSubsequentDecl(D);
1764  return;
1765  }
1766 
1767  if (DeclNameEntries.isNull()) {
1768  DeclNameEntries.setOnlyValue(D);
1769  return;
1770  }
1771 
1772  if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
1773  // This declaration has replaced an existing one for which
1774  // declarationReplaces returns true.
1775  return;
1776  }
1777 
1778  // Put this declaration into the appropriate slot.
1779  DeclNameEntries.AddSubsequentDecl(D);
1780 }
1781 
1783  return cast<UsingDirectiveDecl>(*I);
1784 }
1785 
1786 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1787 /// this context.
1789  // FIXME: Use something more efficient than normal lookup for using
1790  // directives. In C++, using directives are looked up more than anything else.
1791  lookup_result Result = lookup(UsingDirectiveDecl::getName());
1792  return udir_range(Result.begin(), Result.end());
1793 }
1794 
1795 //===----------------------------------------------------------------------===//
1796 // Creation and Destruction of StoredDeclsMaps. //
1797 //===----------------------------------------------------------------------===//
1798 
1799 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1800  assert(!LookupPtr && "context already has a decls map");
1801  assert(getPrimaryContext() == this &&
1802  "creating decls map on non-primary context");
1803 
1804  StoredDeclsMap *M;
1805  bool Dependent = isDependentContext();
1806  if (Dependent)
1807  M = new DependentStoredDeclsMap();
1808  else
1809  M = new StoredDeclsMap();
1810  M->Previous = C.LastSDM;
1811  C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1812  LookupPtr = M;
1813  return M;
1814 }
1815 
1816 void ASTContext::ReleaseDeclContextMaps() {
1817  // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1818  // pointer because the subclass doesn't add anything that needs to
1819  // be deleted.
1820  StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1821 }
1822 
1823 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1824  while (Map) {
1825  // Advance the iteration before we invalidate memory.
1826  llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1827 
1828  if (Dependent)
1829  delete static_cast<DependentStoredDeclsMap*>(Map);
1830  else
1831  delete Map;
1832 
1833  Map = Next.getPointer();
1834  Dependent = Next.getInt();
1835  }
1836 }
1837 
1839  DeclContext *Parent,
1840  const PartialDiagnostic &PDiag) {
1841  assert(Parent->isDependentContext()
1842  && "cannot iterate dependent diagnostics of non-dependent context");
1843  Parent = Parent->getPrimaryContext();
1844  if (!Parent->LookupPtr)
1845  Parent->CreateStoredDeclsMap(C);
1846 
1848  static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
1849 
1850  // Allocate the copy of the PartialDiagnostic via the ASTContext's
1851  // BumpPtrAllocator, rather than the ASTContext itself.
1852  PartialDiagnostic::Storage *DiagStorage = nullptr;
1853  if (PDiag.hasStorage())
1854  DiagStorage = new (C) PartialDiagnostic::Storage;
1855 
1856  DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1857 
1858  // TODO: Maybe we shouldn't reverse the order during insertion.
1859  DD->NextDiagnostic = Map->FirstDiagnostic;
1860  Map->FirstDiagnostic = DD;
1861 
1862  return DD;
1863 }
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...
static StringRef getRealizedPlatform(const AvailabilityAttr *A, const ASTContext &Context)
Definition: DeclBase.cpp:453
bool hasOwningModule() const
Is this declaration owned by some module?
Definition: DeclBase.h:732
Defines the clang::ASTContext interface.
SourceLocation getEnd() const
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1618
AttrVec & getDeclAttrs(const Decl *D)
Retrieve the attributes for the given declaration.
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:1041
iterator begin() const
Definition: DeclBase.h:1182
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:1906
void updateOutOfDate(IdentifierInfo &II) const
Update a potentially out-of-date declaration.
Definition: DeclBase.cpp:43
static DeclContext * castToDeclContext(const Decl *)
Definition: DeclBase.cpp:832
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2224
static bool shouldBeHidden(NamedDecl *D)
shouldBeHidden - Determine whether a declaration which was declared within its semantic context shoul...
Definition: DeclBase.cpp:1414
A (possibly-)qualified type.
Definition: Type.h:616
UsingDirectiveDecl * operator*() const
Definition: DeclBase.cpp:1782
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration...
Definition: DeclBase.cpp:211
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...
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
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple()) const
Determine the availability of the given declaration.
Definition: DeclBase.cpp:562
static Decl * castFromDeclContext(const DeclContext *)
Definition: DeclBase.cpp:813
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
Definition: Decl.h:232
static bool isLinkageSpecContext(const DeclContext *DC, LinkageSpecDecl::LanguageIDs ID)
Definition: DeclBase.cpp:1050
Stmt - This represents one statement.
Definition: Stmt.h:60
bool hasDefiningAttr() const
Return true if this declaration has an attribute which acts as definition of the entity, such as 'alias' or 'ifunc'.
Definition: DeclBase.cpp:441
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1060
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:2923
C Language Family Type Representation.
const DeclContext * getParentFunctionOrMethod() const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext...
Definition: DeclBase.cpp:222
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:172
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:922
bool isInStdNamespace() const
Definition: DeclBase.cpp:327
static DeclContextLookupResult SetExternalVisibleDeclsForName(const DeclContext *DC, DeclarationName Name, ArrayRef< NamedDecl * > Decls)
Definition: DeclBase.cpp:1258
bool isStdNamespace() const
Definition: DeclBase.cpp:993
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1009
std::unique_ptr< llvm::MemoryBuffer > Buffer
NamespaceDecl - Represent a C++ namespace.
Definition: Decl.h:461
bool isWeakImported() const
Determine whether this is a weak-imported symbol.
Definition: DeclBase.cpp:653
bool isBlockPointerType() const
Definition: Type.h:5718
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:1597
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:920
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 ...
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:758
VersionTuple getPlatformMinVersion() const
Retrieve the minimum desired version of the platform, to which the program should be compiled...
Definition: TargetInfo.h:986
bool decls_empty() const
Definition: DeclBase.cpp:1312
ExternalSourceSymbolAttr * getExternalSourceSymbolAttr() const
Looks on this and related declarations for an applicable external source symbol attribute.
Definition: DeclBase.cpp:420
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:113
Decl * FirstDecl
FirstDecl - The first declaration stored within this declaration context.
Definition: DeclBase.h:1259
udir_range using_directives() const
Returns iterator range [First, Last) of UsingDirectiveDecls stored within this context.
Definition: DeclBase.cpp:1788
ModuleOwnershipKind getModuleOwnershipKind() const
Get the kind of module ownership for this declaration.
Definition: DeclBase.h:757
ParmVarDecl - Represents a parameter to a function.
Definition: Decl.h:1434
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1324
Types, declared with 'struct foo', typedefs, etc.
Definition: DeclBase.h:125
RecordDecl - Represents a struct/union/class.
Definition: Decl.h:3354
ASTMutationListener * getASTMutationListener() const
Definition: DeclBase.cpp:350
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl, 0 if there are none.
Definition: DeclBase.cpp:354
One of these records is kept for each identifier that is lexed.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:128
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1146
bool hasExternalLexicalStorage() const
Whether this DeclContext has external storage containing additional declarations that are lexically i...
Definition: DeclBase.h:1840
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition: DeclBase.cpp:392
unsigned getIdentifierNamespace() const
Definition: DeclBase.h:770
bool isTranslationUnit() const
Definition: DeclBase.h:1364
bool isInlineNamespace() const
Definition: DeclBase.cpp:988
static std::pair< Decl *, Decl * > BuildDeclChain(ArrayRef< Decl * > Decls, bool FieldsAlreadyLoaded)
Build up a chain of declarations.
Definition: DeclBase.cpp:1173
Describes a module or submodule.
Definition: Module.h:57
virtual void updateOutOfDateIdentifier(IdentifierInfo &II)
Update an out-of-date identifier.
T * getAttr() const
Definition: DeclBase.h:518
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:1642
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:643
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...
const LangOptions & getLangOpts() const
Definition: ASTContext.h:659
Namespaces, declared with 'namespace foo {}'.
Definition: DeclBase.h:135
bool isInline() const
Returns true if this is an inline namespace declaration.
Definition: Decl.h:516
StoredDeclsMap * buildLookup()
Ensure the lookup structure is fully-built and return it.
Definition: DeclBase.cpp:1445
const CXXRecordDecl * getParent() const
Returns the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:2018
static DeclContextLookupResult SetNoExternalVisibleDeclsForName(const DeclContext *DC, DeclarationName Name)
Definition: DeclBase.cpp:1243
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1319
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:796
bool hasLocalOwningModuleStorage() const
Definition: DeclBase.cpp:98
bool isExported() const
Whether this declaration is exported (by virtue of being lexically within an ExportDecl or by being a...
Definition: DeclBase.cpp:404
Labels, declared with 'x:' and referenced with 'goto x'.
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:3726
Represents an ObjC class declaration.
Definition: DeclObjC.h:1108
Represents a linkage specification.
Definition: DeclCXX.h:2666
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1306
detail::InMemoryDirectory::const_iterator I
A binding in a decomposition declaration.
Definition: DeclCXX.h:3624
Ordinary names.
Definition: DeclBase.h:139
bool isInvalid() const
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:841
void addDeclInternal(Decl *D)
Add the declaration D into this context, but suppress searches for external declarations with the sam...
Definition: DeclBase.cpp:1404
AvailabilityResult
Captures the result of checking the availability of a declaration.
Definition: DeclBase.h:67
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack...
Definition: DeclBase.cpp:180
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
bool isNamespace() const
Definition: DeclBase.h:1372
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:1545
bool hasWeakClassImport() const
Does this runtime support weakly importing classes?
Definition: ObjCRuntime.h:271
unsigned getOwningModuleID() const
Retrieve the global ID of the module that owns this particular declaration.
Definition: DeclBase.h:693
ASTContext * Context
SourceLocation getBodyRBrace() const
getBodyRBrace - Gets the right brace of the body, if a body exists.
Definition: DeclBase.cpp:851
bool isFunctionPointerType() const
Definition: Type.h:5730
void removeExternalDecls()
Remove any declarations which were imported from an external AST source.
bool trackLocalOwningModule() const
Do we need to track the owning module for a local declaration?
Definition: LangOptions.h:171
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:1310
const char * getDeclKindName() const
Definition: DeclBase.cpp:134
const Type * getTypeForDecl() const
Definition: Decl.h:2663
BlockDecl - This represents a block literal declaration, which is like an unnamed FunctionDecl...
Definition: Decl.h:3557
QualType getPointeeType() const
Definition: Type.h:2341
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
Definition: Decl.h:580
bool isLookupContext() const
Test whether the context supports looking up names.
Definition: DeclBase.h:1355
std::string Label
static unsigned getIdentifierNamespaceForKind(Kind DK)
Definition: DeclBase.cpp:672
llvm::iterator_range< udir_iterator > udir_range
Definition: DeclBase.h:1807
Declaration of a template type parameter.
bool isTemplateDecl() const
returns true if this declaration is a template
Definition: DeclBase.cpp:207
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1080
ASTContext & getParentASTContext() const
Definition: DeclBase.h:1323
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
Definition: DeclBase.cpp:1064
Decl * LastDecl
LastDecl - The last declaration stored within this declaration context.
Definition: DeclBase.h:1265
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:111
This declaration is an OpenMP user defined reduction construction.
Definition: DeclBase.h:173
bool isInAnonymousNamespace() const
Definition: DeclBase.cpp:316
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition: DeclBase.h:937
Kind getKind() const
Definition: DeclBase.h:410
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't attempt to retr...
Definition: DeclBase.cpp:1569
Decl * getNonClosureAncestor()
Find the nearest non-closure ancestor of this context, i.e.
Definition: DeclBase.cpp:944
const char * getDeclKindName() const
Definition: DeclBase.cpp:102
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.
friend class DependentDiagnostic
Definition: DeclBase.h:1897
bool isFunctionOrMethod() const
Definition: DeclBase.h:1343
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:116
This declaration has an owning module, and is visible when that module is imported.
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1294
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition: DeclBase.h:681
unsigned Map[FirstTargetAddressSpace]
The type of a lookup table which maps from language-specific address spaces to target-specific ones...
Definition: AddressSpaces.h:53
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
Definition: Decl.h:258
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
TagDecl * getDefinition() const
getDefinition - Returns the TagDecl that actually defines this struct/union/class/enum.
Definition: Decl.cpp:3698
The result type of a method or function.
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:264
virtual void DeclarationMarkedUsed(const Decl *D)
A declaration is marked used which was not previously marked used.
AttrVec & getAttrs()
Definition: DeclBase.h:466
VersionTuple getVersionIntroduced() const
Retrieve the version of the target platform in which this declaration was introduced.
Definition: DeclBase.cpp:609
Abstract interface for external sources of AST nodes.
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:1679
DeclContext::lookup_result getLookupResult()
getLookupResult - Return an array of all the decls that this list represents.
void print(raw_ostream &OS, const SourceManager &SM) const
SmallVectorImpl< AnnotatedLine * >::const_iterator Next
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:199
Encodes a location in the source.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any...
Definition: ASTContext.h:1014
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:762
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:1661
bool isValid() const
Return true if this is a valid SourceLocation object.
const std::string ID
TagDecl - Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:2816
attr_range attrs() const
Definition: DeclBase.h:482
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:346
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1903
This file defines OpenMP nodes for declarative directives.
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:948
void print(raw_ostream &OS) const override
Definition: DeclBase.cpp:237
ASTContext & getASTContext() const
Definition: Decl.h:90
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1507
bool isFileContext() const
Definition: DeclBase.h:1360
DeclContextLookupResult lookup_result
Definition: DeclBase.h:1736
An array of decls optimized for the common case of only containing one entry.
const Attr * getDefiningAttr() const
Return this declaration's defining attribute if it has one.
Definition: DeclBase.cpp:445
void dropAttrs()
Definition: DeclBase.cpp:801
bool isExternCXXContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1076
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition: Decl.h:3829
QualType getPointeeType() const
Definition: Type.h:2238
decl_iterator - Iterates through the declarations stored within this context.
Definition: DeclBase.h:1496
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:2682
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:911
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:1215
StringRef Name
Definition: USRFinder.cpp:123
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:378
bool empty() const
Determine whether this version information is empty (e.g., all version components are zero)...
Definition: VersionTuple.h:69
bool isInvalidDecl() const
Definition: DeclBase.h:532
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:3672
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:1650
DeclarationName - The name of a declaration.
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
Decl * getNonClosureContext()
Find the innermost non-closure ancestor of this declaration, walking up through blocks, lambdas, etc.
Definition: DeclBase.cpp:940
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible. ...
Definition: DeclBase.cpp:900
bool hasAttrs() const
Definition: DeclBase.h:462
detail::InMemoryDirectory::const_iterator E
Tags, declared with 'struct foo;' and referenced with 'struct foo'.
Definition: DeclBase.h:120
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1102
SmallVector< Context, 8 > Contexts
A dependently-generated diagnostic.
Pointer to a block type.
Definition: Type.h:2327
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
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:6042
Decl::Kind getDeclKind() const
Definition: DeclBase.h:1288
LanguageIDs
Represents the language in a linkage specification.
Definition: DeclCXX.h:2675
virtual ~Decl()
Definition: DeclBase.cpp:262
Module * getOwningModule() const
Get the module that owns this declaration.
Definition: DeclBase.h:737
void setOnlyValue(NamedDecl *ND)
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1634
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1396
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any...
Definition: ASTContext.h:1029
bool isLexicallyWithinFunctionOrMethod() const
Returns true if this declaration lexically is inside a function.
Definition: DeclBase.cpp:304
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
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:267
void addHiddenDecl(Decl *D)
Add the declaration D to this context without modifying any lookup tables.
Definition: DeclBase.cpp:1370
void * Allocate(size_t Size, unsigned Align=8) const
Definition: ASTContext.h:623
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:978
static bool classof(const Decl *D)
Definition: DeclBase.cpp:952
Defines the clang::TargetInfo interface.
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC...
Definition: DeclBase.h:1414
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:3471
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:84
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:897
bool isRecord() const
Definition: DeclBase.h:1368
TranslationUnitDecl - The top declaration context.
Definition: Decl.h:80
static void DestroyAll(StoredDeclsMap *Map, bool Dependent)
Definition: DeclBase.cpp:1823
static void PrintStats()
Definition: DeclBase.cpp:148
NamedDecl * getMostRecentDecl()
Definition: Decl.h:391
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1090
static void EnableStatistics()
Definition: DeclBase.cpp:144
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:192
SourceLocation getLocation() const
Definition: DeclBase.h:407
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:268
NamedDecl - This represents a decl with a name.
Definition: Decl.h:213
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:446
void collectAllContexts(SmallVectorImpl< DeclContext * > &Contexts)
Collects all of the declaration contexts that are semantically connected to this declaration context...
Definition: DeclBase.cpp:1156
Represents C++ using-directive.
Definition: DeclCXX.h:2758
void addedLocalImportDecl(ImportDecl *Import)
Notify the AST context that a new import declaration has been parsed or implicitly created within thi...
TranslationUnitDecl * getTranslationUnitDecl()
Definition: DeclBase.cpp:331
StringRef getPlatformName() const
Retrieve the name of the platform as it is used in the availability attribute.
Definition: TargetInfo.h:982
bool isModulePrivate() const
Whether this declaration was marked as being private to the module in which it was defined...
Definition: DeclBase.h:586
bool isBeingDefined() const
isBeingDefined - Return true if this decl is currently being defined.
Definition: Decl.h:2971
Declaration of a template function.
Definition: DeclTemplate.h:939
const NamedDecl * Result
Definition: USRFinder.cpp:70
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
This declaration is a using declaration.
Definition: DeclBase.h:158
bool hasExternalVisibleStorage() const
Whether this DeclContext has external storage containing additional declarations that are visible in ...
Definition: DeclBase.h:1850
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any...
Definition: Decl.cpp:3139