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