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/Decl.h"
16 #include "clang/AST/DeclContextInternals.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/ExternalASTSource.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/Type.h"
23 #include "clang/AST/Stmt.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <algorithm>
28 #include <cstdio>
29 #include <vector>
30 using namespace clang;
31 
32 //===----------------------------------------------------------------------===//
33 //  Statistics
34 //===----------------------------------------------------------------------===//
35 
36 #define DECL(Derived, Base) static int n##Derived##s = 0;
37 #include "clang/AST/DeclNodes.def"
38 
39 static bool StatSwitch = false;
40 
41 const char *Decl::getDeclKindName() const {
42   switch (DeclKind) {
43   default: assert(0 && "Declaration not in DeclNodes.def!");
44 #define DECL(Derived, Base) case Derived: return #Derived;
45 #include "clang/AST/DeclNodes.def"
46   }
47 }
48 
49 const char *DeclContext::getDeclKindName() const {
50   switch (DeclKind) {
51   default: assert(0 && "Declaration context not in DeclNodes.def!");
52 #define DECL(Derived, Base) case Decl::Derived: return #Derived;
53 #include "clang/AST/DeclNodes.def"
54   }
55 }
56 
57 bool Decl::CollectingStats(bool Enable) {
58   if (Enable)
59     StatSwitch = true;
60   return StatSwitch;
61 }
62 
63 void Decl::PrintStats() {
64   fprintf(stderr, "*** Decl Stats:\n");
65 
66   int totalDecls = 0;
67 #define DECL(Derived, Base) totalDecls += n##Derived##s;
68 #include "clang/AST/DeclNodes.def"
69   fprintf(stderr, "  %d decls total.\n", totalDecls);
70 
71   int totalBytes = 0;
72 #define DECL(Derived, Base)                                             \
73   if (n##Derived##s > 0) {                                              \
74     totalBytes += (int)(n##Derived##s * sizeof(Derived##Decl));         \
75     fprintf(stderr, "    %d " #Derived " decls, %d each (%d bytes)\n",  \
76             n##Derived##s, (int)sizeof(Derived##Decl),                  \
77             (int)(n##Derived##s * sizeof(Derived##Decl)));              \
78   }
79 #include "clang/AST/DeclNodes.def"
80 
81   fprintf(stderr, "Total bytes = %d\n", totalBytes);
82 }
83 
84 void Decl::addDeclKind(Kind k) {
85   switch (k) {
86   default: assert(0 && "Declaration not in DeclNodes.def!");
87 #define DECL(Derived, Base) case Derived: ++n##Derived##s; break;
88 #include "clang/AST/DeclNodes.def"
89   }
90 }
91 
92 bool Decl::isTemplateParameterPack() const {
93   if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
94     return TTP->isParameterPack();
95 
96   return false;
97 }
98 
99 bool Decl::isFunctionOrFunctionTemplate() const {
100   if (const UsingDecl *UD = dyn_cast<UsingDecl>(this))
101     return UD->getTargetDecl()->isFunctionOrFunctionTemplate();
102 
103   return isa<FunctionDecl>(this) || isa<FunctionTemplateDecl>(this);
104 }
105 
106 //===----------------------------------------------------------------------===//
107 // PrettyStackTraceDecl Implementation
108 //===----------------------------------------------------------------------===//
109 
110 void PrettyStackTraceDecl::print(llvm::raw_ostream &OS) const {
111   SourceLocation TheLoc = Loc;
112   if (TheLoc.isInvalid() && TheDecl)
113     TheLoc = TheDecl->getLocation();
114 
115   if (TheLoc.isValid()) {
116     TheLoc.print(OS, SM);
117     OS << ": ";
118   }
119 
120   OS << Message;
121 
122   if (NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl))
123     OS << " '" << DN->getQualifiedNameAsString() << '\'';
124   OS << '\n';
125 }
126 
127 //===----------------------------------------------------------------------===//
128 // Decl Implementation
129 //===----------------------------------------------------------------------===//
130 
131 // Out-of-line virtual method providing a home for Decl.
132 Decl::~Decl() {
133   if (isOutOfSemaDC())
134     delete getMultipleDC();
135 
136   assert(!HasAttrs && "attributes should have been freed by Destroy");
137 }
138 
139 void Decl::setDeclContext(DeclContext *DC) {
140   if (isOutOfSemaDC())
141     delete getMultipleDC();
142 
143   DeclCtx = DC;
144 }
145 
146 void Decl::setLexicalDeclContext(DeclContext *DC) {
147   if (DC == getLexicalDeclContext())
148     return;
149 
150   if (isInSemaDC()) {
151     MultipleDC *MDC = new MultipleDC();
152     MDC->SemanticDC = getDeclContext();
153     MDC->LexicalDC = DC;
154     DeclCtx = MDC;
155   } else {
156     getMultipleDC()->LexicalDC = DC;
157   }
158 }
159 
160 TranslationUnitDecl *Decl::getTranslationUnitDecl() {
161   if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
162     return TUD;
163 
164   DeclContext *DC = getDeclContext();
165   assert(DC && "This decl is not contained in a translation unit!");
166 
167   while (!DC->isTranslationUnit()) {
168     DC = DC->getParent();
169     assert(DC && "This decl is not contained in a translation unit!");
170   }
171 
172   return cast<TranslationUnitDecl>(DC);
173 }
174 
175 ASTContext &Decl::getASTContext() const {
176   return getTranslationUnitDecl()->getASTContext();
177 }
178 
179 unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
180   switch (DeclKind) {
181     default:
182       if (DeclKind >= FunctionFirst && DeclKind <= FunctionLast)
183         return IDNS_Ordinary;
184       assert(0 && "Unknown decl kind!");
185     case OverloadedFunction:
186     case Typedef:
187     case EnumConstant:
188     case Var:
189     case ImplicitParam:
190     case ParmVar:
191     case OriginalParmVar:
192     case NonTypeTemplateParm:
193     case Using:
194     case UnresolvedUsing:
195     case ObjCMethod:
196     case ObjCContainer:
197     case ObjCCategory:
198     case ObjCInterface:
199     case ObjCProperty:
200     case ObjCCompatibleAlias:
201       return IDNS_Ordinary;
202 
203     case ObjCProtocol:
204       return IDNS_ObjCProtocol;
205 
206     case ObjCImplementation:
207       return IDNS_ObjCImplementation;
208 
209     case ObjCCategoryImpl:
210       return IDNS_ObjCCategoryImpl;
211 
212     case Field:
213     case ObjCAtDefsField:
214     case ObjCIvar:
215       return IDNS_Member;
216 
217     case Record:
218     case CXXRecord:
219     case Enum:
220     case TemplateTypeParm:
221       return IDNS_Tag;
222 
223     case Namespace:
224     case Template:
225     case FunctionTemplate:
226     case ClassTemplate:
227     case TemplateTemplateParm:
228     case NamespaceAlias:
229       return IDNS_Tag | IDNS_Ordinary;
230 
231     // Never have names.
232     case Friend:
233     case LinkageSpec:
234     case FileScopeAsm:
235     case StaticAssert:
236     case ObjCClass:
237     case ObjCPropertyImpl:
238     case ObjCForwardProtocol:
239     case Block:
240     case TranslationUnit:
241 
242     // Aren't looked up?
243     case UsingDirective:
244     case ClassTemplateSpecialization:
245     case ClassTemplatePartialSpecialization:
246       return 0;
247   }
248 }
249 
250 void Decl::addAttr(Attr *NewAttr) {
251   Attr *&ExistingAttr = getASTContext().getDeclAttrs(this);
252 
253   NewAttr->setNext(ExistingAttr);
254   ExistingAttr = NewAttr;
255 
256   HasAttrs = true;
257 }
258 
259 void Decl::invalidateAttrs() {
260   if (!HasAttrs) return;
261 
262   HasAttrs = false;
263   getASTContext().eraseDeclAttrs(this);
264 }
265 
266 const Attr *Decl::getAttrsImpl() const {
267   assert(HasAttrs && "getAttrs() should verify this!");
268   return getASTContext().getDeclAttrs(this);
269 }
270 
271 void Decl::swapAttrs(Decl *RHS) {
272   bool HasLHSAttr = this->HasAttrs;
273   bool HasRHSAttr = RHS->HasAttrs;
274 
275   // Usually, neither decl has attrs, nothing to do.
276   if (!HasLHSAttr && !HasRHSAttr) return;
277 
278   // If 'this' has no attrs, swap the other way.
279   if (!HasLHSAttr)
280     return RHS->swapAttrs(this);
281 
282   ASTContext &Context = getASTContext();
283 
284   // Handle the case when both decls have attrs.
285   if (HasRHSAttr) {
286     std::swap(Context.getDeclAttrs(this), Context.getDeclAttrs(RHS));
287     return;
288   }
289 
290   // Otherwise, LHS has an attr and RHS doesn't.
291   Context.getDeclAttrs(RHS) = Context.getDeclAttrs(this);
292   Context.eraseDeclAttrs(this);
293   this->HasAttrs = false;
294   RHS->HasAttrs = true;
295 }
296 
297 
298 void Decl::Destroy(ASTContext &C) {
299   // Free attributes for this decl.
300   if (HasAttrs) {
301     C.getDeclAttrs(this)->Destroy(C);
302     invalidateAttrs();
303     HasAttrs = false;
304   }
305 
306 #if 0
307   // FIXME: Once ownership is fully understood, we can enable this code
308   if (DeclContext *DC = dyn_cast<DeclContext>(this))
309     DC->decls_begin()->Destroy(C);
310 
311   // Observe the unrolled recursion.  By setting N->NextDeclInContext = 0x0
312   // within the loop, only the Destroy method for the first Decl
313   // will deallocate all of the Decls in a chain.
314 
315   Decl* N = getNextDeclInContext();
316 
317   while (N) {
318     Decl* Tmp = N->getNextDeclInContext();
319     N->NextDeclInContext = 0;
320     N->Destroy(C);
321     N = Tmp;
322   }
323 
324   this->~Decl();
325   C.Deallocate((void *)this);
326 #endif
327 }
328 
329 Decl *Decl::castFromDeclContext (const DeclContext *D) {
330   Decl::Kind DK = D->getDeclKind();
331   switch(DK) {
332 #define DECL_CONTEXT(Name) \
333     case Decl::Name:     \
334       return static_cast<Name##Decl*>(const_cast<DeclContext*>(D));
335 #define DECL_CONTEXT_BASE(Name)
336 #include "clang/AST/DeclNodes.def"
337     default:
338 #define DECL_CONTEXT_BASE(Name)                                   \
339       if (DK >= Decl::Name##First && DK <= Decl::Name##Last)    \
340         return static_cast<Name##Decl*>(const_cast<DeclContext*>(D));
341 #include "clang/AST/DeclNodes.def"
342       assert(false && "a decl that inherits DeclContext isn't handled");
343       return 0;
344   }
345 }
346 
347 DeclContext *Decl::castToDeclContext(const Decl *D) {
348   Decl::Kind DK = D->getKind();
349   switch(DK) {
350 #define DECL_CONTEXT(Name) \
351     case Decl::Name:     \
352       return static_cast<Name##Decl*>(const_cast<Decl*>(D));
353 #define DECL_CONTEXT_BASE(Name)
354 #include "clang/AST/DeclNodes.def"
355     default:
356 #define DECL_CONTEXT_BASE(Name)                                   \
357       if (DK >= Decl::Name##First && DK <= Decl::Name##Last)    \
358         return static_cast<Name##Decl*>(const_cast<Decl*>(D));
359 #include "clang/AST/DeclNodes.def"
360       assert(false && "a decl that inherits DeclContext isn't handled");
361       return 0;
362   }
363 }
364 
365 CompoundStmt* Decl::getCompoundBody() const {
366   return dyn_cast_or_null<CompoundStmt>(getBody());
367 }
368 
369 SourceLocation Decl::getBodyRBrace() const {
370   Stmt *Body = getBody();
371   if (!Body)
372     return SourceLocation();
373   if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Body))
374     return CS->getRBracLoc();
375   assert(isa<CXXTryStmt>(Body) &&
376          "Body can only be CompoundStmt or CXXTryStmt");
377   return cast<CXXTryStmt>(Body)->getSourceRange().getEnd();
378 }
379 
380 #ifndef NDEBUG
381 void Decl::CheckAccessDeclContext() const {
382   // If the decl is the toplevel translation unit or if we're not in a
383   // record decl context, we don't need to check anything.
384   if (isa<TranslationUnitDecl>(this) ||
385       !isa<CXXRecordDecl>(getDeclContext()))
386     return;
387 
388   assert(Access != AS_none &&
389          "Access specifier is AS_none inside a record decl");
390 }
391 
392 #endif
393 
394 //===----------------------------------------------------------------------===//
395 // DeclContext Implementation
396 //===----------------------------------------------------------------------===//
397 
398 bool DeclContext::classof(const Decl *D) {
399   switch (D->getKind()) {
400 #define DECL_CONTEXT(Name) case Decl::Name:
401 #define DECL_CONTEXT_BASE(Name)
402 #include "clang/AST/DeclNodes.def"
403       return true;
404     default:
405 #define DECL_CONTEXT_BASE(Name)                   \
406       if (D->getKind() >= Decl::Name##First &&  \
407           D->getKind() <= Decl::Name##Last)     \
408         return true;
409 #include "clang/AST/DeclNodes.def"
410       return false;
411   }
412 }
413 
414 DeclContext::~DeclContext() {
415   delete static_cast<StoredDeclsMap*>(LookupPtr);
416 }
417 
418 void DeclContext::DestroyDecls(ASTContext &C) {
419   for (decl_iterator D = decls_begin(); D != decls_end(); )
420     (*D++)->Destroy(C);
421 }
422 
423 /// \brief Find the parent context of this context that will be
424 /// used for unqualified name lookup.
425 ///
426 /// Generally, the parent lookup context is the semantic context. However, for
427 /// a friend function the parent lookup context is the lexical context, which
428 /// is the class in which the friend is declared.
429 DeclContext *DeclContext::getLookupParent() {
430   // FIXME: Find a better way to identify friends
431   if (isa<FunctionDecl>(this))
432     if (getParent()->getLookupContext()->isFileContext() &&
433         getLexicalParent()->getLookupContext()->isRecord())
434       return getLexicalParent();
435 
436   return getParent();
437 }
438 
439 bool DeclContext::isDependentContext() const {
440   if (isFileContext())
441     return false;
442 
443   if (isa<ClassTemplatePartialSpecializationDecl>(this))
444     return true;
445 
446   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
447     if (Record->getDescribedClassTemplate())
448       return true;
449 
450   if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this))
451     if (Function->getDescribedFunctionTemplate())
452       return true;
453 
454   return getParent() && getParent()->isDependentContext();
455 }
456 
457 bool DeclContext::isTransparentContext() const {
458   if (DeclKind == Decl::Enum)
459     return true; // FIXME: Check for C++0x scoped enums
460   else if (DeclKind == Decl::LinkageSpec)
461     return true;
462   else if (DeclKind >= Decl::RecordFirst && DeclKind <= Decl::RecordLast)
463     return cast<RecordDecl>(this)->isAnonymousStructOrUnion();
464   else if (DeclKind == Decl::Namespace)
465     return false; // FIXME: Check for C++0x inline namespaces
466 
467   return false;
468 }
469 
470 bool DeclContext::Encloses(DeclContext *DC) {
471   if (getPrimaryContext() != this)
472     return getPrimaryContext()->Encloses(DC);
473 
474   for (; DC; DC = DC->getParent())
475     if (DC->getPrimaryContext() == this)
476       return true;
477   return false;
478 }
479 
480 DeclContext *DeclContext::getPrimaryContext() {
481   switch (DeclKind) {
482   case Decl::TranslationUnit:
483   case Decl::LinkageSpec:
484   case Decl::Block:
485     // There is only one DeclContext for these entities.
486     return this;
487 
488   case Decl::Namespace:
489     // The original namespace is our primary context.
490     return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
491 
492   case Decl::ObjCMethod:
493     return this;
494 
495   case Decl::ObjCInterface:
496   case Decl::ObjCProtocol:
497   case Decl::ObjCCategory:
498     // FIXME: Can Objective-C interfaces be forward-declared?
499     return this;
500 
501   case Decl::ObjCImplementation:
502   case Decl::ObjCCategoryImpl:
503     return this;
504 
505   default:
506     if (DeclKind >= Decl::TagFirst && DeclKind <= Decl::TagLast) {
507       // If this is a tag type that has a definition or is currently
508       // being defined, that definition is our primary context.
509       if (const TagType *TagT =cast<TagDecl>(this)->TypeForDecl->getAs<TagType>())
510         if (TagT->isBeingDefined() ||
511             (TagT->getDecl() && TagT->getDecl()->isDefinition()))
512           return TagT->getDecl();
513       return this;
514     }
515 
516     assert(DeclKind >= Decl::FunctionFirst && DeclKind <= Decl::FunctionLast &&
517           "Unknown DeclContext kind");
518     return this;
519   }
520 }
521 
522 DeclContext *DeclContext::getNextContext() {
523   switch (DeclKind) {
524   case Decl::Namespace:
525     // Return the next namespace
526     return static_cast<NamespaceDecl*>(this)->getNextNamespace();
527 
528   default:
529     return 0;
530   }
531 }
532 
533 /// \brief Load the declarations within this lexical storage from an
534 /// external source.
535 void
536 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
537   ExternalASTSource *Source = getParentASTContext().getExternalSource();
538   assert(hasExternalLexicalStorage() && Source && "No external storage?");
539 
540   llvm::SmallVector<uint32_t, 64> Decls;
541   if (Source->ReadDeclsLexicallyInContext(const_cast<DeclContext *>(this),
542                                           Decls))
543     return;
544 
545   // There is no longer any lexical storage in this context
546   ExternalLexicalStorage = false;
547 
548   if (Decls.empty())
549     return;
550 
551   // Resolve all of the declaration IDs into declarations, building up
552   // a chain of declarations via the Decl::NextDeclInContext field.
553   Decl *FirstNewDecl = 0;
554   Decl *PrevDecl = 0;
555   for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
556     Decl *D = Source->GetDecl(Decls[I]);
557     if (PrevDecl)
558       PrevDecl->NextDeclInContext = D;
559     else
560       FirstNewDecl = D;
561 
562     PrevDecl = D;
563   }
564 
565   // Splice the newly-read declarations into the beginning of the list
566   // of declarations.
567   PrevDecl->NextDeclInContext = FirstDecl;
568   FirstDecl = FirstNewDecl;
569   if (!LastDecl)
570     LastDecl = PrevDecl;
571 }
572 
573 void
574 DeclContext::LoadVisibleDeclsFromExternalStorage() const {
575   DeclContext *This = const_cast<DeclContext *>(this);
576   ExternalASTSource *Source = getParentASTContext().getExternalSource();
577   assert(hasExternalVisibleStorage() && Source && "No external storage?");
578 
579   llvm::SmallVector<VisibleDeclaration, 64> Decls;
580   if (Source->ReadDeclsVisibleInContext(This, Decls))
581     return;
582 
583   // There is no longer any visible storage in this context
584   ExternalVisibleStorage = false;
585 
586   // Load the declaration IDs for all of the names visible in this
587   // context.
588   assert(!LookupPtr && "Have a lookup map before de-serialization?");
589   StoredDeclsMap *Map = new StoredDeclsMap;
590   LookupPtr = Map;
591   for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
592     (*Map)[Decls[I].Name].setFromDeclIDs(Decls[I].Declarations);
593   }
594 }
595 
596 DeclContext::decl_iterator DeclContext::decls_begin() const {
597   if (hasExternalLexicalStorage())
598     LoadLexicalDeclsFromExternalStorage();
599 
600   // FIXME: Check whether we need to load some declarations from
601   // external storage.
602   return decl_iterator(FirstDecl);
603 }
604 
605 DeclContext::decl_iterator DeclContext::decls_end() const {
606   if (hasExternalLexicalStorage())
607     LoadLexicalDeclsFromExternalStorage();
608 
609   return decl_iterator();
610 }
611 
612 bool DeclContext::decls_empty() const {
613   if (hasExternalLexicalStorage())
614     LoadLexicalDeclsFromExternalStorage();
615 
616   return !FirstDecl;
617 }
618 
619 void DeclContext::addHiddenDecl(Decl *D) {
620   assert(D->getLexicalDeclContext() == this &&
621          "Decl inserted into wrong lexical context");
622   assert(!D->getNextDeclInContext() && D != LastDecl &&
623          "Decl already inserted into a DeclContext");
624 
625   if (FirstDecl) {
626     LastDecl->NextDeclInContext = D;
627     LastDecl = D;
628   } else {
629     FirstDecl = LastDecl = D;
630   }
631 }
632 
633 void DeclContext::addDecl(Decl *D) {
634   addHiddenDecl(D);
635 
636   if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
637     ND->getDeclContext()->makeDeclVisibleInContext(ND);
638 }
639 
640 /// buildLookup - Build the lookup data structure with all of the
641 /// declarations in DCtx (and any other contexts linked to it or
642 /// transparent contexts nested within it).
643 void DeclContext::buildLookup(DeclContext *DCtx) {
644   for (; DCtx; DCtx = DCtx->getNextContext()) {
645     for (decl_iterator D = DCtx->decls_begin(),
646                     DEnd = DCtx->decls_end();
647          D != DEnd; ++D) {
648       // Insert this declaration into the lookup structure, but only
649       // if it's semantically in its decl context.  During non-lazy
650       // lookup building, this is implicitly enforced by addDecl.
651       if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
652         if (D->getDeclContext() == DCtx)
653           makeDeclVisibleInContextImpl(ND);
654 
655       // If this declaration is itself a transparent declaration context,
656       // add its members (recursively).
657       if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D))
658         if (InnerCtx->isTransparentContext())
659           buildLookup(InnerCtx->getPrimaryContext());
660     }
661   }
662 }
663 
664 DeclContext::lookup_result
665 DeclContext::lookup(DeclarationName Name) {
666   DeclContext *PrimaryContext = getPrimaryContext();
667   if (PrimaryContext != this)
668     return PrimaryContext->lookup(Name);
669 
670   if (hasExternalVisibleStorage())
671     LoadVisibleDeclsFromExternalStorage();
672 
673   /// If there is no lookup data structure, build one now by walking
674   /// all of the linked DeclContexts (in declaration order!) and
675   /// inserting their values.
676   if (!LookupPtr) {
677     buildLookup(this);
678 
679     if (!LookupPtr)
680       return lookup_result(0, 0);
681   }
682 
683   StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(LookupPtr);
684   StoredDeclsMap::iterator Pos = Map->find(Name);
685   if (Pos == Map->end())
686     return lookup_result(0, 0);
687   return Pos->second.getLookupResult(getParentASTContext());
688 }
689 
690 DeclContext::lookup_const_result
691 DeclContext::lookup(DeclarationName Name) const {
692   return const_cast<DeclContext*>(this)->lookup(Name);
693 }
694 
695 DeclContext *DeclContext::getLookupContext() {
696   DeclContext *Ctx = this;
697   // Skip through transparent contexts.
698   while (Ctx->isTransparentContext())
699     Ctx = Ctx->getParent();
700   return Ctx;
701 }
702 
703 DeclContext *DeclContext::getEnclosingNamespaceContext() {
704   DeclContext *Ctx = this;
705   // Skip through non-namespace, non-translation-unit contexts.
706   while (!Ctx->isFileContext() || Ctx->isTransparentContext())
707     Ctx = Ctx->getParent();
708   return Ctx->getPrimaryContext();
709 }
710 
711 void DeclContext::makeDeclVisibleInContext(NamedDecl *D, bool Recoverable) {
712   // FIXME: This feels like a hack. Should DeclarationName support
713   // template-ids, or is there a better way to keep specializations
714   // from being visible?
715   if (isa<ClassTemplateSpecializationDecl>(D))
716     return;
717 
718   DeclContext *PrimaryContext = getPrimaryContext();
719   if (PrimaryContext != this) {
720     PrimaryContext->makeDeclVisibleInContext(D, Recoverable);
721     return;
722   }
723 
724   // If we already have a lookup data structure, perform the insertion
725   // into it. Otherwise, be lazy and don't build that structure until
726   // someone asks for it.
727   if (LookupPtr || !Recoverable)
728     makeDeclVisibleInContextImpl(D);
729 
730   // If we are a transparent context, insert into our parent context,
731   // too. This operation is recursive.
732   if (isTransparentContext())
733     getParent()->makeDeclVisibleInContext(D, Recoverable);
734 }
735 
736 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D) {
737   // Skip unnamed declarations.
738   if (!D->getDeclName())
739     return;
740 
741   // FIXME: This feels like a hack. Should DeclarationName support
742   // template-ids, or is there a better way to keep specializations
743   // from being visible?
744   if (isa<ClassTemplateSpecializationDecl>(D))
745     return;
746 
747   if (!LookupPtr)
748     LookupPtr = new StoredDeclsMap;
749 
750   // Insert this declaration into the map.
751   StoredDeclsMap &Map = *static_cast<StoredDeclsMap*>(LookupPtr);
752   StoredDeclsList &DeclNameEntries = Map[D->getDeclName()];
753   if (DeclNameEntries.isNull()) {
754     DeclNameEntries.setOnlyValue(D);
755     return;
756   }
757 
758   // If it is possible that this is a redeclaration, check to see if there is
759   // already a decl for which declarationReplaces returns true.  If there is
760   // one, just replace it and return.
761   if (DeclNameEntries.HandleRedeclaration(getParentASTContext(), D))
762     return;
763 
764   // Put this declaration into the appropriate slot.
765   DeclNameEntries.AddSubsequentDecl(D);
766 }
767 
768 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
769 /// this context.
770 DeclContext::udir_iterator_range
771 DeclContext::getUsingDirectives() const {
772   lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
773   return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.first),
774                              reinterpret_cast<udir_iterator>(Result.second));
775 }
776 
777 void StoredDeclsList::materializeDecls(ASTContext &Context) {
778   if (isNull())
779     return;
780 
781   switch ((DataKind)(Data & 0x03)) {
782   case DK_Decl:
783   case DK_Decl_Vector:
784     break;
785 
786   case DK_DeclID: {
787     // Resolve this declaration ID to an actual declaration by
788     // querying the external AST source.
789     unsigned DeclID = Data >> 2;
790 
791     ExternalASTSource *Source = Context.getExternalSource();
792     assert(Source && "No external AST source available!");
793 
794     Data = reinterpret_cast<uintptr_t>(Source->GetDecl(DeclID));
795     break;
796   }
797 
798   case DK_ID_Vector: {
799     // We have a vector of declaration IDs. Resolve all of them to
800     // actual declarations.
801     VectorTy &Vector = *getAsVector();
802     ExternalASTSource *Source = Context.getExternalSource();
803     assert(Source && "No external AST source available!");
804 
805     for (unsigned I = 0, N = Vector.size(); I != N; ++I)
806       Vector[I] = reinterpret_cast<uintptr_t>(Source->GetDecl(Vector[I]));
807 
808     Data = (Data & ~0x03) | DK_Decl_Vector;
809     break;
810   }
811   }
812 }
813