DeclBase.cpp revision bcfd1f55bfbb3e5944cd5e03d07b343e280838c4
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 "clang/Basic/TargetInfo.h"
29#include "llvm/ADT/DenseMap.h"
30#include "llvm/Support/raw_ostream.h"
31#include <algorithm>
32using namespace clang;
33
34//===----------------------------------------------------------------------===//
35//  Statistics
36//===----------------------------------------------------------------------===//
37
38#define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
39#define ABSTRACT_DECL(DECL)
40#include "clang/AST/DeclNodes.inc"
41
42static bool StatSwitch = false;
43
44const char *Decl::getDeclKindName() const {
45  switch (DeclKind) {
46  default: assert(0 && "Declaration not in DeclNodes.inc!");
47#define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
48#define ABSTRACT_DECL(DECL)
49#include "clang/AST/DeclNodes.inc"
50  }
51}
52
53void Decl::setInvalidDecl(bool Invalid) {
54  InvalidDecl = Invalid;
55  if (Invalid) {
56    // Defensive maneuver for ill-formed code: we're likely not to make it to
57    // a point where we set the access specifier, so default it to "public"
58    // to avoid triggering asserts elsewhere in the front end.
59    setAccess(AS_public);
60  }
61}
62
63const char *DeclContext::getDeclKindName() const {
64  switch (DeclKind) {
65  default: assert(0 && "Declaration context not in DeclNodes.inc!");
66#define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
67#define ABSTRACT_DECL(DECL)
68#include "clang/AST/DeclNodes.inc"
69  }
70}
71
72bool Decl::CollectingStats(bool Enable) {
73  if (Enable) StatSwitch = true;
74  return StatSwitch;
75}
76
77void Decl::PrintStats() {
78  llvm::errs() << "\n*** Decl Stats:\n";
79
80  int totalDecls = 0;
81#define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
82#define ABSTRACT_DECL(DECL)
83#include "clang/AST/DeclNodes.inc"
84  llvm::errs() << "  " << totalDecls << " decls total.\n";
85
86  int totalBytes = 0;
87#define DECL(DERIVED, BASE)                                             \
88  if (n##DERIVED##s > 0) {                                              \
89    totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl));         \
90    llvm::errs() << "    " << n##DERIVED##s << " " #DERIVED " decls, "  \
91                 << sizeof(DERIVED##Decl) << " each ("                  \
92                 << n##DERIVED##s * sizeof(DERIVED##Decl)               \
93                 << " bytes)\n";                                        \
94  }
95#define ABSTRACT_DECL(DECL)
96#include "clang/AST/DeclNodes.inc"
97
98  llvm::errs() << "Total bytes = " << totalBytes << "\n";
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(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
244bool Decl::isReferenced() const {
245  if (Referenced)
246    return true;
247
248  // Check redeclarations.
249  for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
250    if (I->Referenced)
251      return true;
252
253  return false;
254}
255
256/// \brief Determine the availability of the given declaration based on
257/// the target platform.
258///
259/// When it returns an availability result other than \c AR_Available,
260/// if the \p Message parameter is non-NULL, it will be set to a
261/// string describing why the entity is unavailable.
262///
263/// FIXME: Make these strings localizable, since they end up in
264/// diagnostics.
265static AvailabilityResult CheckAvailability(ASTContext &Context,
266                                            const AvailabilityAttr *A,
267                                            std::string *Message) {
268  StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
269  StringRef PrettyPlatformName
270    = AvailabilityAttr::getPrettyPlatformName(TargetPlatform);
271  if (PrettyPlatformName.empty())
272    PrettyPlatformName = TargetPlatform;
273
274  VersionTuple TargetMinVersion = Context.getTargetInfo().getPlatformMinVersion();
275  if (TargetMinVersion.empty())
276    return AR_Available;
277
278  // Match the platform name.
279  if (A->getPlatform()->getName() != TargetPlatform)
280    return AR_Available;
281
282  // Make sure that this declaration has not been marked 'unavailable'.
283  if (A->getUnavailable()) {
284    if (Message) {
285      Message->clear();
286      llvm::raw_string_ostream Out(*Message);
287      Out << "not available on " << PrettyPlatformName;
288    }
289
290    return AR_Unavailable;
291  }
292
293  // Make sure that this declaration has already been introduced.
294  if (!A->getIntroduced().empty() &&
295      TargetMinVersion < A->getIntroduced()) {
296    if (Message) {
297      Message->clear();
298      llvm::raw_string_ostream Out(*Message);
299      Out << "introduced in " << PrettyPlatformName << ' '
300          << A->getIntroduced();
301    }
302
303    return AR_NotYetIntroduced;
304  }
305
306  // Make sure that this declaration hasn't been obsoleted.
307  if (!A->getObsoleted().empty() && TargetMinVersion >= A->getObsoleted()) {
308    if (Message) {
309      Message->clear();
310      llvm::raw_string_ostream Out(*Message);
311      Out << "obsoleted in " << PrettyPlatformName << ' '
312          << A->getObsoleted();
313    }
314
315    return AR_Unavailable;
316  }
317
318  // Make sure that this declaration hasn't been deprecated.
319  if (!A->getDeprecated().empty() && TargetMinVersion >= A->getDeprecated()) {
320    if (Message) {
321      Message->clear();
322      llvm::raw_string_ostream Out(*Message);
323      Out << "first deprecated in " << PrettyPlatformName << ' '
324          << A->getDeprecated();
325    }
326
327    return AR_Deprecated;
328  }
329
330  return AR_Available;
331}
332
333AvailabilityResult Decl::getAvailability(std::string *Message) const {
334  AvailabilityResult Result = AR_Available;
335  std::string ResultMessage;
336
337  for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) {
338    if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(*A)) {
339      if (Result >= AR_Deprecated)
340        continue;
341
342      if (Message)
343        ResultMessage = Deprecated->getMessage();
344
345      Result = AR_Deprecated;
346      continue;
347    }
348
349    if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(*A)) {
350      if (Message)
351        *Message = Unavailable->getMessage();
352      return AR_Unavailable;
353    }
354
355    if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) {
356      AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
357                                                Message);
358
359      if (AR == AR_Unavailable)
360        return AR_Unavailable;
361
362      if (AR > Result) {
363        Result = AR;
364        if (Message)
365          ResultMessage.swap(*Message);
366      }
367      continue;
368    }
369  }
370
371  if (Message)
372    Message->swap(ResultMessage);
373  return Result;
374}
375
376bool Decl::canBeWeakImported(bool &IsDefinition) const {
377  IsDefinition = false;
378  if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
379    if (!Var->hasExternalStorage() || Var->getInit()) {
380      IsDefinition = true;
381      return false;
382    }
383  } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
384    if (FD->hasBody()) {
385      IsDefinition = true;
386      return false;
387    }
388  } else if (isa<ObjCPropertyDecl>(this) || isa<ObjCMethodDecl>(this))
389    return false;
390  else if (!(getASTContext().getLangOptions().ObjCNonFragileABI &&
391             isa<ObjCInterfaceDecl>(this)))
392    return false;
393
394  return true;
395}
396
397bool Decl::isWeakImported() const {
398  bool IsDefinition;
399  if (!canBeWeakImported(IsDefinition))
400    return false;
401
402  for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) {
403    if (isa<WeakImportAttr>(*A))
404      return true;
405
406    if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) {
407      if (CheckAvailability(getASTContext(), Availability, 0)
408                                                         == AR_NotYetIntroduced)
409        return true;
410    }
411  }
412
413  return false;
414}
415
416unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
417  switch (DeclKind) {
418    case Function:
419    case CXXMethod:
420    case CXXConstructor:
421    case CXXDestructor:
422    case CXXConversion:
423    case EnumConstant:
424    case Var:
425    case ImplicitParam:
426    case ParmVar:
427    case NonTypeTemplateParm:
428    case ObjCMethod:
429    case ObjCProperty:
430      return IDNS_Ordinary;
431    case Label:
432      return IDNS_Label;
433    case IndirectField:
434      return IDNS_Ordinary | IDNS_Member;
435
436    case ObjCCompatibleAlias:
437    case ObjCInterface:
438      return IDNS_Ordinary | IDNS_Type;
439
440    case Typedef:
441    case TypeAlias:
442    case TypeAliasTemplate:
443    case UnresolvedUsingTypename:
444    case TemplateTypeParm:
445      return IDNS_Ordinary | IDNS_Type;
446
447    case UsingShadow:
448      return 0; // we'll actually overwrite this later
449
450    case UnresolvedUsingValue:
451      return IDNS_Ordinary | IDNS_Using;
452
453    case Using:
454      return IDNS_Using;
455
456    case ObjCProtocol:
457      return IDNS_ObjCProtocol;
458
459    case Field:
460    case ObjCAtDefsField:
461    case ObjCIvar:
462      return IDNS_Member;
463
464    case Record:
465    case CXXRecord:
466    case Enum:
467      return IDNS_Tag | IDNS_Type;
468
469    case Namespace:
470    case NamespaceAlias:
471      return IDNS_Namespace;
472
473    case FunctionTemplate:
474      return IDNS_Ordinary;
475
476    case ClassTemplate:
477    case TemplateTemplateParm:
478      return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
479
480    // Never have names.
481    case Friend:
482    case FriendTemplate:
483    case AccessSpec:
484    case LinkageSpec:
485    case FileScopeAsm:
486    case StaticAssert:
487    case ObjCClass:
488    case ObjCPropertyImpl:
489    case ObjCForwardProtocol:
490    case Block:
491    case TranslationUnit:
492
493    case UsingDirective:
494    case ClassTemplateSpecialization:
495    case ClassTemplatePartialSpecialization:
496    case ClassScopeFunctionSpecialization:
497    case ObjCImplementation:
498    case ObjCCategory:
499    case ObjCCategoryImpl:
500      // Never looked up by name.
501      return 0;
502  }
503
504  return 0;
505}
506
507void Decl::setAttrs(const AttrVec &attrs) {
508  assert(!HasAttrs && "Decl already contains attrs.");
509
510  AttrVec &AttrBlank = getASTContext().getDeclAttrs(this);
511  assert(AttrBlank.empty() && "HasAttrs was wrong?");
512
513  AttrBlank = attrs;
514  HasAttrs = true;
515}
516
517void Decl::dropAttrs() {
518  if (!HasAttrs) return;
519
520  HasAttrs = false;
521  getASTContext().eraseDeclAttrs(this);
522}
523
524const AttrVec &Decl::getAttrs() const {
525  assert(HasAttrs && "No attrs to get!");
526  return getASTContext().getDeclAttrs(this);
527}
528
529void Decl::swapAttrs(Decl *RHS) {
530  bool HasLHSAttr = this->HasAttrs;
531  bool HasRHSAttr = RHS->HasAttrs;
532
533  // Usually, neither decl has attrs, nothing to do.
534  if (!HasLHSAttr && !HasRHSAttr) return;
535
536  // If 'this' has no attrs, swap the other way.
537  if (!HasLHSAttr)
538    return RHS->swapAttrs(this);
539
540  ASTContext &Context = getASTContext();
541
542  // Handle the case when both decls have attrs.
543  if (HasRHSAttr) {
544    std::swap(Context.getDeclAttrs(this), Context.getDeclAttrs(RHS));
545    return;
546  }
547
548  // Otherwise, LHS has an attr and RHS doesn't.
549  Context.getDeclAttrs(RHS) = Context.getDeclAttrs(this);
550  Context.eraseDeclAttrs(this);
551  this->HasAttrs = false;
552  RHS->HasAttrs = true;
553}
554
555Decl *Decl::castFromDeclContext (const DeclContext *D) {
556  Decl::Kind DK = D->getDeclKind();
557  switch(DK) {
558#define DECL(NAME, BASE)
559#define DECL_CONTEXT(NAME) \
560    case Decl::NAME:       \
561      return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
562#define DECL_CONTEXT_BASE(NAME)
563#include "clang/AST/DeclNodes.inc"
564    default:
565#define DECL(NAME, BASE)
566#define DECL_CONTEXT_BASE(NAME)                  \
567      if (DK >= first##NAME && DK <= last##NAME) \
568        return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
569#include "clang/AST/DeclNodes.inc"
570      assert(false && "a decl that inherits DeclContext isn't handled");
571      return 0;
572  }
573}
574
575DeclContext *Decl::castToDeclContext(const Decl *D) {
576  Decl::Kind DK = D->getKind();
577  switch(DK) {
578#define DECL(NAME, BASE)
579#define DECL_CONTEXT(NAME) \
580    case Decl::NAME:       \
581      return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
582#define DECL_CONTEXT_BASE(NAME)
583#include "clang/AST/DeclNodes.inc"
584    default:
585#define DECL(NAME, BASE)
586#define DECL_CONTEXT_BASE(NAME)                                   \
587      if (DK >= first##NAME && DK <= last##NAME)                  \
588        return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
589#include "clang/AST/DeclNodes.inc"
590      assert(false && "a decl that inherits DeclContext isn't handled");
591      return 0;
592  }
593}
594
595SourceLocation Decl::getBodyRBrace() const {
596  // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
597  // FunctionDecl stores EndRangeLoc for this purpose.
598  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
599    const FunctionDecl *Definition;
600    if (FD->hasBody(Definition))
601      return Definition->getSourceRange().getEnd();
602    return SourceLocation();
603  }
604
605  if (Stmt *Body = getBody())
606    return Body->getSourceRange().getEnd();
607
608  return SourceLocation();
609}
610
611void Decl::CheckAccessDeclContext() const {
612#ifndef NDEBUG
613  // Suppress this check if any of the following hold:
614  // 1. this is the translation unit (and thus has no parent)
615  // 2. this is a template parameter (and thus doesn't belong to its context)
616  // 3. this is a non-type template parameter
617  // 4. the context is not a record
618  // 5. it's invalid
619  // 6. it's a C++0x static_assert.
620  if (isa<TranslationUnitDecl>(this) ||
621      isa<TemplateTypeParmDecl>(this) ||
622      isa<NonTypeTemplateParmDecl>(this) ||
623      !isa<CXXRecordDecl>(getDeclContext()) ||
624      isInvalidDecl() ||
625      isa<StaticAssertDecl>(this) ||
626      // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
627      // as DeclContext (?).
628      isa<ParmVarDecl>(this) ||
629      // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
630      // AS_none as access specifier.
631      isa<CXXRecordDecl>(this) ||
632      isa<ClassScopeFunctionSpecializationDecl>(this))
633    return;
634
635  assert(Access != AS_none &&
636         "Access specifier is AS_none inside a record decl");
637#endif
638}
639
640DeclContext *Decl::getNonClosureContext() {
641  DeclContext *DC = getDeclContext();
642
643  // This is basically "while (DC->isClosure()) DC = DC->getParent();"
644  // except that it's significantly more efficient to cast to a known
645  // decl type and call getDeclContext() than to call getParent().
646  while (isa<BlockDecl>(DC))
647    DC = cast<BlockDecl>(DC)->getDeclContext();
648
649  assert(!DC->isClosure());
650  return DC;
651}
652
653//===----------------------------------------------------------------------===//
654// DeclContext Implementation
655//===----------------------------------------------------------------------===//
656
657bool DeclContext::classof(const Decl *D) {
658  switch (D->getKind()) {
659#define DECL(NAME, BASE)
660#define DECL_CONTEXT(NAME) case Decl::NAME:
661#define DECL_CONTEXT_BASE(NAME)
662#include "clang/AST/DeclNodes.inc"
663      return true;
664    default:
665#define DECL(NAME, BASE)
666#define DECL_CONTEXT_BASE(NAME)                 \
667      if (D->getKind() >= Decl::first##NAME &&  \
668          D->getKind() <= Decl::last##NAME)     \
669        return true;
670#include "clang/AST/DeclNodes.inc"
671      return false;
672  }
673}
674
675DeclContext::~DeclContext() { }
676
677/// \brief Find the parent context of this context that will be
678/// used for unqualified name lookup.
679///
680/// Generally, the parent lookup context is the semantic context. However, for
681/// a friend function the parent lookup context is the lexical context, which
682/// is the class in which the friend is declared.
683DeclContext *DeclContext::getLookupParent() {
684  // FIXME: Find a better way to identify friends
685  if (isa<FunctionDecl>(this))
686    if (getParent()->getRedeclContext()->isFileContext() &&
687        getLexicalParent()->getRedeclContext()->isRecord())
688      return getLexicalParent();
689
690  return getParent();
691}
692
693bool DeclContext::isInlineNamespace() const {
694  return isNamespace() &&
695         cast<NamespaceDecl>(this)->isInline();
696}
697
698bool DeclContext::isDependentContext() const {
699  if (isFileContext())
700    return false;
701
702  if (isa<ClassTemplatePartialSpecializationDecl>(this))
703    return true;
704
705  if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
706    if (Record->getDescribedClassTemplate())
707      return true;
708
709  if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
710    if (Function->getDescribedFunctionTemplate())
711      return true;
712
713    // Friend function declarations are dependent if their *lexical*
714    // context is dependent.
715    if (cast<Decl>(this)->getFriendObjectKind())
716      return getLexicalParent()->isDependentContext();
717  }
718
719  return getParent() && getParent()->isDependentContext();
720}
721
722bool DeclContext::isTransparentContext() const {
723  if (DeclKind == Decl::Enum)
724    return !cast<EnumDecl>(this)->isScoped();
725  else if (DeclKind == Decl::LinkageSpec)
726    return true;
727
728  return false;
729}
730
731bool DeclContext::isExternCContext() const {
732  const DeclContext *DC = this;
733  while (DC->DeclKind != Decl::TranslationUnit) {
734    if (DC->DeclKind == Decl::LinkageSpec)
735      return cast<LinkageSpecDecl>(DC)->getLanguage()
736        == LinkageSpecDecl::lang_c;
737    DC = DC->getParent();
738  }
739  return false;
740}
741
742bool DeclContext::Encloses(const DeclContext *DC) const {
743  if (getPrimaryContext() != this)
744    return getPrimaryContext()->Encloses(DC);
745
746  for (; DC; DC = DC->getParent())
747    if (DC->getPrimaryContext() == this)
748      return true;
749  return false;
750}
751
752DeclContext *DeclContext::getPrimaryContext() {
753  switch (DeclKind) {
754  case Decl::TranslationUnit:
755  case Decl::LinkageSpec:
756  case Decl::Block:
757    // There is only one DeclContext for these entities.
758    return this;
759
760  case Decl::Namespace:
761    // The original namespace is our primary context.
762    return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
763
764  case Decl::ObjCMethod:
765    return this;
766
767  case Decl::ObjCInterface:
768  case Decl::ObjCProtocol:
769  case Decl::ObjCCategory:
770    // FIXME: Can Objective-C interfaces be forward-declared?
771    return this;
772
773  case Decl::ObjCImplementation:
774  case Decl::ObjCCategoryImpl:
775    return this;
776
777  default:
778    if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
779      // If this is a tag type that has a definition or is currently
780      // being defined, that definition is our primary context.
781      TagDecl *Tag = cast<TagDecl>(this);
782      assert(isa<TagType>(Tag->TypeForDecl) ||
783             isa<InjectedClassNameType>(Tag->TypeForDecl));
784
785      if (TagDecl *Def = Tag->getDefinition())
786        return Def;
787
788      if (!isa<InjectedClassNameType>(Tag->TypeForDecl)) {
789        const TagType *TagTy = cast<TagType>(Tag->TypeForDecl);
790        if (TagTy->isBeingDefined())
791          // FIXME: is it necessarily being defined in the decl
792          // that owns the type?
793          return TagTy->getDecl();
794      }
795
796      return Tag;
797    }
798
799    assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
800          "Unknown DeclContext kind");
801    return this;
802  }
803}
804
805DeclContext *DeclContext::getNextContext() {
806  switch (DeclKind) {
807  case Decl::Namespace:
808    // Return the next namespace
809    return static_cast<NamespaceDecl*>(this)->getNextNamespace();
810
811  default:
812    return 0;
813  }
814}
815
816std::pair<Decl *, Decl *>
817DeclContext::BuildDeclChain(const SmallVectorImpl<Decl*> &Decls) {
818  // Build up a chain of declarations via the Decl::NextDeclInContext field.
819  Decl *FirstNewDecl = 0;
820  Decl *PrevDecl = 0;
821  for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
822    Decl *D = Decls[I];
823    if (PrevDecl)
824      PrevDecl->NextDeclInContext = D;
825    else
826      FirstNewDecl = D;
827
828    PrevDecl = D;
829  }
830
831  return std::make_pair(FirstNewDecl, PrevDecl);
832}
833
834/// \brief Load the declarations within this lexical storage from an
835/// external source.
836void
837DeclContext::LoadLexicalDeclsFromExternalStorage() const {
838  ExternalASTSource *Source = getParentASTContext().getExternalSource();
839  assert(hasExternalLexicalStorage() && Source && "No external storage?");
840
841  // Notify that we have a DeclContext that is initializing.
842  ExternalASTSource::Deserializing ADeclContext(Source);
843
844  // We may have already loaded just the fields of this record, in which case
845  // we remove all of the fields from the list. The fields will be reloaded
846  // from the external source as part of re-establishing the context.
847  if (const RecordDecl *RD = dyn_cast<RecordDecl>(this)) {
848    if (RD->LoadedFieldsFromExternalStorage) {
849      while (FirstDecl && isa<FieldDecl>(FirstDecl)) {
850        Decl *Next = FirstDecl->NextDeclInContext;
851        FirstDecl->NextDeclInContext = 0;
852        FirstDecl = Next;
853      }
854
855      if (!FirstDecl)
856        LastDecl = 0;
857    }
858  }
859
860  // Load the external declarations, if any.
861  SmallVector<Decl*, 64> Decls;
862  ExternalLexicalStorage = false;
863  switch (Source->FindExternalLexicalDecls(this, Decls)) {
864  case ELR_Success:
865    break;
866
867  case ELR_Failure:
868  case ELR_AlreadyLoaded:
869    return;
870  }
871
872  if (Decls.empty())
873    return;
874
875  // Splice the newly-read declarations into the beginning of the list
876  // of declarations.
877  Decl *ExternalFirst, *ExternalLast;
878  llvm::tie(ExternalFirst, ExternalLast) = BuildDeclChain(Decls);
879  ExternalLast->NextDeclInContext = FirstDecl;
880  FirstDecl = ExternalFirst;
881  if (!LastDecl)
882    LastDecl = ExternalLast;
883}
884
885DeclContext::lookup_result
886ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
887                                                    DeclarationName Name) {
888  ASTContext &Context = DC->getParentASTContext();
889  StoredDeclsMap *Map;
890  if (!(Map = DC->LookupPtr))
891    Map = DC->CreateStoredDeclsMap(Context);
892
893  StoredDeclsList &List = (*Map)[Name];
894  assert(List.isNull());
895  (void) List;
896
897  return DeclContext::lookup_result();
898}
899
900DeclContext::lookup_result
901ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
902                                                  DeclarationName Name,
903                                    SmallVectorImpl<NamedDecl*> &Decls) {
904  ASTContext &Context = DC->getParentASTContext();;
905
906  StoredDeclsMap *Map;
907  if (!(Map = DC->LookupPtr))
908    Map = DC->CreateStoredDeclsMap(Context);
909
910  StoredDeclsList &List = (*Map)[Name];
911  for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
912    if (List.isNull())
913      List.setOnlyValue(Decls[I]);
914    else
915      List.AddSubsequentDecl(Decls[I]);
916  }
917
918  return List.getLookupResult();
919}
920
921DeclContext::decl_iterator DeclContext::noload_decls_begin() const {
922  return decl_iterator(FirstDecl);
923}
924
925DeclContext::decl_iterator DeclContext::noload_decls_end() const {
926  return decl_iterator();
927}
928
929DeclContext::decl_iterator DeclContext::decls_begin() const {
930  if (hasExternalLexicalStorage())
931    LoadLexicalDeclsFromExternalStorage();
932
933  return decl_iterator(FirstDecl);
934}
935
936DeclContext::decl_iterator DeclContext::decls_end() const {
937  if (hasExternalLexicalStorage())
938    LoadLexicalDeclsFromExternalStorage();
939
940  return decl_iterator();
941}
942
943bool DeclContext::decls_empty() const {
944  if (hasExternalLexicalStorage())
945    LoadLexicalDeclsFromExternalStorage();
946
947  return !FirstDecl;
948}
949
950void DeclContext::removeDecl(Decl *D) {
951  assert(D->getLexicalDeclContext() == this &&
952         "decl being removed from non-lexical context");
953  assert((D->NextDeclInContext || D == LastDecl) &&
954         "decl is not in decls list");
955
956  // Remove D from the decl chain.  This is O(n) but hopefully rare.
957  if (D == FirstDecl) {
958    if (D == LastDecl)
959      FirstDecl = LastDecl = 0;
960    else
961      FirstDecl = D->NextDeclInContext;
962  } else {
963    for (Decl *I = FirstDecl; true; I = I->NextDeclInContext) {
964      assert(I && "decl not found in linked list");
965      if (I->NextDeclInContext == D) {
966        I->NextDeclInContext = D->NextDeclInContext;
967        if (D == LastDecl) LastDecl = I;
968        break;
969      }
970    }
971  }
972
973  // Mark that D is no longer in the decl chain.
974  D->NextDeclInContext = 0;
975
976  // Remove D from the lookup table if necessary.
977  if (isa<NamedDecl>(D)) {
978    NamedDecl *ND = cast<NamedDecl>(D);
979
980    // Remove only decls that have a name
981    if (!ND->getDeclName()) return;
982
983    StoredDeclsMap *Map = getPrimaryContext()->LookupPtr;
984    if (!Map) return;
985
986    StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
987    assert(Pos != Map->end() && "no lookup entry for decl");
988    Pos->second.remove(ND);
989  }
990}
991
992void DeclContext::addHiddenDecl(Decl *D) {
993  assert(D->getLexicalDeclContext() == this &&
994         "Decl inserted into wrong lexical context");
995  assert(!D->getNextDeclInContext() && D != LastDecl &&
996         "Decl already inserted into a DeclContext");
997
998  if (FirstDecl) {
999    LastDecl->NextDeclInContext = D;
1000    LastDecl = D;
1001  } else {
1002    FirstDecl = LastDecl = D;
1003  }
1004
1005  // Notify a C++ record declaration that we've added a member, so it can
1006  // update it's class-specific state.
1007  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1008    Record->addedMember(D);
1009}
1010
1011void DeclContext::addDecl(Decl *D) {
1012  addHiddenDecl(D);
1013
1014  if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1015    ND->getDeclContext()->makeDeclVisibleInContext(ND);
1016}
1017
1018/// buildLookup - Build the lookup data structure with all of the
1019/// declarations in DCtx (and any other contexts linked to it or
1020/// transparent contexts nested within it).
1021void DeclContext::buildLookup(DeclContext *DCtx) {
1022  for (; DCtx; DCtx = DCtx->getNextContext()) {
1023    for (decl_iterator D = DCtx->decls_begin(),
1024                    DEnd = DCtx->decls_end();
1025         D != DEnd; ++D) {
1026      // Insert this declaration into the lookup structure, but only
1027      // if it's semantically in its decl context.  During non-lazy
1028      // lookup building, this is implicitly enforced by addDecl.
1029      if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
1030        if (D->getDeclContext() == DCtx)
1031          makeDeclVisibleInContextImpl(ND);
1032
1033      // Insert any forward-declared Objective-C interface into the lookup
1034      // data structure.
1035      if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D))
1036        makeDeclVisibleInContextImpl(Class->getForwardInterfaceDecl());
1037
1038      // If this declaration is itself a transparent declaration context or
1039      // inline namespace, add its members (recursively).
1040      if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D))
1041        if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1042          buildLookup(InnerCtx->getPrimaryContext());
1043    }
1044  }
1045}
1046
1047DeclContext::lookup_result
1048DeclContext::lookup(DeclarationName Name) {
1049  DeclContext *PrimaryContext = getPrimaryContext();
1050  if (PrimaryContext != this)
1051    return PrimaryContext->lookup(Name);
1052
1053  if (hasExternalVisibleStorage()) {
1054    // Check to see if we've already cached the lookup results.
1055    if (LookupPtr) {
1056      StoredDeclsMap::iterator I = LookupPtr->find(Name);
1057      if (I != LookupPtr->end())
1058        return I->second.getLookupResult();
1059    }
1060
1061    ExternalASTSource *Source = getParentASTContext().getExternalSource();
1062    return Source->FindExternalVisibleDeclsByName(this, Name);
1063  }
1064
1065  /// If there is no lookup data structure, build one now by walking
1066  /// all of the linked DeclContexts (in declaration order!) and
1067  /// inserting their values.
1068  if (!LookupPtr) {
1069    buildLookup(this);
1070
1071    if (!LookupPtr)
1072      return lookup_result(lookup_iterator(0), lookup_iterator(0));
1073  }
1074
1075  StoredDeclsMap::iterator Pos = LookupPtr->find(Name);
1076  if (Pos == LookupPtr->end())
1077    return lookup_result(lookup_iterator(0), lookup_iterator(0));
1078  return Pos->second.getLookupResult();
1079}
1080
1081DeclContext::lookup_const_result
1082DeclContext::lookup(DeclarationName Name) const {
1083  return const_cast<DeclContext*>(this)->lookup(Name);
1084}
1085
1086DeclContext *DeclContext::getRedeclContext() {
1087  DeclContext *Ctx = this;
1088  // Skip through transparent contexts.
1089  while (Ctx->isTransparentContext())
1090    Ctx = Ctx->getParent();
1091  return Ctx;
1092}
1093
1094DeclContext *DeclContext::getEnclosingNamespaceContext() {
1095  DeclContext *Ctx = this;
1096  // Skip through non-namespace, non-translation-unit contexts.
1097  while (!Ctx->isFileContext())
1098    Ctx = Ctx->getParent();
1099  return Ctx->getPrimaryContext();
1100}
1101
1102bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1103  // For non-file contexts, this is equivalent to Equals.
1104  if (!isFileContext())
1105    return O->Equals(this);
1106
1107  do {
1108    if (O->Equals(this))
1109      return true;
1110
1111    const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1112    if (!NS || !NS->isInline())
1113      break;
1114    O = NS->getParent();
1115  } while (O);
1116
1117  return false;
1118}
1119
1120void DeclContext::makeDeclVisibleInContext(NamedDecl *D, bool Recoverable) {
1121  // FIXME: This feels like a hack. Should DeclarationName support
1122  // template-ids, or is there a better way to keep specializations
1123  // from being visible?
1124  if (isa<ClassTemplateSpecializationDecl>(D) || D->isTemplateParameter())
1125    return;
1126  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1127    if (FD->isFunctionTemplateSpecialization())
1128      return;
1129
1130  DeclContext *PrimaryContext = getPrimaryContext();
1131  if (PrimaryContext != this) {
1132    PrimaryContext->makeDeclVisibleInContext(D, Recoverable);
1133    return;
1134  }
1135
1136  // If we already have a lookup data structure, perform the insertion
1137  // into it. If we haven't deserialized externally stored decls, deserialize
1138  // them so we can add the decl. Otherwise, be lazy and don't build that
1139  // structure until someone asks for it.
1140  if (LookupPtr || !Recoverable || hasExternalVisibleStorage())
1141    makeDeclVisibleInContextImpl(D);
1142
1143  // If we are a transparent context or inline namespace, insert into our
1144  // parent context, too. This operation is recursive.
1145  if (isTransparentContext() || isInlineNamespace())
1146    getParent()->makeDeclVisibleInContext(D, Recoverable);
1147
1148  Decl *DCAsDecl = cast<Decl>(this);
1149  // Notify that a decl was made visible unless it's a Tag being defined.
1150  if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1151    if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1152      L->AddedVisibleDecl(this, D);
1153}
1154
1155void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D) {
1156  // Skip unnamed declarations.
1157  if (!D->getDeclName())
1158    return;
1159
1160  // Skip entities that can't be found by name lookup into a particular
1161  // context.
1162  if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1163      D->isTemplateParameter())
1164    return;
1165
1166  ASTContext *C = 0;
1167  if (!LookupPtr) {
1168    C = &getParentASTContext();
1169    CreateStoredDeclsMap(*C);
1170  }
1171
1172  // If there is an external AST source, load any declarations it knows about
1173  // with this declaration's name.
1174  // If the lookup table contains an entry about this name it means that we
1175  // have already checked the external source.
1176  if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1177    if (hasExternalVisibleStorage() &&
1178        LookupPtr->find(D->getDeclName()) == LookupPtr->end())
1179      Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1180
1181  // Insert this declaration into the map.
1182  StoredDeclsList &DeclNameEntries = (*LookupPtr)[D->getDeclName()];
1183  if (DeclNameEntries.isNull()) {
1184    DeclNameEntries.setOnlyValue(D);
1185    return;
1186  }
1187
1188  // If it is possible that this is a redeclaration, check to see if there is
1189  // already a decl for which declarationReplaces returns true.  If there is
1190  // one, just replace it and return.
1191  if (DeclNameEntries.HandleRedeclaration(D))
1192    return;
1193
1194  // Put this declaration into the appropriate slot.
1195  DeclNameEntries.AddSubsequentDecl(D);
1196}
1197
1198/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1199/// this context.
1200DeclContext::udir_iterator_range
1201DeclContext::getUsingDirectives() const {
1202  lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
1203  return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.first),
1204                             reinterpret_cast<udir_iterator>(Result.second));
1205}
1206
1207//===----------------------------------------------------------------------===//
1208// Creation and Destruction of StoredDeclsMaps.                               //
1209//===----------------------------------------------------------------------===//
1210
1211StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1212  assert(!LookupPtr && "context already has a decls map");
1213  assert(getPrimaryContext() == this &&
1214         "creating decls map on non-primary context");
1215
1216  StoredDeclsMap *M;
1217  bool Dependent = isDependentContext();
1218  if (Dependent)
1219    M = new DependentStoredDeclsMap();
1220  else
1221    M = new StoredDeclsMap();
1222  M->Previous = C.LastSDM;
1223  C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1224  LookupPtr = M;
1225  return M;
1226}
1227
1228void ASTContext::ReleaseDeclContextMaps() {
1229  // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1230  // pointer because the subclass doesn't add anything that needs to
1231  // be deleted.
1232  StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1233}
1234
1235void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1236  while (Map) {
1237    // Advance the iteration before we invalidate memory.
1238    llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1239
1240    if (Dependent)
1241      delete static_cast<DependentStoredDeclsMap*>(Map);
1242    else
1243      delete Map;
1244
1245    Map = Next.getPointer();
1246    Dependent = Next.getInt();
1247  }
1248}
1249
1250DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1251                                                 DeclContext *Parent,
1252                                           const PartialDiagnostic &PDiag) {
1253  assert(Parent->isDependentContext()
1254         && "cannot iterate dependent diagnostics of non-dependent context");
1255  Parent = Parent->getPrimaryContext();
1256  if (!Parent->LookupPtr)
1257    Parent->CreateStoredDeclsMap(C);
1258
1259  DependentStoredDeclsMap *Map
1260    = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr);
1261
1262  // Allocate the copy of the PartialDiagnostic via the ASTContext's
1263  // BumpPtrAllocator, rather than the ASTContext itself.
1264  PartialDiagnostic::Storage *DiagStorage = 0;
1265  if (PDiag.hasStorage())
1266    DiagStorage = new (C) PartialDiagnostic::Storage;
1267
1268  DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1269
1270  // TODO: Maybe we shouldn't reverse the order during insertion.
1271  DD->NextDiagnostic = Map->FirstDiagnostic;
1272  Map->FirstDiagnostic = DD;
1273
1274  return DD;
1275}
1276