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