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