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/DeclTemplate.h"
24 #include "clang/AST/DependentDiagnostic.h"
25 #include "clang/AST/ExternalASTSource.h"
26 #include "clang/AST/Stmt.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/AST/Type.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "llvm/ADT/DenseMap.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 
43 void *Decl::AllocateDeserializedDecl(const ASTContext &Context,
44                                      unsigned ID,
45                                      unsigned Size) {
46   // Allocate an extra 8 bytes worth of storage, which ensures that the
47   // resulting pointer will still be 8-byte aligned.
48   void *Start = Context.Allocate(Size + 8);
49   void *Result = (char*)Start + 8;
50 
51   unsigned *PrefixPtr = (unsigned *)Result - 2;
52 
53   // Zero out the first 4 bytes; this is used to store the owning module ID.
54   PrefixPtr[0] = 0;
55 
56   // Store the global declaration ID in the second 4 bytes.
57   PrefixPtr[1] = ID;
58 
59   return Result;
60 }
61 
62 const char *Decl::getDeclKindName() const {
63   switch (DeclKind) {
64   default: llvm_unreachable("Declaration not in DeclNodes.inc!");
65 #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
66 #define ABSTRACT_DECL(DECL)
67 #include "clang/AST/DeclNodes.inc"
68   }
69 }
70 
71 void Decl::setInvalidDecl(bool Invalid) {
72   InvalidDecl = Invalid;
73   if (Invalid && !isa<ParmVarDecl>(this)) {
74     // Defensive maneuver for ill-formed code: we're likely not to make it to
75     // a point where we set the access specifier, so default it to "public"
76     // to avoid triggering asserts elsewhere in the front end.
77     setAccess(AS_public);
78   }
79 }
80 
81 const char *DeclContext::getDeclKindName() const {
82   switch (DeclKind) {
83   default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
84 #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
85 #define ABSTRACT_DECL(DECL)
86 #include "clang/AST/DeclNodes.inc"
87   }
88 }
89 
90 bool Decl::StatisticsEnabled = false;
91 void Decl::EnableStatistics() {
92   StatisticsEnabled = true;
93 }
94 
95 void Decl::PrintStats() {
96   llvm::errs() << "\n*** Decl Stats:\n";
97 
98   int totalDecls = 0;
99 #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
100 #define ABSTRACT_DECL(DECL)
101 #include "clang/AST/DeclNodes.inc"
102   llvm::errs() << "  " << totalDecls << " decls total.\n";
103 
104   int totalBytes = 0;
105 #define DECL(DERIVED, BASE)                                             \
106   if (n##DERIVED##s > 0) {                                              \
107     totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl));         \
108     llvm::errs() << "    " << n##DERIVED##s << " " #DERIVED " decls, "  \
109                  << sizeof(DERIVED##Decl) << " each ("                  \
110                  << n##DERIVED##s * sizeof(DERIVED##Decl)               \
111                  << " bytes)\n";                                        \
112   }
113 #define ABSTRACT_DECL(DECL)
114 #include "clang/AST/DeclNodes.inc"
115 
116   llvm::errs() << "Total bytes = " << totalBytes << "\n";
117 }
118 
119 void Decl::add(Kind k) {
120   switch (k) {
121 #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
122 #define ABSTRACT_DECL(DECL)
123 #include "clang/AST/DeclNodes.inc"
124   }
125 }
126 
127 bool Decl::isTemplateParameterPack() const {
128   if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
129     return TTP->isParameterPack();
130   if (const NonTypeTemplateParmDecl *NTTP
131                                 = dyn_cast<NonTypeTemplateParmDecl>(this))
132     return NTTP->isParameterPack();
133   if (const TemplateTemplateParmDecl *TTP
134                                     = dyn_cast<TemplateTemplateParmDecl>(this))
135     return TTP->isParameterPack();
136   return false;
137 }
138 
139 bool Decl::isParameterPack() const {
140   if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
141     return Parm->isParameterPack();
142 
143   return isTemplateParameterPack();
144 }
145 
146 bool Decl::isFunctionOrFunctionTemplate() const {
147   if (const UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(this))
148     return UD->getTargetDecl()->isFunctionOrFunctionTemplate();
149 
150   return isa<FunctionDecl>(this) || isa<FunctionTemplateDecl>(this);
151 }
152 
153 bool Decl::isTemplateDecl() const {
154   return isa<TemplateDecl>(this);
155 }
156 
157 const DeclContext *Decl::getParentFunctionOrMethod() const {
158   for (const DeclContext *DC = getDeclContext();
159        DC && !DC->isTranslationUnit() && !DC->isNamespace();
160        DC = DC->getParent())
161     if (DC->isFunctionOrMethod())
162       return DC;
163 
164   return 0;
165 }
166 
167 
168 //===----------------------------------------------------------------------===//
169 // PrettyStackTraceDecl Implementation
170 //===----------------------------------------------------------------------===//
171 
172 void PrettyStackTraceDecl::print(raw_ostream &OS) const {
173   SourceLocation TheLoc = Loc;
174   if (TheLoc.isInvalid() && TheDecl)
175     TheLoc = TheDecl->getLocation();
176 
177   if (TheLoc.isValid()) {
178     TheLoc.print(OS, SM);
179     OS << ": ";
180   }
181 
182   OS << Message;
183 
184   if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl))
185     OS << " '" << DN->getQualifiedNameAsString() << '\'';
186   OS << '\n';
187 }
188 
189 //===----------------------------------------------------------------------===//
190 // Decl Implementation
191 //===----------------------------------------------------------------------===//
192 
193 // Out-of-line virtual method providing a home for Decl.
194 Decl::~Decl() { }
195 
196 void Decl::setDeclContext(DeclContext *DC) {
197   DeclCtx = DC;
198 }
199 
200 void Decl::setLexicalDeclContext(DeclContext *DC) {
201   if (DC == getLexicalDeclContext())
202     return;
203 
204   if (isInSemaDC()) {
205     setDeclContextsImpl(getDeclContext(), DC, getASTContext());
206   } else {
207     getMultipleDC()->LexicalDC = DC;
208   }
209 }
210 
211 void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
212                                ASTContext &Ctx) {
213   if (SemaDC == LexicalDC) {
214     DeclCtx = SemaDC;
215   } else {
216     Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
217     MDC->SemanticDC = SemaDC;
218     MDC->LexicalDC = LexicalDC;
219     DeclCtx = MDC;
220   }
221 }
222 
223 bool Decl::isInAnonymousNamespace() const {
224   const DeclContext *DC = getDeclContext();
225   do {
226     if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
227       if (ND->isAnonymousNamespace())
228         return true;
229   } while ((DC = DC->getParent()));
230 
231   return false;
232 }
233 
234 TranslationUnitDecl *Decl::getTranslationUnitDecl() {
235   if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
236     return TUD;
237 
238   DeclContext *DC = getDeclContext();
239   assert(DC && "This decl is not contained in a translation unit!");
240 
241   while (!DC->isTranslationUnit()) {
242     DC = DC->getParent();
243     assert(DC && "This decl is not contained in a translation unit!");
244   }
245 
246   return cast<TranslationUnitDecl>(DC);
247 }
248 
249 ASTContext &Decl::getASTContext() const {
250   return getTranslationUnitDecl()->getASTContext();
251 }
252 
253 ASTMutationListener *Decl::getASTMutationListener() const {
254   return getASTContext().getASTMutationListener();
255 }
256 
257 unsigned Decl::getMaxAlignment() const {
258   if (!hasAttrs())
259     return 0;
260 
261   unsigned Align = 0;
262   const AttrVec &V = getAttrs();
263   ASTContext &Ctx = getASTContext();
264   specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
265   for (; I != E; ++I)
266     Align = std::max(Align, I->getAlignment(Ctx));
267   return Align;
268 }
269 
270 bool Decl::isUsed(bool CheckUsedAttr) const {
271   if (Used)
272     return true;
273 
274   // Check for used attribute.
275   if (CheckUsedAttr && hasAttr<UsedAttr>())
276     return true;
277 
278   return false;
279 }
280 
281 bool Decl::isReferenced() const {
282   if (Referenced)
283     return true;
284 
285   // Check redeclarations.
286   for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
287     if (I->Referenced)
288       return true;
289 
290   return false;
291 }
292 
293 /// \brief Determine the availability of the given declaration based on
294 /// the target platform.
295 ///
296 /// When it returns an availability result other than \c AR_Available,
297 /// if the \p Message parameter is non-NULL, it will be set to a
298 /// string describing why the entity is unavailable.
299 ///
300 /// FIXME: Make these strings localizable, since they end up in
301 /// diagnostics.
302 static AvailabilityResult CheckAvailability(ASTContext &Context,
303                                             const AvailabilityAttr *A,
304                                             std::string *Message) {
305   StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
306   StringRef PrettyPlatformName
307     = AvailabilityAttr::getPrettyPlatformName(TargetPlatform);
308   if (PrettyPlatformName.empty())
309     PrettyPlatformName = TargetPlatform;
310 
311   VersionTuple TargetMinVersion = Context.getTargetInfo().getPlatformMinVersion();
312   if (TargetMinVersion.empty())
313     return AR_Available;
314 
315   // Match the platform name.
316   if (A->getPlatform()->getName() != TargetPlatform)
317     return AR_Available;
318 
319   std::string HintMessage;
320   if (!A->getMessage().empty()) {
321     HintMessage = " - ";
322     HintMessage += A->getMessage();
323   }
324 
325   // Make sure that this declaration has not been marked 'unavailable'.
326   if (A->getUnavailable()) {
327     if (Message) {
328       Message->clear();
329       llvm::raw_string_ostream Out(*Message);
330       Out << "not available on " << PrettyPlatformName
331           << HintMessage;
332     }
333 
334     return AR_Unavailable;
335   }
336 
337   // Make sure that this declaration has already been introduced.
338   if (!A->getIntroduced().empty() &&
339       TargetMinVersion < A->getIntroduced()) {
340     if (Message) {
341       Message->clear();
342       llvm::raw_string_ostream Out(*Message);
343       Out << "introduced in " << PrettyPlatformName << ' '
344           << A->getIntroduced() << HintMessage;
345     }
346 
347     return AR_NotYetIntroduced;
348   }
349 
350   // Make sure that this declaration hasn't been obsoleted.
351   if (!A->getObsoleted().empty() && TargetMinVersion >= A->getObsoleted()) {
352     if (Message) {
353       Message->clear();
354       llvm::raw_string_ostream Out(*Message);
355       Out << "obsoleted in " << PrettyPlatformName << ' '
356           << A->getObsoleted() << HintMessage;
357     }
358 
359     return AR_Unavailable;
360   }
361 
362   // Make sure that this declaration hasn't been deprecated.
363   if (!A->getDeprecated().empty() && TargetMinVersion >= A->getDeprecated()) {
364     if (Message) {
365       Message->clear();
366       llvm::raw_string_ostream Out(*Message);
367       Out << "first deprecated in " << PrettyPlatformName << ' '
368           << A->getDeprecated() << HintMessage;
369     }
370 
371     return AR_Deprecated;
372   }
373 
374   return AR_Available;
375 }
376 
377 AvailabilityResult Decl::getAvailability(std::string *Message) const {
378   AvailabilityResult Result = AR_Available;
379   std::string ResultMessage;
380 
381   for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) {
382     if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(*A)) {
383       if (Result >= AR_Deprecated)
384         continue;
385 
386       if (Message)
387         ResultMessage = Deprecated->getMessage();
388 
389       Result = AR_Deprecated;
390       continue;
391     }
392 
393     if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(*A)) {
394       if (Message)
395         *Message = Unavailable->getMessage();
396       return AR_Unavailable;
397     }
398 
399     if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) {
400       AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
401                                                 Message);
402 
403       if (AR == AR_Unavailable)
404         return AR_Unavailable;
405 
406       if (AR > Result) {
407         Result = AR;
408         if (Message)
409           ResultMessage.swap(*Message);
410       }
411       continue;
412     }
413   }
414 
415   if (Message)
416     Message->swap(ResultMessage);
417   return Result;
418 }
419 
420 bool Decl::canBeWeakImported(bool &IsDefinition) const {
421   IsDefinition = false;
422 
423   // Variables, if they aren't definitions.
424   if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
425     if (!Var->hasExternalStorage() || Var->getInit()) {
426       IsDefinition = true;
427       return false;
428     }
429     return true;
430 
431   // Functions, if they aren't definitions.
432   } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
433     if (FD->hasBody()) {
434       IsDefinition = true;
435       return false;
436     }
437     return true;
438 
439   // Objective-C classes, if this is the non-fragile runtime.
440   } else if (isa<ObjCInterfaceDecl>(this) &&
441              getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
442     return true;
443 
444   // Nothing else.
445   } else {
446     return false;
447   }
448 }
449 
450 bool Decl::isWeakImported() const {
451   bool IsDefinition;
452   if (!canBeWeakImported(IsDefinition))
453     return false;
454 
455   for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) {
456     if (isa<WeakImportAttr>(*A))
457       return true;
458 
459     if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) {
460       if (CheckAvailability(getASTContext(), Availability, 0)
461                                                          == AR_NotYetIntroduced)
462         return true;
463     }
464   }
465 
466   return false;
467 }
468 
469 unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
470   switch (DeclKind) {
471     case Function:
472     case CXXMethod:
473     case CXXConstructor:
474     case CXXDestructor:
475     case CXXConversion:
476     case EnumConstant:
477     case Var:
478     case ImplicitParam:
479     case ParmVar:
480     case NonTypeTemplateParm:
481     case ObjCMethod:
482     case ObjCProperty:
483       return IDNS_Ordinary;
484     case Label:
485       return IDNS_Label;
486     case IndirectField:
487       return IDNS_Ordinary | IDNS_Member;
488 
489     case ObjCCompatibleAlias:
490     case ObjCInterface:
491       return IDNS_Ordinary | IDNS_Type;
492 
493     case Typedef:
494     case TypeAlias:
495     case TypeAliasTemplate:
496     case UnresolvedUsingTypename:
497     case TemplateTypeParm:
498       return IDNS_Ordinary | IDNS_Type;
499 
500     case UsingShadow:
501       return 0; // we'll actually overwrite this later
502 
503     case UnresolvedUsingValue:
504       return IDNS_Ordinary | IDNS_Using;
505 
506     case Using:
507       return IDNS_Using;
508 
509     case ObjCProtocol:
510       return IDNS_ObjCProtocol;
511 
512     case Field:
513     case ObjCAtDefsField:
514     case ObjCIvar:
515       return IDNS_Member;
516 
517     case Record:
518     case CXXRecord:
519     case Enum:
520       return IDNS_Tag | IDNS_Type;
521 
522     case Namespace:
523     case NamespaceAlias:
524       return IDNS_Namespace;
525 
526     case FunctionTemplate:
527       return IDNS_Ordinary;
528 
529     case ClassTemplate:
530     case TemplateTemplateParm:
531       return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
532 
533     // Never have names.
534     case Friend:
535     case FriendTemplate:
536     case AccessSpec:
537     case LinkageSpec:
538     case FileScopeAsm:
539     case StaticAssert:
540     case ObjCPropertyImpl:
541     case Block:
542     case TranslationUnit:
543 
544     case UsingDirective:
545     case ClassTemplateSpecialization:
546     case ClassTemplatePartialSpecialization:
547     case ClassScopeFunctionSpecialization:
548     case ObjCImplementation:
549     case ObjCCategory:
550     case ObjCCategoryImpl:
551     case Import:
552       // Never looked up by name.
553       return 0;
554   }
555 
556   llvm_unreachable("Invalid DeclKind!");
557 }
558 
559 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
560   assert(!HasAttrs && "Decl already contains attrs.");
561 
562   AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
563   assert(AttrBlank.empty() && "HasAttrs was wrong?");
564 
565   AttrBlank = attrs;
566   HasAttrs = true;
567 }
568 
569 void Decl::dropAttrs() {
570   if (!HasAttrs) return;
571 
572   HasAttrs = false;
573   getASTContext().eraseDeclAttrs(this);
574 }
575 
576 const AttrVec &Decl::getAttrs() const {
577   assert(HasAttrs && "No attrs to get!");
578   return getASTContext().getDeclAttrs(this);
579 }
580 
581 void Decl::swapAttrs(Decl *RHS) {
582   bool HasLHSAttr = this->HasAttrs;
583   bool HasRHSAttr = RHS->HasAttrs;
584 
585   // Usually, neither decl has attrs, nothing to do.
586   if (!HasLHSAttr && !HasRHSAttr) return;
587 
588   // If 'this' has no attrs, swap the other way.
589   if (!HasLHSAttr)
590     return RHS->swapAttrs(this);
591 
592   ASTContext &Context = getASTContext();
593 
594   // Handle the case when both decls have attrs.
595   if (HasRHSAttr) {
596     std::swap(Context.getDeclAttrs(this), Context.getDeclAttrs(RHS));
597     return;
598   }
599 
600   // Otherwise, LHS has an attr and RHS doesn't.
601   Context.getDeclAttrs(RHS) = Context.getDeclAttrs(this);
602   Context.eraseDeclAttrs(this);
603   this->HasAttrs = false;
604   RHS->HasAttrs = true;
605 }
606 
607 Decl *Decl::castFromDeclContext (const DeclContext *D) {
608   Decl::Kind DK = D->getDeclKind();
609   switch(DK) {
610 #define DECL(NAME, BASE)
611 #define DECL_CONTEXT(NAME) \
612     case Decl::NAME:       \
613       return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
614 #define DECL_CONTEXT_BASE(NAME)
615 #include "clang/AST/DeclNodes.inc"
616     default:
617 #define DECL(NAME, BASE)
618 #define DECL_CONTEXT_BASE(NAME)                  \
619       if (DK >= first##NAME && DK <= last##NAME) \
620         return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
621 #include "clang/AST/DeclNodes.inc"
622       llvm_unreachable("a decl that inherits DeclContext isn't handled");
623   }
624 }
625 
626 DeclContext *Decl::castToDeclContext(const Decl *D) {
627   Decl::Kind DK = D->getKind();
628   switch(DK) {
629 #define DECL(NAME, BASE)
630 #define DECL_CONTEXT(NAME) \
631     case Decl::NAME:       \
632       return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
633 #define DECL_CONTEXT_BASE(NAME)
634 #include "clang/AST/DeclNodes.inc"
635     default:
636 #define DECL(NAME, BASE)
637 #define DECL_CONTEXT_BASE(NAME)                                   \
638       if (DK >= first##NAME && DK <= last##NAME)                  \
639         return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
640 #include "clang/AST/DeclNodes.inc"
641       llvm_unreachable("a decl that inherits DeclContext isn't handled");
642   }
643 }
644 
645 SourceLocation Decl::getBodyRBrace() const {
646   // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
647   // FunctionDecl stores EndRangeLoc for this purpose.
648   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
649     const FunctionDecl *Definition;
650     if (FD->hasBody(Definition))
651       return Definition->getSourceRange().getEnd();
652     return SourceLocation();
653   }
654 
655   if (Stmt *Body = getBody())
656     return Body->getSourceRange().getEnd();
657 
658   return SourceLocation();
659 }
660 
661 void Decl::CheckAccessDeclContext() const {
662 #ifndef NDEBUG
663   // Suppress this check if any of the following hold:
664   // 1. this is the translation unit (and thus has no parent)
665   // 2. this is a template parameter (and thus doesn't belong to its context)
666   // 3. this is a non-type template parameter
667   // 4. the context is not a record
668   // 5. it's invalid
669   // 6. it's a C++0x static_assert.
670   if (isa<TranslationUnitDecl>(this) ||
671       isa<TemplateTypeParmDecl>(this) ||
672       isa<NonTypeTemplateParmDecl>(this) ||
673       !isa<CXXRecordDecl>(getDeclContext()) ||
674       isInvalidDecl() ||
675       isa<StaticAssertDecl>(this) ||
676       // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
677       // as DeclContext (?).
678       isa<ParmVarDecl>(this) ||
679       // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
680       // AS_none as access specifier.
681       isa<CXXRecordDecl>(this) ||
682       isa<ClassScopeFunctionSpecializationDecl>(this))
683     return;
684 
685   assert(Access != AS_none &&
686          "Access specifier is AS_none inside a record decl");
687 #endif
688 }
689 
690 DeclContext *Decl::getNonClosureContext() {
691   return getDeclContext()->getNonClosureAncestor();
692 }
693 
694 DeclContext *DeclContext::getNonClosureAncestor() {
695   DeclContext *DC = this;
696 
697   // This is basically "while (DC->isClosure()) DC = DC->getParent();"
698   // except that it's significantly more efficient to cast to a known
699   // decl type and call getDeclContext() than to call getParent().
700   while (isa<BlockDecl>(DC))
701     DC = cast<BlockDecl>(DC)->getDeclContext();
702 
703   assert(!DC->isClosure());
704   return DC;
705 }
706 
707 //===----------------------------------------------------------------------===//
708 // DeclContext Implementation
709 //===----------------------------------------------------------------------===//
710 
711 bool DeclContext::classof(const Decl *D) {
712   switch (D->getKind()) {
713 #define DECL(NAME, BASE)
714 #define DECL_CONTEXT(NAME) case Decl::NAME:
715 #define DECL_CONTEXT_BASE(NAME)
716 #include "clang/AST/DeclNodes.inc"
717       return true;
718     default:
719 #define DECL(NAME, BASE)
720 #define DECL_CONTEXT_BASE(NAME)                 \
721       if (D->getKind() >= Decl::first##NAME &&  \
722           D->getKind() <= Decl::last##NAME)     \
723         return true;
724 #include "clang/AST/DeclNodes.inc"
725       return false;
726   }
727 }
728 
729 DeclContext::~DeclContext() { }
730 
731 /// \brief Find the parent context of this context that will be
732 /// used for unqualified name lookup.
733 ///
734 /// Generally, the parent lookup context is the semantic context. However, for
735 /// a friend function the parent lookup context is the lexical context, which
736 /// is the class in which the friend is declared.
737 DeclContext *DeclContext::getLookupParent() {
738   // FIXME: Find a better way to identify friends
739   if (isa<FunctionDecl>(this))
740     if (getParent()->getRedeclContext()->isFileContext() &&
741         getLexicalParent()->getRedeclContext()->isRecord())
742       return getLexicalParent();
743 
744   return getParent();
745 }
746 
747 bool DeclContext::isInlineNamespace() const {
748   return isNamespace() &&
749          cast<NamespaceDecl>(this)->isInline();
750 }
751 
752 bool DeclContext::isDependentContext() const {
753   if (isFileContext())
754     return false;
755 
756   if (isa<ClassTemplatePartialSpecializationDecl>(this))
757     return true;
758 
759   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
760     if (Record->getDescribedClassTemplate())
761       return true;
762 
763     if (Record->isDependentLambda())
764       return true;
765   }
766 
767   if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
768     if (Function->getDescribedFunctionTemplate())
769       return true;
770 
771     // Friend function declarations are dependent if their *lexical*
772     // context is dependent.
773     if (cast<Decl>(this)->getFriendObjectKind())
774       return getLexicalParent()->isDependentContext();
775   }
776 
777   return getParent() && getParent()->isDependentContext();
778 }
779 
780 bool DeclContext::isTransparentContext() const {
781   if (DeclKind == Decl::Enum)
782     return !cast<EnumDecl>(this)->isScoped();
783   else if (DeclKind == Decl::LinkageSpec)
784     return true;
785 
786   return false;
787 }
788 
789 bool DeclContext::isExternCContext() const {
790   const DeclContext *DC = this;
791   while (DC->DeclKind != Decl::TranslationUnit) {
792     if (DC->DeclKind == Decl::LinkageSpec)
793       return cast<LinkageSpecDecl>(DC)->getLanguage()
794         == LinkageSpecDecl::lang_c;
795     DC = DC->getParent();
796   }
797   return false;
798 }
799 
800 bool DeclContext::Encloses(const DeclContext *DC) const {
801   if (getPrimaryContext() != this)
802     return getPrimaryContext()->Encloses(DC);
803 
804   for (; DC; DC = DC->getParent())
805     if (DC->getPrimaryContext() == this)
806       return true;
807   return false;
808 }
809 
810 DeclContext *DeclContext::getPrimaryContext() {
811   switch (DeclKind) {
812   case Decl::TranslationUnit:
813   case Decl::LinkageSpec:
814   case Decl::Block:
815     // There is only one DeclContext for these entities.
816     return this;
817 
818   case Decl::Namespace:
819     // The original namespace is our primary context.
820     return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
821 
822   case Decl::ObjCMethod:
823     return this;
824 
825   case Decl::ObjCInterface:
826     if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
827       return Def;
828 
829     return this;
830 
831   case Decl::ObjCProtocol:
832     if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
833       return Def;
834 
835     return this;
836 
837   case Decl::ObjCCategory:
838     return this;
839 
840   case Decl::ObjCImplementation:
841   case Decl::ObjCCategoryImpl:
842     return this;
843 
844   default:
845     if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
846       // If this is a tag type that has a definition or is currently
847       // being defined, that definition is our primary context.
848       TagDecl *Tag = cast<TagDecl>(this);
849       assert(isa<TagType>(Tag->TypeForDecl) ||
850              isa<InjectedClassNameType>(Tag->TypeForDecl));
851 
852       if (TagDecl *Def = Tag->getDefinition())
853         return Def;
854 
855       if (!isa<InjectedClassNameType>(Tag->TypeForDecl)) {
856         const TagType *TagTy = cast<TagType>(Tag->TypeForDecl);
857         if (TagTy->isBeingDefined())
858           // FIXME: is it necessarily being defined in the decl
859           // that owns the type?
860           return TagTy->getDecl();
861       }
862 
863       return Tag;
864     }
865 
866     assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
867           "Unknown DeclContext kind");
868     return this;
869   }
870 }
871 
872 void
873 DeclContext::collectAllContexts(llvm::SmallVectorImpl<DeclContext *> &Contexts){
874   Contexts.clear();
875 
876   if (DeclKind != Decl::Namespace) {
877     Contexts.push_back(this);
878     return;
879   }
880 
881   NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
882   for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
883        N = N->getPreviousDecl())
884     Contexts.push_back(N);
885 
886   std::reverse(Contexts.begin(), Contexts.end());
887 }
888 
889 std::pair<Decl *, Decl *>
890 DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
891                             bool FieldsAlreadyLoaded) {
892   // Build up a chain of declarations via the Decl::NextInContextAndBits field.
893   Decl *FirstNewDecl = 0;
894   Decl *PrevDecl = 0;
895   for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
896     if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
897       continue;
898 
899     Decl *D = Decls[I];
900     if (PrevDecl)
901       PrevDecl->NextInContextAndBits.setPointer(D);
902     else
903       FirstNewDecl = D;
904 
905     PrevDecl = D;
906   }
907 
908   return std::make_pair(FirstNewDecl, PrevDecl);
909 }
910 
911 /// \brief Load the declarations within this lexical storage from an
912 /// external source.
913 void
914 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
915   ExternalASTSource *Source = getParentASTContext().getExternalSource();
916   assert(hasExternalLexicalStorage() && Source && "No external storage?");
917 
918   // Notify that we have a DeclContext that is initializing.
919   ExternalASTSource::Deserializing ADeclContext(Source);
920 
921   // Load the external declarations, if any.
922   SmallVector<Decl*, 64> Decls;
923   ExternalLexicalStorage = false;
924   switch (Source->FindExternalLexicalDecls(this, Decls)) {
925   case ELR_Success:
926     break;
927 
928   case ELR_Failure:
929   case ELR_AlreadyLoaded:
930     return;
931   }
932 
933   if (Decls.empty())
934     return;
935 
936   // We may have already loaded just the fields of this record, in which case
937   // we need to ignore them.
938   bool FieldsAlreadyLoaded = false;
939   if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
940     FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
941 
942   // Splice the newly-read declarations into the beginning of the list
943   // of declarations.
944   Decl *ExternalFirst, *ExternalLast;
945   llvm::tie(ExternalFirst, ExternalLast) = BuildDeclChain(Decls,
946                                                           FieldsAlreadyLoaded);
947   ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
948   FirstDecl = ExternalFirst;
949   if (!LastDecl)
950     LastDecl = ExternalLast;
951 }
952 
953 DeclContext::lookup_result
954 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
955                                                     DeclarationName Name) {
956   ASTContext &Context = DC->getParentASTContext();
957   StoredDeclsMap *Map;
958   if (!(Map = DC->LookupPtr.getPointer()))
959     Map = DC->CreateStoredDeclsMap(Context);
960 
961   StoredDeclsList &List = (*Map)[Name];
962   assert(List.isNull());
963   (void) List;
964 
965   return DeclContext::lookup_result();
966 }
967 
968 DeclContext::lookup_result
969 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
970                                                   DeclarationName Name,
971                                                   ArrayRef<NamedDecl*> Decls) {
972   ASTContext &Context = DC->getParentASTContext();
973 
974   StoredDeclsMap *Map;
975   if (!(Map = DC->LookupPtr.getPointer()))
976     Map = DC->CreateStoredDeclsMap(Context);
977 
978   StoredDeclsList &List = (*Map)[Name];
979   for (ArrayRef<NamedDecl*>::iterator
980          I = Decls.begin(), E = Decls.end(); I != E; ++I) {
981     if (List.isNull())
982       List.setOnlyValue(*I);
983     else
984       List.AddSubsequentDecl(*I);
985   }
986 
987   return List.getLookupResult();
988 }
989 
990 DeclContext::decl_iterator DeclContext::noload_decls_begin() const {
991   return decl_iterator(FirstDecl);
992 }
993 
994 DeclContext::decl_iterator DeclContext::decls_begin() const {
995   if (hasExternalLexicalStorage())
996     LoadLexicalDeclsFromExternalStorage();
997 
998   return decl_iterator(FirstDecl);
999 }
1000 
1001 bool DeclContext::decls_empty() const {
1002   if (hasExternalLexicalStorage())
1003     LoadLexicalDeclsFromExternalStorage();
1004 
1005   return !FirstDecl;
1006 }
1007 
1008 void DeclContext::removeDecl(Decl *D) {
1009   assert(D->getLexicalDeclContext() == this &&
1010          "decl being removed from non-lexical context");
1011   assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1012          "decl is not in decls list");
1013 
1014   // Remove D from the decl chain.  This is O(n) but hopefully rare.
1015   if (D == FirstDecl) {
1016     if (D == LastDecl)
1017       FirstDecl = LastDecl = 0;
1018     else
1019       FirstDecl = D->NextInContextAndBits.getPointer();
1020   } else {
1021     for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1022       assert(I && "decl not found in linked list");
1023       if (I->NextInContextAndBits.getPointer() == D) {
1024         I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1025         if (D == LastDecl) LastDecl = I;
1026         break;
1027       }
1028     }
1029   }
1030 
1031   // Mark that D is no longer in the decl chain.
1032   D->NextInContextAndBits.setPointer(0);
1033 
1034   // Remove D from the lookup table if necessary.
1035   if (isa<NamedDecl>(D)) {
1036     NamedDecl *ND = cast<NamedDecl>(D);
1037 
1038     // Remove only decls that have a name
1039     if (!ND->getDeclName()) return;
1040 
1041     StoredDeclsMap *Map = getPrimaryContext()->LookupPtr.getPointer();
1042     if (!Map) return;
1043 
1044     StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1045     assert(Pos != Map->end() && "no lookup entry for decl");
1046     if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1047       Pos->second.remove(ND);
1048   }
1049 }
1050 
1051 void DeclContext::addHiddenDecl(Decl *D) {
1052   assert(D->getLexicalDeclContext() == this &&
1053          "Decl inserted into wrong lexical context");
1054   assert(!D->getNextDeclInContext() && D != LastDecl &&
1055          "Decl already inserted into a DeclContext");
1056 
1057   if (FirstDecl) {
1058     LastDecl->NextInContextAndBits.setPointer(D);
1059     LastDecl = D;
1060   } else {
1061     FirstDecl = LastDecl = D;
1062   }
1063 
1064   // Notify a C++ record declaration that we've added a member, so it can
1065   // update it's class-specific state.
1066   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1067     Record->addedMember(D);
1068 
1069   // If this is a newly-created (not de-serialized) import declaration, wire
1070   // it in to the list of local import declarations.
1071   if (!D->isFromASTFile()) {
1072     if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1073       D->getASTContext().addedLocalImportDecl(Import);
1074   }
1075 }
1076 
1077 void DeclContext::addDecl(Decl *D) {
1078   addHiddenDecl(D);
1079 
1080   if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1081     ND->getDeclContext()->getPrimaryContext()->
1082         makeDeclVisibleInContextWithFlags(ND, false, true);
1083 }
1084 
1085 void DeclContext::addDeclInternal(Decl *D) {
1086   addHiddenDecl(D);
1087 
1088   if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1089     ND->getDeclContext()->getPrimaryContext()->
1090         makeDeclVisibleInContextWithFlags(ND, true, true);
1091 }
1092 
1093 /// shouldBeHidden - Determine whether a declaration which was declared
1094 /// within its semantic context should be invisible to qualified name lookup.
1095 static bool shouldBeHidden(NamedDecl *D) {
1096   // Skip unnamed declarations.
1097   if (!D->getDeclName())
1098     return true;
1099 
1100   // Skip entities that can't be found by name lookup into a particular
1101   // context.
1102   if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1103       D->isTemplateParameter())
1104     return true;
1105 
1106   // Skip template specializations.
1107   // FIXME: This feels like a hack. Should DeclarationName support
1108   // template-ids, or is there a better way to keep specializations
1109   // from being visible?
1110   if (isa<ClassTemplateSpecializationDecl>(D))
1111     return true;
1112   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1113     if (FD->isFunctionTemplateSpecialization())
1114       return true;
1115 
1116   return false;
1117 }
1118 
1119 /// buildLookup - Build the lookup data structure with all of the
1120 /// declarations in this DeclContext (and any other contexts linked
1121 /// to it or transparent contexts nested within it) and return it.
1122 StoredDeclsMap *DeclContext::buildLookup() {
1123   assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1124 
1125   if (!LookupPtr.getInt())
1126     return LookupPtr.getPointer();
1127 
1128   llvm::SmallVector<DeclContext *, 2> Contexts;
1129   collectAllContexts(Contexts);
1130   for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1131     buildLookupImpl(Contexts[I]);
1132 
1133   // We no longer have any lazy decls.
1134   LookupPtr.setInt(false);
1135   return LookupPtr.getPointer();
1136 }
1137 
1138 /// buildLookupImpl - Build part of the lookup data structure for the
1139 /// declarations contained within DCtx, which will either be this
1140 /// DeclContext, a DeclContext linked to it, or a transparent context
1141 /// nested within it.
1142 void DeclContext::buildLookupImpl(DeclContext *DCtx) {
1143   for (decl_iterator I = DCtx->decls_begin(), E = DCtx->decls_end();
1144        I != E; ++I) {
1145     Decl *D = *I;
1146 
1147     // Insert this declaration into the lookup structure, but only if
1148     // it's semantically within its decl context. Any other decls which
1149     // should be found in this context are added eagerly.
1150     if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1151       if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND))
1152         makeDeclVisibleInContextImpl(ND, false);
1153 
1154     // If this declaration is itself a transparent declaration context
1155     // or inline namespace, add the members of this declaration of that
1156     // context (recursively).
1157     if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1158       if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1159         buildLookupImpl(InnerCtx);
1160   }
1161 }
1162 
1163 DeclContext::lookup_result
1164 DeclContext::lookup(DeclarationName Name) {
1165   assert(DeclKind != Decl::LinkageSpec &&
1166          "Should not perform lookups into linkage specs!");
1167 
1168   DeclContext *PrimaryContext = getPrimaryContext();
1169   if (PrimaryContext != this)
1170     return PrimaryContext->lookup(Name);
1171 
1172   if (hasExternalVisibleStorage()) {
1173     // If a PCH has a result for this name, and we have a local declaration, we
1174     // will have imported the PCH result when adding the local declaration.
1175     // FIXME: For modules, we could have had more declarations added by module
1176     // imoprts since we saw the declaration of the local name.
1177     if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
1178       StoredDeclsMap::iterator I = Map->find(Name);
1179       if (I != Map->end())
1180         return I->second.getLookupResult();
1181     }
1182 
1183     ExternalASTSource *Source = getParentASTContext().getExternalSource();
1184     return Source->FindExternalVisibleDeclsByName(this, Name);
1185   }
1186 
1187   StoredDeclsMap *Map = LookupPtr.getPointer();
1188   if (LookupPtr.getInt())
1189     Map = buildLookup();
1190 
1191   if (!Map)
1192     return lookup_result(lookup_iterator(0), lookup_iterator(0));
1193 
1194   StoredDeclsMap::iterator I = Map->find(Name);
1195   if (I == Map->end())
1196     return lookup_result(lookup_iterator(0), lookup_iterator(0));
1197 
1198   return I->second.getLookupResult();
1199 }
1200 
1201 void DeclContext::localUncachedLookup(DeclarationName Name,
1202                                   llvm::SmallVectorImpl<NamedDecl *> &Results) {
1203   Results.clear();
1204 
1205   // If there's no external storage, just perform a normal lookup and copy
1206   // the results.
1207   if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1208     lookup_result LookupResults = lookup(Name);
1209     Results.insert(Results.end(), LookupResults.first, LookupResults.second);
1210     return;
1211   }
1212 
1213   // If we have a lookup table, check there first. Maybe we'll get lucky.
1214   if (Name) {
1215     if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
1216       StoredDeclsMap::iterator Pos = Map->find(Name);
1217       if (Pos != Map->end()) {
1218         Results.insert(Results.end(),
1219                        Pos->second.getLookupResult().first,
1220                        Pos->second.getLookupResult().second);
1221         return;
1222       }
1223     }
1224   }
1225 
1226   // Slow case: grovel through the declarations in our chain looking for
1227   // matches.
1228   for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1229     if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1230       if (ND->getDeclName() == Name)
1231         Results.push_back(ND);
1232   }
1233 }
1234 
1235 DeclContext *DeclContext::getRedeclContext() {
1236   DeclContext *Ctx = this;
1237   // Skip through transparent contexts.
1238   while (Ctx->isTransparentContext())
1239     Ctx = Ctx->getParent();
1240   return Ctx;
1241 }
1242 
1243 DeclContext *DeclContext::getEnclosingNamespaceContext() {
1244   DeclContext *Ctx = this;
1245   // Skip through non-namespace, non-translation-unit contexts.
1246   while (!Ctx->isFileContext())
1247     Ctx = Ctx->getParent();
1248   return Ctx->getPrimaryContext();
1249 }
1250 
1251 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1252   // For non-file contexts, this is equivalent to Equals.
1253   if (!isFileContext())
1254     return O->Equals(this);
1255 
1256   do {
1257     if (O->Equals(this))
1258       return true;
1259 
1260     const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1261     if (!NS || !NS->isInline())
1262       break;
1263     O = NS->getParent();
1264   } while (O);
1265 
1266   return false;
1267 }
1268 
1269 void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1270   DeclContext *PrimaryDC = this->getPrimaryContext();
1271   DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1272   // If the decl is being added outside of its semantic decl context, we
1273   // need to ensure that we eagerly build the lookup information for it.
1274   PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1275 }
1276 
1277 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1278                                                     bool Recoverable) {
1279   assert(this == getPrimaryContext() && "expected a primary DC");
1280 
1281   // Skip declarations within functions.
1282   // FIXME: We shouldn't need to build lookup tables for function declarations
1283   // ever, and we can't do so correctly because we can't model the nesting of
1284   // scopes which occurs within functions. We use "qualified" lookup into
1285   // function declarations when handling friend declarations inside nested
1286   // classes, and consequently accept the following invalid code:
1287   //
1288   //   void f() { void g(); { int g; struct S { friend void g(); }; } }
1289   if (isFunctionOrMethod() && !isa<FunctionDecl>(D))
1290     return;
1291 
1292   // Skip declarations which should be invisible to name lookup.
1293   if (shouldBeHidden(D))
1294     return;
1295 
1296   // If we already have a lookup data structure, perform the insertion into
1297   // it. If we might have externally-stored decls with this name, look them
1298   // up and perform the insertion. If this decl was declared outside its
1299   // semantic context, buildLookup won't add it, so add it now.
1300   //
1301   // FIXME: As a performance hack, don't add such decls into the translation
1302   // unit unless we're in C++, since qualified lookup into the TU is never
1303   // performed.
1304   if (LookupPtr.getPointer() || hasExternalVisibleStorage() ||
1305       ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1306        (getParentASTContext().getLangOpts().CPlusPlus ||
1307         !isTranslationUnit()))) {
1308     // If we have lazily omitted any decls, they might have the same name as
1309     // the decl which we are adding, so build a full lookup table before adding
1310     // this decl.
1311     buildLookup();
1312     makeDeclVisibleInContextImpl(D, Internal);
1313   } else {
1314     LookupPtr.setInt(true);
1315   }
1316 
1317   // If we are a transparent context or inline namespace, insert into our
1318   // parent context, too. This operation is recursive.
1319   if (isTransparentContext() || isInlineNamespace())
1320     getParent()->getPrimaryContext()->
1321         makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1322 
1323   Decl *DCAsDecl = cast<Decl>(this);
1324   // Notify that a decl was made visible unless we are a Tag being defined.
1325   if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1326     if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1327       L->AddedVisibleDecl(this, D);
1328 }
1329 
1330 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1331   // Find or create the stored declaration map.
1332   StoredDeclsMap *Map = LookupPtr.getPointer();
1333   if (!Map) {
1334     ASTContext *C = &getParentASTContext();
1335     Map = CreateStoredDeclsMap(*C);
1336   }
1337 
1338   // If there is an external AST source, load any declarations it knows about
1339   // with this declaration's name.
1340   // If the lookup table contains an entry about this name it means that we
1341   // have already checked the external source.
1342   if (!Internal)
1343     if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1344       if (hasExternalVisibleStorage() &&
1345           Map->find(D->getDeclName()) == Map->end())
1346         Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1347 
1348   // Insert this declaration into the map.
1349   StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1350   if (DeclNameEntries.isNull()) {
1351     DeclNameEntries.setOnlyValue(D);
1352     return;
1353   }
1354 
1355   if (DeclNameEntries.HandleRedeclaration(D)) {
1356     // This declaration has replaced an existing one for which
1357     // declarationReplaces returns true.
1358     return;
1359   }
1360 
1361   // Put this declaration into the appropriate slot.
1362   DeclNameEntries.AddSubsequentDecl(D);
1363 }
1364 
1365 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1366 /// this context.
1367 DeclContext::udir_iterator_range
1368 DeclContext::getUsingDirectives() const {
1369   // FIXME: Use something more efficient than normal lookup for using
1370   // directives. In C++, using directives are looked up more than anything else.
1371   lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
1372   return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.first),
1373                              reinterpret_cast<udir_iterator>(Result.second));
1374 }
1375 
1376 //===----------------------------------------------------------------------===//
1377 // Creation and Destruction of StoredDeclsMaps.                               //
1378 //===----------------------------------------------------------------------===//
1379 
1380 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1381   assert(!LookupPtr.getPointer() && "context already has a decls map");
1382   assert(getPrimaryContext() == this &&
1383          "creating decls map on non-primary context");
1384 
1385   StoredDeclsMap *M;
1386   bool Dependent = isDependentContext();
1387   if (Dependent)
1388     M = new DependentStoredDeclsMap();
1389   else
1390     M = new StoredDeclsMap();
1391   M->Previous = C.LastSDM;
1392   C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1393   LookupPtr.setPointer(M);
1394   return M;
1395 }
1396 
1397 void ASTContext::ReleaseDeclContextMaps() {
1398   // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1399   // pointer because the subclass doesn't add anything that needs to
1400   // be deleted.
1401   StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1402 }
1403 
1404 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1405   while (Map) {
1406     // Advance the iteration before we invalidate memory.
1407     llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1408 
1409     if (Dependent)
1410       delete static_cast<DependentStoredDeclsMap*>(Map);
1411     else
1412       delete Map;
1413 
1414     Map = Next.getPointer();
1415     Dependent = Next.getInt();
1416   }
1417 }
1418 
1419 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1420                                                  DeclContext *Parent,
1421                                            const PartialDiagnostic &PDiag) {
1422   assert(Parent->isDependentContext()
1423          && "cannot iterate dependent diagnostics of non-dependent context");
1424   Parent = Parent->getPrimaryContext();
1425   if (!Parent->LookupPtr.getPointer())
1426     Parent->CreateStoredDeclsMap(C);
1427 
1428   DependentStoredDeclsMap *Map
1429     = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr.getPointer());
1430 
1431   // Allocate the copy of the PartialDiagnostic via the ASTContext's
1432   // BumpPtrAllocator, rather than the ASTContext itself.
1433   PartialDiagnostic::Storage *DiagStorage = 0;
1434   if (PDiag.hasStorage())
1435     DiagStorage = new (C) PartialDiagnostic::Storage;
1436 
1437   DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1438 
1439   // TODO: Maybe we shouldn't reverse the order during insertion.
1440   DD->NextDiagnostic = Map->FirstDiagnostic;
1441   Map->FirstDiagnostic = DD;
1442 
1443   return DD;
1444 }
1445