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