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 bool Decl::isTemplated() const {
244   // A declaration is dependent if it is a template or a template pattern, or
245   // is within (lexcially for a friend, semantically otherwise) a dependent
246   // context.
247   // FIXME: Should local extern declarations be treated like friends?
248   if (auto *AsDC = dyn_cast<DeclContext>(this))
249     return AsDC->isDependentContext();
250   auto *DC = getFriendObjectKind() ? getLexicalDeclContext() : getDeclContext();
251   return DC->isDependentContext() || isTemplateDecl() || getDescribedTemplate();
252 }
253 
254 const DeclContext *Decl::getParentFunctionOrMethod() const {
255   for (const DeclContext *DC = getDeclContext();
256        DC && !DC->isTranslationUnit() && !DC->isNamespace();
257        DC = DC->getParent())
258     if (DC->isFunctionOrMethod())
259       return DC;
260 
261   return nullptr;
262 }
263 
264 //===----------------------------------------------------------------------===//
265 // PrettyStackTraceDecl Implementation
266 //===----------------------------------------------------------------------===//
267 
268 void PrettyStackTraceDecl::print(raw_ostream &OS) const {
269   SourceLocation TheLoc = Loc;
270   if (TheLoc.isInvalid() && TheDecl)
271     TheLoc = TheDecl->getLocation();
272 
273   if (TheLoc.isValid()) {
274     TheLoc.print(OS, SM);
275     OS << ": ";
276   }
277 
278   OS << Message;
279 
280   if (const auto *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
281     OS << " '";
282     DN->printQualifiedName(OS);
283     OS << '\'';
284   }
285   OS << '\n';
286 }
287 
288 //===----------------------------------------------------------------------===//
289 // Decl Implementation
290 //===----------------------------------------------------------------------===//
291 
292 // Out-of-line virtual method providing a home for Decl.
293 Decl::~Decl() = default;
294 
295 void Decl::setDeclContext(DeclContext *DC) {
296   DeclCtx = DC;
297 }
298 
299 void Decl::setLexicalDeclContext(DeclContext *DC) {
300   if (DC == getLexicalDeclContext())
301     return;
302 
303   if (isInSemaDC()) {
304     setDeclContextsImpl(getDeclContext(), DC, getASTContext());
305   } else {
306     getMultipleDC()->LexicalDC = DC;
307   }
308 
309   // FIXME: We shouldn't be changing the lexical context of declarations
310   // imported from AST files.
311   if (!isFromASTFile()) {
312     setModuleOwnershipKind(getModuleOwnershipKindForChildOf(DC));
313     if (hasOwningModule())
314       setLocalOwningModule(cast<Decl>(DC)->getOwningModule());
315   }
316 
317   assert(
318       (getModuleOwnershipKind() != ModuleOwnershipKind::VisibleWhenImported ||
319        getOwningModule()) &&
320       "hidden declaration has no owning module");
321 }
322 
323 void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
324                                ASTContext &Ctx) {
325   if (SemaDC == LexicalDC) {
326     DeclCtx = SemaDC;
327   } else {
328     auto *MDC = new (Ctx) Decl::MultipleDC();
329     MDC->SemanticDC = SemaDC;
330     MDC->LexicalDC = LexicalDC;
331     DeclCtx = MDC;
332   }
333 }
334 
335 bool Decl::isInLocalScope() const {
336   const DeclContext *LDC = getLexicalDeclContext();
337   while (true) {
338     if (LDC->isFunctionOrMethod())
339       return true;
340     if (!isa<TagDecl>(LDC))
341       return false;
342     if (const auto *CRD = dyn_cast<CXXRecordDecl>(LDC))
343       if (CRD->isLambda())
344         return true;
345     LDC = LDC->getLexicalParent();
346   }
347   return false;
348 }
349 
350 bool Decl::isInAnonymousNamespace() const {
351   for (const DeclContext *DC = getDeclContext(); DC; DC = DC->getParent()) {
352     if (const auto *ND = dyn_cast<NamespaceDecl>(DC))
353       if (ND->isAnonymousNamespace())
354         return true;
355   }
356 
357   return false;
358 }
359 
360 bool Decl::isInStdNamespace() const {
361   const DeclContext *DC = getDeclContext();
362   return DC && DC->isStdNamespace();
363 }
364 
365 TranslationUnitDecl *Decl::getTranslationUnitDecl() {
366   if (auto *TUD = dyn_cast<TranslationUnitDecl>(this))
367     return TUD;
368 
369   DeclContext *DC = getDeclContext();
370   assert(DC && "This decl is not contained in a translation unit!");
371 
372   while (!DC->isTranslationUnit()) {
373     DC = DC->getParent();
374     assert(DC && "This decl is not contained in a translation unit!");
375   }
376 
377   return cast<TranslationUnitDecl>(DC);
378 }
379 
380 ASTContext &Decl::getASTContext() const {
381   return getTranslationUnitDecl()->getASTContext();
382 }
383 
384 /// Helper to get the language options from the ASTContext.
385 /// Defined out of line to avoid depending on ASTContext.h.
386 const LangOptions &Decl::getLangOpts() const {
387   return getASTContext().getLangOpts();
388 }
389 
390 ASTMutationListener *Decl::getASTMutationListener() const {
391   return getASTContext().getASTMutationListener();
392 }
393 
394 unsigned Decl::getMaxAlignment() const {
395   if (!hasAttrs())
396     return 0;
397 
398   unsigned Align = 0;
399   const AttrVec &V = getAttrs();
400   ASTContext &Ctx = getASTContext();
401   specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
402   for (; I != E; ++I) {
403     if (!I->isAlignmentErrorDependent())
404       Align = std::max(Align, I->getAlignment(Ctx));
405   }
406   return Align;
407 }
408 
409 bool Decl::isUsed(bool CheckUsedAttr) const {
410   const Decl *CanonD = getCanonicalDecl();
411   if (CanonD->Used)
412     return true;
413 
414   // Check for used attribute.
415   // Ask the most recent decl, since attributes accumulate in the redecl chain.
416   if (CheckUsedAttr && getMostRecentDecl()->hasAttr<UsedAttr>())
417     return true;
418 
419   // The information may have not been deserialized yet. Force deserialization
420   // to complete the needed information.
421   return getMostRecentDecl()->getCanonicalDecl()->Used;
422 }
423 
424 void Decl::markUsed(ASTContext &C) {
425   if (isUsed(false))
426     return;
427 
428   if (C.getASTMutationListener())
429     C.getASTMutationListener()->DeclarationMarkedUsed(this);
430 
431   setIsUsed();
432 }
433 
434 bool Decl::isReferenced() const {
435   if (Referenced)
436     return true;
437 
438   // Check redeclarations.
439   for (const auto *I : redecls())
440     if (I->Referenced)
441       return true;
442 
443   return false;
444 }
445 
446 ExternalSourceSymbolAttr *Decl::getExternalSourceSymbolAttr() const {
447   const Decl *Definition = nullptr;
448   if (auto *ID = dyn_cast<ObjCInterfaceDecl>(this)) {
449     Definition = ID->getDefinition();
450   } else if (auto *PD = dyn_cast<ObjCProtocolDecl>(this)) {
451     Definition = PD->getDefinition();
452   } else if (auto *TD = dyn_cast<TagDecl>(this)) {
453     Definition = TD->getDefinition();
454   }
455   if (!Definition)
456     Definition = this;
457 
458   if (auto *attr = Definition->getAttr<ExternalSourceSymbolAttr>())
459     return attr;
460   if (auto *dcd = dyn_cast<Decl>(getDeclContext())) {
461     return dcd->getAttr<ExternalSourceSymbolAttr>();
462   }
463 
464   return nullptr;
465 }
466 
467 bool Decl::hasDefiningAttr() const {
468   return hasAttr<AliasAttr>() || hasAttr<IFuncAttr>() ||
469          hasAttr<LoaderUninitializedAttr>();
470 }
471 
472 const Attr *Decl::getDefiningAttr() const {
473   if (auto *AA = getAttr<AliasAttr>())
474     return AA;
475   if (auto *IFA = getAttr<IFuncAttr>())
476     return IFA;
477   if (auto *NZA = getAttr<LoaderUninitializedAttr>())
478     return NZA;
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 = std::string(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 = std::string(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     case Concept:
729       // These (C++-only) declarations are found by redeclaration lookup for
730       // tag types, so we include them in the tag namespace.
731       return IDNS_Ordinary | IDNS_Tag;
732 
733     case ObjCCompatibleAlias:
734     case ObjCInterface:
735       return IDNS_Ordinary | IDNS_Type;
736 
737     case Typedef:
738     case TypeAlias:
739     case TemplateTypeParm:
740     case ObjCTypeParam:
741       return IDNS_Ordinary | IDNS_Type;
742 
743     case UnresolvedUsingTypename:
744       return IDNS_Ordinary | IDNS_Type | IDNS_Using;
745 
746     case UsingShadow:
747       return 0; // we'll actually overwrite this later
748 
749     case UnresolvedUsingValue:
750       return IDNS_Ordinary | IDNS_Using;
751 
752     case Using:
753     case UsingPack:
754       return IDNS_Using;
755 
756     case ObjCProtocol:
757       return IDNS_ObjCProtocol;
758 
759     case Field:
760     case ObjCAtDefsField:
761     case ObjCIvar:
762       return IDNS_Member;
763 
764     case Record:
765     case CXXRecord:
766     case Enum:
767       return IDNS_Tag | IDNS_Type;
768 
769     case Namespace:
770     case NamespaceAlias:
771       return IDNS_Namespace;
772 
773     case FunctionTemplate:
774       return IDNS_Ordinary;
775 
776     case ClassTemplate:
777     case TemplateTemplateParm:
778     case TypeAliasTemplate:
779       return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
780 
781     case OMPDeclareReduction:
782       return IDNS_OMPReduction;
783 
784     case OMPDeclareMapper:
785       return IDNS_OMPMapper;
786 
787     // Never have names.
788     case Friend:
789     case FriendTemplate:
790     case AccessSpec:
791     case LinkageSpec:
792     case Export:
793     case FileScopeAsm:
794     case StaticAssert:
795     case ObjCPropertyImpl:
796     case PragmaComment:
797     case PragmaDetectMismatch:
798     case Block:
799     case Captured:
800     case TranslationUnit:
801     case ExternCContext:
802     case Decomposition:
803     case MSGuid:
804 
805     case UsingDirective:
806     case BuiltinTemplate:
807     case ClassTemplateSpecialization:
808     case ClassTemplatePartialSpecialization:
809     case ClassScopeFunctionSpecialization:
810     case VarTemplateSpecialization:
811     case VarTemplatePartialSpecialization:
812     case ObjCImplementation:
813     case ObjCCategory:
814     case ObjCCategoryImpl:
815     case Import:
816     case OMPThreadPrivate:
817     case OMPAllocate:
818     case OMPRequires:
819     case OMPCapturedExpr:
820     case Empty:
821     case LifetimeExtendedTemporary:
822     case RequiresExprBody:
823       // Never looked up by name.
824       return 0;
825   }
826 
827   llvm_unreachable("Invalid DeclKind!");
828 }
829 
830 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
831   assert(!HasAttrs && "Decl already contains attrs.");
832 
833   AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
834   assert(AttrBlank.empty() && "HasAttrs was wrong?");
835 
836   AttrBlank = attrs;
837   HasAttrs = true;
838 }
839 
840 void Decl::dropAttrs() {
841   if (!HasAttrs) return;
842 
843   HasAttrs = false;
844   getASTContext().eraseDeclAttrs(this);
845 }
846 
847 void Decl::addAttr(Attr *A) {
848   if (!hasAttrs()) {
849     setAttrs(AttrVec(1, A));
850     return;
851   }
852 
853   AttrVec &Attrs = getAttrs();
854   if (!A->isInherited()) {
855     Attrs.push_back(A);
856     return;
857   }
858 
859   // Attribute inheritance is processed after attribute parsing. To keep the
860   // order as in the source code, add inherited attributes before non-inherited
861   // ones.
862   auto I = Attrs.begin(), E = Attrs.end();
863   for (; I != E; ++I) {
864     if (!(*I)->isInherited())
865       break;
866   }
867   Attrs.insert(I, A);
868 }
869 
870 const AttrVec &Decl::getAttrs() const {
871   assert(HasAttrs && "No attrs to get!");
872   return getASTContext().getDeclAttrs(this);
873 }
874 
875 Decl *Decl::castFromDeclContext (const DeclContext *D) {
876   Decl::Kind DK = D->getDeclKind();
877   switch(DK) {
878 #define DECL(NAME, BASE)
879 #define DECL_CONTEXT(NAME) \
880     case Decl::NAME:       \
881       return static_cast<NAME##Decl *>(const_cast<DeclContext *>(D));
882 #define DECL_CONTEXT_BASE(NAME)
883 #include "clang/AST/DeclNodes.inc"
884     default:
885 #define DECL(NAME, BASE)
886 #define DECL_CONTEXT_BASE(NAME)                  \
887       if (DK >= first##NAME && DK <= last##NAME) \
888         return static_cast<NAME##Decl *>(const_cast<DeclContext *>(D));
889 #include "clang/AST/DeclNodes.inc"
890       llvm_unreachable("a decl that inherits DeclContext isn't handled");
891   }
892 }
893 
894 DeclContext *Decl::castToDeclContext(const Decl *D) {
895   Decl::Kind DK = D->getKind();
896   switch(DK) {
897 #define DECL(NAME, BASE)
898 #define DECL_CONTEXT(NAME) \
899     case Decl::NAME:       \
900       return static_cast<NAME##Decl *>(const_cast<Decl *>(D));
901 #define DECL_CONTEXT_BASE(NAME)
902 #include "clang/AST/DeclNodes.inc"
903     default:
904 #define DECL(NAME, BASE)
905 #define DECL_CONTEXT_BASE(NAME)                                   \
906       if (DK >= first##NAME && DK <= last##NAME)                  \
907         return static_cast<NAME##Decl *>(const_cast<Decl *>(D));
908 #include "clang/AST/DeclNodes.inc"
909       llvm_unreachable("a decl that inherits DeclContext isn't handled");
910   }
911 }
912 
913 SourceLocation Decl::getBodyRBrace() const {
914   // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
915   // FunctionDecl stores EndRangeLoc for this purpose.
916   if (const auto *FD = dyn_cast<FunctionDecl>(this)) {
917     const FunctionDecl *Definition;
918     if (FD->hasBody(Definition))
919       return Definition->getSourceRange().getEnd();
920     return {};
921   }
922 
923   if (Stmt *Body = getBody())
924     return Body->getSourceRange().getEnd();
925 
926   return {};
927 }
928 
929 bool Decl::AccessDeclContextSanity() const {
930 #ifndef NDEBUG
931   // Suppress this check if any of the following hold:
932   // 1. this is the translation unit (and thus has no parent)
933   // 2. this is a template parameter (and thus doesn't belong to its context)
934   // 3. this is a non-type template parameter
935   // 4. the context is not a record
936   // 5. it's invalid
937   // 6. it's a C++0x static_assert.
938   // 7. it's a block literal declaration
939   if (isa<TranslationUnitDecl>(this) ||
940       isa<TemplateTypeParmDecl>(this) ||
941       isa<NonTypeTemplateParmDecl>(this) ||
942       !getDeclContext() ||
943       !isa<CXXRecordDecl>(getDeclContext()) ||
944       isInvalidDecl() ||
945       isa<StaticAssertDecl>(this) ||
946       isa<BlockDecl>(this) ||
947       // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
948       // as DeclContext (?).
949       isa<ParmVarDecl>(this) ||
950       // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
951       // AS_none as access specifier.
952       isa<CXXRecordDecl>(this) ||
953       isa<ClassScopeFunctionSpecializationDecl>(this))
954     return true;
955 
956   assert(Access != AS_none &&
957          "Access specifier is AS_none inside a record decl");
958 #endif
959   return true;
960 }
961 
962 static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
963 static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
964 
965 int64_t Decl::getID() const {
966   return getASTContext().getAllocator().identifyKnownAlignedObject<Decl>(this);
967 }
968 
969 const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
970   QualType Ty;
971   if (const auto *D = dyn_cast<ValueDecl>(this))
972     Ty = D->getType();
973   else if (const auto *D = dyn_cast<TypedefNameDecl>(this))
974     Ty = D->getUnderlyingType();
975   else
976     return nullptr;
977 
978   if (Ty->isFunctionPointerType())
979     Ty = Ty->castAs<PointerType>()->getPointeeType();
980   else if (Ty->isFunctionReferenceType())
981     Ty = Ty->castAs<ReferenceType>()->getPointeeType();
982   else if (BlocksToo && Ty->isBlockPointerType())
983     Ty = Ty->castAs<BlockPointerType>()->getPointeeType();
984 
985   return Ty->getAs<FunctionType>();
986 }
987 
988 /// Starting at a given context (a Decl or DeclContext), look for a
989 /// code context that is not a closure (a lambda, block, etc.).
990 template <class T> static Decl *getNonClosureContext(T *D) {
991   if (getKind(D) == Decl::CXXMethod) {
992     auto *MD = cast<CXXMethodDecl>(D);
993     if (MD->getOverloadedOperator() == OO_Call &&
994         MD->getParent()->isLambda())
995       return getNonClosureContext(MD->getParent()->getParent());
996     return MD;
997   } else if (auto *FD = dyn_cast<FunctionDecl>(D))
998     return FD;
999   else if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
1000     return MD;
1001   else if (auto *BD = dyn_cast<BlockDecl>(D))
1002     return getNonClosureContext(BD->getParent());
1003   else if (auto *CD = dyn_cast<CapturedDecl>(D))
1004     return getNonClosureContext(CD->getParent());
1005   else
1006     return nullptr;
1007 }
1008 
1009 Decl *Decl::getNonClosureContext() {
1010   return ::getNonClosureContext(this);
1011 }
1012 
1013 Decl *DeclContext::getNonClosureAncestor() {
1014   return ::getNonClosureContext(this);
1015 }
1016 
1017 //===----------------------------------------------------------------------===//
1018 // DeclContext Implementation
1019 //===----------------------------------------------------------------------===//
1020 
1021 DeclContext::DeclContext(Decl::Kind K) {
1022   DeclContextBits.DeclKind = K;
1023   setHasExternalLexicalStorage(false);
1024   setHasExternalVisibleStorage(false);
1025   setNeedToReconcileExternalVisibleStorage(false);
1026   setHasLazyLocalLexicalLookups(false);
1027   setHasLazyExternalLexicalLookups(false);
1028   setUseQualifiedLookup(false);
1029 }
1030 
1031 bool DeclContext::classof(const Decl *D) {
1032   switch (D->getKind()) {
1033 #define DECL(NAME, BASE)
1034 #define DECL_CONTEXT(NAME) case Decl::NAME:
1035 #define DECL_CONTEXT_BASE(NAME)
1036 #include "clang/AST/DeclNodes.inc"
1037       return true;
1038     default:
1039 #define DECL(NAME, BASE)
1040 #define DECL_CONTEXT_BASE(NAME)                 \
1041       if (D->getKind() >= Decl::first##NAME &&  \
1042           D->getKind() <= Decl::last##NAME)     \
1043         return true;
1044 #include "clang/AST/DeclNodes.inc"
1045       return false;
1046   }
1047 }
1048 
1049 DeclContext::~DeclContext() = default;
1050 
1051 /// Find the parent context of this context that will be
1052 /// used for unqualified name lookup.
1053 ///
1054 /// Generally, the parent lookup context is the semantic context. However, for
1055 /// a friend function the parent lookup context is the lexical context, which
1056 /// is the class in which the friend is declared.
1057 DeclContext *DeclContext::getLookupParent() {
1058   // FIXME: Find a better way to identify friends.
1059   if (isa<FunctionDecl>(this))
1060     if (getParent()->getRedeclContext()->isFileContext() &&
1061         getLexicalParent()->getRedeclContext()->isRecord())
1062       return getLexicalParent();
1063 
1064   // A lookup within the call operator of a lambda never looks in the lambda
1065   // class; instead, skip to the context in which that closure type is
1066   // declared.
1067   if (isLambdaCallOperator(this))
1068     return getParent()->getParent();
1069 
1070   return getParent();
1071 }
1072 
1073 const BlockDecl *DeclContext::getInnermostBlockDecl() const {
1074   const DeclContext *Ctx = this;
1075 
1076   do {
1077     if (Ctx->isClosure())
1078       return cast<BlockDecl>(Ctx);
1079     Ctx = Ctx->getParent();
1080   } while (Ctx);
1081 
1082   return nullptr;
1083 }
1084 
1085 bool DeclContext::isInlineNamespace() const {
1086   return isNamespace() &&
1087          cast<NamespaceDecl>(this)->isInline();
1088 }
1089 
1090 bool DeclContext::isStdNamespace() const {
1091   if (!isNamespace())
1092     return false;
1093 
1094   const auto *ND = cast<NamespaceDecl>(this);
1095   if (ND->isInline()) {
1096     return ND->getParent()->isStdNamespace();
1097   }
1098 
1099   if (!getParent()->getRedeclContext()->isTranslationUnit())
1100     return false;
1101 
1102   const IdentifierInfo *II = ND->getIdentifier();
1103   return II && II->isStr("std");
1104 }
1105 
1106 bool DeclContext::isDependentContext() const {
1107   if (isFileContext())
1108     return false;
1109 
1110   if (isa<ClassTemplatePartialSpecializationDecl>(this))
1111     return true;
1112 
1113   if (const auto *Record = dyn_cast<CXXRecordDecl>(this)) {
1114     if (Record->getDescribedClassTemplate())
1115       return true;
1116 
1117     if (Record->isDependentLambda())
1118       return true;
1119   }
1120 
1121   if (const auto *Function = dyn_cast<FunctionDecl>(this)) {
1122     if (Function->getDescribedFunctionTemplate())
1123       return true;
1124 
1125     // Friend function declarations are dependent if their *lexical*
1126     // context is dependent.
1127     if (cast<Decl>(this)->getFriendObjectKind())
1128       return getLexicalParent()->isDependentContext();
1129   }
1130 
1131   // FIXME: A variable template is a dependent context, but is not a
1132   // DeclContext. A context within it (such as a lambda-expression)
1133   // should be considered dependent.
1134 
1135   return getParent() && getParent()->isDependentContext();
1136 }
1137 
1138 bool DeclContext::isTransparentContext() const {
1139   if (getDeclKind() == Decl::Enum)
1140     return !cast<EnumDecl>(this)->isScoped();
1141   else if (getDeclKind() == Decl::LinkageSpec || getDeclKind() == Decl::Export)
1142     return true;
1143 
1144   return false;
1145 }
1146 
1147 static bool isLinkageSpecContext(const DeclContext *DC,
1148                                  LinkageSpecDecl::LanguageIDs ID) {
1149   while (DC->getDeclKind() != Decl::TranslationUnit) {
1150     if (DC->getDeclKind() == Decl::LinkageSpec)
1151       return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
1152     DC = DC->getLexicalParent();
1153   }
1154   return false;
1155 }
1156 
1157 bool DeclContext::isExternCContext() const {
1158   return isLinkageSpecContext(this, LinkageSpecDecl::lang_c);
1159 }
1160 
1161 const LinkageSpecDecl *DeclContext::getExternCContext() const {
1162   const DeclContext *DC = this;
1163   while (DC->getDeclKind() != Decl::TranslationUnit) {
1164     if (DC->getDeclKind() == Decl::LinkageSpec &&
1165         cast<LinkageSpecDecl>(DC)->getLanguage() == LinkageSpecDecl::lang_c)
1166       return cast<LinkageSpecDecl>(DC);
1167     DC = DC->getLexicalParent();
1168   }
1169   return nullptr;
1170 }
1171 
1172 bool DeclContext::isExternCXXContext() const {
1173   return isLinkageSpecContext(this, LinkageSpecDecl::lang_cxx);
1174 }
1175 
1176 bool DeclContext::Encloses(const DeclContext *DC) const {
1177   if (getPrimaryContext() != this)
1178     return getPrimaryContext()->Encloses(DC);
1179 
1180   for (; DC; DC = DC->getParent())
1181     if (DC->getPrimaryContext() == this)
1182       return true;
1183   return false;
1184 }
1185 
1186 DeclContext *DeclContext::getPrimaryContext() {
1187   switch (getDeclKind()) {
1188   case Decl::TranslationUnit:
1189   case Decl::ExternCContext:
1190   case Decl::LinkageSpec:
1191   case Decl::Export:
1192   case Decl::Block:
1193   case Decl::Captured:
1194   case Decl::OMPDeclareReduction:
1195   case Decl::OMPDeclareMapper:
1196   case Decl::RequiresExprBody:
1197     // There is only one DeclContext for these entities.
1198     return this;
1199 
1200   case Decl::Namespace:
1201     // The original namespace is our primary context.
1202     return static_cast<NamespaceDecl *>(this)->getOriginalNamespace();
1203 
1204   case Decl::ObjCMethod:
1205     return this;
1206 
1207   case Decl::ObjCInterface:
1208     if (auto *OID = dyn_cast<ObjCInterfaceDecl>(this))
1209       if (auto *Def = OID->getDefinition())
1210         return Def;
1211     return this;
1212 
1213   case Decl::ObjCProtocol:
1214     if (auto *OPD = dyn_cast<ObjCProtocolDecl>(this))
1215       if (auto *Def = OPD->getDefinition())
1216         return Def;
1217     return this;
1218 
1219   case Decl::ObjCCategory:
1220     return this;
1221 
1222   case Decl::ObjCImplementation:
1223   case Decl::ObjCCategoryImpl:
1224     return this;
1225 
1226   default:
1227     if (getDeclKind() >= Decl::firstTag && getDeclKind() <= Decl::lastTag) {
1228       // If this is a tag type that has a definition or is currently
1229       // being defined, that definition is our primary context.
1230       auto *Tag = cast<TagDecl>(this);
1231 
1232       if (TagDecl *Def = Tag->getDefinition())
1233         return Def;
1234 
1235       if (const auto *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
1236         // Note, TagType::getDecl returns the (partial) definition one exists.
1237         TagDecl *PossiblePartialDef = TagTy->getDecl();
1238         if (PossiblePartialDef->isBeingDefined())
1239           return PossiblePartialDef;
1240       } else {
1241         assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
1242       }
1243 
1244       return Tag;
1245     }
1246 
1247     assert(getDeclKind() >= Decl::firstFunction &&
1248            getDeclKind() <= Decl::lastFunction &&
1249           "Unknown DeclContext kind");
1250     return this;
1251   }
1252 }
1253 
1254 void
1255 DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
1256   Contexts.clear();
1257 
1258   if (getDeclKind() != Decl::Namespace) {
1259     Contexts.push_back(this);
1260     return;
1261   }
1262 
1263   auto *Self = static_cast<NamespaceDecl *>(this);
1264   for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
1265        N = N->getPreviousDecl())
1266     Contexts.push_back(N);
1267 
1268   std::reverse(Contexts.begin(), Contexts.end());
1269 }
1270 
1271 std::pair<Decl *, Decl *>
1272 DeclContext::BuildDeclChain(ArrayRef<Decl *> Decls,
1273                             bool FieldsAlreadyLoaded) {
1274   // Build up a chain of declarations via the Decl::NextInContextAndBits field.
1275   Decl *FirstNewDecl = nullptr;
1276   Decl *PrevDecl = nullptr;
1277   for (auto *D : Decls) {
1278     if (FieldsAlreadyLoaded && isa<FieldDecl>(D))
1279       continue;
1280 
1281     if (PrevDecl)
1282       PrevDecl->NextInContextAndBits.setPointer(D);
1283     else
1284       FirstNewDecl = D;
1285 
1286     PrevDecl = D;
1287   }
1288 
1289   return std::make_pair(FirstNewDecl, PrevDecl);
1290 }
1291 
1292 /// We have just acquired external visible storage, and we already have
1293 /// built a lookup map. For every name in the map, pull in the new names from
1294 /// the external storage.
1295 void DeclContext::reconcileExternalVisibleStorage() const {
1296   assert(hasNeedToReconcileExternalVisibleStorage() && LookupPtr);
1297   setNeedToReconcileExternalVisibleStorage(false);
1298 
1299   for (auto &Lookup : *LookupPtr)
1300     Lookup.second.setHasExternalDecls();
1301 }
1302 
1303 /// Load the declarations within this lexical storage from an
1304 /// external source.
1305 /// \return \c true if any declarations were added.
1306 bool
1307 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1308   ExternalASTSource *Source = getParentASTContext().getExternalSource();
1309   assert(hasExternalLexicalStorage() && Source && "No external storage?");
1310 
1311   // Notify that we have a DeclContext that is initializing.
1312   ExternalASTSource::Deserializing ADeclContext(Source);
1313 
1314   // Load the external declarations, if any.
1315   SmallVector<Decl*, 64> Decls;
1316   setHasExternalLexicalStorage(false);
1317   Source->FindExternalLexicalDecls(this, Decls);
1318 
1319   if (Decls.empty())
1320     return false;
1321 
1322   // We may have already loaded just the fields of this record, in which case
1323   // we need to ignore them.
1324   bool FieldsAlreadyLoaded = false;
1325   if (const auto *RD = dyn_cast<RecordDecl>(this))
1326     FieldsAlreadyLoaded = RD->hasLoadedFieldsFromExternalStorage();
1327 
1328   // Splice the newly-read declarations into the beginning of the list
1329   // of declarations.
1330   Decl *ExternalFirst, *ExternalLast;
1331   std::tie(ExternalFirst, ExternalLast) =
1332       BuildDeclChain(Decls, FieldsAlreadyLoaded);
1333   ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1334   FirstDecl = ExternalFirst;
1335   if (!LastDecl)
1336     LastDecl = ExternalLast;
1337   return true;
1338 }
1339 
1340 DeclContext::lookup_result
1341 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1342                                                     DeclarationName Name) {
1343   ASTContext &Context = DC->getParentASTContext();
1344   StoredDeclsMap *Map;
1345   if (!(Map = DC->LookupPtr))
1346     Map = DC->CreateStoredDeclsMap(Context);
1347   if (DC->hasNeedToReconcileExternalVisibleStorage())
1348     DC->reconcileExternalVisibleStorage();
1349 
1350   (*Map)[Name].removeExternalDecls();
1351 
1352   return DeclContext::lookup_result();
1353 }
1354 
1355 DeclContext::lookup_result
1356 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1357                                                   DeclarationName Name,
1358                                                   ArrayRef<NamedDecl*> Decls) {
1359   ASTContext &Context = DC->getParentASTContext();
1360   StoredDeclsMap *Map;
1361   if (!(Map = DC->LookupPtr))
1362     Map = DC->CreateStoredDeclsMap(Context);
1363   if (DC->hasNeedToReconcileExternalVisibleStorage())
1364     DC->reconcileExternalVisibleStorage();
1365 
1366   StoredDeclsList &List = (*Map)[Name];
1367 
1368   // Clear out any old external visible declarations, to avoid quadratic
1369   // performance in the redeclaration checks below.
1370   List.removeExternalDecls();
1371 
1372   if (!List.isNull()) {
1373     // We have both existing declarations and new declarations for this name.
1374     // Some of the declarations may simply replace existing ones. Handle those
1375     // first.
1376     llvm::SmallVector<unsigned, 8> Skip;
1377     for (unsigned I = 0, N = Decls.size(); I != N; ++I)
1378       if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
1379         Skip.push_back(I);
1380     Skip.push_back(Decls.size());
1381 
1382     // Add in any new declarations.
1383     unsigned SkipPos = 0;
1384     for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1385       if (I == Skip[SkipPos])
1386         ++SkipPos;
1387       else
1388         List.AddSubsequentDecl(Decls[I]);
1389     }
1390   } else {
1391     // Convert the array to a StoredDeclsList.
1392     for (auto *D : Decls) {
1393       if (List.isNull())
1394         List.setOnlyValue(D);
1395       else
1396         List.AddSubsequentDecl(D);
1397     }
1398   }
1399 
1400   return List.getLookupResult();
1401 }
1402 
1403 DeclContext::decl_iterator DeclContext::decls_begin() const {
1404   if (hasExternalLexicalStorage())
1405     LoadLexicalDeclsFromExternalStorage();
1406   return decl_iterator(FirstDecl);
1407 }
1408 
1409 bool DeclContext::decls_empty() const {
1410   if (hasExternalLexicalStorage())
1411     LoadLexicalDeclsFromExternalStorage();
1412 
1413   return !FirstDecl;
1414 }
1415 
1416 bool DeclContext::containsDecl(Decl *D) const {
1417   return (D->getLexicalDeclContext() == this &&
1418           (D->NextInContextAndBits.getPointer() || D == LastDecl));
1419 }
1420 
1421 bool DeclContext::containsDeclAndLoad(Decl *D) const {
1422   if (hasExternalLexicalStorage())
1423     LoadLexicalDeclsFromExternalStorage();
1424   return containsDecl(D);
1425 }
1426 
1427 /// shouldBeHidden - Determine whether a declaration which was declared
1428 /// within its semantic context should be invisible to qualified name lookup.
1429 static bool shouldBeHidden(NamedDecl *D) {
1430   // Skip unnamed declarations.
1431   if (!D->getDeclName())
1432     return true;
1433 
1434   // Skip entities that can't be found by name lookup into a particular
1435   // context.
1436   if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1437       D->isTemplateParameter())
1438     return true;
1439 
1440   // Skip friends and local extern declarations unless they're the first
1441   // declaration of the entity.
1442   if ((D->isLocalExternDecl() || D->getFriendObjectKind()) &&
1443       D != D->getCanonicalDecl())
1444     return true;
1445 
1446   // Skip template specializations.
1447   // FIXME: This feels like a hack. Should DeclarationName support
1448   // template-ids, or is there a better way to keep specializations
1449   // from being visible?
1450   if (isa<ClassTemplateSpecializationDecl>(D))
1451     return true;
1452   if (auto *FD = dyn_cast<FunctionDecl>(D))
1453     if (FD->isFunctionTemplateSpecialization())
1454       return true;
1455 
1456   return false;
1457 }
1458 
1459 void DeclContext::removeDecl(Decl *D) {
1460   assert(D->getLexicalDeclContext() == this &&
1461          "decl being removed from non-lexical context");
1462   assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1463          "decl is not in decls list");
1464 
1465   // Remove D from the decl chain.  This is O(n) but hopefully rare.
1466   if (D == FirstDecl) {
1467     if (D == LastDecl)
1468       FirstDecl = LastDecl = nullptr;
1469     else
1470       FirstDecl = D->NextInContextAndBits.getPointer();
1471   } else {
1472     for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1473       assert(I && "decl not found in linked list");
1474       if (I->NextInContextAndBits.getPointer() == D) {
1475         I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1476         if (D == LastDecl) LastDecl = I;
1477         break;
1478       }
1479     }
1480   }
1481 
1482   // Mark that D is no longer in the decl chain.
1483   D->NextInContextAndBits.setPointer(nullptr);
1484 
1485   // Remove D from the lookup table if necessary.
1486   if (isa<NamedDecl>(D)) {
1487     auto *ND = cast<NamedDecl>(D);
1488 
1489     // Do not try to remove the declaration if that is invisible to qualified
1490     // lookup.  E.g. template specializations are skipped.
1491     if (shouldBeHidden(ND))
1492       return;
1493 
1494     // Remove only decls that have a name
1495     if (!ND->getDeclName())
1496       return;
1497 
1498     auto *DC = D->getDeclContext();
1499     do {
1500       StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1501       if (Map) {
1502         StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1503         assert(Pos != Map->end() && "no lookup entry for decl");
1504         // Remove the decl only if it is contained.
1505         StoredDeclsList::DeclsTy *Vec = Pos->second.getAsVector();
1506         if ((Vec && is_contained(*Vec, ND)) || Pos->second.getAsDecl() == ND)
1507           Pos->second.remove(ND);
1508       }
1509     } while (DC->isTransparentContext() && (DC = DC->getParent()));
1510   }
1511 }
1512 
1513 void DeclContext::addHiddenDecl(Decl *D) {
1514   assert(D->getLexicalDeclContext() == this &&
1515          "Decl inserted into wrong lexical context");
1516   assert(!D->getNextDeclInContext() && D != LastDecl &&
1517          "Decl already inserted into a DeclContext");
1518 
1519   if (FirstDecl) {
1520     LastDecl->NextInContextAndBits.setPointer(D);
1521     LastDecl = D;
1522   } else {
1523     FirstDecl = LastDecl = D;
1524   }
1525 
1526   // Notify a C++ record declaration that we've added a member, so it can
1527   // update its class-specific state.
1528   if (auto *Record = dyn_cast<CXXRecordDecl>(this))
1529     Record->addedMember(D);
1530 
1531   // If this is a newly-created (not de-serialized) import declaration, wire
1532   // it in to the list of local import declarations.
1533   if (!D->isFromASTFile()) {
1534     if (auto *Import = dyn_cast<ImportDecl>(D))
1535       D->getASTContext().addedLocalImportDecl(Import);
1536   }
1537 }
1538 
1539 void DeclContext::addDecl(Decl *D) {
1540   addHiddenDecl(D);
1541 
1542   if (auto *ND = dyn_cast<NamedDecl>(D))
1543     ND->getDeclContext()->getPrimaryContext()->
1544         makeDeclVisibleInContextWithFlags(ND, false, true);
1545 }
1546 
1547 void DeclContext::addDeclInternal(Decl *D) {
1548   addHiddenDecl(D);
1549 
1550   if (auto *ND = dyn_cast<NamedDecl>(D))
1551     ND->getDeclContext()->getPrimaryContext()->
1552         makeDeclVisibleInContextWithFlags(ND, true, true);
1553 }
1554 
1555 /// buildLookup - Build the lookup data structure with all of the
1556 /// declarations in this DeclContext (and any other contexts linked
1557 /// to it or transparent contexts nested within it) and return it.
1558 ///
1559 /// Note that the produced map may miss out declarations from an
1560 /// external source. If it does, those entries will be marked with
1561 /// the 'hasExternalDecls' flag.
1562 StoredDeclsMap *DeclContext::buildLookup() {
1563   assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1564 
1565   if (!hasLazyLocalLexicalLookups() &&
1566       !hasLazyExternalLexicalLookups())
1567     return LookupPtr;
1568 
1569   SmallVector<DeclContext *, 2> Contexts;
1570   collectAllContexts(Contexts);
1571 
1572   if (hasLazyExternalLexicalLookups()) {
1573     setHasLazyExternalLexicalLookups(false);
1574     for (auto *DC : Contexts) {
1575       if (DC->hasExternalLexicalStorage()) {
1576         bool LoadedDecls = DC->LoadLexicalDeclsFromExternalStorage();
1577         setHasLazyLocalLexicalLookups(
1578             hasLazyLocalLexicalLookups() | LoadedDecls );
1579       }
1580     }
1581 
1582     if (!hasLazyLocalLexicalLookups())
1583       return LookupPtr;
1584   }
1585 
1586   for (auto *DC : Contexts)
1587     buildLookupImpl(DC, hasExternalVisibleStorage());
1588 
1589   // We no longer have any lazy decls.
1590   setHasLazyLocalLexicalLookups(false);
1591   return LookupPtr;
1592 }
1593 
1594 /// buildLookupImpl - Build part of the lookup data structure for the
1595 /// declarations contained within DCtx, which will either be this
1596 /// DeclContext, a DeclContext linked to it, or a transparent context
1597 /// nested within it.
1598 void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
1599   for (auto *D : DCtx->noload_decls()) {
1600     // Insert this declaration into the lookup structure, but only if
1601     // it's semantically within its decl context. Any other decls which
1602     // should be found in this context are added eagerly.
1603     //
1604     // If it's from an AST file, don't add it now. It'll get handled by
1605     // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1606     // in C++, we do not track external visible decls for the TU, so in
1607     // that case we need to collect them all here.
1608     if (auto *ND = dyn_cast<NamedDecl>(D))
1609       if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1610           (!ND->isFromASTFile() ||
1611            (isTranslationUnit() &&
1612             !getParentASTContext().getLangOpts().CPlusPlus)))
1613         makeDeclVisibleInContextImpl(ND, Internal);
1614 
1615     // If this declaration is itself a transparent declaration context
1616     // or inline namespace, add the members of this declaration of that
1617     // context (recursively).
1618     if (auto *InnerCtx = dyn_cast<DeclContext>(D))
1619       if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1620         buildLookupImpl(InnerCtx, Internal);
1621   }
1622 }
1623 
1624 NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1625 
1626 DeclContext::lookup_result
1627 DeclContext::lookup(DeclarationName Name) const {
1628   assert(getDeclKind() != Decl::LinkageSpec &&
1629          getDeclKind() != Decl::Export &&
1630          "should not perform lookups into transparent contexts");
1631 
1632   const DeclContext *PrimaryContext = getPrimaryContext();
1633   if (PrimaryContext != this)
1634     return PrimaryContext->lookup(Name);
1635 
1636   // If we have an external source, ensure that any later redeclarations of this
1637   // context have been loaded, since they may add names to the result of this
1638   // lookup (or add external visible storage).
1639   ExternalASTSource *Source = getParentASTContext().getExternalSource();
1640   if (Source)
1641     (void)cast<Decl>(this)->getMostRecentDecl();
1642 
1643   if (hasExternalVisibleStorage()) {
1644     assert(Source && "external visible storage but no external source?");
1645 
1646     if (hasNeedToReconcileExternalVisibleStorage())
1647       reconcileExternalVisibleStorage();
1648 
1649     StoredDeclsMap *Map = LookupPtr;
1650 
1651     if (hasLazyLocalLexicalLookups() ||
1652         hasLazyExternalLexicalLookups())
1653       // FIXME: Make buildLookup const?
1654       Map = const_cast<DeclContext*>(this)->buildLookup();
1655 
1656     if (!Map)
1657       Map = CreateStoredDeclsMap(getParentASTContext());
1658 
1659     // If we have a lookup result with no external decls, we are done.
1660     std::pair<StoredDeclsMap::iterator, bool> R =
1661         Map->insert(std::make_pair(Name, StoredDeclsList()));
1662     if (!R.second && !R.first->second.hasExternalDecls())
1663       return R.first->second.getLookupResult();
1664 
1665     if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
1666       if (StoredDeclsMap *Map = LookupPtr) {
1667         StoredDeclsMap::iterator I = Map->find(Name);
1668         if (I != Map->end())
1669           return I->second.getLookupResult();
1670       }
1671     }
1672 
1673     return {};
1674   }
1675 
1676   StoredDeclsMap *Map = LookupPtr;
1677   if (hasLazyLocalLexicalLookups() ||
1678       hasLazyExternalLexicalLookups())
1679     Map = const_cast<DeclContext*>(this)->buildLookup();
1680 
1681   if (!Map)
1682     return {};
1683 
1684   StoredDeclsMap::iterator I = Map->find(Name);
1685   if (I == Map->end())
1686     return {};
1687 
1688   return I->second.getLookupResult();
1689 }
1690 
1691 DeclContext::lookup_result
1692 DeclContext::noload_lookup(DeclarationName Name) {
1693   assert(getDeclKind() != Decl::LinkageSpec &&
1694          getDeclKind() != Decl::Export &&
1695          "should not perform lookups into transparent contexts");
1696 
1697   DeclContext *PrimaryContext = getPrimaryContext();
1698   if (PrimaryContext != this)
1699     return PrimaryContext->noload_lookup(Name);
1700 
1701   loadLazyLocalLexicalLookups();
1702   StoredDeclsMap *Map = LookupPtr;
1703   if (!Map)
1704     return {};
1705 
1706   StoredDeclsMap::iterator I = Map->find(Name);
1707   return I != Map->end() ? I->second.getLookupResult()
1708                          : lookup_result();
1709 }
1710 
1711 // If we have any lazy lexical declarations not in our lookup map, add them
1712 // now. Don't import any external declarations, not even if we know we have
1713 // some missing from the external visible lookups.
1714 void DeclContext::loadLazyLocalLexicalLookups() {
1715   if (hasLazyLocalLexicalLookups()) {
1716     SmallVector<DeclContext *, 2> Contexts;
1717     collectAllContexts(Contexts);
1718     for (auto *Context : Contexts)
1719       buildLookupImpl(Context, hasExternalVisibleStorage());
1720     setHasLazyLocalLexicalLookups(false);
1721   }
1722 }
1723 
1724 void DeclContext::localUncachedLookup(DeclarationName Name,
1725                                       SmallVectorImpl<NamedDecl *> &Results) {
1726   Results.clear();
1727 
1728   // If there's no external storage, just perform a normal lookup and copy
1729   // the results.
1730   if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1731     lookup_result LookupResults = lookup(Name);
1732     Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1733     return;
1734   }
1735 
1736   // If we have a lookup table, check there first. Maybe we'll get lucky.
1737   // FIXME: Should we be checking these flags on the primary context?
1738   if (Name && !hasLazyLocalLexicalLookups() &&
1739       !hasLazyExternalLexicalLookups()) {
1740     if (StoredDeclsMap *Map = LookupPtr) {
1741       StoredDeclsMap::iterator Pos = Map->find(Name);
1742       if (Pos != Map->end()) {
1743         Results.insert(Results.end(),
1744                        Pos->second.getLookupResult().begin(),
1745                        Pos->second.getLookupResult().end());
1746         return;
1747       }
1748     }
1749   }
1750 
1751   // Slow case: grovel through the declarations in our chain looking for
1752   // matches.
1753   // FIXME: If we have lazy external declarations, this will not find them!
1754   // FIXME: Should we CollectAllContexts and walk them all here?
1755   for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1756     if (auto *ND = dyn_cast<NamedDecl>(D))
1757       if (ND->getDeclName() == Name)
1758         Results.push_back(ND);
1759   }
1760 }
1761 
1762 DeclContext *DeclContext::getRedeclContext() {
1763   DeclContext *Ctx = this;
1764 
1765   // In C, a record type is the redeclaration context for its fields only. If
1766   // we arrive at a record context after skipping anything else, we should skip
1767   // the record as well. Currently, this means skipping enumerations because
1768   // they're the only transparent context that can exist within a struct or
1769   // union.
1770   bool SkipRecords = getDeclKind() == Decl::Kind::Enum &&
1771                      !getParentASTContext().getLangOpts().CPlusPlus;
1772 
1773   // Skip through contexts to get to the redeclaration context. Transparent
1774   // contexts are always skipped.
1775   while ((SkipRecords && Ctx->isRecord()) || Ctx->isTransparentContext())
1776     Ctx = Ctx->getParent();
1777   return Ctx;
1778 }
1779 
1780 DeclContext *DeclContext::getEnclosingNamespaceContext() {
1781   DeclContext *Ctx = this;
1782   // Skip through non-namespace, non-translation-unit contexts.
1783   while (!Ctx->isFileContext())
1784     Ctx = Ctx->getParent();
1785   return Ctx->getPrimaryContext();
1786 }
1787 
1788 RecordDecl *DeclContext::getOuterLexicalRecordContext() {
1789   // Loop until we find a non-record context.
1790   RecordDecl *OutermostRD = nullptr;
1791   DeclContext *DC = this;
1792   while (DC->isRecord()) {
1793     OutermostRD = cast<RecordDecl>(DC);
1794     DC = DC->getLexicalParent();
1795   }
1796   return OutermostRD;
1797 }
1798 
1799 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1800   // For non-file contexts, this is equivalent to Equals.
1801   if (!isFileContext())
1802     return O->Equals(this);
1803 
1804   do {
1805     if (O->Equals(this))
1806       return true;
1807 
1808     const auto *NS = dyn_cast<NamespaceDecl>(O);
1809     if (!NS || !NS->isInline())
1810       break;
1811     O = NS->getParent();
1812   } while (O);
1813 
1814   return false;
1815 }
1816 
1817 void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1818   DeclContext *PrimaryDC = this->getPrimaryContext();
1819   DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1820   // If the decl is being added outside of its semantic decl context, we
1821   // need to ensure that we eagerly build the lookup information for it.
1822   PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1823 }
1824 
1825 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1826                                                     bool Recoverable) {
1827   assert(this == getPrimaryContext() && "expected a primary DC");
1828 
1829   if (!isLookupContext()) {
1830     if (isTransparentContext())
1831       getParent()->getPrimaryContext()
1832         ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1833     return;
1834   }
1835 
1836   // Skip declarations which should be invisible to name lookup.
1837   if (shouldBeHidden(D))
1838     return;
1839 
1840   // If we already have a lookup data structure, perform the insertion into
1841   // it. If we might have externally-stored decls with this name, look them
1842   // up and perform the insertion. If this decl was declared outside its
1843   // semantic context, buildLookup won't add it, so add it now.
1844   //
1845   // FIXME: As a performance hack, don't add such decls into the translation
1846   // unit unless we're in C++, since qualified lookup into the TU is never
1847   // performed.
1848   if (LookupPtr || hasExternalVisibleStorage() ||
1849       ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1850        (getParentASTContext().getLangOpts().CPlusPlus ||
1851         !isTranslationUnit()))) {
1852     // If we have lazily omitted any decls, they might have the same name as
1853     // the decl which we are adding, so build a full lookup table before adding
1854     // this decl.
1855     buildLookup();
1856     makeDeclVisibleInContextImpl(D, Internal);
1857   } else {
1858     setHasLazyLocalLexicalLookups(true);
1859   }
1860 
1861   // If we are a transparent context or inline namespace, insert into our
1862   // parent context, too. This operation is recursive.
1863   if (isTransparentContext() || isInlineNamespace())
1864     getParent()->getPrimaryContext()->
1865         makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1866 
1867   auto *DCAsDecl = cast<Decl>(this);
1868   // Notify that a decl was made visible unless we are a Tag being defined.
1869   if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1870     if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1871       L->AddedVisibleDecl(this, D);
1872 }
1873 
1874 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1875   // Find or create the stored declaration map.
1876   StoredDeclsMap *Map = LookupPtr;
1877   if (!Map) {
1878     ASTContext *C = &getParentASTContext();
1879     Map = CreateStoredDeclsMap(*C);
1880   }
1881 
1882   // If there is an external AST source, load any declarations it knows about
1883   // with this declaration's name.
1884   // If the lookup table contains an entry about this name it means that we
1885   // have already checked the external source.
1886   if (!Internal)
1887     if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1888       if (hasExternalVisibleStorage() &&
1889           Map->find(D->getDeclName()) == Map->end())
1890         Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1891 
1892   // Insert this declaration into the map.
1893   StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1894 
1895   if (Internal) {
1896     // If this is being added as part of loading an external declaration,
1897     // this may not be the only external declaration with this name.
1898     // In this case, we never try to replace an existing declaration; we'll
1899     // handle that when we finalize the list of declarations for this name.
1900     DeclNameEntries.setHasExternalDecls();
1901     DeclNameEntries.AddSubsequentDecl(D);
1902     return;
1903   }
1904 
1905   if (DeclNameEntries.isNull()) {
1906     DeclNameEntries.setOnlyValue(D);
1907     return;
1908   }
1909 
1910   if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
1911     // This declaration has replaced an existing one for which
1912     // declarationReplaces returns true.
1913     return;
1914   }
1915 
1916   // Put this declaration into the appropriate slot.
1917   DeclNameEntries.AddSubsequentDecl(D);
1918 }
1919 
1920 UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
1921   return cast<UsingDirectiveDecl>(*I);
1922 }
1923 
1924 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1925 /// this context.
1926 DeclContext::udir_range DeclContext::using_directives() const {
1927   // FIXME: Use something more efficient than normal lookup for using
1928   // directives. In C++, using directives are looked up more than anything else.
1929   lookup_result Result = lookup(UsingDirectiveDecl::getName());
1930   return udir_range(Result.begin(), Result.end());
1931 }
1932 
1933 //===----------------------------------------------------------------------===//
1934 // Creation and Destruction of StoredDeclsMaps.                               //
1935 //===----------------------------------------------------------------------===//
1936 
1937 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1938   assert(!LookupPtr && "context already has a decls map");
1939   assert(getPrimaryContext() == this &&
1940          "creating decls map on non-primary context");
1941 
1942   StoredDeclsMap *M;
1943   bool Dependent = isDependentContext();
1944   if (Dependent)
1945     M = new DependentStoredDeclsMap();
1946   else
1947     M = new StoredDeclsMap();
1948   M->Previous = C.LastSDM;
1949   C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1950   LookupPtr = M;
1951   return M;
1952 }
1953 
1954 void ASTContext::ReleaseDeclContextMaps() {
1955   // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1956   // pointer because the subclass doesn't add anything that needs to
1957   // be deleted.
1958   StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1959 }
1960 
1961 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1962   while (Map) {
1963     // Advance the iteration before we invalidate memory.
1964     llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1965 
1966     if (Dependent)
1967       delete static_cast<DependentStoredDeclsMap*>(Map);
1968     else
1969       delete Map;
1970 
1971     Map = Next.getPointer();
1972     Dependent = Next.getInt();
1973   }
1974 }
1975 
1976 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1977                                                  DeclContext *Parent,
1978                                            const PartialDiagnostic &PDiag) {
1979   assert(Parent->isDependentContext()
1980          && "cannot iterate dependent diagnostics of non-dependent context");
1981   Parent = Parent->getPrimaryContext();
1982   if (!Parent->LookupPtr)
1983     Parent->CreateStoredDeclsMap(C);
1984 
1985   auto *Map = static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
1986 
1987   // Allocate the copy of the PartialDiagnostic via the ASTContext's
1988   // BumpPtrAllocator, rather than the ASTContext itself.
1989   PartialDiagnostic::Storage *DiagStorage = nullptr;
1990   if (PDiag.hasStorage())
1991     DiagStorage = new (C) PartialDiagnostic::Storage;
1992 
1993   auto *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1994 
1995   // TODO: Maybe we shouldn't reverse the order during insertion.
1996   DD->NextDiagnostic = Map->FirstDiagnostic;
1997   Map->FirstDiagnostic = DD;
1998 
1999   return DD;
2000 }
2001