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