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