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