1 //===- DeclBase.cpp - Declaration AST Node Implementation -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Decl and DeclContext classes.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/DeclBase.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTMutationListener.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/AttrIterator.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/Type.h"
29 #include "clang/Basic/IdentifierTable.h"
30 #include "clang/Basic/LLVM.h"
31 #include "clang/Basic/LangOptions.h"
32 #include "clang/Basic/ObjCRuntime.h"
33 #include "clang/Basic/PartialDiagnostic.h"
34 #include "clang/Basic/SourceLocation.h"
35 #include "clang/Basic/TargetInfo.h"
36 #include "llvm/ADT/ArrayRef.h"
37 #include "llvm/ADT/PointerIntPair.h"
38 #include "llvm/ADT/SmallVector.h"
39 #include "llvm/ADT/StringRef.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/VersionTuple.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include <algorithm>
46 #include <cassert>
47 #include <cstddef>
48 #include <string>
49 #include <tuple>
50 #include <utility>
51 
52 using namespace clang;
53 
54 //===----------------------------------------------------------------------===//
55 //  Statistics
56 //===----------------------------------------------------------------------===//
57 
58 #define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
59 #define ABSTRACT_DECL(DECL)
60 #include "clang/AST/DeclNodes.inc"
61 
62 void Decl::updateOutOfDate(IdentifierInfo &II) const {
63   getASTContext().getExternalSource()->updateOutOfDateIdentifier(II);
64 }
65 
66 #define DECL(DERIVED, BASE)                                                    \
67   static_assert(alignof(Decl) >= alignof(DERIVED##Decl),                       \
68                 "Alignment sufficient after objects prepended to " #DERIVED);
69 #define ABSTRACT_DECL(DECL)
70 #include "clang/AST/DeclNodes.inc"
71 
72 void *Decl::operator new(std::size_t Size, const ASTContext &Context,
73                          unsigned ID, std::size_t Extra) {
74   // Allocate an extra 8 bytes worth of storage, which ensures that the
75   // resulting pointer will still be 8-byte aligned.
76   static_assert(sizeof(unsigned) * 2 >= alignof(Decl),
77                 "Decl won't be misaligned");
78   void *Start = Context.Allocate(Size + Extra + 8);
79   void *Result = (char*)Start + 8;
80 
81   unsigned *PrefixPtr = (unsigned *)Result - 2;
82 
83   // Zero out the first 4 bytes; this is used to store the owning module ID.
84   PrefixPtr[0] = 0;
85 
86   // Store the global declaration ID in the second 4 bytes.
87   PrefixPtr[1] = ID;
88 
89   return Result;
90 }
91 
92 void *Decl::operator new(std::size_t Size, const ASTContext &Ctx,
93                          DeclContext *Parent, std::size_t Extra) {
94   assert(!Parent || &Parent->getParentASTContext() == &Ctx);
95   // With local visibility enabled, we track the owning module even for local
96   // declarations. We create the TU decl early and may not yet know what the
97   // LangOpts are, so conservatively allocate the storage.
98   if (Ctx.getLangOpts().trackLocalOwningModule() || !Parent) {
99     // Ensure required alignment of the resulting object by adding extra
100     // padding at the start if required.
101     size_t ExtraAlign =
102         llvm::OffsetToAlignment(sizeof(Module *), alignof(Decl));
103     auto *Buffer = reinterpret_cast<char *>(
104         ::operator new(ExtraAlign + sizeof(Module *) + Size + Extra, Ctx));
105     Buffer += ExtraAlign;
106     auto *ParentModule =
107         Parent ? cast<Decl>(Parent)->getOwningModule() : nullptr;
108     return new (Buffer) Module*(ParentModule) + 1;
109   }
110   return ::operator new(Size + Extra, Ctx);
111 }
112 
113 Module *Decl::getOwningModuleSlow() const {
114   assert(isFromASTFile() && "Not from AST file?");
115   return getASTContext().getExternalSource()->getModule(getOwningModuleID());
116 }
117 
118 bool Decl::hasLocalOwningModuleStorage() const {
119   return getASTContext().getLangOpts().trackLocalOwningModule();
120 }
121 
122 const char *Decl::getDeclKindName() const {
123   switch (DeclKind) {
124   default: llvm_unreachable("Declaration not in DeclNodes.inc!");
125 #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
126 #define ABSTRACT_DECL(DECL)
127 #include "clang/AST/DeclNodes.inc"
128   }
129 }
130 
131 void Decl::setInvalidDecl(bool Invalid) {
132   InvalidDecl = Invalid;
133   assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
134   if (!Invalid) {
135     return;
136   }
137 
138   if (!isa<ParmVarDecl>(this)) {
139     // Defensive maneuver for ill-formed code: we're likely not to make it to
140     // a point where we set the access specifier, so default it to "public"
141     // to avoid triggering asserts elsewhere in the front end.
142     setAccess(AS_public);
143   }
144 
145   // Marking a DecompositionDecl as invalid implies all the child BindingDecl's
146   // are invalid too.
147   if (auto *DD = dyn_cast<DecompositionDecl>(this)) {
148     for (auto *Binding : DD->bindings()) {
149       Binding->setInvalidDecl();
150     }
151   }
152 }
153 
154 const char *DeclContext::getDeclKindName() const {
155   switch (getDeclKind()) {
156 #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
157 #define ABSTRACT_DECL(DECL)
158 #include "clang/AST/DeclNodes.inc"
159   }
160   llvm_unreachable("Declaration context not in DeclNodes.inc!");
161 }
162 
163 bool Decl::StatisticsEnabled = false;
164 void Decl::EnableStatistics() {
165   StatisticsEnabled = true;
166 }
167 
168 void Decl::PrintStats() {
169   llvm::errs() << "\n*** Decl Stats:\n";
170 
171   int totalDecls = 0;
172 #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
173 #define ABSTRACT_DECL(DECL)
174 #include "clang/AST/DeclNodes.inc"
175   llvm::errs() << "  " << totalDecls << " decls total.\n";
176 
177   int totalBytes = 0;
178 #define DECL(DERIVED, BASE)                                             \
179   if (n##DERIVED##s > 0) {                                              \
180     totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl));         \
181     llvm::errs() << "    " << n##DERIVED##s << " " #DERIVED " decls, "  \
182                  << sizeof(DERIVED##Decl) << " each ("                  \
183                  << n##DERIVED##s * sizeof(DERIVED##Decl)               \
184                  << " bytes)\n";                                        \
185   }
186 #define ABSTRACT_DECL(DECL)
187 #include "clang/AST/DeclNodes.inc"
188 
189   llvm::errs() << "Total bytes = " << totalBytes << "\n";
190 }
191 
192 void Decl::add(Kind k) {
193   switch (k) {
194 #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
195 #define ABSTRACT_DECL(DECL)
196 #include "clang/AST/DeclNodes.inc"
197   }
198 }
199 
200 bool Decl::isTemplateParameterPack() const {
201   if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(this))
202     return TTP->isParameterPack();
203   if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(this))
204     return NTTP->isParameterPack();
205   if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(this))
206     return TTP->isParameterPack();
207   return false;
208 }
209 
210 bool Decl::isParameterPack() const {
211   if (const auto *Parm = dyn_cast<ParmVarDecl>(this))
212     return Parm->isParameterPack();
213 
214   return isTemplateParameterPack();
215 }
216 
217 FunctionDecl *Decl::getAsFunction() {
218   if (auto *FD = dyn_cast<FunctionDecl>(this))
219     return FD;
220   if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
221     return FTD->getTemplatedDecl();
222   return nullptr;
223 }
224 
225 bool Decl::isTemplateDecl() const {
226   return isa<TemplateDecl>(this);
227 }
228 
229 TemplateDecl *Decl::getDescribedTemplate() const {
230   if (auto *FD = dyn_cast<FunctionDecl>(this))
231     return FD->getDescribedFunctionTemplate();
232   else if (auto *RD = dyn_cast<CXXRecordDecl>(this))
233     return RD->getDescribedClassTemplate();
234   else if (auto *VD = dyn_cast<VarDecl>(this))
235     return VD->getDescribedVarTemplate();
236   else if (auto *AD = dyn_cast<TypeAliasDecl>(this))
237     return AD->getDescribedAliasTemplate();
238 
239   return nullptr;
240 }
241 
242 bool Decl::isTemplated() const {
243   // A declaration is dependent if it is a template or a template pattern, or
244   // is within (lexcially for a friend, semantically otherwise) a dependent
245   // context.
246   // FIXME: Should local extern declarations be treated like friends?
247   if (auto *AsDC = dyn_cast<DeclContext>(this))
248     return AsDC->isDependentContext();
249   auto *DC = getFriendObjectKind() ? getLexicalDeclContext() : getDeclContext();
250   return DC->isDependentContext() || isTemplateDecl() || getDescribedTemplate();
251 }
252 
253 const DeclContext *Decl::getParentFunctionOrMethod() const {
254   for (const DeclContext *DC = getDeclContext();
255        DC && !DC->isTranslationUnit() && !DC->isNamespace();
256        DC = DC->getParent())
257     if (DC->isFunctionOrMethod())
258       return DC;
259 
260   return nullptr;
261 }
262 
263 //===----------------------------------------------------------------------===//
264 // PrettyStackTraceDecl Implementation
265 //===----------------------------------------------------------------------===//
266 
267 void PrettyStackTraceDecl::print(raw_ostream &OS) const {
268   SourceLocation TheLoc = Loc;
269   if (TheLoc.isInvalid() && TheDecl)
270     TheLoc = TheDecl->getLocation();
271 
272   if (TheLoc.isValid()) {
273     TheLoc.print(OS, SM);
274     OS << ": ";
275   }
276 
277   OS << Message;
278 
279   if (const auto *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
280     OS << " '";
281     DN->printQualifiedName(OS);
282     OS << '\'';
283   }
284   OS << '\n';
285 }
286 
287 //===----------------------------------------------------------------------===//
288 // Decl Implementation
289 //===----------------------------------------------------------------------===//
290 
291 // Out-of-line virtual method providing a home for Decl.
292 Decl::~Decl() = default;
293 
294 void Decl::setDeclContext(DeclContext *DC) {
295   DeclCtx = DC;
296 }
297 
298 void Decl::setLexicalDeclContext(DeclContext *DC) {
299   if (DC == getLexicalDeclContext())
300     return;
301 
302   if (isInSemaDC()) {
303     setDeclContextsImpl(getDeclContext(), DC, getASTContext());
304   } else {
305     getMultipleDC()->LexicalDC = DC;
306   }
307 
308   // FIXME: We shouldn't be changing the lexical context of declarations
309   // imported from AST files.
310   if (!isFromASTFile()) {
311     setModuleOwnershipKind(getModuleOwnershipKindForChildOf(DC));
312     if (hasOwningModule())
313       setLocalOwningModule(cast<Decl>(DC)->getOwningModule());
314   }
315 
316   assert(
317       (getModuleOwnershipKind() != ModuleOwnershipKind::VisibleWhenImported ||
318        getOwningModule()) &&
319       "hidden declaration has no owning module");
320 }
321 
322 void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
323                                ASTContext &Ctx) {
324   if (SemaDC == LexicalDC) {
325     DeclCtx = SemaDC;
326   } else {
327     auto *MDC = new (Ctx) Decl::MultipleDC();
328     MDC->SemanticDC = SemaDC;
329     MDC->LexicalDC = LexicalDC;
330     DeclCtx = MDC;
331   }
332 }
333 
334 bool Decl::isLexicallyWithinFunctionOrMethod() const {
335   const DeclContext *LDC = getLexicalDeclContext();
336   while (true) {
337     if (LDC->isFunctionOrMethod())
338       return true;
339     if (!isa<TagDecl>(LDC))
340       return false;
341     LDC = LDC->getLexicalParent();
342   }
343   return false;
344 }
345 
346 bool Decl::isInAnonymousNamespace() const {
347   for (const DeclContext *DC = getDeclContext(); DC; DC = DC->getParent()) {
348     if (const auto *ND = dyn_cast<NamespaceDecl>(DC))
349       if (ND->isAnonymousNamespace())
350         return true;
351   }
352 
353   return false;
354 }
355 
356 bool Decl::isInStdNamespace() const {
357   return getDeclContext()->isStdNamespace();
358 }
359 
360 TranslationUnitDecl *Decl::getTranslationUnitDecl() {
361   if (auto *TUD = dyn_cast<TranslationUnitDecl>(this))
362     return TUD;
363 
364   DeclContext *DC = getDeclContext();
365   assert(DC && "This decl is not contained in a translation unit!");
366 
367   while (!DC->isTranslationUnit()) {
368     DC = DC->getParent();
369     assert(DC && "This decl is not contained in a translation unit!");
370   }
371 
372   return cast<TranslationUnitDecl>(DC);
373 }
374 
375 ASTContext &Decl::getASTContext() const {
376   return getTranslationUnitDecl()->getASTContext();
377 }
378 
379 ASTMutationListener *Decl::getASTMutationListener() const {
380   return getASTContext().getASTMutationListener();
381 }
382 
383 unsigned Decl::getMaxAlignment() const {
384   if (!hasAttrs())
385     return 0;
386 
387   unsigned Align = 0;
388   const AttrVec &V = getAttrs();
389   ASTContext &Ctx = getASTContext();
390   specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
391   for (; I != E; ++I)
392     Align = std::max(Align, I->getAlignment(Ctx));
393   return Align;
394 }
395 
396 bool Decl::isUsed(bool CheckUsedAttr) const {
397   const Decl *CanonD = getCanonicalDecl();
398   if (CanonD->Used)
399     return true;
400 
401   // Check for used attribute.
402   // Ask the most recent decl, since attributes accumulate in the redecl chain.
403   if (CheckUsedAttr && getMostRecentDecl()->hasAttr<UsedAttr>())
404     return true;
405 
406   // The information may have not been deserialized yet. Force deserialization
407   // to complete the needed information.
408   return getMostRecentDecl()->getCanonicalDecl()->Used;
409 }
410 
411 void Decl::markUsed(ASTContext &C) {
412   if (isUsed(false))
413     return;
414 
415   if (C.getASTMutationListener())
416     C.getASTMutationListener()->DeclarationMarkedUsed(this);
417 
418   setIsUsed();
419 }
420 
421 bool Decl::isReferenced() const {
422   if (Referenced)
423     return true;
424 
425   // Check redeclarations.
426   for (const auto *I : redecls())
427     if (I->Referenced)
428       return true;
429 
430   return false;
431 }
432 
433 bool Decl::isExported() const {
434   if (isModulePrivate())
435     return false;
436   // Namespaces are always exported.
437   if (isa<TranslationUnitDecl>(this) || isa<NamespaceDecl>(this))
438     return true;
439   // Otherwise, this is a strictly lexical check.
440   for (auto *DC = getLexicalDeclContext(); DC; DC = DC->getLexicalParent()) {
441     if (cast<Decl>(DC)->isModulePrivate())
442       return false;
443     if (isa<ExportDecl>(DC))
444       return true;
445   }
446   return false;
447 }
448 
449 ExternalSourceSymbolAttr *Decl::getExternalSourceSymbolAttr() const {
450   const Decl *Definition = nullptr;
451   if (auto *ID = dyn_cast<ObjCInterfaceDecl>(this)) {
452     Definition = ID->getDefinition();
453   } else if (auto *PD = dyn_cast<ObjCProtocolDecl>(this)) {
454     Definition = PD->getDefinition();
455   } else if (auto *TD = dyn_cast<TagDecl>(this)) {
456     Definition = TD->getDefinition();
457   }
458   if (!Definition)
459     Definition = this;
460 
461   if (auto *attr = Definition->getAttr<ExternalSourceSymbolAttr>())
462     return attr;
463   if (auto *dcd = dyn_cast<Decl>(getDeclContext())) {
464     return dcd->getAttr<ExternalSourceSymbolAttr>();
465   }
466 
467   return nullptr;
468 }
469 
470 bool Decl::hasDefiningAttr() const {
471   return hasAttr<AliasAttr>() || hasAttr<IFuncAttr>();
472 }
473 
474 const Attr *Decl::getDefiningAttr() const {
475   if (auto *AA = getAttr<AliasAttr>())
476     return AA;
477   if (auto *IFA = getAttr<IFuncAttr>())
478     return IFA;
479   return nullptr;
480 }
481 
482 static StringRef getRealizedPlatform(const AvailabilityAttr *A,
483                                      const ASTContext &Context) {
484   // Check if this is an App Extension "platform", and if so chop off
485   // the suffix for matching with the actual platform.
486   StringRef RealizedPlatform = A->getPlatform()->getName();
487   if (!Context.getLangOpts().AppExt)
488     return RealizedPlatform;
489   size_t suffix = RealizedPlatform.rfind("_app_extension");
490   if (suffix != StringRef::npos)
491     return RealizedPlatform.slice(0, suffix);
492   return RealizedPlatform;
493 }
494 
495 /// Determine the availability of the given declaration based on
496 /// the target platform.
497 ///
498 /// When it returns an availability result other than \c AR_Available,
499 /// if the \p Message parameter is non-NULL, it will be set to a
500 /// string describing why the entity is unavailable.
501 ///
502 /// FIXME: Make these strings localizable, since they end up in
503 /// diagnostics.
504 static AvailabilityResult CheckAvailability(ASTContext &Context,
505                                             const AvailabilityAttr *A,
506                                             std::string *Message,
507                                             VersionTuple EnclosingVersion) {
508   if (EnclosingVersion.empty())
509     EnclosingVersion = Context.getTargetInfo().getPlatformMinVersion();
510 
511   if (EnclosingVersion.empty())
512     return AR_Available;
513 
514   StringRef ActualPlatform = A->getPlatform()->getName();
515   StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
516 
517   // Match the platform name.
518   if (getRealizedPlatform(A, Context) != TargetPlatform)
519     return AR_Available;
520 
521   StringRef PrettyPlatformName
522     = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
523 
524   if (PrettyPlatformName.empty())
525     PrettyPlatformName = ActualPlatform;
526 
527   std::string HintMessage;
528   if (!A->getMessage().empty()) {
529     HintMessage = " - ";
530     HintMessage += A->getMessage();
531   }
532 
533   // Make sure that this declaration has not been marked 'unavailable'.
534   if (A->getUnavailable()) {
535     if (Message) {
536       Message->clear();
537       llvm::raw_string_ostream Out(*Message);
538       Out << "not available on " << PrettyPlatformName
539           << HintMessage;
540     }
541 
542     return AR_Unavailable;
543   }
544 
545   // Make sure that this declaration has already been introduced.
546   if (!A->getIntroduced().empty() &&
547       EnclosingVersion < A->getIntroduced()) {
548     if (Message) {
549       Message->clear();
550       llvm::raw_string_ostream Out(*Message);
551       VersionTuple VTI(A->getIntroduced());
552       Out << "introduced in " << PrettyPlatformName << ' '
553           << VTI << HintMessage;
554     }
555 
556     return A->getStrict() ? AR_Unavailable : AR_NotYetIntroduced;
557   }
558 
559   // Make sure that this declaration hasn't been obsoleted.
560   if (!A->getObsoleted().empty() && EnclosingVersion >= A->getObsoleted()) {
561     if (Message) {
562       Message->clear();
563       llvm::raw_string_ostream Out(*Message);
564       VersionTuple VTO(A->getObsoleted());
565       Out << "obsoleted in " << PrettyPlatformName << ' '
566           << VTO << HintMessage;
567     }
568 
569     return AR_Unavailable;
570   }
571 
572   // Make sure that this declaration hasn't been deprecated.
573   if (!A->getDeprecated().empty() && EnclosingVersion >= A->getDeprecated()) {
574     if (Message) {
575       Message->clear();
576       llvm::raw_string_ostream Out(*Message);
577       VersionTuple VTD(A->getDeprecated());
578       Out << "first deprecated in " << PrettyPlatformName << ' '
579           << VTD << HintMessage;
580     }
581 
582     return AR_Deprecated;
583   }
584 
585   return AR_Available;
586 }
587 
588 AvailabilityResult Decl::getAvailability(std::string *Message,
589                                          VersionTuple EnclosingVersion,
590                                          StringRef *RealizedPlatform) const {
591   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
592     return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion,
593                                                     RealizedPlatform);
594 
595   AvailabilityResult Result = AR_Available;
596   std::string ResultMessage;
597 
598   for (const auto *A : attrs()) {
599     if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
600       if (Result >= AR_Deprecated)
601         continue;
602 
603       if (Message)
604         ResultMessage = Deprecated->getMessage();
605 
606       Result = AR_Deprecated;
607       continue;
608     }
609 
610     if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
611       if (Message)
612         *Message = Unavailable->getMessage();
613       return AR_Unavailable;
614     }
615 
616     if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
617       AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
618                                                 Message, EnclosingVersion);
619 
620       if (AR == AR_Unavailable) {
621         if (RealizedPlatform)
622           *RealizedPlatform = Availability->getPlatform()->getName();
623         return AR_Unavailable;
624       }
625 
626       if (AR > Result) {
627         Result = AR;
628         if (Message)
629           ResultMessage.swap(*Message);
630       }
631       continue;
632     }
633   }
634 
635   if (Message)
636     Message->swap(ResultMessage);
637   return Result;
638 }
639 
640 VersionTuple Decl::getVersionIntroduced() const {
641   const ASTContext &Context = getASTContext();
642   StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
643   for (const auto *A : attrs()) {
644     if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
645       if (getRealizedPlatform(Availability, Context) != TargetPlatform)
646         continue;
647       if (!Availability->getIntroduced().empty())
648         return Availability->getIntroduced();
649     }
650   }
651   return {};
652 }
653 
654 bool Decl::canBeWeakImported(bool &IsDefinition) const {
655   IsDefinition = false;
656 
657   // Variables, if they aren't definitions.
658   if (const auto *Var = dyn_cast<VarDecl>(this)) {
659     if (Var->isThisDeclarationADefinition()) {
660       IsDefinition = true;
661       return false;
662     }
663     return true;
664 
665   // Functions, if they aren't definitions.
666   } else if (const auto *FD = dyn_cast<FunctionDecl>(this)) {
667     if (FD->hasBody()) {
668       IsDefinition = true;
669       return false;
670     }
671     return true;
672 
673   // Objective-C classes, if this is the non-fragile runtime.
674   } else if (isa<ObjCInterfaceDecl>(this) &&
675              getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
676     return true;
677 
678   // Nothing else.
679   } else {
680     return false;
681   }
682 }
683 
684 bool Decl::isWeakImported() const {
685   bool IsDefinition;
686   if (!canBeWeakImported(IsDefinition))
687     return false;
688 
689   for (const auto *A : attrs()) {
690     if (isa<WeakImportAttr>(A))
691       return true;
692 
693     if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
694       if (CheckAvailability(getASTContext(), Availability, nullptr,
695                             VersionTuple()) == AR_NotYetIntroduced)
696         return true;
697     }
698   }
699 
700   return false;
701 }
702 
703 unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
704   switch (DeclKind) {
705     case Function:
706     case CXXDeductionGuide:
707     case CXXMethod:
708     case CXXConstructor:
709     case ConstructorUsingShadow:
710     case CXXDestructor:
711     case CXXConversion:
712     case EnumConstant:
713     case Var:
714     case ImplicitParam:
715     case ParmVar:
716     case ObjCMethod:
717     case ObjCProperty:
718     case MSProperty:
719       return IDNS_Ordinary;
720     case Label:
721       return IDNS_Label;
722     case IndirectField:
723       return IDNS_Ordinary | IDNS_Member;
724 
725     case Binding:
726     case NonTypeTemplateParm:
727     case VarTemplate:
728       // These (C++-only) declarations are found by redeclaration lookup for
729       // tag types, so we include them in the tag namespace.
730       return IDNS_Ordinary | IDNS_Tag;
731 
732     case ObjCCompatibleAlias:
733     case ObjCInterface:
734       return IDNS_Ordinary | IDNS_Type;
735 
736     case Typedef:
737     case TypeAlias:
738     case TemplateTypeParm:
739     case ObjCTypeParam:
740       return IDNS_Ordinary | IDNS_Type;
741 
742     case UnresolvedUsingTypename:
743       return IDNS_Ordinary | IDNS_Type | IDNS_Using;
744 
745     case UsingShadow:
746       return 0; // we'll actually overwrite this later
747 
748     case UnresolvedUsingValue:
749       return IDNS_Ordinary | IDNS_Using;
750 
751     case Using:
752     case UsingPack:
753       return IDNS_Using;
754 
755     case ObjCProtocol:
756       return IDNS_ObjCProtocol;
757 
758     case Field:
759     case ObjCAtDefsField:
760     case ObjCIvar:
761       return IDNS_Member;
762 
763     case Record:
764     case CXXRecord:
765     case Enum:
766       return IDNS_Tag | IDNS_Type;
767 
768     case Namespace:
769     case NamespaceAlias:
770       return IDNS_Namespace;
771 
772     case FunctionTemplate:
773       return IDNS_Ordinary;
774 
775     case ClassTemplate:
776     case TemplateTemplateParm:
777     case TypeAliasTemplate:
778       return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
779 
780     case OMPDeclareReduction:
781       return IDNS_OMPReduction;
782 
783     case OMPDeclareMapper:
784       return IDNS_OMPMapper;
785 
786     // Never have names.
787     case Friend:
788     case FriendTemplate:
789     case AccessSpec:
790     case LinkageSpec:
791     case Export:
792     case FileScopeAsm:
793     case StaticAssert:
794     case ObjCPropertyImpl:
795     case PragmaComment:
796     case PragmaDetectMismatch:
797     case Block:
798     case Captured:
799     case TranslationUnit:
800     case ExternCContext:
801     case Decomposition:
802 
803     case UsingDirective:
804     case BuiltinTemplate:
805     case ClassTemplateSpecialization:
806     case ClassTemplatePartialSpecialization:
807     case ClassScopeFunctionSpecialization:
808     case VarTemplateSpecialization:
809     case VarTemplatePartialSpecialization:
810     case ObjCImplementation:
811     case ObjCCategory:
812     case ObjCCategoryImpl:
813     case Import:
814     case OMPThreadPrivate:
815     case OMPRequires:
816     case OMPCapturedExpr:
817     case Empty:
818       // Never looked up by name.
819       return 0;
820   }
821 
822   llvm_unreachable("Invalid DeclKind!");
823 }
824 
825 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
826   assert(!HasAttrs && "Decl already contains attrs.");
827 
828   AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
829   assert(AttrBlank.empty() && "HasAttrs was wrong?");
830 
831   AttrBlank = attrs;
832   HasAttrs = true;
833 }
834 
835 void Decl::dropAttrs() {
836   if (!HasAttrs) return;
837 
838   HasAttrs = false;
839   getASTContext().eraseDeclAttrs(this);
840 }
841 
842 void Decl::addAttr(Attr *A) {
843   if (!hasAttrs()) {
844     setAttrs(AttrVec(1, A));
845     return;
846   }
847 
848   AttrVec &Attrs = getAttrs();
849   if (!A->isInherited()) {
850     Attrs.push_back(A);
851     return;
852   }
853 
854   // Attribute inheritance is processed after attribute parsing. To keep the
855   // order as in the source code, add inherited attributes before non-inherited
856   // ones.
857   auto I = Attrs.begin(), E = Attrs.end();
858   for (; I != E; ++I) {
859     if (!(*I)->isInherited())
860       break;
861   }
862   Attrs.insert(I, A);
863 }
864 
865 const AttrVec &Decl::getAttrs() const {
866   assert(HasAttrs && "No attrs to get!");
867   return getASTContext().getDeclAttrs(this);
868 }
869 
870 Decl *Decl::castFromDeclContext (const DeclContext *D) {
871   Decl::Kind DK = D->getDeclKind();
872   switch(DK) {
873 #define DECL(NAME, BASE)
874 #define DECL_CONTEXT(NAME) \
875     case Decl::NAME:       \
876       return static_cast<NAME##Decl *>(const_cast<DeclContext *>(D));
877 #define DECL_CONTEXT_BASE(NAME)
878 #include "clang/AST/DeclNodes.inc"
879     default:
880 #define DECL(NAME, BASE)
881 #define DECL_CONTEXT_BASE(NAME)                  \
882       if (DK >= first##NAME && DK <= last##NAME) \
883         return static_cast<NAME##Decl *>(const_cast<DeclContext *>(D));
884 #include "clang/AST/DeclNodes.inc"
885       llvm_unreachable("a decl that inherits DeclContext isn't handled");
886   }
887 }
888 
889 DeclContext *Decl::castToDeclContext(const Decl *D) {
890   Decl::Kind DK = D->getKind();
891   switch(DK) {
892 #define DECL(NAME, BASE)
893 #define DECL_CONTEXT(NAME) \
894     case Decl::NAME:       \
895       return static_cast<NAME##Decl *>(const_cast<Decl *>(D));
896 #define DECL_CONTEXT_BASE(NAME)
897 #include "clang/AST/DeclNodes.inc"
898     default:
899 #define DECL(NAME, BASE)
900 #define DECL_CONTEXT_BASE(NAME)                                   \
901       if (DK >= first##NAME && DK <= last##NAME)                  \
902         return static_cast<NAME##Decl *>(const_cast<Decl *>(D));
903 #include "clang/AST/DeclNodes.inc"
904       llvm_unreachable("a decl that inherits DeclContext isn't handled");
905   }
906 }
907 
908 SourceLocation Decl::getBodyRBrace() const {
909   // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
910   // FunctionDecl stores EndRangeLoc for this purpose.
911   if (const auto *FD = dyn_cast<FunctionDecl>(this)) {
912     const FunctionDecl *Definition;
913     if (FD->hasBody(Definition))
914       return Definition->getSourceRange().getEnd();
915     return {};
916   }
917 
918   if (Stmt *Body = getBody())
919     return Body->getSourceRange().getEnd();
920 
921   return {};
922 }
923 
924 bool Decl::AccessDeclContextSanity() const {
925 #ifndef NDEBUG
926   // Suppress this check if any of the following hold:
927   // 1. this is the translation unit (and thus has no parent)
928   // 2. this is a template parameter (and thus doesn't belong to its context)
929   // 3. this is a non-type template parameter
930   // 4. the context is not a record
931   // 5. it's invalid
932   // 6. it's a C++0x static_assert.
933   // 7. it's a block literal declaration
934   if (isa<TranslationUnitDecl>(this) ||
935       isa<TemplateTypeParmDecl>(this) ||
936       isa<NonTypeTemplateParmDecl>(this) ||
937       !isa<CXXRecordDecl>(getDeclContext()) ||
938       isInvalidDecl() ||
939       isa<StaticAssertDecl>(this) ||
940       isa<BlockDecl>(this) ||
941       // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
942       // as DeclContext (?).
943       isa<ParmVarDecl>(this) ||
944       // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
945       // AS_none as access specifier.
946       isa<CXXRecordDecl>(this) ||
947       isa<ClassScopeFunctionSpecializationDecl>(this))
948     return true;
949 
950   assert(Access != AS_none &&
951          "Access specifier is AS_none inside a record decl");
952 #endif
953   return true;
954 }
955 
956 static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
957 static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
958 
959 int64_t Decl::getID() const {
960   return getASTContext().getAllocator().identifyKnownAlignedObject<Decl>(this);
961 }
962 
963 const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
964   QualType Ty;
965   if (const auto *D = dyn_cast<ValueDecl>(this))
966     Ty = D->getType();
967   else if (const auto *D = dyn_cast<TypedefNameDecl>(this))
968     Ty = D->getUnderlyingType();
969   else
970     return nullptr;
971 
972   if (Ty->isFunctionPointerType())
973     Ty = Ty->getAs<PointerType>()->getPointeeType();
974   else if (BlocksToo && Ty->isBlockPointerType())
975     Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
976 
977   return Ty->getAs<FunctionType>();
978 }
979 
980 /// Starting at a given context (a Decl or DeclContext), look for a
981 /// code context that is not a closure (a lambda, block, etc.).
982 template <class T> static Decl *getNonClosureContext(T *D) {
983   if (getKind(D) == Decl::CXXMethod) {
984     auto *MD = cast<CXXMethodDecl>(D);
985     if (MD->getOverloadedOperator() == OO_Call &&
986         MD->getParent()->isLambda())
987       return getNonClosureContext(MD->getParent()->getParent());
988     return MD;
989   } else if (auto *FD = dyn_cast<FunctionDecl>(D))
990     return FD;
991   else if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
992     return MD;
993   else if (auto *BD = dyn_cast<BlockDecl>(D))
994     return getNonClosureContext(BD->getParent());
995   else if (auto *CD = dyn_cast<CapturedDecl>(D))
996     return getNonClosureContext(CD->getParent());
997   else
998     return nullptr;
999 }
1000 
1001 Decl *Decl::getNonClosureContext() {
1002   return ::getNonClosureContext(this);
1003 }
1004 
1005 Decl *DeclContext::getNonClosureAncestor() {
1006   return ::getNonClosureContext(this);
1007 }
1008 
1009 //===----------------------------------------------------------------------===//
1010 // DeclContext Implementation
1011 //===----------------------------------------------------------------------===//
1012 
1013 DeclContext::DeclContext(Decl::Kind K) {
1014   DeclContextBits.DeclKind = K;
1015   setHasExternalLexicalStorage(false);
1016   setHasExternalVisibleStorage(false);
1017   setNeedToReconcileExternalVisibleStorage(false);
1018   setHasLazyLocalLexicalLookups(false);
1019   setHasLazyExternalLexicalLookups(false);
1020   setUseQualifiedLookup(false);
1021 }
1022 
1023 bool DeclContext::classof(const Decl *D) {
1024   switch (D->getKind()) {
1025 #define DECL(NAME, BASE)
1026 #define DECL_CONTEXT(NAME) case Decl::NAME:
1027 #define DECL_CONTEXT_BASE(NAME)
1028 #include "clang/AST/DeclNodes.inc"
1029       return true;
1030     default:
1031 #define DECL(NAME, BASE)
1032 #define DECL_CONTEXT_BASE(NAME)                 \
1033       if (D->getKind() >= Decl::first##NAME &&  \
1034           D->getKind() <= Decl::last##NAME)     \
1035         return true;
1036 #include "clang/AST/DeclNodes.inc"
1037       return false;
1038   }
1039 }
1040 
1041 DeclContext::~DeclContext() = default;
1042 
1043 /// Find the parent context of this context that will be
1044 /// used for unqualified name lookup.
1045 ///
1046 /// Generally, the parent lookup context is the semantic context. However, for
1047 /// a friend function the parent lookup context is the lexical context, which
1048 /// is the class in which the friend is declared.
1049 DeclContext *DeclContext::getLookupParent() {
1050   // FIXME: Find a better way to identify friends.
1051   if (isa<FunctionDecl>(this))
1052     if (getParent()->getRedeclContext()->isFileContext() &&
1053         getLexicalParent()->getRedeclContext()->isRecord())
1054       return getLexicalParent();
1055 
1056   return getParent();
1057 }
1058 
1059 bool DeclContext::isInlineNamespace() const {
1060   return isNamespace() &&
1061          cast<NamespaceDecl>(this)->isInline();
1062 }
1063 
1064 bool DeclContext::isStdNamespace() const {
1065   if (!isNamespace())
1066     return false;
1067 
1068   const auto *ND = cast<NamespaceDecl>(this);
1069   if (ND->isInline()) {
1070     return ND->getParent()->isStdNamespace();
1071   }
1072 
1073   if (!getParent()->getRedeclContext()->isTranslationUnit())
1074     return false;
1075 
1076   const IdentifierInfo *II = ND->getIdentifier();
1077   return II && II->isStr("std");
1078 }
1079 
1080 bool DeclContext::isDependentContext() const {
1081   if (isFileContext())
1082     return false;
1083 
1084   if (isa<ClassTemplatePartialSpecializationDecl>(this))
1085     return true;
1086 
1087   if (const auto *Record = dyn_cast<CXXRecordDecl>(this)) {
1088     if (Record->getDescribedClassTemplate())
1089       return true;
1090 
1091     if (Record->isDependentLambda())
1092       return true;
1093   }
1094 
1095   if (const auto *Function = dyn_cast<FunctionDecl>(this)) {
1096     if (Function->getDescribedFunctionTemplate())
1097       return true;
1098 
1099     // Friend function declarations are dependent if their *lexical*
1100     // context is dependent.
1101     if (cast<Decl>(this)->getFriendObjectKind())
1102       return getLexicalParent()->isDependentContext();
1103   }
1104 
1105   // FIXME: A variable template is a dependent context, but is not a
1106   // DeclContext. A context within it (such as a lambda-expression)
1107   // should be considered dependent.
1108 
1109   return getParent() && getParent()->isDependentContext();
1110 }
1111 
1112 bool DeclContext::isTransparentContext() const {
1113   if (getDeclKind() == Decl::Enum)
1114     return !cast<EnumDecl>(this)->isScoped();
1115   else if (getDeclKind() == Decl::LinkageSpec || getDeclKind() == Decl::Export)
1116     return true;
1117 
1118   return false;
1119 }
1120 
1121 static bool isLinkageSpecContext(const DeclContext *DC,
1122                                  LinkageSpecDecl::LanguageIDs ID) {
1123   while (DC->getDeclKind() != Decl::TranslationUnit) {
1124     if (DC->getDeclKind() == Decl::LinkageSpec)
1125       return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
1126     DC = DC->getLexicalParent();
1127   }
1128   return false;
1129 }
1130 
1131 bool DeclContext::isExternCContext() const {
1132   return isLinkageSpecContext(this, LinkageSpecDecl::lang_c);
1133 }
1134 
1135 const LinkageSpecDecl *DeclContext::getExternCContext() const {
1136   const DeclContext *DC = this;
1137   while (DC->getDeclKind() != Decl::TranslationUnit) {
1138     if (DC->getDeclKind() == Decl::LinkageSpec &&
1139         cast<LinkageSpecDecl>(DC)->getLanguage() == LinkageSpecDecl::lang_c)
1140       return cast<LinkageSpecDecl>(DC);
1141     DC = DC->getLexicalParent();
1142   }
1143   return nullptr;
1144 }
1145 
1146 bool DeclContext::isExternCXXContext() const {
1147   return isLinkageSpecContext(this, LinkageSpecDecl::lang_cxx);
1148 }
1149 
1150 bool DeclContext::Encloses(const DeclContext *DC) const {
1151   if (getPrimaryContext() != this)
1152     return getPrimaryContext()->Encloses(DC);
1153 
1154   for (; DC; DC = DC->getParent())
1155     if (DC->getPrimaryContext() == this)
1156       return true;
1157   return false;
1158 }
1159 
1160 DeclContext *DeclContext::getPrimaryContext() {
1161   switch (getDeclKind()) {
1162   case Decl::TranslationUnit:
1163   case Decl::ExternCContext:
1164   case Decl::LinkageSpec:
1165   case Decl::Export:
1166   case Decl::Block:
1167   case Decl::Captured:
1168   case Decl::OMPDeclareReduction:
1169   case Decl::OMPDeclareMapper:
1170     // There is only one DeclContext for these entities.
1171     return this;
1172 
1173   case Decl::Namespace:
1174     // The original namespace is our primary context.
1175     return static_cast<NamespaceDecl *>(this)->getOriginalNamespace();
1176 
1177   case Decl::ObjCMethod:
1178     return this;
1179 
1180   case Decl::ObjCInterface:
1181     if (auto *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
1182       return Def;
1183     return this;
1184 
1185   case Decl::ObjCProtocol:
1186     if (auto *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
1187       return Def;
1188     return this;
1189 
1190   case Decl::ObjCCategory:
1191     return this;
1192 
1193   case Decl::ObjCImplementation:
1194   case Decl::ObjCCategoryImpl:
1195     return this;
1196 
1197   default:
1198     if (getDeclKind() >= Decl::firstTag && getDeclKind() <= Decl::lastTag) {
1199       // If this is a tag type that has a definition or is currently
1200       // being defined, that definition is our primary context.
1201       auto *Tag = cast<TagDecl>(this);
1202 
1203       if (TagDecl *Def = Tag->getDefinition())
1204         return Def;
1205 
1206       if (const auto *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
1207         // Note, TagType::getDecl returns the (partial) definition one exists.
1208         TagDecl *PossiblePartialDef = TagTy->getDecl();
1209         if (PossiblePartialDef->isBeingDefined())
1210           return PossiblePartialDef;
1211       } else {
1212         assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
1213       }
1214 
1215       return Tag;
1216     }
1217 
1218     assert(getDeclKind() >= Decl::firstFunction &&
1219            getDeclKind() <= Decl::lastFunction &&
1220           "Unknown DeclContext kind");
1221     return this;
1222   }
1223 }
1224 
1225 void
1226 DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
1227   Contexts.clear();
1228 
1229   if (getDeclKind() != Decl::Namespace) {
1230     Contexts.push_back(this);
1231     return;
1232   }
1233 
1234   auto *Self = static_cast<NamespaceDecl *>(this);
1235   for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
1236        N = N->getPreviousDecl())
1237     Contexts.push_back(N);
1238 
1239   std::reverse(Contexts.begin(), Contexts.end());
1240 }
1241 
1242 std::pair<Decl *, Decl *>
1243 DeclContext::BuildDeclChain(ArrayRef<Decl *> Decls,
1244                             bool FieldsAlreadyLoaded) {
1245   // Build up a chain of declarations via the Decl::NextInContextAndBits field.
1246   Decl *FirstNewDecl = nullptr;
1247   Decl *PrevDecl = nullptr;
1248   for (auto *D : Decls) {
1249     if (FieldsAlreadyLoaded && isa<FieldDecl>(D))
1250       continue;
1251 
1252     if (PrevDecl)
1253       PrevDecl->NextInContextAndBits.setPointer(D);
1254     else
1255       FirstNewDecl = D;
1256 
1257     PrevDecl = D;
1258   }
1259 
1260   return std::make_pair(FirstNewDecl, PrevDecl);
1261 }
1262 
1263 /// We have just acquired external visible storage, and we already have
1264 /// built a lookup map. For every name in the map, pull in the new names from
1265 /// the external storage.
1266 void DeclContext::reconcileExternalVisibleStorage() const {
1267   assert(hasNeedToReconcileExternalVisibleStorage() && LookupPtr);
1268   setNeedToReconcileExternalVisibleStorage(false);
1269 
1270   for (auto &Lookup : *LookupPtr)
1271     Lookup.second.setHasExternalDecls();
1272 }
1273 
1274 /// Load the declarations within this lexical storage from an
1275 /// external source.
1276 /// \return \c true if any declarations were added.
1277 bool
1278 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1279   ExternalASTSource *Source = getParentASTContext().getExternalSource();
1280   assert(hasExternalLexicalStorage() && Source && "No external storage?");
1281 
1282   // Notify that we have a DeclContext that is initializing.
1283   ExternalASTSource::Deserializing ADeclContext(Source);
1284 
1285   // Load the external declarations, if any.
1286   SmallVector<Decl*, 64> Decls;
1287   setHasExternalLexicalStorage(false);
1288   Source->FindExternalLexicalDecls(this, Decls);
1289 
1290   if (Decls.empty())
1291     return false;
1292 
1293   // We may have already loaded just the fields of this record, in which case
1294   // we need to ignore them.
1295   bool FieldsAlreadyLoaded = false;
1296   if (const auto *RD = dyn_cast<RecordDecl>(this))
1297     FieldsAlreadyLoaded = RD->hasLoadedFieldsFromExternalStorage();
1298 
1299   // Splice the newly-read declarations into the beginning of the list
1300   // of declarations.
1301   Decl *ExternalFirst, *ExternalLast;
1302   std::tie(ExternalFirst, ExternalLast) =
1303       BuildDeclChain(Decls, FieldsAlreadyLoaded);
1304   ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1305   FirstDecl = ExternalFirst;
1306   if (!LastDecl)
1307     LastDecl = ExternalLast;
1308   return true;
1309 }
1310 
1311 DeclContext::lookup_result
1312 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1313                                                     DeclarationName Name) {
1314   ASTContext &Context = DC->getParentASTContext();
1315   StoredDeclsMap *Map;
1316   if (!(Map = DC->LookupPtr))
1317     Map = DC->CreateStoredDeclsMap(Context);
1318   if (DC->hasNeedToReconcileExternalVisibleStorage())
1319     DC->reconcileExternalVisibleStorage();
1320 
1321   (*Map)[Name].removeExternalDecls();
1322 
1323   return DeclContext::lookup_result();
1324 }
1325 
1326 DeclContext::lookup_result
1327 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1328                                                   DeclarationName Name,
1329                                                   ArrayRef<NamedDecl*> Decls) {
1330   ASTContext &Context = DC->getParentASTContext();
1331   StoredDeclsMap *Map;
1332   if (!(Map = DC->LookupPtr))
1333     Map = DC->CreateStoredDeclsMap(Context);
1334   if (DC->hasNeedToReconcileExternalVisibleStorage())
1335     DC->reconcileExternalVisibleStorage();
1336 
1337   StoredDeclsList &List = (*Map)[Name];
1338 
1339   // Clear out any old external visible declarations, to avoid quadratic
1340   // performance in the redeclaration checks below.
1341   List.removeExternalDecls();
1342 
1343   if (!List.isNull()) {
1344     // We have both existing declarations and new declarations for this name.
1345     // Some of the declarations may simply replace existing ones. Handle those
1346     // first.
1347     llvm::SmallVector<unsigned, 8> Skip;
1348     for (unsigned I = 0, N = Decls.size(); I != N; ++I)
1349       if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
1350         Skip.push_back(I);
1351     Skip.push_back(Decls.size());
1352 
1353     // Add in any new declarations.
1354     unsigned SkipPos = 0;
1355     for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1356       if (I == Skip[SkipPos])
1357         ++SkipPos;
1358       else
1359         List.AddSubsequentDecl(Decls[I]);
1360     }
1361   } else {
1362     // Convert the array to a StoredDeclsList.
1363     for (auto *D : Decls) {
1364       if (List.isNull())
1365         List.setOnlyValue(D);
1366       else
1367         List.AddSubsequentDecl(D);
1368     }
1369   }
1370 
1371   return List.getLookupResult();
1372 }
1373 
1374 DeclContext::decl_iterator DeclContext::decls_begin() const {
1375   if (hasExternalLexicalStorage())
1376     LoadLexicalDeclsFromExternalStorage();
1377   return decl_iterator(FirstDecl);
1378 }
1379 
1380 bool DeclContext::decls_empty() const {
1381   if (hasExternalLexicalStorage())
1382     LoadLexicalDeclsFromExternalStorage();
1383 
1384   return !FirstDecl;
1385 }
1386 
1387 bool DeclContext::containsDecl(Decl *D) const {
1388   return (D->getLexicalDeclContext() == this &&
1389           (D->NextInContextAndBits.getPointer() || D == LastDecl));
1390 }
1391 
1392 bool DeclContext::containsDeclAndLoad(Decl *D) const {
1393   if (hasExternalLexicalStorage())
1394     LoadLexicalDeclsFromExternalStorage();
1395   return containsDecl(D);
1396 }
1397 
1398 /// shouldBeHidden - Determine whether a declaration which was declared
1399 /// within its semantic context should be invisible to qualified name lookup.
1400 static bool shouldBeHidden(NamedDecl *D) {
1401   // Skip unnamed declarations.
1402   if (!D->getDeclName())
1403     return true;
1404 
1405   // Skip entities that can't be found by name lookup into a particular
1406   // context.
1407   if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1408       D->isTemplateParameter())
1409     return true;
1410 
1411   // Skip friends and local extern declarations unless they're the first
1412   // declaration of the entity.
1413   if ((D->isLocalExternDecl() || D->getFriendObjectKind()) &&
1414       D != D->getCanonicalDecl())
1415     return true;
1416 
1417   // Skip template specializations.
1418   // FIXME: This feels like a hack. Should DeclarationName support
1419   // template-ids, or is there a better way to keep specializations
1420   // from being visible?
1421   if (isa<ClassTemplateSpecializationDecl>(D))
1422     return true;
1423   if (auto *FD = dyn_cast<FunctionDecl>(D))
1424     if (FD->isFunctionTemplateSpecialization())
1425       return true;
1426 
1427   return false;
1428 }
1429 
1430 void DeclContext::removeDecl(Decl *D) {
1431   assert(D->getLexicalDeclContext() == this &&
1432          "decl being removed from non-lexical context");
1433   assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1434          "decl is not in decls list");
1435 
1436   // Remove D from the decl chain.  This is O(n) but hopefully rare.
1437   if (D == FirstDecl) {
1438     if (D == LastDecl)
1439       FirstDecl = LastDecl = nullptr;
1440     else
1441       FirstDecl = D->NextInContextAndBits.getPointer();
1442   } else {
1443     for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1444       assert(I && "decl not found in linked list");
1445       if (I->NextInContextAndBits.getPointer() == D) {
1446         I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1447         if (D == LastDecl) LastDecl = I;
1448         break;
1449       }
1450     }
1451   }
1452 
1453   // Mark that D is no longer in the decl chain.
1454   D->NextInContextAndBits.setPointer(nullptr);
1455 
1456   // Remove D from the lookup table if necessary.
1457   if (isa<NamedDecl>(D)) {
1458     auto *ND = cast<NamedDecl>(D);
1459 
1460     // Do not try to remove the declaration if that is invisible to qualified
1461     // lookup.  E.g. template specializations are skipped.
1462     if (shouldBeHidden(ND))
1463       return;
1464 
1465     // Remove only decls that have a name
1466     if (!ND->getDeclName())
1467       return;
1468 
1469     auto *DC = D->getDeclContext();
1470     do {
1471       StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1472       if (Map) {
1473         StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1474         assert(Pos != Map->end() && "no lookup entry for decl");
1475         // Remove the decl only if it is contained.
1476         StoredDeclsList::DeclsTy *Vec = Pos->second.getAsVector();
1477         if ((Vec && is_contained(*Vec, ND)) || Pos->second.getAsDecl() == ND)
1478           Pos->second.remove(ND);
1479       }
1480     } while (DC->isTransparentContext() && (DC = DC->getParent()));
1481   }
1482 }
1483 
1484 void DeclContext::addHiddenDecl(Decl *D) {
1485   assert(D->getLexicalDeclContext() == this &&
1486          "Decl inserted into wrong lexical context");
1487   assert(!D->getNextDeclInContext() && D != LastDecl &&
1488          "Decl already inserted into a DeclContext");
1489 
1490   if (FirstDecl) {
1491     LastDecl->NextInContextAndBits.setPointer(D);
1492     LastDecl = D;
1493   } else {
1494     FirstDecl = LastDecl = D;
1495   }
1496 
1497   // Notify a C++ record declaration that we've added a member, so it can
1498   // update its class-specific state.
1499   if (auto *Record = dyn_cast<CXXRecordDecl>(this))
1500     Record->addedMember(D);
1501 
1502   // If this is a newly-created (not de-serialized) import declaration, wire
1503   // it in to the list of local import declarations.
1504   if (!D->isFromASTFile()) {
1505     if (auto *Import = dyn_cast<ImportDecl>(D))
1506       D->getASTContext().addedLocalImportDecl(Import);
1507   }
1508 }
1509 
1510 void DeclContext::addDecl(Decl *D) {
1511   addHiddenDecl(D);
1512 
1513   if (auto *ND = dyn_cast<NamedDecl>(D))
1514     ND->getDeclContext()->getPrimaryContext()->
1515         makeDeclVisibleInContextWithFlags(ND, false, true);
1516 }
1517 
1518 void DeclContext::addDeclInternal(Decl *D) {
1519   addHiddenDecl(D);
1520 
1521   if (auto *ND = dyn_cast<NamedDecl>(D))
1522     ND->getDeclContext()->getPrimaryContext()->
1523         makeDeclVisibleInContextWithFlags(ND, true, true);
1524 }
1525 
1526 /// buildLookup - Build the lookup data structure with all of the
1527 /// declarations in this DeclContext (and any other contexts linked
1528 /// to it or transparent contexts nested within it) and return it.
1529 ///
1530 /// Note that the produced map may miss out declarations from an
1531 /// external source. If it does, those entries will be marked with
1532 /// the 'hasExternalDecls' flag.
1533 StoredDeclsMap *DeclContext::buildLookup() {
1534   assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1535 
1536   if (!hasLazyLocalLexicalLookups() &&
1537       !hasLazyExternalLexicalLookups())
1538     return LookupPtr;
1539 
1540   SmallVector<DeclContext *, 2> Contexts;
1541   collectAllContexts(Contexts);
1542 
1543   if (hasLazyExternalLexicalLookups()) {
1544     setHasLazyExternalLexicalLookups(false);
1545     for (auto *DC : Contexts) {
1546       if (DC->hasExternalLexicalStorage()) {
1547         bool LoadedDecls = DC->LoadLexicalDeclsFromExternalStorage();
1548         setHasLazyLocalLexicalLookups(
1549             hasLazyLocalLexicalLookups() | LoadedDecls );
1550       }
1551     }
1552 
1553     if (!hasLazyLocalLexicalLookups())
1554       return LookupPtr;
1555   }
1556 
1557   for (auto *DC : Contexts)
1558     buildLookupImpl(DC, hasExternalVisibleStorage());
1559 
1560   // We no longer have any lazy decls.
1561   setHasLazyLocalLexicalLookups(false);
1562   return LookupPtr;
1563 }
1564 
1565 /// buildLookupImpl - Build part of the lookup data structure for the
1566 /// declarations contained within DCtx, which will either be this
1567 /// DeclContext, a DeclContext linked to it, or a transparent context
1568 /// nested within it.
1569 void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
1570   for (auto *D : DCtx->noload_decls()) {
1571     // Insert this declaration into the lookup structure, but only if
1572     // it's semantically within its decl context. Any other decls which
1573     // should be found in this context are added eagerly.
1574     //
1575     // If it's from an AST file, don't add it now. It'll get handled by
1576     // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1577     // in C++, we do not track external visible decls for the TU, so in
1578     // that case we need to collect them all here.
1579     if (auto *ND = dyn_cast<NamedDecl>(D))
1580       if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1581           (!ND->isFromASTFile() ||
1582            (isTranslationUnit() &&
1583             !getParentASTContext().getLangOpts().CPlusPlus)))
1584         makeDeclVisibleInContextImpl(ND, Internal);
1585 
1586     // If this declaration is itself a transparent declaration context
1587     // or inline namespace, add the members of this declaration of that
1588     // context (recursively).
1589     if (auto *InnerCtx = dyn_cast<DeclContext>(D))
1590       if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1591         buildLookupImpl(InnerCtx, Internal);
1592   }
1593 }
1594 
1595 NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1596 
1597 DeclContext::lookup_result
1598 DeclContext::lookup(DeclarationName Name) const {
1599   assert(getDeclKind() != Decl::LinkageSpec &&
1600          getDeclKind() != Decl::Export &&
1601          "should not perform lookups into transparent contexts");
1602 
1603   const DeclContext *PrimaryContext = getPrimaryContext();
1604   if (PrimaryContext != this)
1605     return PrimaryContext->lookup(Name);
1606 
1607   // If we have an external source, ensure that any later redeclarations of this
1608   // context have been loaded, since they may add names to the result of this
1609   // lookup (or add external visible storage).
1610   ExternalASTSource *Source = getParentASTContext().getExternalSource();
1611   if (Source)
1612     (void)cast<Decl>(this)->getMostRecentDecl();
1613 
1614   if (hasExternalVisibleStorage()) {
1615     assert(Source && "external visible storage but no external source?");
1616 
1617     if (hasNeedToReconcileExternalVisibleStorage())
1618       reconcileExternalVisibleStorage();
1619 
1620     StoredDeclsMap *Map = LookupPtr;
1621 
1622     if (hasLazyLocalLexicalLookups() ||
1623         hasLazyExternalLexicalLookups())
1624       // FIXME: Make buildLookup const?
1625       Map = const_cast<DeclContext*>(this)->buildLookup();
1626 
1627     if (!Map)
1628       Map = CreateStoredDeclsMap(getParentASTContext());
1629 
1630     // If we have a lookup result with no external decls, we are done.
1631     std::pair<StoredDeclsMap::iterator, bool> R =
1632         Map->insert(std::make_pair(Name, StoredDeclsList()));
1633     if (!R.second && !R.first->second.hasExternalDecls())
1634       return R.first->second.getLookupResult();
1635 
1636     if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
1637       if (StoredDeclsMap *Map = LookupPtr) {
1638         StoredDeclsMap::iterator I = Map->find(Name);
1639         if (I != Map->end())
1640           return I->second.getLookupResult();
1641       }
1642     }
1643 
1644     return {};
1645   }
1646 
1647   StoredDeclsMap *Map = LookupPtr;
1648   if (hasLazyLocalLexicalLookups() ||
1649       hasLazyExternalLexicalLookups())
1650     Map = const_cast<DeclContext*>(this)->buildLookup();
1651 
1652   if (!Map)
1653     return {};
1654 
1655   StoredDeclsMap::iterator I = Map->find(Name);
1656   if (I == Map->end())
1657     return {};
1658 
1659   return I->second.getLookupResult();
1660 }
1661 
1662 DeclContext::lookup_result
1663 DeclContext::noload_lookup(DeclarationName Name) {
1664   assert(getDeclKind() != Decl::LinkageSpec &&
1665          getDeclKind() != Decl::Export &&
1666          "should not perform lookups into transparent contexts");
1667 
1668   DeclContext *PrimaryContext = getPrimaryContext();
1669   if (PrimaryContext != this)
1670     return PrimaryContext->noload_lookup(Name);
1671 
1672   loadLazyLocalLexicalLookups();
1673   StoredDeclsMap *Map = LookupPtr;
1674   if (!Map)
1675     return {};
1676 
1677   StoredDeclsMap::iterator I = Map->find(Name);
1678   return I != Map->end() ? I->second.getLookupResult()
1679                          : lookup_result();
1680 }
1681 
1682 // If we have any lazy lexical declarations not in our lookup map, add them
1683 // now. Don't import any external declarations, not even if we know we have
1684 // some missing from the external visible lookups.
1685 void DeclContext::loadLazyLocalLexicalLookups() {
1686   if (hasLazyLocalLexicalLookups()) {
1687     SmallVector<DeclContext *, 2> Contexts;
1688     collectAllContexts(Contexts);
1689     for (auto *Context : Contexts)
1690       buildLookupImpl(Context, hasExternalVisibleStorage());
1691     setHasLazyLocalLexicalLookups(false);
1692   }
1693 }
1694 
1695 void DeclContext::localUncachedLookup(DeclarationName Name,
1696                                       SmallVectorImpl<NamedDecl *> &Results) {
1697   Results.clear();
1698 
1699   // If there's no external storage, just perform a normal lookup and copy
1700   // the results.
1701   if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1702     lookup_result LookupResults = lookup(Name);
1703     Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1704     return;
1705   }
1706 
1707   // If we have a lookup table, check there first. Maybe we'll get lucky.
1708   // FIXME: Should we be checking these flags on the primary context?
1709   if (Name && !hasLazyLocalLexicalLookups() &&
1710       !hasLazyExternalLexicalLookups()) {
1711     if (StoredDeclsMap *Map = LookupPtr) {
1712       StoredDeclsMap::iterator Pos = Map->find(Name);
1713       if (Pos != Map->end()) {
1714         Results.insert(Results.end(),
1715                        Pos->second.getLookupResult().begin(),
1716                        Pos->second.getLookupResult().end());
1717         return;
1718       }
1719     }
1720   }
1721 
1722   // Slow case: grovel through the declarations in our chain looking for
1723   // matches.
1724   // FIXME: If we have lazy external declarations, this will not find them!
1725   // FIXME: Should we CollectAllContexts and walk them all here?
1726   for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1727     if (auto *ND = dyn_cast<NamedDecl>(D))
1728       if (ND->getDeclName() == Name)
1729         Results.push_back(ND);
1730   }
1731 }
1732 
1733 DeclContext *DeclContext::getRedeclContext() {
1734   DeclContext *Ctx = this;
1735 
1736   // In C, a record type is the redeclaration context for its fields only. If
1737   // we arrive at a record context after skipping anything else, we should skip
1738   // the record as well. Currently, this means skipping enumerations because
1739   // they're the only transparent context that can exist within a struct or
1740   // union.
1741   bool SkipRecords = getDeclKind() == Decl::Kind::Enum &&
1742                      !getParentASTContext().getLangOpts().CPlusPlus;
1743 
1744   // Skip through contexts to get to the redeclaration context. Transparent
1745   // contexts are always skipped.
1746   while ((SkipRecords && Ctx->isRecord()) || Ctx->isTransparentContext())
1747     Ctx = Ctx->getParent();
1748   return Ctx;
1749 }
1750 
1751 DeclContext *DeclContext::getEnclosingNamespaceContext() {
1752   DeclContext *Ctx = this;
1753   // Skip through non-namespace, non-translation-unit contexts.
1754   while (!Ctx->isFileContext())
1755     Ctx = Ctx->getParent();
1756   return Ctx->getPrimaryContext();
1757 }
1758 
1759 RecordDecl *DeclContext::getOuterLexicalRecordContext() {
1760   // Loop until we find a non-record context.
1761   RecordDecl *OutermostRD = nullptr;
1762   DeclContext *DC = this;
1763   while (DC->isRecord()) {
1764     OutermostRD = cast<RecordDecl>(DC);
1765     DC = DC->getLexicalParent();
1766   }
1767   return OutermostRD;
1768 }
1769 
1770 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1771   // For non-file contexts, this is equivalent to Equals.
1772   if (!isFileContext())
1773     return O->Equals(this);
1774 
1775   do {
1776     if (O->Equals(this))
1777       return true;
1778 
1779     const auto *NS = dyn_cast<NamespaceDecl>(O);
1780     if (!NS || !NS->isInline())
1781       break;
1782     O = NS->getParent();
1783   } while (O);
1784 
1785   return false;
1786 }
1787 
1788 void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1789   DeclContext *PrimaryDC = this->getPrimaryContext();
1790   DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1791   // If the decl is being added outside of its semantic decl context, we
1792   // need to ensure that we eagerly build the lookup information for it.
1793   PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1794 }
1795 
1796 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1797                                                     bool Recoverable) {
1798   assert(this == getPrimaryContext() && "expected a primary DC");
1799 
1800   if (!isLookupContext()) {
1801     if (isTransparentContext())
1802       getParent()->getPrimaryContext()
1803         ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1804     return;
1805   }
1806 
1807   // Skip declarations which should be invisible to name lookup.
1808   if (shouldBeHidden(D))
1809     return;
1810 
1811   // If we already have a lookup data structure, perform the insertion into
1812   // it. If we might have externally-stored decls with this name, look them
1813   // up and perform the insertion. If this decl was declared outside its
1814   // semantic context, buildLookup won't add it, so add it now.
1815   //
1816   // FIXME: As a performance hack, don't add such decls into the translation
1817   // unit unless we're in C++, since qualified lookup into the TU is never
1818   // performed.
1819   if (LookupPtr || hasExternalVisibleStorage() ||
1820       ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1821        (getParentASTContext().getLangOpts().CPlusPlus ||
1822         !isTranslationUnit()))) {
1823     // If we have lazily omitted any decls, they might have the same name as
1824     // the decl which we are adding, so build a full lookup table before adding
1825     // this decl.
1826     buildLookup();
1827     makeDeclVisibleInContextImpl(D, Internal);
1828   } else {
1829     setHasLazyLocalLexicalLookups(true);
1830   }
1831 
1832   // If we are a transparent context or inline namespace, insert into our
1833   // parent context, too. This operation is recursive.
1834   if (isTransparentContext() || isInlineNamespace())
1835     getParent()->getPrimaryContext()->
1836         makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1837 
1838   auto *DCAsDecl = cast<Decl>(this);
1839   // Notify that a decl was made visible unless we are a Tag being defined.
1840   if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1841     if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1842       L->AddedVisibleDecl(this, D);
1843 }
1844 
1845 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1846   // Find or create the stored declaration map.
1847   StoredDeclsMap *Map = LookupPtr;
1848   if (!Map) {
1849     ASTContext *C = &getParentASTContext();
1850     Map = CreateStoredDeclsMap(*C);
1851   }
1852 
1853   // If there is an external AST source, load any declarations it knows about
1854   // with this declaration's name.
1855   // If the lookup table contains an entry about this name it means that we
1856   // have already checked the external source.
1857   if (!Internal)
1858     if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1859       if (hasExternalVisibleStorage() &&
1860           Map->find(D->getDeclName()) == Map->end())
1861         Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1862 
1863   // Insert this declaration into the map.
1864   StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1865 
1866   if (Internal) {
1867     // If this is being added as part of loading an external declaration,
1868     // this may not be the only external declaration with this name.
1869     // In this case, we never try to replace an existing declaration; we'll
1870     // handle that when we finalize the list of declarations for this name.
1871     DeclNameEntries.setHasExternalDecls();
1872     DeclNameEntries.AddSubsequentDecl(D);
1873     return;
1874   }
1875 
1876   if (DeclNameEntries.isNull()) {
1877     DeclNameEntries.setOnlyValue(D);
1878     return;
1879   }
1880 
1881   if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
1882     // This declaration has replaced an existing one for which
1883     // declarationReplaces returns true.
1884     return;
1885   }
1886 
1887   // Put this declaration into the appropriate slot.
1888   DeclNameEntries.AddSubsequentDecl(D);
1889 }
1890 
1891 UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
1892   return cast<UsingDirectiveDecl>(*I);
1893 }
1894 
1895 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1896 /// this context.
1897 DeclContext::udir_range DeclContext::using_directives() const {
1898   // FIXME: Use something more efficient than normal lookup for using
1899   // directives. In C++, using directives are looked up more than anything else.
1900   lookup_result Result = lookup(UsingDirectiveDecl::getName());
1901   return udir_range(Result.begin(), Result.end());
1902 }
1903 
1904 //===----------------------------------------------------------------------===//
1905 // Creation and Destruction of StoredDeclsMaps.                               //
1906 //===----------------------------------------------------------------------===//
1907 
1908 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1909   assert(!LookupPtr && "context already has a decls map");
1910   assert(getPrimaryContext() == this &&
1911          "creating decls map on non-primary context");
1912 
1913   StoredDeclsMap *M;
1914   bool Dependent = isDependentContext();
1915   if (Dependent)
1916     M = new DependentStoredDeclsMap();
1917   else
1918     M = new StoredDeclsMap();
1919   M->Previous = C.LastSDM;
1920   C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1921   LookupPtr = M;
1922   return M;
1923 }
1924 
1925 void ASTContext::ReleaseDeclContextMaps() {
1926   // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1927   // pointer because the subclass doesn't add anything that needs to
1928   // be deleted.
1929   StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1930 }
1931 
1932 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1933   while (Map) {
1934     // Advance the iteration before we invalidate memory.
1935     llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1936 
1937     if (Dependent)
1938       delete static_cast<DependentStoredDeclsMap*>(Map);
1939     else
1940       delete Map;
1941 
1942     Map = Next.getPointer();
1943     Dependent = Next.getInt();
1944   }
1945 }
1946 
1947 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1948                                                  DeclContext *Parent,
1949                                            const PartialDiagnostic &PDiag) {
1950   assert(Parent->isDependentContext()
1951          && "cannot iterate dependent diagnostics of non-dependent context");
1952   Parent = Parent->getPrimaryContext();
1953   if (!Parent->LookupPtr)
1954     Parent->CreateStoredDeclsMap(C);
1955 
1956   auto *Map = static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
1957 
1958   // Allocate the copy of the PartialDiagnostic via the ASTContext's
1959   // BumpPtrAllocator, rather than the ASTContext itself.
1960   PartialDiagnostic::Storage *DiagStorage = nullptr;
1961   if (PDiag.hasStorage())
1962     DiagStorage = new (C) PartialDiagnostic::Storage;
1963 
1964   auto *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1965 
1966   // TODO: Maybe we shouldn't reverse the order during insertion.
1967   DD->NextDiagnostic = Map->FirstDiagnostic;
1968   Map->FirstDiagnostic = DD;
1969 
1970   return DD;
1971 }
1972