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