DeclBase.cpp revision 5cb0ef4aed9a4a1741260e16a99d18682335ab9b
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>
32#include <cstdio>
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
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  llvm::StringRef TargetPlatform = Context.Target.getPlatformName();
269  llvm::StringRef PrettyPlatformName
270    = AvailabilityAttr::getPrettyPlatformName(TargetPlatform);
271  if (PrettyPlatformName.empty())
272    PrettyPlatformName = TargetPlatform;
273
274  VersionTuple TargetMinVersion = Context.Target.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 ObjCImplementation:
497    case ObjCCategory:
498    case ObjCCategoryImpl:
499      // Never looked up by name.
500      return 0;
501  }
502
503  return 0;
504}
505
506void Decl::setAttrs(const AttrVec &attrs) {
507  assert(!HasAttrs && "Decl already contains attrs.");
508
509  AttrVec &AttrBlank = getASTContext().getDeclAttrs(this);
510  assert(AttrBlank.empty() && "HasAttrs was wrong?");
511
512  AttrBlank = attrs;
513  HasAttrs = true;
514}
515
516void Decl::dropAttrs() {
517  if (!HasAttrs) return;
518
519  HasAttrs = false;
520  getASTContext().eraseDeclAttrs(this);
521}
522
523const AttrVec &Decl::getAttrs() const {
524  assert(HasAttrs && "No attrs to get!");
525  return getASTContext().getDeclAttrs(this);
526}
527
528void Decl::swapAttrs(Decl *RHS) {
529  bool HasLHSAttr = this->HasAttrs;
530  bool HasRHSAttr = RHS->HasAttrs;
531
532  // Usually, neither decl has attrs, nothing to do.
533  if (!HasLHSAttr && !HasRHSAttr) return;
534
535  // If 'this' has no attrs, swap the other way.
536  if (!HasLHSAttr)
537    return RHS->swapAttrs(this);
538
539  ASTContext &Context = getASTContext();
540
541  // Handle the case when both decls have attrs.
542  if (HasRHSAttr) {
543    std::swap(Context.getDeclAttrs(this), Context.getDeclAttrs(RHS));
544    return;
545  }
546
547  // Otherwise, LHS has an attr and RHS doesn't.
548  Context.getDeclAttrs(RHS) = Context.getDeclAttrs(this);
549  Context.eraseDeclAttrs(this);
550  this->HasAttrs = false;
551  RHS->HasAttrs = true;
552}
553
554Decl *Decl::castFromDeclContext (const DeclContext *D) {
555  Decl::Kind DK = D->getDeclKind();
556  switch(DK) {
557#define DECL(NAME, BASE)
558#define DECL_CONTEXT(NAME) \
559    case Decl::NAME:       \
560      return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
561#define DECL_CONTEXT_BASE(NAME)
562#include "clang/AST/DeclNodes.inc"
563    default:
564#define DECL(NAME, BASE)
565#define DECL_CONTEXT_BASE(NAME)                  \
566      if (DK >= first##NAME && DK <= last##NAME) \
567        return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
568#include "clang/AST/DeclNodes.inc"
569      assert(false && "a decl that inherits DeclContext isn't handled");
570      return 0;
571  }
572}
573
574DeclContext *Decl::castToDeclContext(const Decl *D) {
575  Decl::Kind DK = D->getKind();
576  switch(DK) {
577#define DECL(NAME, BASE)
578#define DECL_CONTEXT(NAME) \
579    case Decl::NAME:       \
580      return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
581#define DECL_CONTEXT_BASE(NAME)
582#include "clang/AST/DeclNodes.inc"
583    default:
584#define DECL(NAME, BASE)
585#define DECL_CONTEXT_BASE(NAME)                                   \
586      if (DK >= first##NAME && DK <= last##NAME)                  \
587        return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
588#include "clang/AST/DeclNodes.inc"
589      assert(false && "a decl that inherits DeclContext isn't handled");
590      return 0;
591  }
592}
593
594SourceLocation Decl::getBodyRBrace() const {
595  // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
596  // FunctionDecl stores EndRangeLoc for this purpose.
597  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
598    const FunctionDecl *Definition;
599    if (FD->hasBody(Definition))
600      return Definition->getSourceRange().getEnd();
601    return SourceLocation();
602  }
603
604  if (Stmt *Body = getBody())
605    return Body->getSourceRange().getEnd();
606
607  return SourceLocation();
608}
609
610void Decl::CheckAccessDeclContext() const {
611#ifndef NDEBUG
612  // Suppress this check if any of the following hold:
613  // 1. this is the translation unit (and thus has no parent)
614  // 2. this is a template parameter (and thus doesn't belong to its context)
615  // 3. this is a non-type template parameter
616  // 4. the context is not a record
617  // 5. it's invalid
618  // 6. it's a C++0x static_assert.
619  if (isa<TranslationUnitDecl>(this) ||
620      isa<TemplateTypeParmDecl>(this) ||
621      isa<NonTypeTemplateParmDecl>(this) ||
622      !isa<CXXRecordDecl>(getDeclContext()) ||
623      isInvalidDecl() ||
624      isa<StaticAssertDecl>(this) ||
625      // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
626      // as DeclContext (?).
627      isa<ParmVarDecl>(this) ||
628      // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
629      // AS_none as access specifier.
630      isa<CXXRecordDecl>(this))
631    return;
632
633  assert(Access != AS_none &&
634         "Access specifier is AS_none inside a record decl");
635#endif
636}
637
638DeclContext *Decl::getNonClosureContext() {
639  DeclContext *DC = getDeclContext();
640
641  // This is basically "while (DC->isClosure()) DC = DC->getParent();"
642  // except that it's significantly more efficient to cast to a known
643  // decl type and call getDeclContext() than to call getParent().
644  do {
645    if (isa<BlockDecl>(DC)) {
646      DC = cast<BlockDecl>(DC)->getDeclContext();
647      continue;
648    }
649  } while (false);
650
651  assert(!DC->isClosure());
652  return DC;
653}
654
655//===----------------------------------------------------------------------===//
656// DeclContext Implementation
657//===----------------------------------------------------------------------===//
658
659bool DeclContext::classof(const Decl *D) {
660  switch (D->getKind()) {
661#define DECL(NAME, BASE)
662#define DECL_CONTEXT(NAME) case Decl::NAME:
663#define DECL_CONTEXT_BASE(NAME)
664#include "clang/AST/DeclNodes.inc"
665      return true;
666    default:
667#define DECL(NAME, BASE)
668#define DECL_CONTEXT_BASE(NAME)                 \
669      if (D->getKind() >= Decl::first##NAME &&  \
670          D->getKind() <= Decl::last##NAME)     \
671        return true;
672#include "clang/AST/DeclNodes.inc"
673      return false;
674  }
675}
676
677DeclContext::~DeclContext() { }
678
679/// \brief Find the parent context of this context that will be
680/// used for unqualified name lookup.
681///
682/// Generally, the parent lookup context is the semantic context. However, for
683/// a friend function the parent lookup context is the lexical context, which
684/// is the class in which the friend is declared.
685DeclContext *DeclContext::getLookupParent() {
686  // FIXME: Find a better way to identify friends
687  if (isa<FunctionDecl>(this))
688    if (getParent()->getRedeclContext()->isFileContext() &&
689        getLexicalParent()->getRedeclContext()->isRecord())
690      return getLexicalParent();
691
692  return getParent();
693}
694
695bool DeclContext::isInlineNamespace() const {
696  return isNamespace() &&
697         cast<NamespaceDecl>(this)->isInline();
698}
699
700bool DeclContext::isDependentContext() const {
701  if (isFileContext())
702    return false;
703
704  if (isa<ClassTemplatePartialSpecializationDecl>(this))
705    return true;
706
707  if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
708    if (Record->getDescribedClassTemplate())
709      return true;
710
711  if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
712    if (Function->getDescribedFunctionTemplate())
713      return true;
714
715    // Friend function declarations are dependent if their *lexical*
716    // context is dependent.
717    if (cast<Decl>(this)->getFriendObjectKind())
718      return getLexicalParent()->isDependentContext();
719  }
720
721  return getParent() && getParent()->isDependentContext();
722}
723
724bool DeclContext::isTransparentContext() const {
725  if (DeclKind == Decl::Enum)
726    return !cast<EnumDecl>(this)->isScoped();
727  else if (DeclKind == Decl::LinkageSpec)
728    return true;
729
730  return false;
731}
732
733bool DeclContext::isExternCContext() const {
734  const DeclContext *DC = this;
735  while (DC->DeclKind != Decl::TranslationUnit) {
736    if (DC->DeclKind == Decl::LinkageSpec)
737      return cast<LinkageSpecDecl>(DC)->getLanguage()
738        == LinkageSpecDecl::lang_c;
739    DC = DC->getParent();
740  }
741  return false;
742}
743
744bool DeclContext::Encloses(const DeclContext *DC) const {
745  if (getPrimaryContext() != this)
746    return getPrimaryContext()->Encloses(DC);
747
748  for (; DC; DC = DC->getParent())
749    if (DC->getPrimaryContext() == this)
750      return true;
751  return false;
752}
753
754DeclContext *DeclContext::getPrimaryContext() {
755  switch (DeclKind) {
756  case Decl::TranslationUnit:
757  case Decl::LinkageSpec:
758  case Decl::Block:
759    // There is only one DeclContext for these entities.
760    return this;
761
762  case Decl::Namespace:
763    // The original namespace is our primary context.
764    return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
765
766  case Decl::ObjCMethod:
767    return this;
768
769  case Decl::ObjCInterface:
770  case Decl::ObjCProtocol:
771  case Decl::ObjCCategory:
772    // FIXME: Can Objective-C interfaces be forward-declared?
773    return this;
774
775  case Decl::ObjCImplementation:
776  case Decl::ObjCCategoryImpl:
777    return this;
778
779  default:
780    if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
781      // If this is a tag type that has a definition or is currently
782      // being defined, that definition is our primary context.
783      TagDecl *Tag = cast<TagDecl>(this);
784      assert(isa<TagType>(Tag->TypeForDecl) ||
785             isa<InjectedClassNameType>(Tag->TypeForDecl));
786
787      if (TagDecl *Def = Tag->getDefinition())
788        return Def;
789
790      if (!isa<InjectedClassNameType>(Tag->TypeForDecl)) {
791        const TagType *TagTy = cast<TagType>(Tag->TypeForDecl);
792        if (TagTy->isBeingDefined())
793          // FIXME: is it necessarily being defined in the decl
794          // that owns the type?
795          return TagTy->getDecl();
796      }
797
798      return Tag;
799    }
800
801    assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
802          "Unknown DeclContext kind");
803    return this;
804  }
805}
806
807DeclContext *DeclContext::getNextContext() {
808  switch (DeclKind) {
809  case Decl::Namespace:
810    // Return the next namespace
811    return static_cast<NamespaceDecl*>(this)->getNextNamespace();
812
813  default:
814    return 0;
815  }
816}
817
818std::pair<Decl *, Decl *>
819DeclContext::BuildDeclChain(const llvm::SmallVectorImpl<Decl*> &Decls) {
820  // Build up a chain of declarations via the Decl::NextDeclInContext field.
821  Decl *FirstNewDecl = 0;
822  Decl *PrevDecl = 0;
823  for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
824    Decl *D = Decls[I];
825    if (PrevDecl)
826      PrevDecl->NextDeclInContext = D;
827    else
828      FirstNewDecl = D;
829
830    PrevDecl = D;
831  }
832
833  return std::make_pair(FirstNewDecl, PrevDecl);
834}
835
836/// \brief Load the declarations within this lexical storage from an
837/// external source.
838void
839DeclContext::LoadLexicalDeclsFromExternalStorage() const {
840  ExternalASTSource *Source = getParentASTContext().getExternalSource();
841  assert(hasExternalLexicalStorage() && Source && "No external storage?");
842
843  // Notify that we have a DeclContext that is initializing.
844  ExternalASTSource::Deserializing ADeclContext(Source);
845
846  llvm::SmallVector<Decl*, 64> Decls;
847  if (Source->FindExternalLexicalDecls(this, Decls))
848    return;
849
850  // There is no longer any lexical storage in this context
851  ExternalLexicalStorage = false;
852
853  if (Decls.empty())
854    return;
855
856  // We may have already loaded just the fields of this record, in which case
857  // don't add the decls, just replace the FirstDecl/LastDecl chain.
858  if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
859    if (RD->LoadedFieldsFromExternalStorage) {
860      llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls);
861      return;
862    }
863
864  // Splice the newly-read declarations into the beginning of the list
865  // of declarations.
866  Decl *ExternalFirst, *ExternalLast;
867  llvm::tie(ExternalFirst, ExternalLast) = BuildDeclChain(Decls);
868  ExternalLast->NextDeclInContext = FirstDecl;
869  FirstDecl = ExternalFirst;
870  if (!LastDecl)
871    LastDecl = ExternalLast;
872}
873
874DeclContext::lookup_result
875ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
876                                                    DeclarationName Name) {
877  ASTContext &Context = DC->getParentASTContext();
878  StoredDeclsMap *Map;
879  if (!(Map = DC->LookupPtr))
880    Map = DC->CreateStoredDeclsMap(Context);
881
882  StoredDeclsList &List = (*Map)[Name];
883  assert(List.isNull());
884  (void) List;
885
886  return DeclContext::lookup_result();
887}
888
889DeclContext::lookup_result
890ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
891                                                  DeclarationName Name,
892                                    llvm::SmallVectorImpl<NamedDecl*> &Decls) {
893  ASTContext &Context = DC->getParentASTContext();;
894
895  StoredDeclsMap *Map;
896  if (!(Map = DC->LookupPtr))
897    Map = DC->CreateStoredDeclsMap(Context);
898
899  StoredDeclsList &List = (*Map)[Name];
900  for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
901    if (List.isNull())
902      List.setOnlyValue(Decls[I]);
903    else
904      List.AddSubsequentDecl(Decls[I]);
905  }
906
907  return List.getLookupResult();
908}
909
910void ExternalASTSource::MaterializeVisibleDeclsForName(const DeclContext *DC,
911                                                       DeclarationName Name,
912                                     llvm::SmallVectorImpl<NamedDecl*> &Decls) {
913  assert(DC->LookupPtr);
914  StoredDeclsMap &Map = *DC->LookupPtr;
915
916  // If there's an entry in the table the visible decls for this name have
917  // already been deserialized.
918  if (Map.find(Name) == Map.end()) {
919    StoredDeclsList &List = Map[Name];
920    for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
921      if (List.isNull())
922        List.setOnlyValue(Decls[I]);
923      else
924        List.AddSubsequentDecl(Decls[I]);
925    }
926  }
927}
928
929DeclContext::decl_iterator DeclContext::noload_decls_begin() const {
930  return decl_iterator(FirstDecl);
931}
932
933DeclContext::decl_iterator DeclContext::noload_decls_end() const {
934  return decl_iterator();
935}
936
937DeclContext::decl_iterator DeclContext::decls_begin() const {
938  if (hasExternalLexicalStorage())
939    LoadLexicalDeclsFromExternalStorage();
940
941  // FIXME: Check whether we need to load some declarations from
942  // external storage.
943  return decl_iterator(FirstDecl);
944}
945
946DeclContext::decl_iterator DeclContext::decls_end() const {
947  if (hasExternalLexicalStorage())
948    LoadLexicalDeclsFromExternalStorage();
949
950  return decl_iterator();
951}
952
953bool DeclContext::decls_empty() const {
954  if (hasExternalLexicalStorage())
955    LoadLexicalDeclsFromExternalStorage();
956
957  return !FirstDecl;
958}
959
960void DeclContext::removeDecl(Decl *D) {
961  assert(D->getLexicalDeclContext() == this &&
962         "decl being removed from non-lexical context");
963  assert((D->NextDeclInContext || D == LastDecl) &&
964         "decl is not in decls list");
965
966  // Remove D from the decl chain.  This is O(n) but hopefully rare.
967  if (D == FirstDecl) {
968    if (D == LastDecl)
969      FirstDecl = LastDecl = 0;
970    else
971      FirstDecl = D->NextDeclInContext;
972  } else {
973    for (Decl *I = FirstDecl; true; I = I->NextDeclInContext) {
974      assert(I && "decl not found in linked list");
975      if (I->NextDeclInContext == D) {
976        I->NextDeclInContext = D->NextDeclInContext;
977        if (D == LastDecl) LastDecl = I;
978        break;
979      }
980    }
981  }
982
983  // Mark that D is no longer in the decl chain.
984  D->NextDeclInContext = 0;
985
986  // Remove D from the lookup table if necessary.
987  if (isa<NamedDecl>(D)) {
988    NamedDecl *ND = cast<NamedDecl>(D);
989
990    StoredDeclsMap *Map = getPrimaryContext()->LookupPtr;
991    if (!Map) return;
992
993    StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
994    assert(Pos != Map->end() && "no lookup entry for decl");
995    Pos->second.remove(ND);
996  }
997}
998
999void DeclContext::addHiddenDecl(Decl *D) {
1000  assert(D->getLexicalDeclContext() == this &&
1001         "Decl inserted into wrong lexical context");
1002  assert(!D->getNextDeclInContext() && D != LastDecl &&
1003         "Decl already inserted into a DeclContext");
1004
1005  if (FirstDecl) {
1006    LastDecl->NextDeclInContext = D;
1007    LastDecl = D;
1008  } else {
1009    FirstDecl = LastDecl = D;
1010  }
1011
1012  // Notify a C++ record declaration that we've added a member, so it can
1013  // update it's class-specific state.
1014  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1015    Record->addedMember(D);
1016}
1017
1018void DeclContext::addDecl(Decl *D) {
1019  addHiddenDecl(D);
1020
1021  if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1022    ND->getDeclContext()->makeDeclVisibleInContext(ND);
1023}
1024
1025/// buildLookup - Build the lookup data structure with all of the
1026/// declarations in DCtx (and any other contexts linked to it or
1027/// transparent contexts nested within it).
1028void DeclContext::buildLookup(DeclContext *DCtx) {
1029  for (; DCtx; DCtx = DCtx->getNextContext()) {
1030    for (decl_iterator D = DCtx->decls_begin(),
1031                    DEnd = DCtx->decls_end();
1032         D != DEnd; ++D) {
1033      // Insert this declaration into the lookup structure, but only
1034      // if it's semantically in its decl context.  During non-lazy
1035      // lookup building, this is implicitly enforced by addDecl.
1036      if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
1037        if (D->getDeclContext() == DCtx)
1038          makeDeclVisibleInContextImpl(ND);
1039
1040      // Insert any forward-declared Objective-C interfaces into the lookup
1041      // data structure.
1042      if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D))
1043        for (ObjCClassDecl::iterator I = Class->begin(), IEnd = Class->end();
1044             I != IEnd; ++I)
1045          makeDeclVisibleInContextImpl(I->getInterface());
1046
1047      // If this declaration is itself a transparent declaration context or
1048      // inline namespace, add its members (recursively).
1049      if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D))
1050        if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1051          buildLookup(InnerCtx->getPrimaryContext());
1052    }
1053  }
1054}
1055
1056DeclContext::lookup_result
1057DeclContext::lookup(DeclarationName Name) {
1058  DeclContext *PrimaryContext = getPrimaryContext();
1059  if (PrimaryContext != this)
1060    return PrimaryContext->lookup(Name);
1061
1062  if (hasExternalVisibleStorage()) {
1063    // Check to see if we've already cached the lookup results.
1064    if (LookupPtr) {
1065      StoredDeclsMap::iterator I = LookupPtr->find(Name);
1066      if (I != LookupPtr->end())
1067        return I->second.getLookupResult();
1068    }
1069
1070    ExternalASTSource *Source = getParentASTContext().getExternalSource();
1071    return Source->FindExternalVisibleDeclsByName(this, Name);
1072  }
1073
1074  /// If there is no lookup data structure, build one now by walking
1075  /// all of the linked DeclContexts (in declaration order!) and
1076  /// inserting their values.
1077  if (!LookupPtr) {
1078    buildLookup(this);
1079
1080    if (!LookupPtr)
1081      return lookup_result(lookup_iterator(0), lookup_iterator(0));
1082  }
1083
1084  StoredDeclsMap::iterator Pos = LookupPtr->find(Name);
1085  if (Pos == LookupPtr->end())
1086    return lookup_result(lookup_iterator(0), lookup_iterator(0));
1087  return Pos->second.getLookupResult();
1088}
1089
1090DeclContext::lookup_const_result
1091DeclContext::lookup(DeclarationName Name) const {
1092  return const_cast<DeclContext*>(this)->lookup(Name);
1093}
1094
1095DeclContext *DeclContext::getRedeclContext() {
1096  DeclContext *Ctx = this;
1097  // Skip through transparent contexts.
1098  while (Ctx->isTransparentContext())
1099    Ctx = Ctx->getParent();
1100  return Ctx;
1101}
1102
1103DeclContext *DeclContext::getEnclosingNamespaceContext() {
1104  DeclContext *Ctx = this;
1105  // Skip through non-namespace, non-translation-unit contexts.
1106  while (!Ctx->isFileContext())
1107    Ctx = Ctx->getParent();
1108  return Ctx->getPrimaryContext();
1109}
1110
1111bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1112  // For non-file contexts, this is equivalent to Equals.
1113  if (!isFileContext())
1114    return O->Equals(this);
1115
1116  do {
1117    if (O->Equals(this))
1118      return true;
1119
1120    const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1121    if (!NS || !NS->isInline())
1122      break;
1123    O = NS->getParent();
1124  } while (O);
1125
1126  return false;
1127}
1128
1129void DeclContext::makeDeclVisibleInContext(NamedDecl *D, bool Recoverable) {
1130  // FIXME: This feels like a hack. Should DeclarationName support
1131  // template-ids, or is there a better way to keep specializations
1132  // from being visible?
1133  if (isa<ClassTemplateSpecializationDecl>(D) || D->isTemplateParameter())
1134    return;
1135  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1136    if (FD->isFunctionTemplateSpecialization())
1137      return;
1138
1139  DeclContext *PrimaryContext = getPrimaryContext();
1140  if (PrimaryContext != this) {
1141    PrimaryContext->makeDeclVisibleInContext(D, Recoverable);
1142    return;
1143  }
1144
1145  // If we already have a lookup data structure, perform the insertion
1146  // into it. If we haven't deserialized externally stored decls, deserialize
1147  // them so we can add the decl. Otherwise, be lazy and don't build that
1148  // structure until someone asks for it.
1149  if (LookupPtr || !Recoverable || hasExternalVisibleStorage())
1150    makeDeclVisibleInContextImpl(D);
1151
1152  // If we are a transparent context or inline namespace, insert into our
1153  // parent context, too. This operation is recursive.
1154  if (isTransparentContext() || isInlineNamespace())
1155    getParent()->makeDeclVisibleInContext(D, Recoverable);
1156
1157  Decl *DCAsDecl = cast<Decl>(this);
1158  // Notify that a decl was made visible unless it's a Tag being defined.
1159  if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1160    if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1161      L->AddedVisibleDecl(this, D);
1162}
1163
1164void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D) {
1165  // Skip unnamed declarations.
1166  if (!D->getDeclName())
1167    return;
1168
1169  // Skip entities that can't be found by name lookup into a particular
1170  // context.
1171  if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1172      D->isTemplateParameter())
1173    return;
1174
1175  ASTContext *C = 0;
1176  if (!LookupPtr) {
1177    C = &getParentASTContext();
1178    CreateStoredDeclsMap(*C);
1179  }
1180
1181  // If there is an external AST source, load any declarations it knows about
1182  // with this declaration's name.
1183  // If the lookup table contains an entry about this name it means that we
1184  // have already checked the external source.
1185  if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1186    if (hasExternalVisibleStorage() &&
1187        LookupPtr->find(D->getDeclName()) == LookupPtr->end())
1188      Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1189
1190  // Insert this declaration into the map.
1191  StoredDeclsList &DeclNameEntries = (*LookupPtr)[D->getDeclName()];
1192  if (DeclNameEntries.isNull()) {
1193    DeclNameEntries.setOnlyValue(D);
1194    return;
1195  }
1196
1197  // If it is possible that this is a redeclaration, check to see if there is
1198  // already a decl for which declarationReplaces returns true.  If there is
1199  // one, just replace it and return.
1200  if (DeclNameEntries.HandleRedeclaration(D))
1201    return;
1202
1203  // Put this declaration into the appropriate slot.
1204  DeclNameEntries.AddSubsequentDecl(D);
1205}
1206
1207void DeclContext::MaterializeVisibleDeclsFromExternalStorage() {
1208  ExternalASTSource *Source = getParentASTContext().getExternalSource();
1209  assert(hasExternalVisibleStorage() && Source && "No external storage?");
1210
1211  if (!LookupPtr)
1212    CreateStoredDeclsMap(getParentASTContext());
1213  Source->MaterializeVisibleDecls(this);
1214}
1215
1216/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1217/// this context.
1218DeclContext::udir_iterator_range
1219DeclContext::getUsingDirectives() const {
1220  lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
1221  return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.first),
1222                             reinterpret_cast<udir_iterator>(Result.second));
1223}
1224
1225//===----------------------------------------------------------------------===//
1226// Creation and Destruction of StoredDeclsMaps.                               //
1227//===----------------------------------------------------------------------===//
1228
1229StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1230  assert(!LookupPtr && "context already has a decls map");
1231  assert(getPrimaryContext() == this &&
1232         "creating decls map on non-primary context");
1233
1234  StoredDeclsMap *M;
1235  bool Dependent = isDependentContext();
1236  if (Dependent)
1237    M = new DependentStoredDeclsMap();
1238  else
1239    M = new StoredDeclsMap();
1240  M->Previous = C.LastSDM;
1241  C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1242  LookupPtr = M;
1243  return M;
1244}
1245
1246void ASTContext::ReleaseDeclContextMaps() {
1247  // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1248  // pointer because the subclass doesn't add anything that needs to
1249  // be deleted.
1250  StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1251}
1252
1253void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1254  while (Map) {
1255    // Advance the iteration before we invalidate memory.
1256    llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1257
1258    if (Dependent)
1259      delete static_cast<DependentStoredDeclsMap*>(Map);
1260    else
1261      delete Map;
1262
1263    Map = Next.getPointer();
1264    Dependent = Next.getInt();
1265  }
1266}
1267
1268DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1269                                                 DeclContext *Parent,
1270                                           const PartialDiagnostic &PDiag) {
1271  assert(Parent->isDependentContext()
1272         && "cannot iterate dependent diagnostics of non-dependent context");
1273  Parent = Parent->getPrimaryContext();
1274  if (!Parent->LookupPtr)
1275    Parent->CreateStoredDeclsMap(C);
1276
1277  DependentStoredDeclsMap *Map
1278    = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr);
1279
1280  // Allocate the copy of the PartialDiagnostic via the ASTContext's
1281  // BumpPtrAllocator, rather than the ASTContext itself.
1282  PartialDiagnostic::Storage *DiagStorage = 0;
1283  if (PDiag.hasStorage())
1284    DiagStorage = new (C) PartialDiagnostic::Storage;
1285
1286  DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1287
1288  // TODO: Maybe we shouldn't reverse the order during insertion.
1289  DD->NextDiagnostic = Map->FirstDiagnostic;
1290  Map->FirstDiagnostic = DD;
1291
1292  return DD;
1293}
1294