DeclBase.cpp revision 074dcc8ef8c5df7a155c85648e8eae786bee6cab
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 "llvm/ADT/DenseMap.h"
28#include "llvm/Support/raw_ostream.h"
29#include <algorithm>
30#include <cstdio>
31#include <vector>
32using 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
42static bool StatSwitch = false;
43
44const char *Decl::getDeclKindName() const {
45  switch (DeclKind) {
46  default: assert(0 && "Declaration not in DeclNodes.inc!");
47#define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
48#define ABSTRACT_DECL(DECL)
49#include "clang/AST/DeclNodes.inc"
50  }
51}
52
53void Decl::setInvalidDecl(bool Invalid) {
54  InvalidDecl = Invalid;
55  if (Invalid) {
56    // Defensive maneuver for ill-formed code: we're likely not to make it to
57    // a point where we set the access specifier, so default it to "public"
58    // to avoid triggering asserts elsewhere in the front end.
59    setAccess(AS_public);
60  }
61}
62
63const char *DeclContext::getDeclKindName() const {
64  switch (DeclKind) {
65  default: assert(0 && "Declaration context not in DeclNodes.inc!");
66#define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
67#define ABSTRACT_DECL(DECL)
68#include "clang/AST/DeclNodes.inc"
69  }
70}
71
72bool Decl::CollectingStats(bool Enable) {
73  if (Enable) StatSwitch = true;
74  return StatSwitch;
75}
76
77void Decl::PrintStats() {
78  fprintf(stderr, "*** Decl Stats:\n");
79
80  int totalDecls = 0;
81#define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
82#define ABSTRACT_DECL(DECL)
83#include "clang/AST/DeclNodes.inc"
84  fprintf(stderr, "  %d decls total.\n", totalDecls);
85
86  int totalBytes = 0;
87#define DECL(DERIVED, BASE)                                             \
88  if (n##DERIVED##s > 0) {                                              \
89    totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl));         \
90    fprintf(stderr, "    %d " #DERIVED " decls, %d each (%d bytes)\n",  \
91            n##DERIVED##s, (int)sizeof(DERIVED##Decl),                  \
92            (int)(n##DERIVED##s * sizeof(DERIVED##Decl)));              \
93  }
94#define ABSTRACT_DECL(DECL)
95#include "clang/AST/DeclNodes.inc"
96
97  fprintf(stderr, "Total bytes = %d\n", totalBytes);
98}
99
100void Decl::add(Kind k) {
101  switch (k) {
102  default: assert(0 && "Declaration not in DeclNodes.inc!");
103#define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
104#define ABSTRACT_DECL(DECL)
105#include "clang/AST/DeclNodes.inc"
106  }
107}
108
109bool Decl::isTemplateParameterPack() const {
110  if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
111    return TTP->isParameterPack();
112
113  return false;
114}
115
116bool Decl::isFunctionOrFunctionTemplate() const {
117  if (const UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(this))
118    return UD->getTargetDecl()->isFunctionOrFunctionTemplate();
119
120  return isa<FunctionDecl>(this) || isa<FunctionTemplateDecl>(this);
121}
122
123bool Decl::isDefinedOutsideFunctionOrMethod() const {
124  for (const DeclContext *DC = getDeclContext();
125       DC && !DC->isTranslationUnit();
126       DC = DC->getParent())
127    if (DC->isFunctionOrMethod())
128      return false;
129
130  return true;
131}
132
133
134//===----------------------------------------------------------------------===//
135// PrettyStackTraceDecl Implementation
136//===----------------------------------------------------------------------===//
137
138void PrettyStackTraceDecl::print(llvm::raw_ostream &OS) const {
139  SourceLocation TheLoc = Loc;
140  if (TheLoc.isInvalid() && TheDecl)
141    TheLoc = TheDecl->getLocation();
142
143  if (TheLoc.isValid()) {
144    TheLoc.print(OS, SM);
145    OS << ": ";
146  }
147
148  OS << Message;
149
150  if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl))
151    OS << " '" << DN->getQualifiedNameAsString() << '\'';
152  OS << '\n';
153}
154
155//===----------------------------------------------------------------------===//
156// Decl Implementation
157//===----------------------------------------------------------------------===//
158
159// Out-of-line virtual method providing a home for Decl.
160Decl::~Decl() { }
161
162void Decl::setDeclContext(DeclContext *DC) {
163  if (isOutOfSemaDC())
164    delete getMultipleDC();
165
166  DeclCtx = DC;
167}
168
169void Decl::setLexicalDeclContext(DeclContext *DC) {
170  if (DC == getLexicalDeclContext())
171    return;
172
173  if (isInSemaDC()) {
174    MultipleDC *MDC = new (getASTContext()) MultipleDC();
175    MDC->SemanticDC = getDeclContext();
176    MDC->LexicalDC = DC;
177    DeclCtx = MDC;
178  } else {
179    getMultipleDC()->LexicalDC = DC;
180  }
181}
182
183bool Decl::isInAnonymousNamespace() const {
184  const DeclContext *DC = getDeclContext();
185  do {
186    if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
187      if (ND->isAnonymousNamespace())
188        return true;
189  } while ((DC = DC->getParent()));
190
191  return false;
192}
193
194TranslationUnitDecl *Decl::getTranslationUnitDecl() {
195  if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
196    return TUD;
197
198  DeclContext *DC = getDeclContext();
199  assert(DC && "This decl is not contained in a translation unit!");
200
201  while (!DC->isTranslationUnit()) {
202    DC = DC->getParent();
203    assert(DC && "This decl is not contained in a translation unit!");
204  }
205
206  return cast<TranslationUnitDecl>(DC);
207}
208
209ASTContext &Decl::getASTContext() const {
210  return getTranslationUnitDecl()->getASTContext();
211}
212
213bool Decl::isUsed(bool CheckUsedAttr) const {
214  if (Used)
215    return true;
216
217  // Check for used attribute.
218  if (CheckUsedAttr && hasAttr<UsedAttr>())
219    return true;
220
221  // Check redeclarations for used attribute.
222  for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
223    if ((CheckUsedAttr && I->hasAttr<UsedAttr>()) || I->Used)
224      return true;
225  }
226
227  return false;
228}
229
230
231unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
232  switch (DeclKind) {
233    case Function:
234    case CXXMethod:
235    case CXXConstructor:
236    case CXXDestructor:
237    case CXXConversion:
238    case EnumConstant:
239    case Var:
240    case ImplicitParam:
241    case ParmVar:
242    case NonTypeTemplateParm:
243    case ObjCMethod:
244    case ObjCProperty:
245      return IDNS_Ordinary;
246
247    case ObjCCompatibleAlias:
248    case ObjCInterface:
249      return IDNS_Ordinary | IDNS_Type;
250
251    case Typedef:
252    case UnresolvedUsingTypename:
253    case TemplateTypeParm:
254      return IDNS_Ordinary | IDNS_Type;
255
256    case UsingShadow:
257      return 0; // we'll actually overwrite this later
258
259    case UnresolvedUsingValue:
260      return IDNS_Ordinary | IDNS_Using;
261
262    case Using:
263      return IDNS_Using;
264
265    case ObjCProtocol:
266      return IDNS_ObjCProtocol;
267
268    case Field:
269    case ObjCAtDefsField:
270    case ObjCIvar:
271      return IDNS_Member;
272
273    case Record:
274    case CXXRecord:
275    case Enum:
276      return IDNS_Tag | IDNS_Type;
277
278    case Namespace:
279    case NamespaceAlias:
280      return IDNS_Namespace;
281
282    case FunctionTemplate:
283      return IDNS_Ordinary;
284
285    case ClassTemplate:
286    case TemplateTemplateParm:
287      return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
288
289    // Never have names.
290    case Friend:
291    case FriendTemplate:
292    case AccessSpec:
293    case LinkageSpec:
294    case FileScopeAsm:
295    case StaticAssert:
296    case ObjCClass:
297    case ObjCPropertyImpl:
298    case ObjCForwardProtocol:
299    case Block:
300    case TranslationUnit:
301
302    case UsingDirective:
303    case ClassTemplateSpecialization:
304    case ClassTemplatePartialSpecialization:
305    case ObjCImplementation:
306    case ObjCCategory:
307    case ObjCCategoryImpl:
308      // Never looked up by name.
309      return 0;
310  }
311
312  return 0;
313}
314
315void Decl::setAttrs(const AttrVec &attrs) {
316  assert(!HasAttrs && "Decl already contains attrs.");
317
318  AttrVec &AttrBlank = getASTContext().getDeclAttrs(this);
319  assert(AttrBlank.empty() && "HasAttrs was wrong?");
320
321  AttrBlank = attrs;
322  HasAttrs = true;
323}
324
325void Decl::dropAttrs() {
326  if (!HasAttrs) return;
327
328  HasAttrs = false;
329  getASTContext().eraseDeclAttrs(this);
330}
331
332const AttrVec &Decl::getAttrs() const {
333  assert(HasAttrs && "No attrs to get!");
334  return getASTContext().getDeclAttrs(this);
335}
336
337void Decl::swapAttrs(Decl *RHS) {
338  bool HasLHSAttr = this->HasAttrs;
339  bool HasRHSAttr = RHS->HasAttrs;
340
341  // Usually, neither decl has attrs, nothing to do.
342  if (!HasLHSAttr && !HasRHSAttr) return;
343
344  // If 'this' has no attrs, swap the other way.
345  if (!HasLHSAttr)
346    return RHS->swapAttrs(this);
347
348  ASTContext &Context = getASTContext();
349
350  // Handle the case when both decls have attrs.
351  if (HasRHSAttr) {
352    std::swap(Context.getDeclAttrs(this), Context.getDeclAttrs(RHS));
353    return;
354  }
355
356  // Otherwise, LHS has an attr and RHS doesn't.
357  Context.getDeclAttrs(RHS) = Context.getDeclAttrs(this);
358  Context.eraseDeclAttrs(this);
359  this->HasAttrs = false;
360  RHS->HasAttrs = true;
361}
362
363Decl *Decl::castFromDeclContext (const DeclContext *D) {
364  Decl::Kind DK = D->getDeclKind();
365  switch(DK) {
366#define DECL(NAME, BASE)
367#define DECL_CONTEXT(NAME) \
368    case Decl::NAME:       \
369      return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
370#define DECL_CONTEXT_BASE(NAME)
371#include "clang/AST/DeclNodes.inc"
372    default:
373#define DECL(NAME, BASE)
374#define DECL_CONTEXT_BASE(NAME)                  \
375      if (DK >= first##NAME && DK <= last##NAME) \
376        return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
377#include "clang/AST/DeclNodes.inc"
378      assert(false && "a decl that inherits DeclContext isn't handled");
379      return 0;
380  }
381}
382
383DeclContext *Decl::castToDeclContext(const Decl *D) {
384  Decl::Kind DK = D->getKind();
385  switch(DK) {
386#define DECL(NAME, BASE)
387#define DECL_CONTEXT(NAME) \
388    case Decl::NAME:       \
389      return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
390#define DECL_CONTEXT_BASE(NAME)
391#include "clang/AST/DeclNodes.inc"
392    default:
393#define DECL(NAME, BASE)
394#define DECL_CONTEXT_BASE(NAME)                                   \
395      if (DK >= first##NAME && DK <= last##NAME)                  \
396        return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
397#include "clang/AST/DeclNodes.inc"
398      assert(false && "a decl that inherits DeclContext isn't handled");
399      return 0;
400  }
401}
402
403SourceLocation Decl::getBodyRBrace() const {
404  // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
405  // FunctionDecl stores EndRangeLoc for this purpose.
406  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
407    const FunctionDecl *Definition;
408    if (FD->hasBody(Definition))
409      return Definition->getSourceRange().getEnd();
410    return SourceLocation();
411  }
412
413  if (Stmt *Body = getBody())
414    return Body->getSourceRange().getEnd();
415
416  return SourceLocation();
417}
418
419#ifndef NDEBUG
420void Decl::CheckAccessDeclContext() const {
421  // FIXME: Disable this until rdar://8146294 "access specifier for inner class
422  // templates is not set or checked" is fixed.
423  return;
424  // Suppress this check if any of the following hold:
425  // 1. this is the translation unit (and thus has no parent)
426  // 2. this is a template parameter (and thus doesn't belong to its context)
427  // 3. the context is not a record
428  // 4. it's invalid
429  if (isa<TranslationUnitDecl>(this) ||
430      isa<TemplateTypeParmDecl>(this) ||
431      !isa<CXXRecordDecl>(getDeclContext()) ||
432      isInvalidDecl())
433    return;
434
435  assert(Access != AS_none &&
436         "Access specifier is AS_none inside a record decl");
437}
438
439#endif
440
441//===----------------------------------------------------------------------===//
442// DeclContext Implementation
443//===----------------------------------------------------------------------===//
444
445bool DeclContext::classof(const Decl *D) {
446  switch (D->getKind()) {
447#define DECL(NAME, BASE)
448#define DECL_CONTEXT(NAME) case Decl::NAME:
449#define DECL_CONTEXT_BASE(NAME)
450#include "clang/AST/DeclNodes.inc"
451      return true;
452    default:
453#define DECL(NAME, BASE)
454#define DECL_CONTEXT_BASE(NAME)                 \
455      if (D->getKind() >= Decl::first##NAME &&  \
456          D->getKind() <= Decl::last##NAME)     \
457        return true;
458#include "clang/AST/DeclNodes.inc"
459      return false;
460  }
461}
462
463DeclContext::~DeclContext() { }
464
465/// \brief Find the parent context of this context that will be
466/// used for unqualified name lookup.
467///
468/// Generally, the parent lookup context is the semantic context. However, for
469/// a friend function the parent lookup context is the lexical context, which
470/// is the class in which the friend is declared.
471DeclContext *DeclContext::getLookupParent() {
472  // FIXME: Find a better way to identify friends
473  if (isa<FunctionDecl>(this))
474    if (getParent()->getLookupContext()->isFileContext() &&
475        getLexicalParent()->getLookupContext()->isRecord())
476      return getLexicalParent();
477
478  return getParent();
479}
480
481bool DeclContext::isDependentContext() const {
482  if (isFileContext())
483    return false;
484
485  if (isa<ClassTemplatePartialSpecializationDecl>(this))
486    return true;
487
488  if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
489    if (Record->getDescribedClassTemplate())
490      return true;
491
492  if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
493    if (Function->getDescribedFunctionTemplate())
494      return true;
495
496    // Friend function declarations are dependent if their *lexical*
497    // context is dependent.
498    if (cast<Decl>(this)->getFriendObjectKind())
499      return getLexicalParent()->isDependentContext();
500  }
501
502  return getParent() && getParent()->isDependentContext();
503}
504
505bool DeclContext::isTransparentContext() const {
506  if (DeclKind == Decl::Enum)
507    return true; // FIXME: Check for C++0x scoped enums
508  else if (DeclKind == Decl::LinkageSpec)
509    return true;
510  else if (DeclKind >= Decl::firstRecord && DeclKind <= Decl::lastRecord)
511    return cast<RecordDecl>(this)->isAnonymousStructOrUnion();
512  else if (DeclKind == Decl::Namespace)
513    return false; // FIXME: Check for C++0x inline namespaces
514
515  return false;
516}
517
518bool DeclContext::Encloses(DeclContext *DC) {
519  if (getPrimaryContext() != this)
520    return getPrimaryContext()->Encloses(DC);
521
522  for (; DC; DC = DC->getParent())
523    if (DC->getPrimaryContext() == this)
524      return true;
525  return false;
526}
527
528DeclContext *DeclContext::getPrimaryContext() {
529  switch (DeclKind) {
530  case Decl::TranslationUnit:
531  case Decl::LinkageSpec:
532  case Decl::Block:
533    // There is only one DeclContext for these entities.
534    return this;
535
536  case Decl::Namespace:
537    // The original namespace is our primary context.
538    return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
539
540  case Decl::ObjCMethod:
541    return this;
542
543  case Decl::ObjCInterface:
544  case Decl::ObjCProtocol:
545  case Decl::ObjCCategory:
546    // FIXME: Can Objective-C interfaces be forward-declared?
547    return this;
548
549  case Decl::ObjCImplementation:
550  case Decl::ObjCCategoryImpl:
551    return this;
552
553  default:
554    if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
555      // If this is a tag type that has a definition or is currently
556      // being defined, that definition is our primary context.
557      TagDecl *Tag = cast<TagDecl>(this);
558      assert(isa<TagType>(Tag->TypeForDecl) ||
559             isa<InjectedClassNameType>(Tag->TypeForDecl));
560
561      if (TagDecl *Def = Tag->getDefinition())
562        return Def;
563
564      if (!isa<InjectedClassNameType>(Tag->TypeForDecl)) {
565        const TagType *TagTy = cast<TagType>(Tag->TypeForDecl);
566        if (TagTy->isBeingDefined())
567          // FIXME: is it necessarily being defined in the decl
568          // that owns the type?
569          return TagTy->getDecl();
570      }
571
572      return Tag;
573    }
574
575    assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
576          "Unknown DeclContext kind");
577    return this;
578  }
579}
580
581DeclContext *DeclContext::getNextContext() {
582  switch (DeclKind) {
583  case Decl::Namespace:
584    // Return the next namespace
585    return static_cast<NamespaceDecl*>(this)->getNextNamespace();
586
587  default:
588    return 0;
589  }
590}
591
592/// \brief Load the declarations within this lexical storage from an
593/// external source.
594void
595DeclContext::LoadLexicalDeclsFromExternalStorage() const {
596  ExternalASTSource *Source = getParentASTContext().getExternalSource();
597  assert(hasExternalLexicalStorage() && Source && "No external storage?");
598
599  // Notify that we have a DeclContext that is initializing.
600  ExternalASTSource::Deserializing ADeclContext(Source);
601
602  llvm::SmallVector<Decl*, 64> Decls;
603  if (Source->FindExternalLexicalDecls(this, Decls))
604    return;
605
606  // There is no longer any lexical storage in this context
607  ExternalLexicalStorage = false;
608
609  if (Decls.empty())
610    return;
611
612  // Resolve all of the declaration IDs into declarations, building up
613  // a chain of declarations via the Decl::NextDeclInContext field.
614  Decl *FirstNewDecl = 0;
615  Decl *PrevDecl = 0;
616  for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
617    Decl *D = Decls[I];
618    if (PrevDecl)
619      PrevDecl->NextDeclInContext = D;
620    else
621      FirstNewDecl = D;
622
623    PrevDecl = D;
624  }
625
626  // Splice the newly-read declarations into the beginning of the list
627  // of declarations.
628  PrevDecl->NextDeclInContext = FirstDecl;
629  FirstDecl = FirstNewDecl;
630  if (!LastDecl)
631    LastDecl = PrevDecl;
632}
633
634DeclContext::lookup_result
635ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
636                                                    DeclarationName Name) {
637  ASTContext &Context = DC->getParentASTContext();
638  StoredDeclsMap *Map;
639  if (!(Map = DC->LookupPtr))
640    Map = DC->CreateStoredDeclsMap(Context);
641
642  StoredDeclsList &List = (*Map)[Name];
643  assert(List.isNull());
644  (void) List;
645
646  return DeclContext::lookup_result();
647}
648
649DeclContext::lookup_result
650ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
651                                                  DeclarationName Name,
652                                    llvm::SmallVectorImpl<NamedDecl*> &Decls) {
653  ASTContext &Context = DC->getParentASTContext();;
654
655  StoredDeclsMap *Map;
656  if (!(Map = DC->LookupPtr))
657    Map = DC->CreateStoredDeclsMap(Context);
658
659  StoredDeclsList &List = (*Map)[Name];
660  for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
661    if (List.isNull())
662      List.setOnlyValue(Decls[I]);
663    else
664      List.AddSubsequentDecl(Decls[I]);
665  }
666
667  return List.getLookupResult();
668}
669
670DeclContext::decl_iterator DeclContext::noload_decls_begin() const {
671  return decl_iterator(FirstDecl);
672}
673
674DeclContext::decl_iterator DeclContext::noload_decls_end() const {
675  return decl_iterator();
676}
677
678DeclContext::decl_iterator DeclContext::decls_begin() const {
679  if (hasExternalLexicalStorage())
680    LoadLexicalDeclsFromExternalStorage();
681
682  // FIXME: Check whether we need to load some declarations from
683  // external storage.
684  return decl_iterator(FirstDecl);
685}
686
687DeclContext::decl_iterator DeclContext::decls_end() const {
688  if (hasExternalLexicalStorage())
689    LoadLexicalDeclsFromExternalStorage();
690
691  return decl_iterator();
692}
693
694bool DeclContext::decls_empty() const {
695  if (hasExternalLexicalStorage())
696    LoadLexicalDeclsFromExternalStorage();
697
698  return !FirstDecl;
699}
700
701void DeclContext::removeDecl(Decl *D) {
702  assert(D->getLexicalDeclContext() == this &&
703         "decl being removed from non-lexical context");
704  assert((D->NextDeclInContext || D == LastDecl) &&
705         "decl is not in decls list");
706
707  // Remove D from the decl chain.  This is O(n) but hopefully rare.
708  if (D == FirstDecl) {
709    if (D == LastDecl)
710      FirstDecl = LastDecl = 0;
711    else
712      FirstDecl = D->NextDeclInContext;
713  } else {
714    for (Decl *I = FirstDecl; true; I = I->NextDeclInContext) {
715      assert(I && "decl not found in linked list");
716      if (I->NextDeclInContext == D) {
717        I->NextDeclInContext = D->NextDeclInContext;
718        if (D == LastDecl) LastDecl = I;
719        break;
720      }
721    }
722  }
723
724  // Mark that D is no longer in the decl chain.
725  D->NextDeclInContext = 0;
726
727  // Remove D from the lookup table if necessary.
728  if (isa<NamedDecl>(D)) {
729    NamedDecl *ND = cast<NamedDecl>(D);
730
731    StoredDeclsMap *Map = getPrimaryContext()->LookupPtr;
732    if (!Map) return;
733
734    StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
735    assert(Pos != Map->end() && "no lookup entry for decl");
736    Pos->second.remove(ND);
737  }
738}
739
740void DeclContext::addHiddenDecl(Decl *D) {
741  assert(D->getLexicalDeclContext() == this &&
742         "Decl inserted into wrong lexical context");
743  assert(!D->getNextDeclInContext() && D != LastDecl &&
744         "Decl already inserted into a DeclContext");
745
746  if (FirstDecl) {
747    LastDecl->NextDeclInContext = D;
748    LastDecl = D;
749  } else {
750    FirstDecl = LastDecl = D;
751  }
752}
753
754void DeclContext::addDecl(Decl *D) {
755  addHiddenDecl(D);
756
757  if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
758    ND->getDeclContext()->makeDeclVisibleInContext(ND);
759}
760
761/// buildLookup - Build the lookup data structure with all of the
762/// declarations in DCtx (and any other contexts linked to it or
763/// transparent contexts nested within it).
764void DeclContext::buildLookup(DeclContext *DCtx) {
765  for (; DCtx; DCtx = DCtx->getNextContext()) {
766    for (decl_iterator D = DCtx->decls_begin(),
767                    DEnd = DCtx->decls_end();
768         D != DEnd; ++D) {
769      // Insert this declaration into the lookup structure, but only
770      // if it's semantically in its decl context.  During non-lazy
771      // lookup building, this is implicitly enforced by addDecl.
772      if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
773        if (D->getDeclContext() == DCtx)
774          makeDeclVisibleInContextImpl(ND);
775
776      // Insert any forward-declared Objective-C interfaces into the lookup
777      // data structure.
778      if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D))
779        for (ObjCClassDecl::iterator I = Class->begin(), IEnd = Class->end();
780             I != IEnd; ++I)
781          makeDeclVisibleInContextImpl(I->getInterface());
782
783      // If this declaration is itself a transparent declaration context,
784      // add its members (recursively).
785      if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D))
786        if (InnerCtx->isTransparentContext())
787          buildLookup(InnerCtx->getPrimaryContext());
788    }
789  }
790}
791
792DeclContext::lookup_result
793DeclContext::lookup(DeclarationName Name) {
794  DeclContext *PrimaryContext = getPrimaryContext();
795  if (PrimaryContext != this)
796    return PrimaryContext->lookup(Name);
797
798  if (hasExternalVisibleStorage()) {
799    // Check to see if we've already cached the lookup results.
800    if (LookupPtr) {
801      StoredDeclsMap::iterator I = LookupPtr->find(Name);
802      if (I != LookupPtr->end())
803        return I->second.getLookupResult();
804    }
805
806    ExternalASTSource *Source = getParentASTContext().getExternalSource();
807    return Source->FindExternalVisibleDeclsByName(this, Name);
808  }
809
810  /// If there is no lookup data structure, build one now by walking
811  /// all of the linked DeclContexts (in declaration order!) and
812  /// inserting their values.
813  if (!LookupPtr) {
814    buildLookup(this);
815
816    if (!LookupPtr)
817      return lookup_result(lookup_iterator(0), lookup_iterator(0));
818  }
819
820  StoredDeclsMap::iterator Pos = LookupPtr->find(Name);
821  if (Pos == LookupPtr->end())
822    return lookup_result(lookup_iterator(0), lookup_iterator(0));
823  return Pos->second.getLookupResult();
824}
825
826DeclContext::lookup_const_result
827DeclContext::lookup(DeclarationName Name) const {
828  return const_cast<DeclContext*>(this)->lookup(Name);
829}
830
831DeclContext *DeclContext::getLookupContext() {
832  DeclContext *Ctx = this;
833  // Skip through transparent contexts.
834  while (Ctx->isTransparentContext())
835    Ctx = Ctx->getParent();
836  return Ctx;
837}
838
839DeclContext *DeclContext::getEnclosingNamespaceContext() {
840  DeclContext *Ctx = this;
841  // Skip through non-namespace, non-translation-unit contexts.
842  while (!Ctx->isFileContext() || Ctx->isTransparentContext())
843    Ctx = Ctx->getParent();
844  return Ctx->getPrimaryContext();
845}
846
847void DeclContext::makeDeclVisibleInContext(NamedDecl *D, bool Recoverable) {
848  // FIXME: This feels like a hack. Should DeclarationName support
849  // template-ids, or is there a better way to keep specializations
850  // from being visible?
851  if (isa<ClassTemplateSpecializationDecl>(D))
852    return;
853  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
854    if (FD->isFunctionTemplateSpecialization())
855      return;
856
857  DeclContext *PrimaryContext = getPrimaryContext();
858  if (PrimaryContext != this) {
859    PrimaryContext->makeDeclVisibleInContext(D, Recoverable);
860    return;
861  }
862
863  // If we already have a lookup data structure, perform the insertion
864  // into it. If we haven't deserialized externally stored decls, deserialize
865  // them so we can add the decl. Otherwise, be lazy and don't build that
866  // structure until someone asks for it.
867  if (LookupPtr || !Recoverable || hasExternalVisibleStorage())
868    makeDeclVisibleInContextImpl(D);
869
870  // If we are a transparent context, insert into our parent context,
871  // too. This operation is recursive.
872  if (isTransparentContext())
873    getParent()->makeDeclVisibleInContext(D, Recoverable);
874}
875
876void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D) {
877  // Skip unnamed declarations.
878  if (!D->getDeclName())
879    return;
880
881  // FIXME: This feels like a hack. Should DeclarationName support
882  // template-ids, or is there a better way to keep specializations
883  // from being visible?
884  if (isa<ClassTemplateSpecializationDecl>(D))
885    return;
886
887  ASTContext *C = 0;
888  if (!LookupPtr) {
889    C = &getParentASTContext();
890    CreateStoredDeclsMap(*C);
891  }
892
893  // If there is an external AST source, load any declarations it knows about
894  // with this declaration's name.
895  // If the lookup table contains an entry about this name it means that we
896  // have already checked the external source.
897  if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
898    if (hasExternalVisibleStorage() &&
899        LookupPtr->find(D->getDeclName()) == LookupPtr->end())
900      Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
901
902  // Insert this declaration into the map.
903  StoredDeclsList &DeclNameEntries = (*LookupPtr)[D->getDeclName()];
904  if (DeclNameEntries.isNull()) {
905    DeclNameEntries.setOnlyValue(D);
906    return;
907  }
908
909  // If it is possible that this is a redeclaration, check to see if there is
910  // already a decl for which declarationReplaces returns true.  If there is
911  // one, just replace it and return.
912  if (DeclNameEntries.HandleRedeclaration(D))
913    return;
914
915  // Put this declaration into the appropriate slot.
916  DeclNameEntries.AddSubsequentDecl(D);
917}
918
919/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
920/// this context.
921DeclContext::udir_iterator_range
922DeclContext::getUsingDirectives() const {
923  lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
924  return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.first),
925                             reinterpret_cast<udir_iterator>(Result.second));
926}
927
928//===----------------------------------------------------------------------===//
929// Creation and Destruction of StoredDeclsMaps.                               //
930//===----------------------------------------------------------------------===//
931
932StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
933  assert(!LookupPtr && "context already has a decls map");
934  assert(getPrimaryContext() == this &&
935         "creating decls map on non-primary context");
936
937  StoredDeclsMap *M;
938  bool Dependent = isDependentContext();
939  if (Dependent)
940    M = new DependentStoredDeclsMap();
941  else
942    M = new StoredDeclsMap();
943  M->Previous = C.LastSDM;
944  C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
945  LookupPtr = M;
946  return M;
947}
948
949void ASTContext::ReleaseDeclContextMaps() {
950  // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
951  // pointer because the subclass doesn't add anything that needs to
952  // be deleted.
953  StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
954}
955
956void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
957  while (Map) {
958    // Advance the iteration before we invalidate memory.
959    llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
960
961    if (Dependent)
962      delete static_cast<DependentStoredDeclsMap*>(Map);
963    else
964      delete Map;
965
966    Map = Next.getPointer();
967    Dependent = Next.getInt();
968  }
969}
970
971DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
972                                                 DeclContext *Parent,
973                                           const PartialDiagnostic &PDiag) {
974  assert(Parent->isDependentContext()
975         && "cannot iterate dependent diagnostics of non-dependent context");
976  Parent = Parent->getPrimaryContext();
977  if (!Parent->LookupPtr)
978    Parent->CreateStoredDeclsMap(C);
979
980  DependentStoredDeclsMap *Map
981    = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr);
982
983  // Allocate the copy of the PartialDiagnostic via the ASTContext's
984  // BumpPtrAllocator, rather than the ASTContext itself.
985  PartialDiagnostic::Storage *DiagStorage = 0;
986  if (PDiag.hasStorage())
987    DiagStorage = new (C) PartialDiagnostic::Storage;
988
989  DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
990
991  // TODO: Maybe we shouldn't reverse the order during insertion.
992  DD->NextDiagnostic = Map->FirstDiagnostic;
993  Map->FirstDiagnostic = DD;
994
995  return DD;
996}
997