DeclBase.cpp revision f4a03cc2b022fab0ffac6c65449555c52036dece
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
432SourceLocation Decl::getBodyRBrace() const {
433  // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
434  // FunctionDecl stores EndRangeLoc for this purpose.
435  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
436    const FunctionDecl *Definition;
437    if (FD->hasBody(Definition))
438      return Definition->getSourceRange().getEnd();
439    return SourceLocation();
440  }
441
442  if (Stmt *Body = getBody())
443    return Body->getSourceRange().getEnd();
444
445  return SourceLocation();
446}
447
448void Decl::CheckAccessDeclContext() const {
449#ifndef NDEBUG
450  // Suppress this check if any of the following hold:
451  // 1. this is the translation unit (and thus has no parent)
452  // 2. this is a template parameter (and thus doesn't belong to its context)
453  // 3. this is a non-type template parameter
454  // 4. the context is not a record
455  // 5. it's invalid
456  // 6. it's a C++0x static_assert.
457  if (isa<TranslationUnitDecl>(this) ||
458      isa<TemplateTypeParmDecl>(this) ||
459      isa<NonTypeTemplateParmDecl>(this) ||
460      !isa<CXXRecordDecl>(getDeclContext()) ||
461      isInvalidDecl() ||
462      isa<StaticAssertDecl>(this) ||
463      // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
464      // as DeclContext (?).
465      isa<ParmVarDecl>(this) ||
466      // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
467      // AS_none as access specifier.
468      isa<CXXRecordDecl>(this))
469    return;
470
471  assert(Access != AS_none &&
472         "Access specifier is AS_none inside a record decl");
473#endif
474}
475
476
477//===----------------------------------------------------------------------===//
478// DeclContext Implementation
479//===----------------------------------------------------------------------===//
480
481bool DeclContext::classof(const Decl *D) {
482  switch (D->getKind()) {
483#define DECL(NAME, BASE)
484#define DECL_CONTEXT(NAME) case Decl::NAME:
485#define DECL_CONTEXT_BASE(NAME)
486#include "clang/AST/DeclNodes.inc"
487      return true;
488    default:
489#define DECL(NAME, BASE)
490#define DECL_CONTEXT_BASE(NAME)                 \
491      if (D->getKind() >= Decl::first##NAME &&  \
492          D->getKind() <= Decl::last##NAME)     \
493        return true;
494#include "clang/AST/DeclNodes.inc"
495      return false;
496  }
497}
498
499DeclContext::~DeclContext() { }
500
501/// \brief Find the parent context of this context that will be
502/// used for unqualified name lookup.
503///
504/// Generally, the parent lookup context is the semantic context. However, for
505/// a friend function the parent lookup context is the lexical context, which
506/// is the class in which the friend is declared.
507DeclContext *DeclContext::getLookupParent() {
508  // FIXME: Find a better way to identify friends
509  if (isa<FunctionDecl>(this))
510    if (getParent()->getRedeclContext()->isFileContext() &&
511        getLexicalParent()->getRedeclContext()->isRecord())
512      return getLexicalParent();
513
514  return getParent();
515}
516
517bool DeclContext::isInlineNamespace() const {
518  return isNamespace() &&
519         cast<NamespaceDecl>(this)->isInline();
520}
521
522bool DeclContext::isDependentContext() const {
523  if (isFileContext())
524    return false;
525
526  if (isa<ClassTemplatePartialSpecializationDecl>(this))
527    return true;
528
529  if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
530    if (Record->getDescribedClassTemplate())
531      return true;
532
533  if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
534    if (Function->getDescribedFunctionTemplate())
535      return true;
536
537    // Friend function declarations are dependent if their *lexical*
538    // context is dependent.
539    if (cast<Decl>(this)->getFriendObjectKind())
540      return getLexicalParent()->isDependentContext();
541  }
542
543  return getParent() && getParent()->isDependentContext();
544}
545
546bool DeclContext::isTransparentContext() const {
547  if (DeclKind == Decl::Enum)
548    return !cast<EnumDecl>(this)->isScoped();
549  else if (DeclKind == Decl::LinkageSpec)
550    return true;
551
552  return false;
553}
554
555bool DeclContext::isExternCContext() const {
556  const DeclContext *DC = this;
557  while (DC->DeclKind != Decl::TranslationUnit) {
558    if (DC->DeclKind == Decl::LinkageSpec)
559      return cast<LinkageSpecDecl>(DC)->getLanguage()
560        == LinkageSpecDecl::lang_c;
561    DC = DC->getParent();
562  }
563  return false;
564}
565
566bool DeclContext::Encloses(const DeclContext *DC) const {
567  if (getPrimaryContext() != this)
568    return getPrimaryContext()->Encloses(DC);
569
570  for (; DC; DC = DC->getParent())
571    if (DC->getPrimaryContext() == this)
572      return true;
573  return false;
574}
575
576DeclContext *DeclContext::getPrimaryContext() {
577  switch (DeclKind) {
578  case Decl::TranslationUnit:
579  case Decl::LinkageSpec:
580  case Decl::Block:
581    // There is only one DeclContext for these entities.
582    return this;
583
584  case Decl::Namespace:
585    // The original namespace is our primary context.
586    return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
587
588  case Decl::ObjCMethod:
589    return this;
590
591  case Decl::ObjCInterface:
592  case Decl::ObjCProtocol:
593  case Decl::ObjCCategory:
594    // FIXME: Can Objective-C interfaces be forward-declared?
595    return this;
596
597  case Decl::ObjCImplementation:
598  case Decl::ObjCCategoryImpl:
599    return this;
600
601  default:
602    if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
603      // If this is a tag type that has a definition or is currently
604      // being defined, that definition is our primary context.
605      TagDecl *Tag = cast<TagDecl>(this);
606      assert(isa<TagType>(Tag->TypeForDecl) ||
607             isa<InjectedClassNameType>(Tag->TypeForDecl));
608
609      if (TagDecl *Def = Tag->getDefinition())
610        return Def;
611
612      if (!isa<InjectedClassNameType>(Tag->TypeForDecl)) {
613        const TagType *TagTy = cast<TagType>(Tag->TypeForDecl);
614        if (TagTy->isBeingDefined())
615          // FIXME: is it necessarily being defined in the decl
616          // that owns the type?
617          return TagTy->getDecl();
618      }
619
620      return Tag;
621    }
622
623    assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
624          "Unknown DeclContext kind");
625    return this;
626  }
627}
628
629DeclContext *DeclContext::getNextContext() {
630  switch (DeclKind) {
631  case Decl::Namespace:
632    // Return the next namespace
633    return static_cast<NamespaceDecl*>(this)->getNextNamespace();
634
635  default:
636    return 0;
637  }
638}
639
640std::pair<Decl *, Decl *>
641DeclContext::BuildDeclChain(const llvm::SmallVectorImpl<Decl*> &Decls) {
642  // Build up a chain of declarations via the Decl::NextDeclInContext field.
643  Decl *FirstNewDecl = 0;
644  Decl *PrevDecl = 0;
645  for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
646    Decl *D = Decls[I];
647    if (PrevDecl)
648      PrevDecl->NextDeclInContext = D;
649    else
650      FirstNewDecl = D;
651
652    PrevDecl = D;
653  }
654
655  return std::make_pair(FirstNewDecl, PrevDecl);
656}
657
658/// \brief Load the declarations within this lexical storage from an
659/// external source.
660void
661DeclContext::LoadLexicalDeclsFromExternalStorage() const {
662  ExternalASTSource *Source = getParentASTContext().getExternalSource();
663  assert(hasExternalLexicalStorage() && Source && "No external storage?");
664
665  // Notify that we have a DeclContext that is initializing.
666  ExternalASTSource::Deserializing ADeclContext(Source);
667
668  llvm::SmallVector<Decl*, 64> Decls;
669  if (Source->FindExternalLexicalDecls(this, Decls))
670    return;
671
672  // There is no longer any lexical storage in this context
673  ExternalLexicalStorage = false;
674
675  if (Decls.empty())
676    return;
677
678  // We may have already loaded just the fields of this record, in which case
679  // don't add the decls, just replace the FirstDecl/LastDecl chain.
680  if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
681    if (RD->LoadedFieldsFromExternalStorage) {
682      llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls);
683      return;
684    }
685
686  // Splice the newly-read declarations into the beginning of the list
687  // of declarations.
688  Decl *ExternalFirst, *ExternalLast;
689  llvm::tie(ExternalFirst, ExternalLast) = BuildDeclChain(Decls);
690  ExternalLast->NextDeclInContext = FirstDecl;
691  FirstDecl = ExternalFirst;
692  if (!LastDecl)
693    LastDecl = ExternalLast;
694}
695
696DeclContext::lookup_result
697ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
698                                                    DeclarationName Name) {
699  ASTContext &Context = DC->getParentASTContext();
700  StoredDeclsMap *Map;
701  if (!(Map = DC->LookupPtr))
702    Map = DC->CreateStoredDeclsMap(Context);
703
704  StoredDeclsList &List = (*Map)[Name];
705  assert(List.isNull());
706  (void) List;
707
708  return DeclContext::lookup_result();
709}
710
711DeclContext::lookup_result
712ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
713                                                  DeclarationName Name,
714                                    llvm::SmallVectorImpl<NamedDecl*> &Decls) {
715  ASTContext &Context = DC->getParentASTContext();;
716
717  StoredDeclsMap *Map;
718  if (!(Map = DC->LookupPtr))
719    Map = DC->CreateStoredDeclsMap(Context);
720
721  StoredDeclsList &List = (*Map)[Name];
722  for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
723    if (List.isNull())
724      List.setOnlyValue(Decls[I]);
725    else
726      List.AddSubsequentDecl(Decls[I]);
727  }
728
729  return List.getLookupResult();
730}
731
732void ExternalASTSource::MaterializeVisibleDeclsForName(const DeclContext *DC,
733                                                       DeclarationName Name,
734                                     llvm::SmallVectorImpl<NamedDecl*> &Decls) {
735  assert(DC->LookupPtr);
736  StoredDeclsMap &Map = *DC->LookupPtr;
737
738  // If there's an entry in the table the visible decls for this name have
739  // already been deserialized.
740  if (Map.find(Name) == Map.end()) {
741    StoredDeclsList &List = Map[Name];
742    for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
743      if (List.isNull())
744        List.setOnlyValue(Decls[I]);
745      else
746        List.AddSubsequentDecl(Decls[I]);
747    }
748  }
749}
750
751DeclContext::decl_iterator DeclContext::noload_decls_begin() const {
752  return decl_iterator(FirstDecl);
753}
754
755DeclContext::decl_iterator DeclContext::noload_decls_end() const {
756  return decl_iterator();
757}
758
759DeclContext::decl_iterator DeclContext::decls_begin() const {
760  if (hasExternalLexicalStorage())
761    LoadLexicalDeclsFromExternalStorage();
762
763  // FIXME: Check whether we need to load some declarations from
764  // external storage.
765  return decl_iterator(FirstDecl);
766}
767
768DeclContext::decl_iterator DeclContext::decls_end() const {
769  if (hasExternalLexicalStorage())
770    LoadLexicalDeclsFromExternalStorage();
771
772  return decl_iterator();
773}
774
775bool DeclContext::decls_empty() const {
776  if (hasExternalLexicalStorage())
777    LoadLexicalDeclsFromExternalStorage();
778
779  return !FirstDecl;
780}
781
782void DeclContext::removeDecl(Decl *D) {
783  assert(D->getLexicalDeclContext() == this &&
784         "decl being removed from non-lexical context");
785  assert((D->NextDeclInContext || D == LastDecl) &&
786         "decl is not in decls list");
787
788  // Remove D from the decl chain.  This is O(n) but hopefully rare.
789  if (D == FirstDecl) {
790    if (D == LastDecl)
791      FirstDecl = LastDecl = 0;
792    else
793      FirstDecl = D->NextDeclInContext;
794  } else {
795    for (Decl *I = FirstDecl; true; I = I->NextDeclInContext) {
796      assert(I && "decl not found in linked list");
797      if (I->NextDeclInContext == D) {
798        I->NextDeclInContext = D->NextDeclInContext;
799        if (D == LastDecl) LastDecl = I;
800        break;
801      }
802    }
803  }
804
805  // Mark that D is no longer in the decl chain.
806  D->NextDeclInContext = 0;
807
808  // Remove D from the lookup table if necessary.
809  if (isa<NamedDecl>(D)) {
810    NamedDecl *ND = cast<NamedDecl>(D);
811
812    StoredDeclsMap *Map = getPrimaryContext()->LookupPtr;
813    if (!Map) return;
814
815    StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
816    assert(Pos != Map->end() && "no lookup entry for decl");
817    Pos->second.remove(ND);
818  }
819}
820
821void DeclContext::addHiddenDecl(Decl *D) {
822  assert(D->getLexicalDeclContext() == this &&
823         "Decl inserted into wrong lexical context");
824  assert(!D->getNextDeclInContext() && D != LastDecl &&
825         "Decl already inserted into a DeclContext");
826
827  if (FirstDecl) {
828    LastDecl->NextDeclInContext = D;
829    LastDecl = D;
830  } else {
831    FirstDecl = LastDecl = D;
832  }
833
834  // Notify a C++ record declaration that we've added a member, so it can
835  // update it's class-specific state.
836  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
837    Record->addedMember(D);
838}
839
840void DeclContext::addDecl(Decl *D) {
841  addHiddenDecl(D);
842
843  if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
844    ND->getDeclContext()->makeDeclVisibleInContext(ND);
845}
846
847/// buildLookup - Build the lookup data structure with all of the
848/// declarations in DCtx (and any other contexts linked to it or
849/// transparent contexts nested within it).
850void DeclContext::buildLookup(DeclContext *DCtx) {
851  for (; DCtx; DCtx = DCtx->getNextContext()) {
852    for (decl_iterator D = DCtx->decls_begin(),
853                    DEnd = DCtx->decls_end();
854         D != DEnd; ++D) {
855      // Insert this declaration into the lookup structure, but only
856      // if it's semantically in its decl context.  During non-lazy
857      // lookup building, this is implicitly enforced by addDecl.
858      if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
859        if (D->getDeclContext() == DCtx)
860          makeDeclVisibleInContextImpl(ND);
861
862      // Insert any forward-declared Objective-C interfaces into the lookup
863      // data structure.
864      if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D))
865        for (ObjCClassDecl::iterator I = Class->begin(), IEnd = Class->end();
866             I != IEnd; ++I)
867          makeDeclVisibleInContextImpl(I->getInterface());
868
869      // If this declaration is itself a transparent declaration context or
870      // inline namespace, add its members (recursively).
871      if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D))
872        if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
873          buildLookup(InnerCtx->getPrimaryContext());
874    }
875  }
876}
877
878DeclContext::lookup_result
879DeclContext::lookup(DeclarationName Name) {
880  DeclContext *PrimaryContext = getPrimaryContext();
881  if (PrimaryContext != this)
882    return PrimaryContext->lookup(Name);
883
884  if (hasExternalVisibleStorage()) {
885    // Check to see if we've already cached the lookup results.
886    if (LookupPtr) {
887      StoredDeclsMap::iterator I = LookupPtr->find(Name);
888      if (I != LookupPtr->end())
889        return I->second.getLookupResult();
890    }
891
892    ExternalASTSource *Source = getParentASTContext().getExternalSource();
893    return Source->FindExternalVisibleDeclsByName(this, Name);
894  }
895
896  /// If there is no lookup data structure, build one now by walking
897  /// all of the linked DeclContexts (in declaration order!) and
898  /// inserting their values.
899  if (!LookupPtr) {
900    buildLookup(this);
901
902    if (!LookupPtr)
903      return lookup_result(lookup_iterator(0), lookup_iterator(0));
904  }
905
906  StoredDeclsMap::iterator Pos = LookupPtr->find(Name);
907  if (Pos == LookupPtr->end())
908    return lookup_result(lookup_iterator(0), lookup_iterator(0));
909  return Pos->second.getLookupResult();
910}
911
912DeclContext::lookup_const_result
913DeclContext::lookup(DeclarationName Name) const {
914  return const_cast<DeclContext*>(this)->lookup(Name);
915}
916
917DeclContext *DeclContext::getRedeclContext() {
918  DeclContext *Ctx = this;
919  // Skip through transparent contexts.
920  while (Ctx->isTransparentContext())
921    Ctx = Ctx->getParent();
922  return Ctx;
923}
924
925DeclContext *DeclContext::getEnclosingNamespaceContext() {
926  DeclContext *Ctx = this;
927  // Skip through non-namespace, non-translation-unit contexts.
928  while (!Ctx->isFileContext())
929    Ctx = Ctx->getParent();
930  return Ctx->getPrimaryContext();
931}
932
933bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
934  // For non-file contexts, this is equivalent to Equals.
935  if (!isFileContext())
936    return O->Equals(this);
937
938  do {
939    if (O->Equals(this))
940      return true;
941
942    const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
943    if (!NS || !NS->isInline())
944      break;
945    O = NS->getParent();
946  } while (O);
947
948  return false;
949}
950
951void DeclContext::makeDeclVisibleInContext(NamedDecl *D, bool Recoverable) {
952  // FIXME: This feels like a hack. Should DeclarationName support
953  // template-ids, or is there a better way to keep specializations
954  // from being visible?
955  if (isa<ClassTemplateSpecializationDecl>(D))
956    return;
957  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
958    if (FD->isFunctionTemplateSpecialization())
959      return;
960
961  DeclContext *PrimaryContext = getPrimaryContext();
962  if (PrimaryContext != this) {
963    PrimaryContext->makeDeclVisibleInContext(D, Recoverable);
964    return;
965  }
966
967  // If we already have a lookup data structure, perform the insertion
968  // into it. If we haven't deserialized externally stored decls, deserialize
969  // them so we can add the decl. Otherwise, be lazy and don't build that
970  // structure until someone asks for it.
971  if (LookupPtr || !Recoverable || hasExternalVisibleStorage())
972    makeDeclVisibleInContextImpl(D);
973
974  // If we are a transparent context or inline namespace, insert into our
975  // parent context, too. This operation is recursive.
976  if (isTransparentContext() || isInlineNamespace())
977    getParent()->makeDeclVisibleInContext(D, Recoverable);
978
979  Decl *DCAsDecl = cast<Decl>(this);
980  // Notify that a decl was made visible unless it's a Tag being defined.
981  if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
982    if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
983      L->AddedVisibleDecl(this, D);
984}
985
986void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D) {
987  // Skip unnamed declarations.
988  if (!D->getDeclName())
989    return;
990
991  // FIXME: This feels like a hack. Should DeclarationName support
992  // template-ids, or is there a better way to keep specializations
993  // from being visible?
994  if (isa<ClassTemplateSpecializationDecl>(D))
995    return;
996
997  ASTContext *C = 0;
998  if (!LookupPtr) {
999    C = &getParentASTContext();
1000    CreateStoredDeclsMap(*C);
1001  }
1002
1003  // If there is an external AST source, load any declarations it knows about
1004  // with this declaration's name.
1005  // If the lookup table contains an entry about this name it means that we
1006  // have already checked the external source.
1007  if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1008    if (hasExternalVisibleStorage() &&
1009        LookupPtr->find(D->getDeclName()) == LookupPtr->end())
1010      Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1011
1012  // Insert this declaration into the map.
1013  StoredDeclsList &DeclNameEntries = (*LookupPtr)[D->getDeclName()];
1014  if (DeclNameEntries.isNull()) {
1015    DeclNameEntries.setOnlyValue(D);
1016    return;
1017  }
1018
1019  // If it is possible that this is a redeclaration, check to see if there is
1020  // already a decl for which declarationReplaces returns true.  If there is
1021  // one, just replace it and return.
1022  if (DeclNameEntries.HandleRedeclaration(D))
1023    return;
1024
1025  // Put this declaration into the appropriate slot.
1026  DeclNameEntries.AddSubsequentDecl(D);
1027}
1028
1029void DeclContext::MaterializeVisibleDeclsFromExternalStorage() {
1030  ExternalASTSource *Source = getParentASTContext().getExternalSource();
1031  assert(hasExternalVisibleStorage() && Source && "No external storage?");
1032
1033  if (!LookupPtr)
1034    CreateStoredDeclsMap(getParentASTContext());
1035  Source->MaterializeVisibleDecls(this);
1036}
1037
1038/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1039/// this context.
1040DeclContext::udir_iterator_range
1041DeclContext::getUsingDirectives() const {
1042  lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
1043  return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.first),
1044                             reinterpret_cast<udir_iterator>(Result.second));
1045}
1046
1047//===----------------------------------------------------------------------===//
1048// Creation and Destruction of StoredDeclsMaps.                               //
1049//===----------------------------------------------------------------------===//
1050
1051StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1052  assert(!LookupPtr && "context already has a decls map");
1053  assert(getPrimaryContext() == this &&
1054         "creating decls map on non-primary context");
1055
1056  StoredDeclsMap *M;
1057  bool Dependent = isDependentContext();
1058  if (Dependent)
1059    M = new DependentStoredDeclsMap();
1060  else
1061    M = new StoredDeclsMap();
1062  M->Previous = C.LastSDM;
1063  C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1064  LookupPtr = M;
1065  return M;
1066}
1067
1068void ASTContext::ReleaseDeclContextMaps() {
1069  // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1070  // pointer because the subclass doesn't add anything that needs to
1071  // be deleted.
1072  StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1073}
1074
1075void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1076  while (Map) {
1077    // Advance the iteration before we invalidate memory.
1078    llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1079
1080    if (Dependent)
1081      delete static_cast<DependentStoredDeclsMap*>(Map);
1082    else
1083      delete Map;
1084
1085    Map = Next.getPointer();
1086    Dependent = Next.getInt();
1087  }
1088}
1089
1090DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1091                                                 DeclContext *Parent,
1092                                           const PartialDiagnostic &PDiag) {
1093  assert(Parent->isDependentContext()
1094         && "cannot iterate dependent diagnostics of non-dependent context");
1095  Parent = Parent->getPrimaryContext();
1096  if (!Parent->LookupPtr)
1097    Parent->CreateStoredDeclsMap(C);
1098
1099  DependentStoredDeclsMap *Map
1100    = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr);
1101
1102  // Allocate the copy of the PartialDiagnostic via the ASTContext's
1103  // BumpPtrAllocator, rather than the ASTContext itself.
1104  PartialDiagnostic::Storage *DiagStorage = 0;
1105  if (PDiag.hasStorage())
1106    DiagStorage = new (C) PartialDiagnostic::Storage;
1107
1108  DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1109
1110  // TODO: Maybe we shouldn't reverse the order during insertion.
1111  DD->NextDiagnostic = Map->FirstDiagnostic;
1112  Map->FirstDiagnostic = DD;
1113
1114  return DD;
1115}
1116