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