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"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclContextInternals.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"
25 #include "clang/AST/DependentDiagnostic.h"
26 #include "clang/AST/ExternalASTSource.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/ADT/DenseMap.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <algorithm>
34 using namespace clang;
35 
36 //===----------------------------------------------------------------------===//
37 //  Statistics
38 //===----------------------------------------------------------------------===//
39 
40 #define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
41 #define ABSTRACT_DECL(DECL)
42 #include "clang/AST/DeclNodes.inc"
43 
updateOutOfDate(IdentifierInfo & II) const44 void Decl::updateOutOfDate(IdentifierInfo &II) const {
45   getASTContext().getExternalSource()->updateOutOfDateIdentifier(II);
46 }
47 
48 #define DECL(DERIVED, BASE)                                                    \
49   static_assert(Decl::DeclObjAlignment >=                                      \
50                     llvm::AlignOf<DERIVED##Decl>::Alignment,                   \
51                 "Alignment sufficient after objects prepended to " #DERIVED);
52 #define ABSTRACT_DECL(DECL)
53 #include "clang/AST/DeclNodes.inc"
54 
operator new(std::size_t Size,const ASTContext & Context,unsigned ID,std::size_t Extra)55 void *Decl::operator new(std::size_t Size, const ASTContext &Context,
56                          unsigned ID, std::size_t Extra) {
57   // Allocate an extra 8 bytes worth of storage, which ensures that the
58   // resulting pointer will still be 8-byte aligned.
59   static_assert(sizeof(unsigned) * 2 >= DeclObjAlignment,
60                 "Decl won't be misaligned");
61   void *Start = Context.Allocate(Size + Extra + 8);
62   void *Result = (char*)Start + 8;
63 
64   unsigned *PrefixPtr = (unsigned *)Result - 2;
65 
66   // Zero out the first 4 bytes; this is used to store the owning module ID.
67   PrefixPtr[0] = 0;
68 
69   // Store the global declaration ID in the second 4 bytes.
70   PrefixPtr[1] = ID;
71 
72   return Result;
73 }
74 
operator new(std::size_t Size,const ASTContext & Ctx,DeclContext * Parent,std::size_t Extra)75 void *Decl::operator new(std::size_t Size, const ASTContext &Ctx,
76                          DeclContext *Parent, std::size_t Extra) {
77   assert(!Parent || &Parent->getParentASTContext() == &Ctx);
78   // With local visibility enabled, we track the owning module even for local
79   // declarations.
80   if (Ctx.getLangOpts().ModulesLocalVisibility) {
81     // Ensure required alignment of the resulting object by adding extra
82     // padding at the start if required.
83     size_t ExtraAlign =
84         llvm::OffsetToAlignment(sizeof(Module *), DeclObjAlignment);
85     char *Buffer = reinterpret_cast<char *>(
86         ::operator new(ExtraAlign + sizeof(Module *) + Size + Extra, Ctx));
87     Buffer += ExtraAlign;
88     return new (Buffer) Module*(nullptr) + 1;
89   }
90   return ::operator new(Size + Extra, Ctx);
91 }
92 
getOwningModuleSlow() const93 Module *Decl::getOwningModuleSlow() const {
94   assert(isFromASTFile() && "Not from AST file?");
95   return getASTContext().getExternalSource()->getModule(getOwningModuleID());
96 }
97 
hasLocalOwningModuleStorage() const98 bool Decl::hasLocalOwningModuleStorage() const {
99   return getASTContext().getLangOpts().ModulesLocalVisibility;
100 }
101 
getDeclKindName() const102 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 
setInvalidDecl(bool Invalid)111 void Decl::setInvalidDecl(bool Invalid) {
112   InvalidDecl = Invalid;
113   assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
114   if (Invalid && !isa<ParmVarDecl>(this)) {
115     // Defensive maneuver for ill-formed code: we're likely not to make it to
116     // a point where we set the access specifier, so default it to "public"
117     // to avoid triggering asserts elsewhere in the front end.
118     setAccess(AS_public);
119   }
120 }
121 
getDeclKindName() const122 const char *DeclContext::getDeclKindName() const {
123   switch (DeclKind) {
124   default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
125 #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
126 #define ABSTRACT_DECL(DECL)
127 #include "clang/AST/DeclNodes.inc"
128   }
129 }
130 
131 bool Decl::StatisticsEnabled = false;
EnableStatistics()132 void Decl::EnableStatistics() {
133   StatisticsEnabled = true;
134 }
135 
PrintStats()136 void Decl::PrintStats() {
137   llvm::errs() << "\n*** Decl Stats:\n";
138 
139   int totalDecls = 0;
140 #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
141 #define ABSTRACT_DECL(DECL)
142 #include "clang/AST/DeclNodes.inc"
143   llvm::errs() << "  " << totalDecls << " decls total.\n";
144 
145   int totalBytes = 0;
146 #define DECL(DERIVED, BASE)                                             \
147   if (n##DERIVED##s > 0) {                                              \
148     totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl));         \
149     llvm::errs() << "    " << n##DERIVED##s << " " #DERIVED " decls, "  \
150                  << sizeof(DERIVED##Decl) << " each ("                  \
151                  << n##DERIVED##s * sizeof(DERIVED##Decl)               \
152                  << " bytes)\n";                                        \
153   }
154 #define ABSTRACT_DECL(DECL)
155 #include "clang/AST/DeclNodes.inc"
156 
157   llvm::errs() << "Total bytes = " << totalBytes << "\n";
158 }
159 
add(Kind k)160 void Decl::add(Kind k) {
161   switch (k) {
162 #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
163 #define ABSTRACT_DECL(DECL)
164 #include "clang/AST/DeclNodes.inc"
165   }
166 }
167 
isTemplateParameterPack() const168 bool Decl::isTemplateParameterPack() const {
169   if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
170     return TTP->isParameterPack();
171   if (const NonTypeTemplateParmDecl *NTTP
172                                 = dyn_cast<NonTypeTemplateParmDecl>(this))
173     return NTTP->isParameterPack();
174   if (const TemplateTemplateParmDecl *TTP
175                                     = dyn_cast<TemplateTemplateParmDecl>(this))
176     return TTP->isParameterPack();
177   return false;
178 }
179 
isParameterPack() const180 bool Decl::isParameterPack() const {
181   if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
182     return Parm->isParameterPack();
183 
184   return isTemplateParameterPack();
185 }
186 
getAsFunction()187 FunctionDecl *Decl::getAsFunction() {
188   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
189     return FD;
190   if (const FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(this))
191     return FTD->getTemplatedDecl();
192   return nullptr;
193 }
194 
isTemplateDecl() const195 bool Decl::isTemplateDecl() const {
196   return isa<TemplateDecl>(this);
197 }
198 
getParentFunctionOrMethod() const199 const DeclContext *Decl::getParentFunctionOrMethod() const {
200   for (const DeclContext *DC = getDeclContext();
201        DC && !DC->isTranslationUnit() && !DC->isNamespace();
202        DC = DC->getParent())
203     if (DC->isFunctionOrMethod())
204       return DC;
205 
206   return nullptr;
207 }
208 
209 
210 //===----------------------------------------------------------------------===//
211 // PrettyStackTraceDecl Implementation
212 //===----------------------------------------------------------------------===//
213 
print(raw_ostream & OS) const214 void PrettyStackTraceDecl::print(raw_ostream &OS) const {
215   SourceLocation TheLoc = Loc;
216   if (TheLoc.isInvalid() && TheDecl)
217     TheLoc = TheDecl->getLocation();
218 
219   if (TheLoc.isValid()) {
220     TheLoc.print(OS, SM);
221     OS << ": ";
222   }
223 
224   OS << Message;
225 
226   if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
227     OS << " '";
228     DN->printQualifiedName(OS);
229     OS << '\'';
230   }
231   OS << '\n';
232 }
233 
234 //===----------------------------------------------------------------------===//
235 // Decl Implementation
236 //===----------------------------------------------------------------------===//
237 
238 // Out-of-line virtual method providing a home for Decl.
~Decl()239 Decl::~Decl() { }
240 
setDeclContext(DeclContext * DC)241 void Decl::setDeclContext(DeclContext *DC) {
242   DeclCtx = DC;
243 }
244 
setLexicalDeclContext(DeclContext * DC)245 void Decl::setLexicalDeclContext(DeclContext *DC) {
246   if (DC == getLexicalDeclContext())
247     return;
248 
249   if (isInSemaDC()) {
250     setDeclContextsImpl(getDeclContext(), DC, getASTContext());
251   } else {
252     getMultipleDC()->LexicalDC = DC;
253   }
254   Hidden = cast<Decl>(DC)->Hidden;
255 }
256 
setDeclContextsImpl(DeclContext * SemaDC,DeclContext * LexicalDC,ASTContext & Ctx)257 void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
258                                ASTContext &Ctx) {
259   if (SemaDC == LexicalDC) {
260     DeclCtx = SemaDC;
261   } else {
262     Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
263     MDC->SemanticDC = SemaDC;
264     MDC->LexicalDC = LexicalDC;
265     DeclCtx = MDC;
266   }
267 }
268 
isLexicallyWithinFunctionOrMethod() const269 bool Decl::isLexicallyWithinFunctionOrMethod() const {
270   const DeclContext *LDC = getLexicalDeclContext();
271   while (true) {
272     if (LDC->isFunctionOrMethod())
273       return true;
274     if (!isa<TagDecl>(LDC))
275       return false;
276     LDC = LDC->getLexicalParent();
277   }
278   return false;
279 }
280 
isInAnonymousNamespace() const281 bool Decl::isInAnonymousNamespace() const {
282   const DeclContext *DC = getDeclContext();
283   do {
284     if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
285       if (ND->isAnonymousNamespace())
286         return true;
287   } while ((DC = DC->getParent()));
288 
289   return false;
290 }
291 
isInStdNamespace() const292 bool Decl::isInStdNamespace() const {
293   return getDeclContext()->isStdNamespace();
294 }
295 
getTranslationUnitDecl()296 TranslationUnitDecl *Decl::getTranslationUnitDecl() {
297   if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
298     return TUD;
299 
300   DeclContext *DC = getDeclContext();
301   assert(DC && "This decl is not contained in a translation unit!");
302 
303   while (!DC->isTranslationUnit()) {
304     DC = DC->getParent();
305     assert(DC && "This decl is not contained in a translation unit!");
306   }
307 
308   return cast<TranslationUnitDecl>(DC);
309 }
310 
getASTContext() const311 ASTContext &Decl::getASTContext() const {
312   return getTranslationUnitDecl()->getASTContext();
313 }
314 
getASTMutationListener() const315 ASTMutationListener *Decl::getASTMutationListener() const {
316   return getASTContext().getASTMutationListener();
317 }
318 
getMaxAlignment() const319 unsigned Decl::getMaxAlignment() const {
320   if (!hasAttrs())
321     return 0;
322 
323   unsigned Align = 0;
324   const AttrVec &V = getAttrs();
325   ASTContext &Ctx = getASTContext();
326   specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
327   for (; I != E; ++I)
328     Align = std::max(Align, I->getAlignment(Ctx));
329   return Align;
330 }
331 
isUsed(bool CheckUsedAttr) const332 bool Decl::isUsed(bool CheckUsedAttr) const {
333   if (Used)
334     return true;
335 
336   // Check for used attribute.
337   if (CheckUsedAttr && hasAttr<UsedAttr>())
338     return true;
339 
340   return false;
341 }
342 
markUsed(ASTContext & C)343 void Decl::markUsed(ASTContext &C) {
344   if (Used)
345     return;
346 
347   if (C.getASTMutationListener())
348     C.getASTMutationListener()->DeclarationMarkedUsed(this);
349 
350   Used = true;
351 }
352 
isReferenced() const353 bool Decl::isReferenced() const {
354   if (Referenced)
355     return true;
356 
357   // Check redeclarations.
358   for (auto I : redecls())
359     if (I->Referenced)
360       return true;
361 
362   return false;
363 }
364 
365 /// \brief Determine the availability of the given declaration based on
366 /// the target platform.
367 ///
368 /// When it returns an availability result other than \c AR_Available,
369 /// if the \p Message parameter is non-NULL, it will be set to a
370 /// string describing why the entity is unavailable.
371 ///
372 /// FIXME: Make these strings localizable, since they end up in
373 /// diagnostics.
CheckAvailability(ASTContext & Context,const AvailabilityAttr * A,std::string * Message)374 static AvailabilityResult CheckAvailability(ASTContext &Context,
375                                             const AvailabilityAttr *A,
376                                             std::string *Message) {
377   VersionTuple TargetMinVersion =
378     Context.getTargetInfo().getPlatformMinVersion();
379 
380   if (TargetMinVersion.empty())
381     return AR_Available;
382 
383   // Check if this is an App Extension "platform", and if so chop off
384   // the suffix for matching with the actual platform.
385   StringRef ActualPlatform = A->getPlatform()->getName();
386   StringRef RealizedPlatform = ActualPlatform;
387   if (Context.getLangOpts().AppExt) {
388     size_t suffix = RealizedPlatform.rfind("_app_extension");
389     if (suffix != StringRef::npos)
390       RealizedPlatform = RealizedPlatform.slice(0, suffix);
391   }
392 
393   StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
394 
395   // Match the platform name.
396   if (RealizedPlatform != TargetPlatform)
397     return AR_Available;
398 
399   StringRef PrettyPlatformName
400     = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
401 
402   if (PrettyPlatformName.empty())
403     PrettyPlatformName = ActualPlatform;
404 
405   std::string HintMessage;
406   if (!A->getMessage().empty()) {
407     HintMessage = " - ";
408     HintMessage += A->getMessage();
409   }
410 
411   // Make sure that this declaration has not been marked 'unavailable'.
412   if (A->getUnavailable()) {
413     if (Message) {
414       Message->clear();
415       llvm::raw_string_ostream Out(*Message);
416       Out << "not available on " << PrettyPlatformName
417           << HintMessage;
418     }
419 
420     return AR_Unavailable;
421   }
422 
423   // Make sure that this declaration has already been introduced.
424   if (!A->getIntroduced().empty() &&
425       TargetMinVersion < A->getIntroduced()) {
426     if (Message) {
427       Message->clear();
428       llvm::raw_string_ostream Out(*Message);
429       VersionTuple VTI(A->getIntroduced());
430       VTI.UseDotAsSeparator();
431       Out << "introduced in " << PrettyPlatformName << ' '
432           << VTI << HintMessage;
433     }
434 
435     return AR_NotYetIntroduced;
436   }
437 
438   // Make sure that this declaration hasn't been obsoleted.
439   if (!A->getObsoleted().empty() && TargetMinVersion >= A->getObsoleted()) {
440     if (Message) {
441       Message->clear();
442       llvm::raw_string_ostream Out(*Message);
443       VersionTuple VTO(A->getObsoleted());
444       VTO.UseDotAsSeparator();
445       Out << "obsoleted in " << PrettyPlatformName << ' '
446           << VTO << HintMessage;
447     }
448 
449     return AR_Unavailable;
450   }
451 
452   // Make sure that this declaration hasn't been deprecated.
453   if (!A->getDeprecated().empty() && TargetMinVersion >= A->getDeprecated()) {
454     if (Message) {
455       Message->clear();
456       llvm::raw_string_ostream Out(*Message);
457       VersionTuple VTD(A->getDeprecated());
458       VTD.UseDotAsSeparator();
459       Out << "first deprecated in " << PrettyPlatformName << ' '
460           << VTD << HintMessage;
461     }
462 
463     return AR_Deprecated;
464   }
465 
466   return AR_Available;
467 }
468 
getAvailability(std::string * Message) const469 AvailabilityResult Decl::getAvailability(std::string *Message) const {
470   AvailabilityResult Result = AR_Available;
471   std::string ResultMessage;
472 
473   for (const auto *A : attrs()) {
474     if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
475       if (Result >= AR_Deprecated)
476         continue;
477 
478       if (Message)
479         ResultMessage = Deprecated->getMessage();
480 
481       Result = AR_Deprecated;
482       continue;
483     }
484 
485     if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
486       if (Message)
487         *Message = Unavailable->getMessage();
488       return AR_Unavailable;
489     }
490 
491     if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
492       AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
493                                                 Message);
494 
495       if (AR == AR_Unavailable)
496         return AR_Unavailable;
497 
498       if (AR > Result) {
499         Result = AR;
500         if (Message)
501           ResultMessage.swap(*Message);
502       }
503       continue;
504     }
505   }
506 
507   if (Message)
508     Message->swap(ResultMessage);
509   return Result;
510 }
511 
canBeWeakImported(bool & IsDefinition) const512 bool Decl::canBeWeakImported(bool &IsDefinition) const {
513   IsDefinition = false;
514 
515   // Variables, if they aren't definitions.
516   if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
517     if (Var->isThisDeclarationADefinition()) {
518       IsDefinition = true;
519       return false;
520     }
521     return true;
522 
523   // Functions, if they aren't definitions.
524   } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
525     if (FD->hasBody()) {
526       IsDefinition = true;
527       return false;
528     }
529     return true;
530 
531   // Objective-C classes, if this is the non-fragile runtime.
532   } else if (isa<ObjCInterfaceDecl>(this) &&
533              getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
534     return true;
535 
536   // Nothing else.
537   } else {
538     return false;
539   }
540 }
541 
isWeakImported() const542 bool Decl::isWeakImported() const {
543   bool IsDefinition;
544   if (!canBeWeakImported(IsDefinition))
545     return false;
546 
547   for (const auto *A : attrs()) {
548     if (isa<WeakImportAttr>(A))
549       return true;
550 
551     if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
552       if (CheckAvailability(getASTContext(), Availability,
553                             nullptr) == AR_NotYetIntroduced)
554         return true;
555     }
556   }
557 
558   return false;
559 }
560 
getIdentifierNamespaceForKind(Kind DeclKind)561 unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
562   switch (DeclKind) {
563     case Function:
564     case CXXMethod:
565     case CXXConstructor:
566     case CXXDestructor:
567     case CXXConversion:
568     case EnumConstant:
569     case Var:
570     case ImplicitParam:
571     case ParmVar:
572     case NonTypeTemplateParm:
573     case ObjCMethod:
574     case ObjCProperty:
575     case MSProperty:
576       return IDNS_Ordinary;
577     case Label:
578       return IDNS_Label;
579     case IndirectField:
580       return IDNS_Ordinary | IDNS_Member;
581 
582     case ObjCCompatibleAlias:
583     case ObjCInterface:
584       return IDNS_Ordinary | IDNS_Type;
585 
586     case Typedef:
587     case TypeAlias:
588     case TypeAliasTemplate:
589     case UnresolvedUsingTypename:
590     case TemplateTypeParm:
591     case ObjCTypeParam:
592       return IDNS_Ordinary | IDNS_Type;
593 
594     case UsingShadow:
595       return 0; // we'll actually overwrite this later
596 
597     case UnresolvedUsingValue:
598       return IDNS_Ordinary | IDNS_Using;
599 
600     case Using:
601       return IDNS_Using;
602 
603     case ObjCProtocol:
604       return IDNS_ObjCProtocol;
605 
606     case Field:
607     case ObjCAtDefsField:
608     case ObjCIvar:
609       return IDNS_Member;
610 
611     case Record:
612     case CXXRecord:
613     case Enum:
614       return IDNS_Tag | IDNS_Type;
615 
616     case Namespace:
617     case NamespaceAlias:
618       return IDNS_Namespace;
619 
620     case FunctionTemplate:
621     case VarTemplate:
622       return IDNS_Ordinary;
623 
624     case ClassTemplate:
625     case TemplateTemplateParm:
626       return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
627 
628     // Never have names.
629     case Friend:
630     case FriendTemplate:
631     case AccessSpec:
632     case LinkageSpec:
633     case FileScopeAsm:
634     case StaticAssert:
635     case ObjCPropertyImpl:
636     case Block:
637     case Captured:
638     case TranslationUnit:
639     case ExternCContext:
640 
641     case UsingDirective:
642     case BuiltinTemplate:
643     case ClassTemplateSpecialization:
644     case ClassTemplatePartialSpecialization:
645     case ClassScopeFunctionSpecialization:
646     case VarTemplateSpecialization:
647     case VarTemplatePartialSpecialization:
648     case ObjCImplementation:
649     case ObjCCategory:
650     case ObjCCategoryImpl:
651     case Import:
652     case OMPThreadPrivate:
653     case Empty:
654       // Never looked up by name.
655       return 0;
656   }
657 
658   llvm_unreachable("Invalid DeclKind!");
659 }
660 
setAttrsImpl(const AttrVec & attrs,ASTContext & Ctx)661 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
662   assert(!HasAttrs && "Decl already contains attrs.");
663 
664   AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
665   assert(AttrBlank.empty() && "HasAttrs was wrong?");
666 
667   AttrBlank = attrs;
668   HasAttrs = true;
669 }
670 
dropAttrs()671 void Decl::dropAttrs() {
672   if (!HasAttrs) return;
673 
674   HasAttrs = false;
675   getASTContext().eraseDeclAttrs(this);
676 }
677 
getAttrs() const678 const AttrVec &Decl::getAttrs() const {
679   assert(HasAttrs && "No attrs to get!");
680   return getASTContext().getDeclAttrs(this);
681 }
682 
castFromDeclContext(const DeclContext * D)683 Decl *Decl::castFromDeclContext (const DeclContext *D) {
684   Decl::Kind DK = D->getDeclKind();
685   switch(DK) {
686 #define DECL(NAME, BASE)
687 #define DECL_CONTEXT(NAME) \
688     case Decl::NAME:       \
689       return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
690 #define DECL_CONTEXT_BASE(NAME)
691 #include "clang/AST/DeclNodes.inc"
692     default:
693 #define DECL(NAME, BASE)
694 #define DECL_CONTEXT_BASE(NAME)                  \
695       if (DK >= first##NAME && DK <= last##NAME) \
696         return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
697 #include "clang/AST/DeclNodes.inc"
698       llvm_unreachable("a decl that inherits DeclContext isn't handled");
699   }
700 }
701 
castToDeclContext(const Decl * D)702 DeclContext *Decl::castToDeclContext(const Decl *D) {
703   Decl::Kind DK = D->getKind();
704   switch(DK) {
705 #define DECL(NAME, BASE)
706 #define DECL_CONTEXT(NAME) \
707     case Decl::NAME:       \
708       return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
709 #define DECL_CONTEXT_BASE(NAME)
710 #include "clang/AST/DeclNodes.inc"
711     default:
712 #define DECL(NAME, BASE)
713 #define DECL_CONTEXT_BASE(NAME)                                   \
714       if (DK >= first##NAME && DK <= last##NAME)                  \
715         return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
716 #include "clang/AST/DeclNodes.inc"
717       llvm_unreachable("a decl that inherits DeclContext isn't handled");
718   }
719 }
720 
getBodyRBrace() const721 SourceLocation Decl::getBodyRBrace() const {
722   // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
723   // FunctionDecl stores EndRangeLoc for this purpose.
724   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
725     const FunctionDecl *Definition;
726     if (FD->hasBody(Definition))
727       return Definition->getSourceRange().getEnd();
728     return SourceLocation();
729   }
730 
731   if (Stmt *Body = getBody())
732     return Body->getSourceRange().getEnd();
733 
734   return SourceLocation();
735 }
736 
AccessDeclContextSanity() const737 bool Decl::AccessDeclContextSanity() const {
738 #ifndef NDEBUG
739   // Suppress this check if any of the following hold:
740   // 1. this is the translation unit (and thus has no parent)
741   // 2. this is a template parameter (and thus doesn't belong to its context)
742   // 3. this is a non-type template parameter
743   // 4. the context is not a record
744   // 5. it's invalid
745   // 6. it's a C++0x static_assert.
746   if (isa<TranslationUnitDecl>(this) ||
747       isa<TemplateTypeParmDecl>(this) ||
748       isa<NonTypeTemplateParmDecl>(this) ||
749       !isa<CXXRecordDecl>(getDeclContext()) ||
750       isInvalidDecl() ||
751       isa<StaticAssertDecl>(this) ||
752       // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
753       // as DeclContext (?).
754       isa<ParmVarDecl>(this) ||
755       // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
756       // AS_none as access specifier.
757       isa<CXXRecordDecl>(this) ||
758       isa<ClassScopeFunctionSpecializationDecl>(this))
759     return true;
760 
761   assert(Access != AS_none &&
762          "Access specifier is AS_none inside a record decl");
763 #endif
764   return true;
765 }
766 
getKind(const Decl * D)767 static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
getKind(const DeclContext * DC)768 static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
769 
getFunctionType(bool BlocksToo) const770 const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
771   QualType Ty;
772   if (const ValueDecl *D = dyn_cast<ValueDecl>(this))
773     Ty = D->getType();
774   else if (const TypedefNameDecl *D = dyn_cast<TypedefNameDecl>(this))
775     Ty = D->getUnderlyingType();
776   else
777     return nullptr;
778 
779   if (Ty->isFunctionPointerType())
780     Ty = Ty->getAs<PointerType>()->getPointeeType();
781   else if (BlocksToo && Ty->isBlockPointerType())
782     Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
783 
784   return Ty->getAs<FunctionType>();
785 }
786 
787 
788 /// Starting at a given context (a Decl or DeclContext), look for a
789 /// code context that is not a closure (a lambda, block, etc.).
getNonClosureContext(T * D)790 template <class T> static Decl *getNonClosureContext(T *D) {
791   if (getKind(D) == Decl::CXXMethod) {
792     CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
793     if (MD->getOverloadedOperator() == OO_Call &&
794         MD->getParent()->isLambda())
795       return getNonClosureContext(MD->getParent()->getParent());
796     return MD;
797   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
798     return FD;
799   } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
800     return MD;
801   } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
802     return getNonClosureContext(BD->getParent());
803   } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
804     return getNonClosureContext(CD->getParent());
805   } else {
806     return nullptr;
807   }
808 }
809 
getNonClosureContext()810 Decl *Decl::getNonClosureContext() {
811   return ::getNonClosureContext(this);
812 }
813 
getNonClosureAncestor()814 Decl *DeclContext::getNonClosureAncestor() {
815   return ::getNonClosureContext(this);
816 }
817 
818 //===----------------------------------------------------------------------===//
819 // DeclContext Implementation
820 //===----------------------------------------------------------------------===//
821 
classof(const Decl * D)822 bool DeclContext::classof(const Decl *D) {
823   switch (D->getKind()) {
824 #define DECL(NAME, BASE)
825 #define DECL_CONTEXT(NAME) case Decl::NAME:
826 #define DECL_CONTEXT_BASE(NAME)
827 #include "clang/AST/DeclNodes.inc"
828       return true;
829     default:
830 #define DECL(NAME, BASE)
831 #define DECL_CONTEXT_BASE(NAME)                 \
832       if (D->getKind() >= Decl::first##NAME &&  \
833           D->getKind() <= Decl::last##NAME)     \
834         return true;
835 #include "clang/AST/DeclNodes.inc"
836       return false;
837   }
838 }
839 
~DeclContext()840 DeclContext::~DeclContext() { }
841 
842 /// \brief Find the parent context of this context that will be
843 /// used for unqualified name lookup.
844 ///
845 /// Generally, the parent lookup context is the semantic context. However, for
846 /// a friend function the parent lookup context is the lexical context, which
847 /// is the class in which the friend is declared.
getLookupParent()848 DeclContext *DeclContext::getLookupParent() {
849   // FIXME: Find a better way to identify friends
850   if (isa<FunctionDecl>(this))
851     if (getParent()->getRedeclContext()->isFileContext() &&
852         getLexicalParent()->getRedeclContext()->isRecord())
853       return getLexicalParent();
854 
855   return getParent();
856 }
857 
isInlineNamespace() const858 bool DeclContext::isInlineNamespace() const {
859   return isNamespace() &&
860          cast<NamespaceDecl>(this)->isInline();
861 }
862 
isStdNamespace() const863 bool DeclContext::isStdNamespace() const {
864   if (!isNamespace())
865     return false;
866 
867   const NamespaceDecl *ND = cast<NamespaceDecl>(this);
868   if (ND->isInline()) {
869     return ND->getParent()->isStdNamespace();
870   }
871 
872   if (!getParent()->getRedeclContext()->isTranslationUnit())
873     return false;
874 
875   const IdentifierInfo *II = ND->getIdentifier();
876   return II && II->isStr("std");
877 }
878 
isDependentContext() const879 bool DeclContext::isDependentContext() const {
880   if (isFileContext())
881     return false;
882 
883   if (isa<ClassTemplatePartialSpecializationDecl>(this))
884     return true;
885 
886   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
887     if (Record->getDescribedClassTemplate())
888       return true;
889 
890     if (Record->isDependentLambda())
891       return true;
892   }
893 
894   if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
895     if (Function->getDescribedFunctionTemplate())
896       return true;
897 
898     // Friend function declarations are dependent if their *lexical*
899     // context is dependent.
900     if (cast<Decl>(this)->getFriendObjectKind())
901       return getLexicalParent()->isDependentContext();
902   }
903 
904   // FIXME: A variable template is a dependent context, but is not a
905   // DeclContext. A context within it (such as a lambda-expression)
906   // should be considered dependent.
907 
908   return getParent() && getParent()->isDependentContext();
909 }
910 
isTransparentContext() const911 bool DeclContext::isTransparentContext() const {
912   if (DeclKind == Decl::Enum)
913     return !cast<EnumDecl>(this)->isScoped();
914   else if (DeclKind == Decl::LinkageSpec)
915     return true;
916 
917   return false;
918 }
919 
isLinkageSpecContext(const DeclContext * DC,LinkageSpecDecl::LanguageIDs ID)920 static bool isLinkageSpecContext(const DeclContext *DC,
921                                  LinkageSpecDecl::LanguageIDs ID) {
922   while (DC->getDeclKind() != Decl::TranslationUnit) {
923     if (DC->getDeclKind() == Decl::LinkageSpec)
924       return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
925     DC = DC->getLexicalParent();
926   }
927   return false;
928 }
929 
isExternCContext() const930 bool DeclContext::isExternCContext() const {
931   return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_c);
932 }
933 
isExternCXXContext() const934 bool DeclContext::isExternCXXContext() const {
935   return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_cxx);
936 }
937 
Encloses(const DeclContext * DC) const938 bool DeclContext::Encloses(const DeclContext *DC) const {
939   if (getPrimaryContext() != this)
940     return getPrimaryContext()->Encloses(DC);
941 
942   for (; DC; DC = DC->getParent())
943     if (DC->getPrimaryContext() == this)
944       return true;
945   return false;
946 }
947 
getPrimaryContext()948 DeclContext *DeclContext::getPrimaryContext() {
949   switch (DeclKind) {
950   case Decl::TranslationUnit:
951   case Decl::ExternCContext:
952   case Decl::LinkageSpec:
953   case Decl::Block:
954   case Decl::Captured:
955     // There is only one DeclContext for these entities.
956     return this;
957 
958   case Decl::Namespace:
959     // The original namespace is our primary context.
960     return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
961 
962   case Decl::ObjCMethod:
963     return this;
964 
965   case Decl::ObjCInterface:
966     if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
967       return Def;
968 
969     return this;
970 
971   case Decl::ObjCProtocol:
972     if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
973       return Def;
974 
975     return this;
976 
977   case Decl::ObjCCategory:
978     return this;
979 
980   case Decl::ObjCImplementation:
981   case Decl::ObjCCategoryImpl:
982     return this;
983 
984   default:
985     if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
986       // If this is a tag type that has a definition or is currently
987       // being defined, that definition is our primary context.
988       TagDecl *Tag = cast<TagDecl>(this);
989 
990       if (TagDecl *Def = Tag->getDefinition())
991         return Def;
992 
993       if (const TagType *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
994         // Note, TagType::getDecl returns the (partial) definition one exists.
995         TagDecl *PossiblePartialDef = TagTy->getDecl();
996         if (PossiblePartialDef->isBeingDefined())
997           return PossiblePartialDef;
998       } else {
999         assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
1000       }
1001 
1002       return Tag;
1003     }
1004 
1005     assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
1006           "Unknown DeclContext kind");
1007     return this;
1008   }
1009 }
1010 
1011 void
collectAllContexts(SmallVectorImpl<DeclContext * > & Contexts)1012 DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
1013   Contexts.clear();
1014 
1015   if (DeclKind != Decl::Namespace) {
1016     Contexts.push_back(this);
1017     return;
1018   }
1019 
1020   NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
1021   for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
1022        N = N->getPreviousDecl())
1023     Contexts.push_back(N);
1024 
1025   std::reverse(Contexts.begin(), Contexts.end());
1026 }
1027 
1028 std::pair<Decl *, Decl *>
BuildDeclChain(ArrayRef<Decl * > Decls,bool FieldsAlreadyLoaded)1029 DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
1030                             bool FieldsAlreadyLoaded) {
1031   // Build up a chain of declarations via the Decl::NextInContextAndBits field.
1032   Decl *FirstNewDecl = nullptr;
1033   Decl *PrevDecl = nullptr;
1034   for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1035     if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
1036       continue;
1037 
1038     Decl *D = Decls[I];
1039     if (PrevDecl)
1040       PrevDecl->NextInContextAndBits.setPointer(D);
1041     else
1042       FirstNewDecl = D;
1043 
1044     PrevDecl = D;
1045   }
1046 
1047   return std::make_pair(FirstNewDecl, PrevDecl);
1048 }
1049 
1050 /// \brief We have just acquired external visible storage, and we already have
1051 /// built a lookup map. For every name in the map, pull in the new names from
1052 /// the external storage.
reconcileExternalVisibleStorage() const1053 void DeclContext::reconcileExternalVisibleStorage() const {
1054   assert(NeedToReconcileExternalVisibleStorage && LookupPtr);
1055   NeedToReconcileExternalVisibleStorage = false;
1056 
1057   for (auto &Lookup : *LookupPtr)
1058     Lookup.second.setHasExternalDecls();
1059 }
1060 
1061 /// \brief Load the declarations within this lexical storage from an
1062 /// external source.
1063 /// \return \c true if any declarations were added.
1064 bool
LoadLexicalDeclsFromExternalStorage() const1065 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1066   ExternalASTSource *Source = getParentASTContext().getExternalSource();
1067   assert(hasExternalLexicalStorage() && Source && "No external storage?");
1068 
1069   // Notify that we have a DeclContext that is initializing.
1070   ExternalASTSource::Deserializing ADeclContext(Source);
1071 
1072   // Load the external declarations, if any.
1073   SmallVector<Decl*, 64> Decls;
1074   ExternalLexicalStorage = false;
1075   Source->FindExternalLexicalDecls(this, Decls);
1076 
1077   if (Decls.empty())
1078     return false;
1079 
1080   // We may have already loaded just the fields of this record, in which case
1081   // we need to ignore them.
1082   bool FieldsAlreadyLoaded = false;
1083   if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
1084     FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
1085 
1086   // Splice the newly-read declarations into the beginning of the list
1087   // of declarations.
1088   Decl *ExternalFirst, *ExternalLast;
1089   std::tie(ExternalFirst, ExternalLast) =
1090       BuildDeclChain(Decls, FieldsAlreadyLoaded);
1091   ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1092   FirstDecl = ExternalFirst;
1093   if (!LastDecl)
1094     LastDecl = ExternalLast;
1095   return true;
1096 }
1097 
1098 DeclContext::lookup_result
SetNoExternalVisibleDeclsForName(const DeclContext * DC,DeclarationName Name)1099 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1100                                                     DeclarationName Name) {
1101   ASTContext &Context = DC->getParentASTContext();
1102   StoredDeclsMap *Map;
1103   if (!(Map = DC->LookupPtr))
1104     Map = DC->CreateStoredDeclsMap(Context);
1105   if (DC->NeedToReconcileExternalVisibleStorage)
1106     DC->reconcileExternalVisibleStorage();
1107 
1108   (*Map)[Name].removeExternalDecls();
1109 
1110   return DeclContext::lookup_result();
1111 }
1112 
1113 DeclContext::lookup_result
SetExternalVisibleDeclsForName(const DeclContext * DC,DeclarationName Name,ArrayRef<NamedDecl * > Decls)1114 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1115                                                   DeclarationName Name,
1116                                                   ArrayRef<NamedDecl*> Decls) {
1117   ASTContext &Context = DC->getParentASTContext();
1118   StoredDeclsMap *Map;
1119   if (!(Map = DC->LookupPtr))
1120     Map = DC->CreateStoredDeclsMap(Context);
1121   if (DC->NeedToReconcileExternalVisibleStorage)
1122     DC->reconcileExternalVisibleStorage();
1123 
1124   StoredDeclsList &List = (*Map)[Name];
1125 
1126   // Clear out any old external visible declarations, to avoid quadratic
1127   // performance in the redeclaration checks below.
1128   List.removeExternalDecls();
1129 
1130   if (!List.isNull()) {
1131     // We have both existing declarations and new declarations for this name.
1132     // Some of the declarations may simply replace existing ones. Handle those
1133     // first.
1134     llvm::SmallVector<unsigned, 8> Skip;
1135     for (unsigned I = 0, N = Decls.size(); I != N; ++I)
1136       if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
1137         Skip.push_back(I);
1138     Skip.push_back(Decls.size());
1139 
1140     // Add in any new declarations.
1141     unsigned SkipPos = 0;
1142     for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1143       if (I == Skip[SkipPos])
1144         ++SkipPos;
1145       else
1146         List.AddSubsequentDecl(Decls[I]);
1147     }
1148   } else {
1149     // Convert the array to a StoredDeclsList.
1150     for (ArrayRef<NamedDecl*>::iterator
1151            I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1152       if (List.isNull())
1153         List.setOnlyValue(*I);
1154       else
1155         List.AddSubsequentDecl(*I);
1156     }
1157   }
1158 
1159   return List.getLookupResult();
1160 }
1161 
decls_begin() const1162 DeclContext::decl_iterator DeclContext::decls_begin() const {
1163   if (hasExternalLexicalStorage())
1164     LoadLexicalDeclsFromExternalStorage();
1165   return decl_iterator(FirstDecl);
1166 }
1167 
decls_empty() const1168 bool DeclContext::decls_empty() const {
1169   if (hasExternalLexicalStorage())
1170     LoadLexicalDeclsFromExternalStorage();
1171 
1172   return !FirstDecl;
1173 }
1174 
containsDecl(Decl * D) const1175 bool DeclContext::containsDecl(Decl *D) const {
1176   return (D->getLexicalDeclContext() == this &&
1177           (D->NextInContextAndBits.getPointer() || D == LastDecl));
1178 }
1179 
removeDecl(Decl * D)1180 void DeclContext::removeDecl(Decl *D) {
1181   assert(D->getLexicalDeclContext() == this &&
1182          "decl being removed from non-lexical context");
1183   assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1184          "decl is not in decls list");
1185 
1186   // Remove D from the decl chain.  This is O(n) but hopefully rare.
1187   if (D == FirstDecl) {
1188     if (D == LastDecl)
1189       FirstDecl = LastDecl = nullptr;
1190     else
1191       FirstDecl = D->NextInContextAndBits.getPointer();
1192   } else {
1193     for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1194       assert(I && "decl not found in linked list");
1195       if (I->NextInContextAndBits.getPointer() == D) {
1196         I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1197         if (D == LastDecl) LastDecl = I;
1198         break;
1199       }
1200     }
1201   }
1202 
1203   // Mark that D is no longer in the decl chain.
1204   D->NextInContextAndBits.setPointer(nullptr);
1205 
1206   // Remove D from the lookup table if necessary.
1207   if (isa<NamedDecl>(D)) {
1208     NamedDecl *ND = cast<NamedDecl>(D);
1209 
1210     // Remove only decls that have a name
1211     if (!ND->getDeclName()) return;
1212 
1213     auto *DC = this;
1214     do {
1215       StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1216       if (Map) {
1217         StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1218         assert(Pos != Map->end() && "no lookup entry for decl");
1219         if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1220           Pos->second.remove(ND);
1221       }
1222     } while (DC->isTransparentContext() && (DC = DC->getParent()));
1223   }
1224 }
1225 
addHiddenDecl(Decl * D)1226 void DeclContext::addHiddenDecl(Decl *D) {
1227   assert(D->getLexicalDeclContext() == this &&
1228          "Decl inserted into wrong lexical context");
1229   assert(!D->getNextDeclInContext() && D != LastDecl &&
1230          "Decl already inserted into a DeclContext");
1231 
1232   if (FirstDecl) {
1233     LastDecl->NextInContextAndBits.setPointer(D);
1234     LastDecl = D;
1235   } else {
1236     FirstDecl = LastDecl = D;
1237   }
1238 
1239   // Notify a C++ record declaration that we've added a member, so it can
1240   // update its class-specific state.
1241   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1242     Record->addedMember(D);
1243 
1244   // If this is a newly-created (not de-serialized) import declaration, wire
1245   // it in to the list of local import declarations.
1246   if (!D->isFromASTFile()) {
1247     if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1248       D->getASTContext().addedLocalImportDecl(Import);
1249   }
1250 }
1251 
addDecl(Decl * D)1252 void DeclContext::addDecl(Decl *D) {
1253   addHiddenDecl(D);
1254 
1255   if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1256     ND->getDeclContext()->getPrimaryContext()->
1257         makeDeclVisibleInContextWithFlags(ND, false, true);
1258 }
1259 
addDeclInternal(Decl * D)1260 void DeclContext::addDeclInternal(Decl *D) {
1261   addHiddenDecl(D);
1262 
1263   if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1264     ND->getDeclContext()->getPrimaryContext()->
1265         makeDeclVisibleInContextWithFlags(ND, true, true);
1266 }
1267 
1268 /// shouldBeHidden - Determine whether a declaration which was declared
1269 /// within its semantic context should be invisible to qualified name lookup.
shouldBeHidden(NamedDecl * D)1270 static bool shouldBeHidden(NamedDecl *D) {
1271   // Skip unnamed declarations.
1272   if (!D->getDeclName())
1273     return true;
1274 
1275   // Skip entities that can't be found by name lookup into a particular
1276   // context.
1277   if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1278       D->isTemplateParameter())
1279     return true;
1280 
1281   // Skip template specializations.
1282   // FIXME: This feels like a hack. Should DeclarationName support
1283   // template-ids, or is there a better way to keep specializations
1284   // from being visible?
1285   if (isa<ClassTemplateSpecializationDecl>(D))
1286     return true;
1287   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1288     if (FD->isFunctionTemplateSpecialization())
1289       return true;
1290 
1291   return false;
1292 }
1293 
1294 /// buildLookup - Build the lookup data structure with all of the
1295 /// declarations in this DeclContext (and any other contexts linked
1296 /// to it or transparent contexts nested within it) and return it.
1297 ///
1298 /// Note that the produced map may miss out declarations from an
1299 /// external source. If it does, those entries will be marked with
1300 /// the 'hasExternalDecls' flag.
buildLookup()1301 StoredDeclsMap *DeclContext::buildLookup() {
1302   assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1303 
1304   if (!HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups)
1305     return LookupPtr;
1306 
1307   SmallVector<DeclContext *, 2> Contexts;
1308   collectAllContexts(Contexts);
1309 
1310   if (HasLazyExternalLexicalLookups) {
1311     HasLazyExternalLexicalLookups = false;
1312     for (auto *DC : Contexts) {
1313       if (DC->hasExternalLexicalStorage())
1314         HasLazyLocalLexicalLookups |=
1315             DC->LoadLexicalDeclsFromExternalStorage();
1316     }
1317 
1318     if (!HasLazyLocalLexicalLookups)
1319       return LookupPtr;
1320   }
1321 
1322   for (auto *DC : Contexts)
1323     buildLookupImpl(DC, hasExternalVisibleStorage());
1324 
1325   // We no longer have any lazy decls.
1326   HasLazyLocalLexicalLookups = false;
1327   return LookupPtr;
1328 }
1329 
1330 /// buildLookupImpl - Build part of the lookup data structure for the
1331 /// declarations contained within DCtx, which will either be this
1332 /// DeclContext, a DeclContext linked to it, or a transparent context
1333 /// nested within it.
buildLookupImpl(DeclContext * DCtx,bool Internal)1334 void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
1335   for (Decl *D : DCtx->noload_decls()) {
1336     // Insert this declaration into the lookup structure, but only if
1337     // it's semantically within its decl context. Any other decls which
1338     // should be found in this context are added eagerly.
1339     //
1340     // If it's from an AST file, don't add it now. It'll get handled by
1341     // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1342     // in C++, we do not track external visible decls for the TU, so in
1343     // that case we need to collect them all here.
1344     if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1345       if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1346           (!ND->isFromASTFile() ||
1347            (isTranslationUnit() &&
1348             !getParentASTContext().getLangOpts().CPlusPlus)))
1349         makeDeclVisibleInContextImpl(ND, Internal);
1350 
1351     // If this declaration is itself a transparent declaration context
1352     // or inline namespace, add the members of this declaration of that
1353     // context (recursively).
1354     if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1355       if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1356         buildLookupImpl(InnerCtx, Internal);
1357   }
1358 }
1359 
1360 NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1361 
1362 DeclContext::lookup_result
lookup(DeclarationName Name) const1363 DeclContext::lookup(DeclarationName Name) const {
1364   assert(DeclKind != Decl::LinkageSpec &&
1365          "Should not perform lookups into linkage specs!");
1366 
1367   const DeclContext *PrimaryContext = getPrimaryContext();
1368   if (PrimaryContext != this)
1369     return PrimaryContext->lookup(Name);
1370 
1371   // If we have an external source, ensure that any later redeclarations of this
1372   // context have been loaded, since they may add names to the result of this
1373   // lookup (or add external visible storage).
1374   ExternalASTSource *Source = getParentASTContext().getExternalSource();
1375   if (Source)
1376     (void)cast<Decl>(this)->getMostRecentDecl();
1377 
1378   if (hasExternalVisibleStorage()) {
1379     assert(Source && "external visible storage but no external source?");
1380 
1381     if (NeedToReconcileExternalVisibleStorage)
1382       reconcileExternalVisibleStorage();
1383 
1384     StoredDeclsMap *Map = LookupPtr;
1385 
1386     if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1387       // FIXME: Make buildLookup const?
1388       Map = const_cast<DeclContext*>(this)->buildLookup();
1389 
1390     if (!Map)
1391       Map = CreateStoredDeclsMap(getParentASTContext());
1392 
1393     // If we have a lookup result with no external decls, we are done.
1394     std::pair<StoredDeclsMap::iterator, bool> R =
1395         Map->insert(std::make_pair(Name, StoredDeclsList()));
1396     if (!R.second && !R.first->second.hasExternalDecls())
1397       return R.first->second.getLookupResult();
1398 
1399     if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
1400       if (StoredDeclsMap *Map = LookupPtr) {
1401         StoredDeclsMap::iterator I = Map->find(Name);
1402         if (I != Map->end())
1403           return I->second.getLookupResult();
1404       }
1405     }
1406 
1407     return lookup_result();
1408   }
1409 
1410   StoredDeclsMap *Map = LookupPtr;
1411   if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1412     Map = const_cast<DeclContext*>(this)->buildLookup();
1413 
1414   if (!Map)
1415     return lookup_result();
1416 
1417   StoredDeclsMap::iterator I = Map->find(Name);
1418   if (I == Map->end())
1419     return lookup_result();
1420 
1421   return I->second.getLookupResult();
1422 }
1423 
1424 DeclContext::lookup_result
noload_lookup(DeclarationName Name)1425 DeclContext::noload_lookup(DeclarationName Name) {
1426   assert(DeclKind != Decl::LinkageSpec &&
1427          "Should not perform lookups into linkage specs!");
1428 
1429   DeclContext *PrimaryContext = getPrimaryContext();
1430   if (PrimaryContext != this)
1431     return PrimaryContext->noload_lookup(Name);
1432 
1433   // If we have any lazy lexical declarations not in our lookup map, add them
1434   // now. Don't import any external declarations, not even if we know we have
1435   // some missing from the external visible lookups.
1436   if (HasLazyLocalLexicalLookups) {
1437     SmallVector<DeclContext *, 2> Contexts;
1438     collectAllContexts(Contexts);
1439     for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1440       buildLookupImpl(Contexts[I], hasExternalVisibleStorage());
1441     HasLazyLocalLexicalLookups = false;
1442   }
1443 
1444   StoredDeclsMap *Map = LookupPtr;
1445   if (!Map)
1446     return lookup_result();
1447 
1448   StoredDeclsMap::iterator I = Map->find(Name);
1449   return I != Map->end() ? I->second.getLookupResult()
1450                          : lookup_result();
1451 }
1452 
localUncachedLookup(DeclarationName Name,SmallVectorImpl<NamedDecl * > & Results)1453 void DeclContext::localUncachedLookup(DeclarationName Name,
1454                                       SmallVectorImpl<NamedDecl *> &Results) {
1455   Results.clear();
1456 
1457   // If there's no external storage, just perform a normal lookup and copy
1458   // the results.
1459   if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1460     lookup_result LookupResults = lookup(Name);
1461     Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1462     return;
1463   }
1464 
1465   // If we have a lookup table, check there first. Maybe we'll get lucky.
1466   // FIXME: Should we be checking these flags on the primary context?
1467   if (Name && !HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups) {
1468     if (StoredDeclsMap *Map = LookupPtr) {
1469       StoredDeclsMap::iterator Pos = Map->find(Name);
1470       if (Pos != Map->end()) {
1471         Results.insert(Results.end(),
1472                        Pos->second.getLookupResult().begin(),
1473                        Pos->second.getLookupResult().end());
1474         return;
1475       }
1476     }
1477   }
1478 
1479   // Slow case: grovel through the declarations in our chain looking for
1480   // matches.
1481   // FIXME: If we have lazy external declarations, this will not find them!
1482   // FIXME: Should we CollectAllContexts and walk them all here?
1483   for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1484     if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1485       if (ND->getDeclName() == Name)
1486         Results.push_back(ND);
1487   }
1488 }
1489 
getRedeclContext()1490 DeclContext *DeclContext::getRedeclContext() {
1491   DeclContext *Ctx = this;
1492   // Skip through transparent contexts.
1493   while (Ctx->isTransparentContext())
1494     Ctx = Ctx->getParent();
1495   return Ctx;
1496 }
1497 
getEnclosingNamespaceContext()1498 DeclContext *DeclContext::getEnclosingNamespaceContext() {
1499   DeclContext *Ctx = this;
1500   // Skip through non-namespace, non-translation-unit contexts.
1501   while (!Ctx->isFileContext())
1502     Ctx = Ctx->getParent();
1503   return Ctx->getPrimaryContext();
1504 }
1505 
getOuterLexicalRecordContext()1506 RecordDecl *DeclContext::getOuterLexicalRecordContext() {
1507   // Loop until we find a non-record context.
1508   RecordDecl *OutermostRD = nullptr;
1509   DeclContext *DC = this;
1510   while (DC->isRecord()) {
1511     OutermostRD = cast<RecordDecl>(DC);
1512     DC = DC->getLexicalParent();
1513   }
1514   return OutermostRD;
1515 }
1516 
InEnclosingNamespaceSetOf(const DeclContext * O) const1517 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1518   // For non-file contexts, this is equivalent to Equals.
1519   if (!isFileContext())
1520     return O->Equals(this);
1521 
1522   do {
1523     if (O->Equals(this))
1524       return true;
1525 
1526     const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1527     if (!NS || !NS->isInline())
1528       break;
1529     O = NS->getParent();
1530   } while (O);
1531 
1532   return false;
1533 }
1534 
makeDeclVisibleInContext(NamedDecl * D)1535 void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1536   DeclContext *PrimaryDC = this->getPrimaryContext();
1537   DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1538   // If the decl is being added outside of its semantic decl context, we
1539   // need to ensure that we eagerly build the lookup information for it.
1540   PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1541 }
1542 
makeDeclVisibleInContextWithFlags(NamedDecl * D,bool Internal,bool Recoverable)1543 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1544                                                     bool Recoverable) {
1545   assert(this == getPrimaryContext() && "expected a primary DC");
1546 
1547   // Skip declarations within functions.
1548   if (isFunctionOrMethod())
1549     return;
1550 
1551   // Skip declarations which should be invisible to name lookup.
1552   if (shouldBeHidden(D))
1553     return;
1554 
1555   // If we already have a lookup data structure, perform the insertion into
1556   // it. If we might have externally-stored decls with this name, look them
1557   // up and perform the insertion. If this decl was declared outside its
1558   // semantic context, buildLookup won't add it, so add it now.
1559   //
1560   // FIXME: As a performance hack, don't add such decls into the translation
1561   // unit unless we're in C++, since qualified lookup into the TU is never
1562   // performed.
1563   if (LookupPtr || hasExternalVisibleStorage() ||
1564       ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1565        (getParentASTContext().getLangOpts().CPlusPlus ||
1566         !isTranslationUnit()))) {
1567     // If we have lazily omitted any decls, they might have the same name as
1568     // the decl which we are adding, so build a full lookup table before adding
1569     // this decl.
1570     buildLookup();
1571     makeDeclVisibleInContextImpl(D, Internal);
1572   } else {
1573     HasLazyLocalLexicalLookups = true;
1574   }
1575 
1576   // If we are a transparent context or inline namespace, insert into our
1577   // parent context, too. This operation is recursive.
1578   if (isTransparentContext() || isInlineNamespace())
1579     getParent()->getPrimaryContext()->
1580         makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1581 
1582   Decl *DCAsDecl = cast<Decl>(this);
1583   // Notify that a decl was made visible unless we are a Tag being defined.
1584   if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1585     if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1586       L->AddedVisibleDecl(this, D);
1587 }
1588 
makeDeclVisibleInContextImpl(NamedDecl * D,bool Internal)1589 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1590   // Find or create the stored declaration map.
1591   StoredDeclsMap *Map = LookupPtr;
1592   if (!Map) {
1593     ASTContext *C = &getParentASTContext();
1594     Map = CreateStoredDeclsMap(*C);
1595   }
1596 
1597   // If there is an external AST source, load any declarations it knows about
1598   // with this declaration's name.
1599   // If the lookup table contains an entry about this name it means that we
1600   // have already checked the external source.
1601   if (!Internal)
1602     if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1603       if (hasExternalVisibleStorage() &&
1604           Map->find(D->getDeclName()) == Map->end())
1605         Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1606 
1607   // Insert this declaration into the map.
1608   StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1609 
1610   if (Internal) {
1611     // If this is being added as part of loading an external declaration,
1612     // this may not be the only external declaration with this name.
1613     // In this case, we never try to replace an existing declaration; we'll
1614     // handle that when we finalize the list of declarations for this name.
1615     DeclNameEntries.setHasExternalDecls();
1616     DeclNameEntries.AddSubsequentDecl(D);
1617     return;
1618   }
1619 
1620   if (DeclNameEntries.isNull()) {
1621     DeclNameEntries.setOnlyValue(D);
1622     return;
1623   }
1624 
1625   if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
1626     // This declaration has replaced an existing one for which
1627     // declarationReplaces returns true.
1628     return;
1629   }
1630 
1631   // Put this declaration into the appropriate slot.
1632   DeclNameEntries.AddSubsequentDecl(D);
1633 }
1634 
operator *() const1635 UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
1636   return cast<UsingDirectiveDecl>(*I);
1637 }
1638 
1639 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1640 /// this context.
using_directives() const1641 DeclContext::udir_range DeclContext::using_directives() const {
1642   // FIXME: Use something more efficient than normal lookup for using
1643   // directives. In C++, using directives are looked up more than anything else.
1644   lookup_result Result = lookup(UsingDirectiveDecl::getName());
1645   return udir_range(Result.begin(), Result.end());
1646 }
1647 
1648 //===----------------------------------------------------------------------===//
1649 // Creation and Destruction of StoredDeclsMaps.                               //
1650 //===----------------------------------------------------------------------===//
1651 
CreateStoredDeclsMap(ASTContext & C) const1652 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1653   assert(!LookupPtr && "context already has a decls map");
1654   assert(getPrimaryContext() == this &&
1655          "creating decls map on non-primary context");
1656 
1657   StoredDeclsMap *M;
1658   bool Dependent = isDependentContext();
1659   if (Dependent)
1660     M = new DependentStoredDeclsMap();
1661   else
1662     M = new StoredDeclsMap();
1663   M->Previous = C.LastSDM;
1664   C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1665   LookupPtr = M;
1666   return M;
1667 }
1668 
ReleaseDeclContextMaps()1669 void ASTContext::ReleaseDeclContextMaps() {
1670   // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1671   // pointer because the subclass doesn't add anything that needs to
1672   // be deleted.
1673   StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1674 }
1675 
DestroyAll(StoredDeclsMap * Map,bool Dependent)1676 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1677   while (Map) {
1678     // Advance the iteration before we invalidate memory.
1679     llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1680 
1681     if (Dependent)
1682       delete static_cast<DependentStoredDeclsMap*>(Map);
1683     else
1684       delete Map;
1685 
1686     Map = Next.getPointer();
1687     Dependent = Next.getInt();
1688   }
1689 }
1690 
Create(ASTContext & C,DeclContext * Parent,const PartialDiagnostic & PDiag)1691 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1692                                                  DeclContext *Parent,
1693                                            const PartialDiagnostic &PDiag) {
1694   assert(Parent->isDependentContext()
1695          && "cannot iterate dependent diagnostics of non-dependent context");
1696   Parent = Parent->getPrimaryContext();
1697   if (!Parent->LookupPtr)
1698     Parent->CreateStoredDeclsMap(C);
1699 
1700   DependentStoredDeclsMap *Map =
1701       static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
1702 
1703   // Allocate the copy of the PartialDiagnostic via the ASTContext's
1704   // BumpPtrAllocator, rather than the ASTContext itself.
1705   PartialDiagnostic::Storage *DiagStorage = nullptr;
1706   if (PDiag.hasStorage())
1707     DiagStorage = new (C) PartialDiagnostic::Storage;
1708 
1709   DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1710 
1711   // TODO: Maybe we shouldn't reverse the order during insertion.
1712   DD->NextDiagnostic = Map->FirstDiagnostic;
1713   Map->FirstDiagnostic = DD;
1714 
1715   return DD;
1716 }
1717