DeclBase.cpp revision ddb10f767604d8efa5e491076d6fdd23a19db86c
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/ASTContext.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclContextInternals.h"
21#include "clang/AST/DeclFriend.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclOpenMP.h"
24#include "clang/AST/DeclTemplate.h"
25#include "clang/AST/DependentDiagnostic.h"
26#include "clang/AST/ExternalASTSource.h"
27#include "clang/AST/Stmt.h"
28#include "clang/AST/StmtCXX.h"
29#include "clang/AST/Type.h"
30#include "clang/Basic/TargetInfo.h"
31#include "llvm/ADT/DenseMap.h"
32#include "llvm/Support/raw_ostream.h"
33#include <algorithm>
34using namespace clang;
35
36//===----------------------------------------------------------------------===//
37//  Statistics
38//===----------------------------------------------------------------------===//
39
40#define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
41#define ABSTRACT_DECL(DECL)
42#include "clang/AST/DeclNodes.inc"
43
44void Decl::updateOutOfDate(IdentifierInfo &II) const {
45  getASTContext().getExternalSource()->updateOutOfDateIdentifier(II);
46}
47
48void *Decl::AllocateDeserializedDecl(const ASTContext &Context,
49                                     unsigned ID,
50                                     unsigned Size) {
51  // Allocate an extra 8 bytes worth of storage, which ensures that the
52  // resulting pointer will still be 8-byte aligned.
53  void *Start = Context.Allocate(Size + 8);
54  void *Result = (char*)Start + 8;
55
56  unsigned *PrefixPtr = (unsigned *)Result - 2;
57
58  // Zero out the first 4 bytes; this is used to store the owning module ID.
59  PrefixPtr[0] = 0;
60
61  // Store the global declaration ID in the second 4 bytes.
62  PrefixPtr[1] = ID;
63
64  return Result;
65}
66
67Module *Decl::getOwningModuleSlow() const {
68  assert(isFromASTFile() && "Not from AST file?");
69  return getASTContext().getExternalSource()->getModule(getOwningModuleID());
70}
71
72const char *Decl::getDeclKindName() const {
73  switch (DeclKind) {
74  default: llvm_unreachable("Declaration not in DeclNodes.inc!");
75#define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
76#define ABSTRACT_DECL(DECL)
77#include "clang/AST/DeclNodes.inc"
78  }
79}
80
81void Decl::setInvalidDecl(bool Invalid) {
82  InvalidDecl = Invalid;
83  if (Invalid && !isa<ParmVarDecl>(this)) {
84    // Defensive maneuver for ill-formed code: we're likely not to make it to
85    // a point where we set the access specifier, so default it to "public"
86    // to avoid triggering asserts elsewhere in the front end.
87    setAccess(AS_public);
88  }
89}
90
91const char *DeclContext::getDeclKindName() const {
92  switch (DeclKind) {
93  default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
94#define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
95#define ABSTRACT_DECL(DECL)
96#include "clang/AST/DeclNodes.inc"
97  }
98}
99
100bool Decl::StatisticsEnabled = false;
101void Decl::EnableStatistics() {
102  StatisticsEnabled = true;
103}
104
105void Decl::PrintStats() {
106  llvm::errs() << "\n*** Decl Stats:\n";
107
108  int totalDecls = 0;
109#define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
110#define ABSTRACT_DECL(DECL)
111#include "clang/AST/DeclNodes.inc"
112  llvm::errs() << "  " << totalDecls << " decls total.\n";
113
114  int totalBytes = 0;
115#define DECL(DERIVED, BASE)                                             \
116  if (n##DERIVED##s > 0) {                                              \
117    totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl));         \
118    llvm::errs() << "    " << n##DERIVED##s << " " #DERIVED " decls, "  \
119                 << sizeof(DERIVED##Decl) << " each ("                  \
120                 << n##DERIVED##s * sizeof(DERIVED##Decl)               \
121                 << " bytes)\n";                                        \
122  }
123#define ABSTRACT_DECL(DECL)
124#include "clang/AST/DeclNodes.inc"
125
126  llvm::errs() << "Total bytes = " << totalBytes << "\n";
127}
128
129void Decl::add(Kind k) {
130  switch (k) {
131#define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
132#define ABSTRACT_DECL(DECL)
133#include "clang/AST/DeclNodes.inc"
134  }
135}
136
137bool Decl::isTemplateParameterPack() const {
138  if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
139    return TTP->isParameterPack();
140  if (const NonTypeTemplateParmDecl *NTTP
141                                = dyn_cast<NonTypeTemplateParmDecl>(this))
142    return NTTP->isParameterPack();
143  if (const TemplateTemplateParmDecl *TTP
144                                    = dyn_cast<TemplateTemplateParmDecl>(this))
145    return TTP->isParameterPack();
146  return false;
147}
148
149bool Decl::isParameterPack() const {
150  if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
151    return Parm->isParameterPack();
152
153  return isTemplateParameterPack();
154}
155
156bool Decl::isFunctionOrFunctionTemplate() const {
157  if (const UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(this))
158    return UD->getTargetDecl()->isFunctionOrFunctionTemplate();
159
160  return isa<FunctionDecl>(this) || isa<FunctionTemplateDecl>(this);
161}
162
163bool Decl::isTemplateDecl() const {
164  return isa<TemplateDecl>(this);
165}
166
167const DeclContext *Decl::getParentFunctionOrMethod() const {
168  for (const DeclContext *DC = getDeclContext();
169       DC && !DC->isTranslationUnit() && !DC->isNamespace();
170       DC = DC->getParent())
171    if (DC->isFunctionOrMethod())
172      return DC;
173
174  return 0;
175}
176
177
178//===----------------------------------------------------------------------===//
179// PrettyStackTraceDecl Implementation
180//===----------------------------------------------------------------------===//
181
182void PrettyStackTraceDecl::print(raw_ostream &OS) const {
183  SourceLocation TheLoc = Loc;
184  if (TheLoc.isInvalid() && TheDecl)
185    TheLoc = TheDecl->getLocation();
186
187  if (TheLoc.isValid()) {
188    TheLoc.print(OS, SM);
189    OS << ": ";
190  }
191
192  OS << Message;
193
194  if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
195    OS << " '";
196    DN->printQualifiedName(OS);
197    OS << '\'';
198  }
199  OS << '\n';
200}
201
202//===----------------------------------------------------------------------===//
203// Decl Implementation
204//===----------------------------------------------------------------------===//
205
206// Out-of-line virtual method providing a home for Decl.
207Decl::~Decl() { }
208
209void Decl::setDeclContext(DeclContext *DC) {
210  DeclCtx = DC;
211}
212
213void Decl::setLexicalDeclContext(DeclContext *DC) {
214  if (DC == getLexicalDeclContext())
215    return;
216
217  if (isInSemaDC()) {
218    setDeclContextsImpl(getDeclContext(), DC, getASTContext());
219  } else {
220    getMultipleDC()->LexicalDC = DC;
221  }
222}
223
224void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
225                               ASTContext &Ctx) {
226  if (SemaDC == LexicalDC) {
227    DeclCtx = SemaDC;
228  } else {
229    Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
230    MDC->SemanticDC = SemaDC;
231    MDC->LexicalDC = LexicalDC;
232    DeclCtx = MDC;
233  }
234}
235
236bool Decl::isInAnonymousNamespace() const {
237  const DeclContext *DC = getDeclContext();
238  do {
239    if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
240      if (ND->isAnonymousNamespace())
241        return true;
242  } while ((DC = DC->getParent()));
243
244  return false;
245}
246
247TranslationUnitDecl *Decl::getTranslationUnitDecl() {
248  if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
249    return TUD;
250
251  DeclContext *DC = getDeclContext();
252  assert(DC && "This decl is not contained in a translation unit!");
253
254  while (!DC->isTranslationUnit()) {
255    DC = DC->getParent();
256    assert(DC && "This decl is not contained in a translation unit!");
257  }
258
259  return cast<TranslationUnitDecl>(DC);
260}
261
262ASTContext &Decl::getASTContext() const {
263  return getTranslationUnitDecl()->getASTContext();
264}
265
266ASTMutationListener *Decl::getASTMutationListener() const {
267  return getASTContext().getASTMutationListener();
268}
269
270unsigned Decl::getMaxAlignment() const {
271  if (!hasAttrs())
272    return 0;
273
274  unsigned Align = 0;
275  const AttrVec &V = getAttrs();
276  ASTContext &Ctx = getASTContext();
277  specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
278  for (; I != E; ++I)
279    Align = std::max(Align, I->getAlignment(Ctx));
280  return Align;
281}
282
283bool Decl::isUsed(bool CheckUsedAttr) const {
284  if (Used)
285    return true;
286
287  // Check for used attribute.
288  if (CheckUsedAttr && hasAttr<UsedAttr>())
289    return true;
290
291  return false;
292}
293
294bool Decl::isReferenced() const {
295  if (Referenced)
296    return true;
297
298  // Check redeclarations.
299  for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
300    if (I->Referenced)
301      return true;
302
303  return false;
304}
305
306/// \brief Determine the availability of the given declaration based on
307/// the target platform.
308///
309/// When it returns an availability result other than \c AR_Available,
310/// if the \p Message parameter is non-NULL, it will be set to a
311/// string describing why the entity is unavailable.
312///
313/// FIXME: Make these strings localizable, since they end up in
314/// diagnostics.
315static AvailabilityResult CheckAvailability(ASTContext &Context,
316                                            const AvailabilityAttr *A,
317                                            std::string *Message) {
318  StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
319  StringRef PrettyPlatformName
320    = AvailabilityAttr::getPrettyPlatformName(TargetPlatform);
321  if (PrettyPlatformName.empty())
322    PrettyPlatformName = TargetPlatform;
323
324  VersionTuple TargetMinVersion = Context.getTargetInfo().getPlatformMinVersion();
325  if (TargetMinVersion.empty())
326    return AR_Available;
327
328  // Match the platform name.
329  if (A->getPlatform()->getName() != TargetPlatform)
330    return AR_Available;
331
332  std::string HintMessage;
333  if (!A->getMessage().empty()) {
334    HintMessage = " - ";
335    HintMessage += A->getMessage();
336  }
337
338  // Make sure that this declaration has not been marked 'unavailable'.
339  if (A->getUnavailable()) {
340    if (Message) {
341      Message->clear();
342      llvm::raw_string_ostream Out(*Message);
343      Out << "not available on " << PrettyPlatformName
344          << HintMessage;
345    }
346
347    return AR_Unavailable;
348  }
349
350  // Make sure that this declaration has already been introduced.
351  if (!A->getIntroduced().empty() &&
352      TargetMinVersion < A->getIntroduced()) {
353    if (Message) {
354      Message->clear();
355      llvm::raw_string_ostream Out(*Message);
356      Out << "introduced in " << PrettyPlatformName << ' '
357          << A->getIntroduced() << HintMessage;
358    }
359
360    return AR_NotYetIntroduced;
361  }
362
363  // Make sure that this declaration hasn't been obsoleted.
364  if (!A->getObsoleted().empty() && TargetMinVersion >= A->getObsoleted()) {
365    if (Message) {
366      Message->clear();
367      llvm::raw_string_ostream Out(*Message);
368      Out << "obsoleted in " << PrettyPlatformName << ' '
369          << A->getObsoleted() << HintMessage;
370    }
371
372    return AR_Unavailable;
373  }
374
375  // Make sure that this declaration hasn't been deprecated.
376  if (!A->getDeprecated().empty() && TargetMinVersion >= A->getDeprecated()) {
377    if (Message) {
378      Message->clear();
379      llvm::raw_string_ostream Out(*Message);
380      Out << "first deprecated in " << PrettyPlatformName << ' '
381          << A->getDeprecated() << HintMessage;
382    }
383
384    return AR_Deprecated;
385  }
386
387  return AR_Available;
388}
389
390AvailabilityResult Decl::getAvailability(std::string *Message) const {
391  AvailabilityResult Result = AR_Available;
392  std::string ResultMessage;
393
394  for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) {
395    if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(*A)) {
396      if (Result >= AR_Deprecated)
397        continue;
398
399      if (Message)
400        ResultMessage = Deprecated->getMessage();
401
402      Result = AR_Deprecated;
403      continue;
404    }
405
406    if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(*A)) {
407      if (Message)
408        *Message = Unavailable->getMessage();
409      return AR_Unavailable;
410    }
411
412    if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) {
413      AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
414                                                Message);
415
416      if (AR == AR_Unavailable)
417        return AR_Unavailable;
418
419      if (AR > Result) {
420        Result = AR;
421        if (Message)
422          ResultMessage.swap(*Message);
423      }
424      continue;
425    }
426  }
427
428  if (Message)
429    Message->swap(ResultMessage);
430  return Result;
431}
432
433bool Decl::canBeWeakImported(bool &IsDefinition) const {
434  IsDefinition = false;
435
436  // Variables, if they aren't definitions.
437  if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
438    if (Var->isThisDeclarationADefinition()) {
439      IsDefinition = true;
440      return false;
441    }
442    return true;
443
444  // Functions, if they aren't definitions.
445  } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
446    if (FD->hasBody()) {
447      IsDefinition = true;
448      return false;
449    }
450    return true;
451
452  // Objective-C classes, if this is the non-fragile runtime.
453  } else if (isa<ObjCInterfaceDecl>(this) &&
454             getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
455    return true;
456
457  // Nothing else.
458  } else {
459    return false;
460  }
461}
462
463bool Decl::isWeakImported() const {
464  bool IsDefinition;
465  if (!canBeWeakImported(IsDefinition))
466    return false;
467
468  for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) {
469    if (isa<WeakImportAttr>(*A))
470      return true;
471
472    if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) {
473      if (CheckAvailability(getASTContext(), Availability, 0)
474                                                         == AR_NotYetIntroduced)
475        return true;
476    }
477  }
478
479  return false;
480}
481
482unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
483  switch (DeclKind) {
484    case Function:
485    case CXXMethod:
486    case CXXConstructor:
487    case CXXDestructor:
488    case CXXConversion:
489    case EnumConstant:
490    case Var:
491    case ImplicitParam:
492    case ParmVar:
493    case NonTypeTemplateParm:
494    case ObjCMethod:
495    case ObjCProperty:
496    case MSProperty:
497      return IDNS_Ordinary;
498    case Label:
499      return IDNS_Label;
500    case IndirectField:
501      return IDNS_Ordinary | IDNS_Member;
502
503    case ObjCCompatibleAlias:
504    case ObjCInterface:
505      return IDNS_Ordinary | IDNS_Type;
506
507    case Typedef:
508    case TypeAlias:
509    case TypeAliasTemplate:
510    case UnresolvedUsingTypename:
511    case TemplateTypeParm:
512      return IDNS_Ordinary | IDNS_Type;
513
514    case UsingShadow:
515      return 0; // we'll actually overwrite this later
516
517    case UnresolvedUsingValue:
518      return IDNS_Ordinary | IDNS_Using;
519
520    case Using:
521      return IDNS_Using;
522
523    case ObjCProtocol:
524      return IDNS_ObjCProtocol;
525
526    case Field:
527    case ObjCAtDefsField:
528    case ObjCIvar:
529      return IDNS_Member;
530
531    case Record:
532    case CXXRecord:
533    case Enum:
534      return IDNS_Tag | IDNS_Type;
535
536    case Namespace:
537    case NamespaceAlias:
538      return IDNS_Namespace;
539
540    case FunctionTemplate:
541      return IDNS_Ordinary;
542
543    case ClassTemplate:
544    case TemplateTemplateParm:
545      return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
546
547    // Never have names.
548    case Friend:
549    case FriendTemplate:
550    case AccessSpec:
551    case LinkageSpec:
552    case FileScopeAsm:
553    case StaticAssert:
554    case ObjCPropertyImpl:
555    case Block:
556    case Captured:
557    case TranslationUnit:
558
559    case UsingDirective:
560    case ClassTemplateSpecialization:
561    case ClassTemplatePartialSpecialization:
562    case ClassScopeFunctionSpecialization:
563    case ObjCImplementation:
564    case ObjCCategory:
565    case ObjCCategoryImpl:
566    case Import:
567    case OMPThreadPrivate:
568    case Empty:
569      // Never looked up by name.
570      return 0;
571  }
572
573  llvm_unreachable("Invalid DeclKind!");
574}
575
576void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
577  assert(!HasAttrs && "Decl already contains attrs.");
578
579  AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
580  assert(AttrBlank.empty() && "HasAttrs was wrong?");
581
582  AttrBlank = attrs;
583  HasAttrs = true;
584}
585
586void Decl::dropAttrs() {
587  if (!HasAttrs) return;
588
589  HasAttrs = false;
590  getASTContext().eraseDeclAttrs(this);
591}
592
593const AttrVec &Decl::getAttrs() const {
594  assert(HasAttrs && "No attrs to get!");
595  return getASTContext().getDeclAttrs(this);
596}
597
598void Decl::swapAttrs(Decl *RHS) {
599  bool HasLHSAttr = this->HasAttrs;
600  bool HasRHSAttr = RHS->HasAttrs;
601
602  // Usually, neither decl has attrs, nothing to do.
603  if (!HasLHSAttr && !HasRHSAttr) return;
604
605  // If 'this' has no attrs, swap the other way.
606  if (!HasLHSAttr)
607    return RHS->swapAttrs(this);
608
609  ASTContext &Context = getASTContext();
610
611  // Handle the case when both decls have attrs.
612  if (HasRHSAttr) {
613    std::swap(Context.getDeclAttrs(this), Context.getDeclAttrs(RHS));
614    return;
615  }
616
617  // Otherwise, LHS has an attr and RHS doesn't.
618  Context.getDeclAttrs(RHS) = Context.getDeclAttrs(this);
619  Context.eraseDeclAttrs(this);
620  this->HasAttrs = false;
621  RHS->HasAttrs = true;
622}
623
624Decl *Decl::castFromDeclContext (const DeclContext *D) {
625  Decl::Kind DK = D->getDeclKind();
626  switch(DK) {
627#define DECL(NAME, BASE)
628#define DECL_CONTEXT(NAME) \
629    case Decl::NAME:       \
630      return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
631#define DECL_CONTEXT_BASE(NAME)
632#include "clang/AST/DeclNodes.inc"
633    default:
634#define DECL(NAME, BASE)
635#define DECL_CONTEXT_BASE(NAME)                  \
636      if (DK >= first##NAME && DK <= last##NAME) \
637        return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
638#include "clang/AST/DeclNodes.inc"
639      llvm_unreachable("a decl that inherits DeclContext isn't handled");
640  }
641}
642
643DeclContext *Decl::castToDeclContext(const Decl *D) {
644  Decl::Kind DK = D->getKind();
645  switch(DK) {
646#define DECL(NAME, BASE)
647#define DECL_CONTEXT(NAME) \
648    case Decl::NAME:       \
649      return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
650#define DECL_CONTEXT_BASE(NAME)
651#include "clang/AST/DeclNodes.inc"
652    default:
653#define DECL(NAME, BASE)
654#define DECL_CONTEXT_BASE(NAME)                                   \
655      if (DK >= first##NAME && DK <= last##NAME)                  \
656        return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
657#include "clang/AST/DeclNodes.inc"
658      llvm_unreachable("a decl that inherits DeclContext isn't handled");
659  }
660}
661
662SourceLocation Decl::getBodyRBrace() const {
663  // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
664  // FunctionDecl stores EndRangeLoc for this purpose.
665  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
666    const FunctionDecl *Definition;
667    if (FD->hasBody(Definition))
668      return Definition->getSourceRange().getEnd();
669    return SourceLocation();
670  }
671
672  if (Stmt *Body = getBody())
673    return Body->getSourceRange().getEnd();
674
675  return SourceLocation();
676}
677
678void Decl::CheckAccessDeclContext() const {
679#ifndef NDEBUG
680  // Suppress this check if any of the following hold:
681  // 1. this is the translation unit (and thus has no parent)
682  // 2. this is a template parameter (and thus doesn't belong to its context)
683  // 3. this is a non-type template parameter
684  // 4. the context is not a record
685  // 5. it's invalid
686  // 6. it's a C++0x static_assert.
687  if (isa<TranslationUnitDecl>(this) ||
688      isa<TemplateTypeParmDecl>(this) ||
689      isa<NonTypeTemplateParmDecl>(this) ||
690      !isa<CXXRecordDecl>(getDeclContext()) ||
691      isInvalidDecl() ||
692      isa<StaticAssertDecl>(this) ||
693      // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
694      // as DeclContext (?).
695      isa<ParmVarDecl>(this) ||
696      // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
697      // AS_none as access specifier.
698      isa<CXXRecordDecl>(this) ||
699      isa<ClassScopeFunctionSpecializationDecl>(this))
700    return;
701
702  assert(Access != AS_none &&
703         "Access specifier is AS_none inside a record decl");
704#endif
705}
706
707static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
708static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
709
710/// Starting at a given context (a Decl or DeclContext), look for a
711/// code context that is not a closure (a lambda, block, etc.).
712template <class T> static Decl *getNonClosureContext(T *D) {
713  if (getKind(D) == Decl::CXXMethod) {
714    CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
715    if (MD->getOverloadedOperator() == OO_Call &&
716        MD->getParent()->isLambda())
717      return getNonClosureContext(MD->getParent()->getParent());
718    return MD;
719  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
720    return FD;
721  } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
722    return MD;
723  } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
724    return getNonClosureContext(BD->getParent());
725  } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
726    return getNonClosureContext(CD->getParent());
727  } else {
728    return 0;
729  }
730}
731
732Decl *Decl::getNonClosureContext() {
733  return ::getNonClosureContext(this);
734}
735
736Decl *DeclContext::getNonClosureAncestor() {
737  return ::getNonClosureContext(this);
738}
739
740//===----------------------------------------------------------------------===//
741// DeclContext Implementation
742//===----------------------------------------------------------------------===//
743
744bool DeclContext::classof(const Decl *D) {
745  switch (D->getKind()) {
746#define DECL(NAME, BASE)
747#define DECL_CONTEXT(NAME) case Decl::NAME:
748#define DECL_CONTEXT_BASE(NAME)
749#include "clang/AST/DeclNodes.inc"
750      return true;
751    default:
752#define DECL(NAME, BASE)
753#define DECL_CONTEXT_BASE(NAME)                 \
754      if (D->getKind() >= Decl::first##NAME &&  \
755          D->getKind() <= Decl::last##NAME)     \
756        return true;
757#include "clang/AST/DeclNodes.inc"
758      return false;
759  }
760}
761
762DeclContext::~DeclContext() { }
763
764/// \brief Find the parent context of this context that will be
765/// used for unqualified name lookup.
766///
767/// Generally, the parent lookup context is the semantic context. However, for
768/// a friend function the parent lookup context is the lexical context, which
769/// is the class in which the friend is declared.
770DeclContext *DeclContext::getLookupParent() {
771  // FIXME: Find a better way to identify friends
772  if (isa<FunctionDecl>(this))
773    if (getParent()->getRedeclContext()->isFileContext() &&
774        getLexicalParent()->getRedeclContext()->isRecord())
775      return getLexicalParent();
776
777  return getParent();
778}
779
780bool DeclContext::isInlineNamespace() const {
781  return isNamespace() &&
782         cast<NamespaceDecl>(this)->isInline();
783}
784
785bool DeclContext::isDependentContext() const {
786  if (isFileContext())
787    return false;
788
789  if (isa<ClassTemplatePartialSpecializationDecl>(this))
790    return true;
791
792  if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
793    if (Record->getDescribedClassTemplate())
794      return true;
795
796    if (Record->isDependentLambda())
797      return true;
798  }
799
800  if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
801    if (Function->getDescribedFunctionTemplate())
802      return true;
803
804    // Friend function declarations are dependent if their *lexical*
805    // context is dependent.
806    if (cast<Decl>(this)->getFriendObjectKind())
807      return getLexicalParent()->isDependentContext();
808  }
809
810  return getParent() && getParent()->isDependentContext();
811}
812
813bool DeclContext::isTransparentContext() const {
814  if (DeclKind == Decl::Enum)
815    return !cast<EnumDecl>(this)->isScoped();
816  else if (DeclKind == Decl::LinkageSpec)
817    return true;
818
819  return false;
820}
821
822bool DeclContext::Encloses(const DeclContext *DC) const {
823  if (getPrimaryContext() != this)
824    return getPrimaryContext()->Encloses(DC);
825
826  for (; DC; DC = DC->getParent())
827    if (DC->getPrimaryContext() == this)
828      return true;
829  return false;
830}
831
832DeclContext *DeclContext::getPrimaryContext() {
833  switch (DeclKind) {
834  case Decl::TranslationUnit:
835  case Decl::LinkageSpec:
836  case Decl::Block:
837  case Decl::Captured:
838    // There is only one DeclContext for these entities.
839    return this;
840
841  case Decl::Namespace:
842    // The original namespace is our primary context.
843    return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
844
845  case Decl::ObjCMethod:
846    return this;
847
848  case Decl::ObjCInterface:
849    if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
850      return Def;
851
852    return this;
853
854  case Decl::ObjCProtocol:
855    if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
856      return Def;
857
858    return this;
859
860  case Decl::ObjCCategory:
861    return this;
862
863  case Decl::ObjCImplementation:
864  case Decl::ObjCCategoryImpl:
865    return this;
866
867  default:
868    if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
869      // If this is a tag type that has a definition or is currently
870      // being defined, that definition is our primary context.
871      TagDecl *Tag = cast<TagDecl>(this);
872      assert(isa<TagType>(Tag->TypeForDecl) ||
873             isa<InjectedClassNameType>(Tag->TypeForDecl));
874
875      if (TagDecl *Def = Tag->getDefinition())
876        return Def;
877
878      if (!isa<InjectedClassNameType>(Tag->TypeForDecl)) {
879        const TagType *TagTy = cast<TagType>(Tag->TypeForDecl);
880        if (TagTy->isBeingDefined())
881          // FIXME: is it necessarily being defined in the decl
882          // that owns the type?
883          return TagTy->getDecl();
884      }
885
886      return Tag;
887    }
888
889    assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
890          "Unknown DeclContext kind");
891    return this;
892  }
893}
894
895void
896DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
897  Contexts.clear();
898
899  if (DeclKind != Decl::Namespace) {
900    Contexts.push_back(this);
901    return;
902  }
903
904  NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
905  for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
906       N = N->getPreviousDecl())
907    Contexts.push_back(N);
908
909  std::reverse(Contexts.begin(), Contexts.end());
910}
911
912std::pair<Decl *, Decl *>
913DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
914                            bool FieldsAlreadyLoaded) {
915  // Build up a chain of declarations via the Decl::NextInContextAndBits field.
916  Decl *FirstNewDecl = 0;
917  Decl *PrevDecl = 0;
918  for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
919    if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
920      continue;
921
922    Decl *D = Decls[I];
923    if (PrevDecl)
924      PrevDecl->NextInContextAndBits.setPointer(D);
925    else
926      FirstNewDecl = D;
927
928    PrevDecl = D;
929  }
930
931  return std::make_pair(FirstNewDecl, PrevDecl);
932}
933
934/// \brief We have just acquired external visible storage, and we already have
935/// built a lookup map. For every name in the map, pull in the new names from
936/// the external storage.
937void DeclContext::reconcileExternalVisibleStorage() {
938  assert(NeedToReconcileExternalVisibleStorage && LookupPtr.getPointer());
939  NeedToReconcileExternalVisibleStorage = false;
940
941  StoredDeclsMap &Map = *LookupPtr.getPointer();
942  ExternalASTSource *Source = getParentASTContext().getExternalSource();
943  for (StoredDeclsMap::iterator I = Map.begin(); I != Map.end(); ++I) {
944    I->second.removeExternalDecls();
945    Source->FindExternalVisibleDeclsByName(this, I->first);
946  }
947}
948
949/// \brief Load the declarations within this lexical storage from an
950/// external source.
951void
952DeclContext::LoadLexicalDeclsFromExternalStorage() const {
953  ExternalASTSource *Source = getParentASTContext().getExternalSource();
954  assert(hasExternalLexicalStorage() && Source && "No external storage?");
955
956  // Notify that we have a DeclContext that is initializing.
957  ExternalASTSource::Deserializing ADeclContext(Source);
958
959  // Load the external declarations, if any.
960  SmallVector<Decl*, 64> Decls;
961  ExternalLexicalStorage = false;
962  switch (Source->FindExternalLexicalDecls(this, Decls)) {
963  case ELR_Success:
964    break;
965
966  case ELR_Failure:
967  case ELR_AlreadyLoaded:
968    return;
969  }
970
971  if (Decls.empty())
972    return;
973
974  // We may have already loaded just the fields of this record, in which case
975  // we need to ignore them.
976  bool FieldsAlreadyLoaded = false;
977  if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
978    FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
979
980  // Splice the newly-read declarations into the beginning of the list
981  // of declarations.
982  Decl *ExternalFirst, *ExternalLast;
983  llvm::tie(ExternalFirst, ExternalLast) = BuildDeclChain(Decls,
984                                                          FieldsAlreadyLoaded);
985  ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
986  FirstDecl = ExternalFirst;
987  if (!LastDecl)
988    LastDecl = ExternalLast;
989}
990
991DeclContext::lookup_result
992ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
993                                                    DeclarationName Name) {
994  ASTContext &Context = DC->getParentASTContext();
995  StoredDeclsMap *Map;
996  if (!(Map = DC->LookupPtr.getPointer()))
997    Map = DC->CreateStoredDeclsMap(Context);
998
999  // Add an entry to the map for this name, if it's not already present.
1000  (*Map)[Name];
1001
1002  return DeclContext::lookup_result();
1003}
1004
1005DeclContext::lookup_result
1006ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1007                                                  DeclarationName Name,
1008                                                  ArrayRef<NamedDecl*> Decls) {
1009  ASTContext &Context = DC->getParentASTContext();
1010  StoredDeclsMap *Map;
1011  if (!(Map = DC->LookupPtr.getPointer()))
1012    Map = DC->CreateStoredDeclsMap(Context);
1013
1014  StoredDeclsList &List = (*Map)[Name];
1015
1016  // Clear out any old external visible declarations, to avoid quadratic
1017  // performance in the redeclaration checks below.
1018  List.removeExternalDecls();
1019
1020  if (!List.isNull()) {
1021    // We have both existing declarations and new declarations for this name.
1022    // Some of the declarations may simply replace existing ones. Handle those
1023    // first.
1024    llvm::SmallVector<unsigned, 8> Skip;
1025    for (unsigned I = 0, N = Decls.size(); I != N; ++I)
1026      if (List.HandleRedeclaration(Decls[I]))
1027        Skip.push_back(I);
1028    Skip.push_back(Decls.size());
1029
1030    // Add in any new declarations.
1031    unsigned SkipPos = 0;
1032    for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1033      if (I == Skip[SkipPos])
1034        ++SkipPos;
1035      else
1036        List.AddSubsequentDecl(Decls[I]);
1037    }
1038  } else {
1039    // Convert the array to a StoredDeclsList.
1040    for (ArrayRef<NamedDecl*>::iterator
1041           I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1042      if (List.isNull())
1043        List.setOnlyValue(*I);
1044      else
1045        List.AddSubsequentDecl(*I);
1046    }
1047  }
1048
1049  return List.getLookupResult();
1050}
1051
1052DeclContext::decl_iterator DeclContext::noload_decls_begin() const {
1053  return decl_iterator(FirstDecl);
1054}
1055
1056DeclContext::decl_iterator DeclContext::decls_begin() const {
1057  if (hasExternalLexicalStorage())
1058    LoadLexicalDeclsFromExternalStorage();
1059
1060  return decl_iterator(FirstDecl);
1061}
1062
1063bool DeclContext::decls_empty() const {
1064  if (hasExternalLexicalStorage())
1065    LoadLexicalDeclsFromExternalStorage();
1066
1067  return !FirstDecl;
1068}
1069
1070bool DeclContext::containsDecl(Decl *D) const {
1071  return (D->getLexicalDeclContext() == this &&
1072          (D->NextInContextAndBits.getPointer() || D == LastDecl));
1073}
1074
1075void DeclContext::removeDecl(Decl *D) {
1076  assert(D->getLexicalDeclContext() == this &&
1077         "decl being removed from non-lexical context");
1078  assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1079         "decl is not in decls list");
1080
1081  // Remove D from the decl chain.  This is O(n) but hopefully rare.
1082  if (D == FirstDecl) {
1083    if (D == LastDecl)
1084      FirstDecl = LastDecl = 0;
1085    else
1086      FirstDecl = D->NextInContextAndBits.getPointer();
1087  } else {
1088    for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1089      assert(I && "decl not found in linked list");
1090      if (I->NextInContextAndBits.getPointer() == D) {
1091        I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1092        if (D == LastDecl) LastDecl = I;
1093        break;
1094      }
1095    }
1096  }
1097
1098  // Mark that D is no longer in the decl chain.
1099  D->NextInContextAndBits.setPointer(0);
1100
1101  // Remove D from the lookup table if necessary.
1102  if (isa<NamedDecl>(D)) {
1103    NamedDecl *ND = cast<NamedDecl>(D);
1104
1105    // Remove only decls that have a name
1106    if (!ND->getDeclName()) return;
1107
1108    StoredDeclsMap *Map = getPrimaryContext()->LookupPtr.getPointer();
1109    if (!Map) return;
1110
1111    StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1112    assert(Pos != Map->end() && "no lookup entry for decl");
1113    if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1114      Pos->second.remove(ND);
1115  }
1116}
1117
1118void DeclContext::addHiddenDecl(Decl *D) {
1119  assert(D->getLexicalDeclContext() == this &&
1120         "Decl inserted into wrong lexical context");
1121  assert(!D->getNextDeclInContext() && D != LastDecl &&
1122         "Decl already inserted into a DeclContext");
1123
1124  if (FirstDecl) {
1125    LastDecl->NextInContextAndBits.setPointer(D);
1126    LastDecl = D;
1127  } else {
1128    FirstDecl = LastDecl = D;
1129  }
1130
1131  // Notify a C++ record declaration that we've added a member, so it can
1132  // update it's class-specific state.
1133  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1134    Record->addedMember(D);
1135
1136  // If this is a newly-created (not de-serialized) import declaration, wire
1137  // it in to the list of local import declarations.
1138  if (!D->isFromASTFile()) {
1139    if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1140      D->getASTContext().addedLocalImportDecl(Import);
1141  }
1142}
1143
1144void DeclContext::addDecl(Decl *D) {
1145  addHiddenDecl(D);
1146
1147  if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1148    ND->getDeclContext()->getPrimaryContext()->
1149        makeDeclVisibleInContextWithFlags(ND, false, true);
1150}
1151
1152void DeclContext::addDeclInternal(Decl *D) {
1153  addHiddenDecl(D);
1154
1155  if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1156    ND->getDeclContext()->getPrimaryContext()->
1157        makeDeclVisibleInContextWithFlags(ND, true, true);
1158}
1159
1160/// shouldBeHidden - Determine whether a declaration which was declared
1161/// within its semantic context should be invisible to qualified name lookup.
1162static bool shouldBeHidden(NamedDecl *D) {
1163  // Skip unnamed declarations.
1164  if (!D->getDeclName())
1165    return true;
1166
1167  // Skip entities that can't be found by name lookup into a particular
1168  // context.
1169  if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1170      D->isTemplateParameter())
1171    return true;
1172
1173  // Skip template specializations.
1174  // FIXME: This feels like a hack. Should DeclarationName support
1175  // template-ids, or is there a better way to keep specializations
1176  // from being visible?
1177  if (isa<ClassTemplateSpecializationDecl>(D))
1178    return true;
1179  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1180    if (FD->isFunctionTemplateSpecialization())
1181      return true;
1182
1183  return false;
1184}
1185
1186/// buildLookup - Build the lookup data structure with all of the
1187/// declarations in this DeclContext (and any other contexts linked
1188/// to it or transparent contexts nested within it) and return it.
1189StoredDeclsMap *DeclContext::buildLookup() {
1190  assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1191
1192  // FIXME: Should we keep going if hasExternalVisibleStorage?
1193  if (!LookupPtr.getInt())
1194    return LookupPtr.getPointer();
1195
1196  SmallVector<DeclContext *, 2> Contexts;
1197  collectAllContexts(Contexts);
1198  for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1199    buildLookupImpl(Contexts[I]);
1200
1201  // We no longer have any lazy decls.
1202  LookupPtr.setInt(false);
1203  NeedToReconcileExternalVisibleStorage = false;
1204  return LookupPtr.getPointer();
1205}
1206
1207/// buildLookupImpl - Build part of the lookup data structure for the
1208/// declarations contained within DCtx, which will either be this
1209/// DeclContext, a DeclContext linked to it, or a transparent context
1210/// nested within it.
1211void DeclContext::buildLookupImpl(DeclContext *DCtx) {
1212  for (decl_iterator I = DCtx->decls_begin(), E = DCtx->decls_end();
1213       I != E; ++I) {
1214    Decl *D = *I;
1215
1216    // Insert this declaration into the lookup structure, but only if
1217    // it's semantically within its decl context. Any other decls which
1218    // should be found in this context are added eagerly.
1219    if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1220      if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND))
1221        makeDeclVisibleInContextImpl(ND, false);
1222
1223    // If this declaration is itself a transparent declaration context
1224    // or inline namespace, add the members of this declaration of that
1225    // context (recursively).
1226    if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1227      if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1228        buildLookupImpl(InnerCtx);
1229  }
1230}
1231
1232DeclContext::lookup_result
1233DeclContext::lookup(DeclarationName Name) {
1234  assert(DeclKind != Decl::LinkageSpec &&
1235         "Should not perform lookups into linkage specs!");
1236
1237  DeclContext *PrimaryContext = getPrimaryContext();
1238  if (PrimaryContext != this)
1239    return PrimaryContext->lookup(Name);
1240
1241  if (hasExternalVisibleStorage()) {
1242    StoredDeclsMap *Map = LookupPtr.getPointer();
1243    if (LookupPtr.getInt())
1244      Map = buildLookup();
1245    else if (NeedToReconcileExternalVisibleStorage)
1246      reconcileExternalVisibleStorage();
1247
1248    if (!Map)
1249      Map = CreateStoredDeclsMap(getParentASTContext());
1250
1251    // If a PCH/module has a result for this name, and we have a local
1252    // declaration, we will have imported the PCH/module result when adding the
1253    // local declaration or when reconciling the module.
1254    std::pair<StoredDeclsMap::iterator, bool> R =
1255        Map->insert(std::make_pair(Name, StoredDeclsList()));
1256    if (!R.second)
1257      return R.first->second.getLookupResult();
1258
1259    ExternalASTSource *Source = getParentASTContext().getExternalSource();
1260    if (Source->FindExternalVisibleDeclsByName(this, Name)) {
1261      if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
1262        StoredDeclsMap::iterator I = Map->find(Name);
1263        if (I != Map->end())
1264          return I->second.getLookupResult();
1265      }
1266    }
1267
1268    return lookup_result(lookup_iterator(0), lookup_iterator(0));
1269  }
1270
1271  StoredDeclsMap *Map = LookupPtr.getPointer();
1272  if (LookupPtr.getInt())
1273    Map = buildLookup();
1274
1275  if (!Map)
1276    return lookup_result(lookup_iterator(0), lookup_iterator(0));
1277
1278  StoredDeclsMap::iterator I = Map->find(Name);
1279  if (I == Map->end())
1280    return lookup_result(lookup_iterator(0), lookup_iterator(0));
1281
1282  return I->second.getLookupResult();
1283}
1284
1285void DeclContext::localUncachedLookup(DeclarationName Name,
1286                                      SmallVectorImpl<NamedDecl *> &Results) {
1287  Results.clear();
1288
1289  // If there's no external storage, just perform a normal lookup and copy
1290  // the results.
1291  if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1292    lookup_result LookupResults = lookup(Name);
1293    Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1294    return;
1295  }
1296
1297  // If we have a lookup table, check there first. Maybe we'll get lucky.
1298  if (Name && !LookupPtr.getInt()) {
1299    if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
1300      StoredDeclsMap::iterator Pos = Map->find(Name);
1301      if (Pos != Map->end()) {
1302        Results.insert(Results.end(),
1303                       Pos->second.getLookupResult().begin(),
1304                       Pos->second.getLookupResult().end());
1305        return;
1306      }
1307    }
1308  }
1309
1310  // Slow case: grovel through the declarations in our chain looking for
1311  // matches.
1312  for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1313    if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1314      if (ND->getDeclName() == Name)
1315        Results.push_back(ND);
1316  }
1317}
1318
1319DeclContext *DeclContext::getRedeclContext() {
1320  DeclContext *Ctx = this;
1321  // Skip through transparent contexts.
1322  while (Ctx->isTransparentContext())
1323    Ctx = Ctx->getParent();
1324  return Ctx;
1325}
1326
1327DeclContext *DeclContext::getEnclosingNamespaceContext() {
1328  DeclContext *Ctx = this;
1329  // Skip through non-namespace, non-translation-unit contexts.
1330  while (!Ctx->isFileContext())
1331    Ctx = Ctx->getParent();
1332  return Ctx->getPrimaryContext();
1333}
1334
1335bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1336  // For non-file contexts, this is equivalent to Equals.
1337  if (!isFileContext())
1338    return O->Equals(this);
1339
1340  do {
1341    if (O->Equals(this))
1342      return true;
1343
1344    const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1345    if (!NS || !NS->isInline())
1346      break;
1347    O = NS->getParent();
1348  } while (O);
1349
1350  return false;
1351}
1352
1353void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1354  DeclContext *PrimaryDC = this->getPrimaryContext();
1355  DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1356  // If the decl is being added outside of its semantic decl context, we
1357  // need to ensure that we eagerly build the lookup information for it.
1358  PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1359}
1360
1361void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1362                                                    bool Recoverable) {
1363  assert(this == getPrimaryContext() && "expected a primary DC");
1364
1365  // Skip declarations within functions.
1366  // FIXME: We shouldn't need to build lookup tables for function declarations
1367  // ever, and we can't do so correctly because we can't model the nesting of
1368  // scopes which occurs within functions. We use "qualified" lookup into
1369  // function declarations when handling friend declarations inside nested
1370  // classes, and consequently accept the following invalid code:
1371  //
1372  //   void f() { void g(); { int g; struct S { friend void g(); }; } }
1373  if (isFunctionOrMethod() && !isa<FunctionDecl>(D))
1374    return;
1375
1376  // Skip declarations which should be invisible to name lookup.
1377  if (shouldBeHidden(D))
1378    return;
1379
1380  // If we already have a lookup data structure, perform the insertion into
1381  // it. If we might have externally-stored decls with this name, look them
1382  // up and perform the insertion. If this decl was declared outside its
1383  // semantic context, buildLookup won't add it, so add it now.
1384  //
1385  // FIXME: As a performance hack, don't add such decls into the translation
1386  // unit unless we're in C++, since qualified lookup into the TU is never
1387  // performed.
1388  if (LookupPtr.getPointer() || hasExternalVisibleStorage() ||
1389      ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1390       (getParentASTContext().getLangOpts().CPlusPlus ||
1391        !isTranslationUnit()))) {
1392    // If we have lazily omitted any decls, they might have the same name as
1393    // the decl which we are adding, so build a full lookup table before adding
1394    // this decl.
1395    buildLookup();
1396    makeDeclVisibleInContextImpl(D, Internal);
1397  } else {
1398    LookupPtr.setInt(true);
1399  }
1400
1401  // If we are a transparent context or inline namespace, insert into our
1402  // parent context, too. This operation is recursive.
1403  if (isTransparentContext() || isInlineNamespace())
1404    getParent()->getPrimaryContext()->
1405        makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1406
1407  Decl *DCAsDecl = cast<Decl>(this);
1408  // Notify that a decl was made visible unless we are a Tag being defined.
1409  if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1410    if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1411      L->AddedVisibleDecl(this, D);
1412}
1413
1414void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1415  // Find or create the stored declaration map.
1416  StoredDeclsMap *Map = LookupPtr.getPointer();
1417  if (!Map) {
1418    ASTContext *C = &getParentASTContext();
1419    Map = CreateStoredDeclsMap(*C);
1420  }
1421
1422  // If there is an external AST source, load any declarations it knows about
1423  // with this declaration's name.
1424  // If the lookup table contains an entry about this name it means that we
1425  // have already checked the external source.
1426  if (!Internal)
1427    if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1428      if (hasExternalVisibleStorage() &&
1429          Map->find(D->getDeclName()) == Map->end())
1430        Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1431
1432  // Insert this declaration into the map.
1433  StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1434  if (DeclNameEntries.isNull()) {
1435    DeclNameEntries.setOnlyValue(D);
1436    return;
1437  }
1438
1439  if (DeclNameEntries.HandleRedeclaration(D)) {
1440    // This declaration has replaced an existing one for which
1441    // declarationReplaces returns true.
1442    return;
1443  }
1444
1445  // Put this declaration into the appropriate slot.
1446  DeclNameEntries.AddSubsequentDecl(D);
1447}
1448
1449/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1450/// this context.
1451DeclContext::udir_iterator_range
1452DeclContext::getUsingDirectives() const {
1453  // FIXME: Use something more efficient than normal lookup for using
1454  // directives. In C++, using directives are looked up more than anything else.
1455  lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
1456  return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.begin()),
1457                             reinterpret_cast<udir_iterator>(Result.end()));
1458}
1459
1460//===----------------------------------------------------------------------===//
1461// Creation and Destruction of StoredDeclsMaps.                               //
1462//===----------------------------------------------------------------------===//
1463
1464StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1465  assert(!LookupPtr.getPointer() && "context already has a decls map");
1466  assert(getPrimaryContext() == this &&
1467         "creating decls map on non-primary context");
1468
1469  StoredDeclsMap *M;
1470  bool Dependent = isDependentContext();
1471  if (Dependent)
1472    M = new DependentStoredDeclsMap();
1473  else
1474    M = new StoredDeclsMap();
1475  M->Previous = C.LastSDM;
1476  C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1477  LookupPtr.setPointer(M);
1478  return M;
1479}
1480
1481void ASTContext::ReleaseDeclContextMaps() {
1482  // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1483  // pointer because the subclass doesn't add anything that needs to
1484  // be deleted.
1485  StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1486}
1487
1488void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1489  while (Map) {
1490    // Advance the iteration before we invalidate memory.
1491    llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1492
1493    if (Dependent)
1494      delete static_cast<DependentStoredDeclsMap*>(Map);
1495    else
1496      delete Map;
1497
1498    Map = Next.getPointer();
1499    Dependent = Next.getInt();
1500  }
1501}
1502
1503DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1504                                                 DeclContext *Parent,
1505                                           const PartialDiagnostic &PDiag) {
1506  assert(Parent->isDependentContext()
1507         && "cannot iterate dependent diagnostics of non-dependent context");
1508  Parent = Parent->getPrimaryContext();
1509  if (!Parent->LookupPtr.getPointer())
1510    Parent->CreateStoredDeclsMap(C);
1511
1512  DependentStoredDeclsMap *Map
1513    = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr.getPointer());
1514
1515  // Allocate the copy of the PartialDiagnostic via the ASTContext's
1516  // BumpPtrAllocator, rather than the ASTContext itself.
1517  PartialDiagnostic::Storage *DiagStorage = 0;
1518  if (PDiag.hasStorage())
1519    DiagStorage = new (C) PartialDiagnostic::Storage;
1520
1521  DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1522
1523  // TODO: Maybe we shouldn't reverse the order during insertion.
1524  DD->NextDiagnostic = Map->FirstDiagnostic;
1525  Map->FirstDiagnostic = DD;
1526
1527  return DD;
1528}
1529