xref: /llvm-project/clang/lib/AST/DeclBase.cpp (revision cbdd14ee9de72c277d9f89a6aa57c54a495f5458)
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 static void collectAllContextsImpl(T *Self,
1504                                    SmallVectorImpl<DeclContext *> &Contexts) {
1505   for (T *D = Self->getMostRecentDecl(); D; D = D->getPreviousDecl())
1506     Contexts.push_back(D);
1507 
1508   std::reverse(Contexts.begin(), Contexts.end());
1509 }
1510 
1511 void DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts) {
1512   Contexts.clear();
1513 
1514   Decl::Kind Kind = getDeclKind();
1515 
1516   if (Kind == Decl::TranslationUnit)
1517     collectAllContextsImpl(static_cast<TranslationUnitDecl *>(this), Contexts);
1518   else if (Kind == Decl::Namespace)
1519     collectAllContextsImpl(static_cast<NamespaceDecl *>(this), Contexts);
1520   else
1521     Contexts.push_back(this);
1522 }
1523 
1524 std::pair<Decl *, Decl *>
1525 DeclContext::BuildDeclChain(ArrayRef<Decl *> Decls,
1526                             bool FieldsAlreadyLoaded) {
1527   // Build up a chain of declarations via the Decl::NextInContextAndBits field.
1528   Decl *FirstNewDecl = nullptr;
1529   Decl *PrevDecl = nullptr;
1530   for (auto *D : Decls) {
1531     if (FieldsAlreadyLoaded && isa<FieldDecl>(D))
1532       continue;
1533 
1534     if (PrevDecl)
1535       PrevDecl->NextInContextAndBits.setPointer(D);
1536     else
1537       FirstNewDecl = D;
1538 
1539     PrevDecl = D;
1540   }
1541 
1542   return std::make_pair(FirstNewDecl, PrevDecl);
1543 }
1544 
1545 /// We have just acquired external visible storage, and we already have
1546 /// built a lookup map. For every name in the map, pull in the new names from
1547 /// the external storage.
1548 void DeclContext::reconcileExternalVisibleStorage() const {
1549   assert(hasNeedToReconcileExternalVisibleStorage() && LookupPtr);
1550   setNeedToReconcileExternalVisibleStorage(false);
1551 
1552   for (auto &Lookup : *LookupPtr)
1553     Lookup.second.setHasExternalDecls();
1554 }
1555 
1556 /// Load the declarations within this lexical storage from an
1557 /// external source.
1558 /// \return \c true if any declarations were added.
1559 bool
1560 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1561   ExternalASTSource *Source = getParentASTContext().getExternalSource();
1562   assert(hasExternalLexicalStorage() && Source && "No external storage?");
1563 
1564   // Notify that we have a DeclContext that is initializing.
1565   ExternalASTSource::Deserializing ADeclContext(Source);
1566 
1567   // Load the external declarations, if any.
1568   SmallVector<Decl*, 64> Decls;
1569   setHasExternalLexicalStorage(false);
1570   Source->FindExternalLexicalDecls(this, Decls);
1571 
1572   if (Decls.empty())
1573     return false;
1574 
1575   // We may have already loaded just the fields of this record, in which case
1576   // we need to ignore them.
1577   bool FieldsAlreadyLoaded = false;
1578   if (const auto *RD = dyn_cast<RecordDecl>(this))
1579     FieldsAlreadyLoaded = RD->hasLoadedFieldsFromExternalStorage();
1580 
1581   // Splice the newly-read declarations into the beginning of the list
1582   // of declarations.
1583   Decl *ExternalFirst, *ExternalLast;
1584   std::tie(ExternalFirst, ExternalLast) =
1585       BuildDeclChain(Decls, FieldsAlreadyLoaded);
1586   ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1587   FirstDecl = ExternalFirst;
1588   if (!LastDecl)
1589     LastDecl = ExternalLast;
1590   return true;
1591 }
1592 
1593 DeclContext::lookup_result
1594 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1595                                                     DeclarationName Name) {
1596   ASTContext &Context = DC->getParentASTContext();
1597   StoredDeclsMap *Map;
1598   if (!(Map = DC->LookupPtr))
1599     Map = DC->CreateStoredDeclsMap(Context);
1600   if (DC->hasNeedToReconcileExternalVisibleStorage())
1601     DC->reconcileExternalVisibleStorage();
1602 
1603   (*Map)[Name].removeExternalDecls();
1604 
1605   return DeclContext::lookup_result();
1606 }
1607 
1608 DeclContext::lookup_result
1609 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1610                                                   DeclarationName Name,
1611                                                   ArrayRef<NamedDecl*> Decls) {
1612   ASTContext &Context = DC->getParentASTContext();
1613   StoredDeclsMap *Map;
1614   if (!(Map = DC->LookupPtr))
1615     Map = DC->CreateStoredDeclsMap(Context);
1616   if (DC->hasNeedToReconcileExternalVisibleStorage())
1617     DC->reconcileExternalVisibleStorage();
1618 
1619   StoredDeclsList &List = (*Map)[Name];
1620   List.replaceExternalDecls(Decls);
1621   return List.getLookupResult();
1622 }
1623 
1624 DeclContext::decl_iterator DeclContext::decls_begin() const {
1625   if (hasExternalLexicalStorage())
1626     LoadLexicalDeclsFromExternalStorage();
1627   return decl_iterator(FirstDecl);
1628 }
1629 
1630 bool DeclContext::decls_empty() const {
1631   if (hasExternalLexicalStorage())
1632     LoadLexicalDeclsFromExternalStorage();
1633 
1634   return !FirstDecl;
1635 }
1636 
1637 bool DeclContext::containsDecl(Decl *D) const {
1638   return (D->getLexicalDeclContext() == this &&
1639           (D->NextInContextAndBits.getPointer() || D == LastDecl));
1640 }
1641 
1642 bool DeclContext::containsDeclAndLoad(Decl *D) const {
1643   if (hasExternalLexicalStorage())
1644     LoadLexicalDeclsFromExternalStorage();
1645   return containsDecl(D);
1646 }
1647 
1648 /// shouldBeHidden - Determine whether a declaration which was declared
1649 /// within its semantic context should be invisible to qualified name lookup.
1650 static bool shouldBeHidden(NamedDecl *D) {
1651   // Skip unnamed declarations.
1652   if (!D->getDeclName())
1653     return true;
1654 
1655   // Skip entities that can't be found by name lookup into a particular
1656   // context.
1657   if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1658       D->isTemplateParameter())
1659     return true;
1660 
1661   // Skip friends and local extern declarations unless they're the first
1662   // declaration of the entity.
1663   if ((D->isLocalExternDecl() || D->getFriendObjectKind()) &&
1664       D != D->getCanonicalDecl())
1665     return true;
1666 
1667   // Skip template specializations.
1668   // FIXME: This feels like a hack. Should DeclarationName support
1669   // template-ids, or is there a better way to keep specializations
1670   // from being visible?
1671   if (isa<ClassTemplateSpecializationDecl>(D))
1672     return true;
1673   if (auto *FD = dyn_cast<FunctionDecl>(D))
1674     if (FD->isFunctionTemplateSpecialization())
1675       return true;
1676 
1677   // Hide destructors that are invalid. There should always be one destructor,
1678   // but if it is an invalid decl, another one is created. We need to hide the
1679   // invalid one from places that expect exactly one destructor, like the
1680   // serialization code.
1681   if (isa<CXXDestructorDecl>(D) && D->isInvalidDecl())
1682     return true;
1683 
1684   return false;
1685 }
1686 
1687 void DeclContext::removeDecl(Decl *D) {
1688   assert(D->getLexicalDeclContext() == this &&
1689          "decl being removed from non-lexical context");
1690   assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1691          "decl is not in decls list");
1692 
1693   // Remove D from the decl chain.  This is O(n) but hopefully rare.
1694   if (D == FirstDecl) {
1695     if (D == LastDecl)
1696       FirstDecl = LastDecl = nullptr;
1697     else
1698       FirstDecl = D->NextInContextAndBits.getPointer();
1699   } else {
1700     for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1701       assert(I && "decl not found in linked list");
1702       if (I->NextInContextAndBits.getPointer() == D) {
1703         I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1704         if (D == LastDecl) LastDecl = I;
1705         break;
1706       }
1707     }
1708   }
1709 
1710   // Mark that D is no longer in the decl chain.
1711   D->NextInContextAndBits.setPointer(nullptr);
1712 
1713   // Remove D from the lookup table if necessary.
1714   if (isa<NamedDecl>(D)) {
1715     auto *ND = cast<NamedDecl>(D);
1716 
1717     // Do not try to remove the declaration if that is invisible to qualified
1718     // lookup.  E.g. template specializations are skipped.
1719     if (shouldBeHidden(ND))
1720       return;
1721 
1722     // Remove only decls that have a name
1723     if (!ND->getDeclName())
1724       return;
1725 
1726     auto *DC = D->getDeclContext();
1727     do {
1728       StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1729       if (Map) {
1730         StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1731         assert(Pos != Map->end() && "no lookup entry for decl");
1732         StoredDeclsList &List = Pos->second;
1733         List.remove(ND);
1734         // Clean up the entry if there are no more decls.
1735         if (List.isNull())
1736           Map->erase(Pos);
1737       }
1738     } while (DC->isTransparentContext() && (DC = DC->getParent()));
1739   }
1740 }
1741 
1742 void DeclContext::addHiddenDecl(Decl *D) {
1743   assert(D->getLexicalDeclContext() == this &&
1744          "Decl inserted into wrong lexical context");
1745   assert(!D->getNextDeclInContext() && D != LastDecl &&
1746          "Decl already inserted into a DeclContext");
1747 
1748   if (FirstDecl) {
1749     LastDecl->NextInContextAndBits.setPointer(D);
1750     LastDecl = D;
1751   } else {
1752     FirstDecl = LastDecl = D;
1753   }
1754 
1755   // Notify a C++ record declaration that we've added a member, so it can
1756   // update its class-specific state.
1757   if (auto *Record = dyn_cast<CXXRecordDecl>(this))
1758     Record->addedMember(D);
1759 
1760   // If this is a newly-created (not de-serialized) import declaration, wire
1761   // it in to the list of local import declarations.
1762   if (!D->isFromASTFile()) {
1763     if (auto *Import = dyn_cast<ImportDecl>(D))
1764       D->getASTContext().addedLocalImportDecl(Import);
1765   }
1766 }
1767 
1768 void DeclContext::addDecl(Decl *D) {
1769   addHiddenDecl(D);
1770 
1771   if (auto *ND = dyn_cast<NamedDecl>(D))
1772     ND->getDeclContext()->getPrimaryContext()->
1773         makeDeclVisibleInContextWithFlags(ND, false, true);
1774 }
1775 
1776 void DeclContext::addDeclInternal(Decl *D) {
1777   addHiddenDecl(D);
1778 
1779   if (auto *ND = dyn_cast<NamedDecl>(D))
1780     ND->getDeclContext()->getPrimaryContext()->
1781         makeDeclVisibleInContextWithFlags(ND, true, true);
1782 }
1783 
1784 /// buildLookup - Build the lookup data structure with all of the
1785 /// declarations in this DeclContext (and any other contexts linked
1786 /// to it or transparent contexts nested within it) and return it.
1787 ///
1788 /// Note that the produced map may miss out declarations from an
1789 /// external source. If it does, those entries will be marked with
1790 /// the 'hasExternalDecls' flag.
1791 StoredDeclsMap *DeclContext::buildLookup() {
1792   assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1793 
1794   if (!hasLazyLocalLexicalLookups() &&
1795       !hasLazyExternalLexicalLookups())
1796     return LookupPtr;
1797 
1798   SmallVector<DeclContext *, 2> Contexts;
1799   collectAllContexts(Contexts);
1800 
1801   if (hasLazyExternalLexicalLookups()) {
1802     setHasLazyExternalLexicalLookups(false);
1803     for (auto *DC : Contexts) {
1804       if (DC->hasExternalLexicalStorage()) {
1805         bool LoadedDecls = DC->LoadLexicalDeclsFromExternalStorage();
1806         setHasLazyLocalLexicalLookups(
1807             hasLazyLocalLexicalLookups() | LoadedDecls );
1808       }
1809     }
1810 
1811     if (!hasLazyLocalLexicalLookups())
1812       return LookupPtr;
1813   }
1814 
1815   for (auto *DC : Contexts)
1816     buildLookupImpl(DC, hasExternalVisibleStorage());
1817 
1818   // We no longer have any lazy decls.
1819   setHasLazyLocalLexicalLookups(false);
1820   return LookupPtr;
1821 }
1822 
1823 /// buildLookupImpl - Build part of the lookup data structure for the
1824 /// declarations contained within DCtx, which will either be this
1825 /// DeclContext, a DeclContext linked to it, or a transparent context
1826 /// nested within it.
1827 void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
1828   for (auto *D : DCtx->noload_decls()) {
1829     // Insert this declaration into the lookup structure, but only if
1830     // it's semantically within its decl context. Any other decls which
1831     // should be found in this context are added eagerly.
1832     //
1833     // If it's from an AST file, don't add it now. It'll get handled by
1834     // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1835     // in C++, we do not track external visible decls for the TU, so in
1836     // that case we need to collect them all here.
1837     if (auto *ND = dyn_cast<NamedDecl>(D))
1838       if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1839           (!ND->isFromASTFile() ||
1840            (isTranslationUnit() &&
1841             !getParentASTContext().getLangOpts().CPlusPlus)))
1842         makeDeclVisibleInContextImpl(ND, Internal);
1843 
1844     // If this declaration is itself a transparent declaration context
1845     // or inline namespace, add the members of this declaration of that
1846     // context (recursively).
1847     if (auto *InnerCtx = dyn_cast<DeclContext>(D))
1848       if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1849         buildLookupImpl(InnerCtx, Internal);
1850   }
1851 }
1852 
1853 DeclContext::lookup_result
1854 DeclContext::lookup(DeclarationName Name) const {
1855   // For transparent DeclContext, we should lookup in their enclosing context.
1856   if (getDeclKind() == Decl::LinkageSpec || getDeclKind() == Decl::Export)
1857     return getParent()->lookup(Name);
1858 
1859   const DeclContext *PrimaryContext = getPrimaryContext();
1860   if (PrimaryContext != this)
1861     return PrimaryContext->lookup(Name);
1862 
1863   // If we have an external source, ensure that any later redeclarations of this
1864   // context have been loaded, since they may add names to the result of this
1865   // lookup (or add external visible storage).
1866   ExternalASTSource *Source = getParentASTContext().getExternalSource();
1867   if (Source)
1868     (void)cast<Decl>(this)->getMostRecentDecl();
1869 
1870   if (hasExternalVisibleStorage()) {
1871     assert(Source && "external visible storage but no external source?");
1872 
1873     if (hasNeedToReconcileExternalVisibleStorage())
1874       reconcileExternalVisibleStorage();
1875 
1876     StoredDeclsMap *Map = LookupPtr;
1877 
1878     if (hasLazyLocalLexicalLookups() ||
1879         hasLazyExternalLexicalLookups())
1880       // FIXME: Make buildLookup const?
1881       Map = const_cast<DeclContext*>(this)->buildLookup();
1882 
1883     if (!Map)
1884       Map = CreateStoredDeclsMap(getParentASTContext());
1885 
1886     // If we have a lookup result with no external decls, we are done.
1887     std::pair<StoredDeclsMap::iterator, bool> R =
1888         Map->insert(std::make_pair(Name, StoredDeclsList()));
1889     if (!R.second && !R.first->second.hasExternalDecls())
1890       return R.first->second.getLookupResult();
1891 
1892     if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
1893       if (StoredDeclsMap *Map = LookupPtr) {
1894         StoredDeclsMap::iterator I = Map->find(Name);
1895         if (I != Map->end())
1896           return I->second.getLookupResult();
1897       }
1898     }
1899 
1900     return {};
1901   }
1902 
1903   StoredDeclsMap *Map = LookupPtr;
1904   if (hasLazyLocalLexicalLookups() ||
1905       hasLazyExternalLexicalLookups())
1906     Map = const_cast<DeclContext*>(this)->buildLookup();
1907 
1908   if (!Map)
1909     return {};
1910 
1911   StoredDeclsMap::iterator I = Map->find(Name);
1912   if (I == Map->end())
1913     return {};
1914 
1915   return I->second.getLookupResult();
1916 }
1917 
1918 DeclContext::lookup_result
1919 DeclContext::noload_lookup(DeclarationName Name) {
1920   // For transparent DeclContext, we should lookup in their enclosing context.
1921   if (getDeclKind() == Decl::LinkageSpec || getDeclKind() == Decl::Export)
1922     return getParent()->noload_lookup(Name);
1923 
1924   DeclContext *PrimaryContext = getPrimaryContext();
1925   if (PrimaryContext != this)
1926     return PrimaryContext->noload_lookup(Name);
1927 
1928   loadLazyLocalLexicalLookups();
1929   StoredDeclsMap *Map = LookupPtr;
1930   if (!Map)
1931     return {};
1932 
1933   StoredDeclsMap::iterator I = Map->find(Name);
1934   return I != Map->end() ? I->second.getLookupResult()
1935                          : lookup_result();
1936 }
1937 
1938 // If we have any lazy lexical declarations not in our lookup map, add them
1939 // now. Don't import any external declarations, not even if we know we have
1940 // some missing from the external visible lookups.
1941 void DeclContext::loadLazyLocalLexicalLookups() {
1942   if (hasLazyLocalLexicalLookups()) {
1943     SmallVector<DeclContext *, 2> Contexts;
1944     collectAllContexts(Contexts);
1945     for (auto *Context : Contexts)
1946       buildLookupImpl(Context, hasExternalVisibleStorage());
1947     setHasLazyLocalLexicalLookups(false);
1948   }
1949 }
1950 
1951 void DeclContext::localUncachedLookup(DeclarationName Name,
1952                                       SmallVectorImpl<NamedDecl *> &Results) {
1953   Results.clear();
1954 
1955   // If there's no external storage, just perform a normal lookup and copy
1956   // the results.
1957   if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1958     lookup_result LookupResults = lookup(Name);
1959     Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1960     if (!Results.empty())
1961       return;
1962   }
1963 
1964   // If we have a lookup table, check there first. Maybe we'll get lucky.
1965   // FIXME: Should we be checking these flags on the primary context?
1966   if (Name && !hasLazyLocalLexicalLookups() &&
1967       !hasLazyExternalLexicalLookups()) {
1968     if (StoredDeclsMap *Map = LookupPtr) {
1969       StoredDeclsMap::iterator Pos = Map->find(Name);
1970       if (Pos != Map->end()) {
1971         Results.insert(Results.end(),
1972                        Pos->second.getLookupResult().begin(),
1973                        Pos->second.getLookupResult().end());
1974         return;
1975       }
1976     }
1977   }
1978 
1979   // Slow case: grovel through the declarations in our chain looking for
1980   // matches.
1981   // FIXME: If we have lazy external declarations, this will not find them!
1982   // FIXME: Should we CollectAllContexts and walk them all here?
1983   for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1984     if (auto *ND = dyn_cast<NamedDecl>(D))
1985       if (ND->getDeclName() == Name)
1986         Results.push_back(ND);
1987   }
1988 }
1989 
1990 DeclContext *DeclContext::getRedeclContext() {
1991   DeclContext *Ctx = this;
1992 
1993   // In C, a record type is the redeclaration context for its fields only. If
1994   // we arrive at a record context after skipping anything else, we should skip
1995   // the record as well. Currently, this means skipping enumerations because
1996   // they're the only transparent context that can exist within a struct or
1997   // union.
1998   bool SkipRecords = getDeclKind() == Decl::Kind::Enum &&
1999                      !getParentASTContext().getLangOpts().CPlusPlus;
2000 
2001   // Skip through contexts to get to the redeclaration context. Transparent
2002   // contexts are always skipped.
2003   while ((SkipRecords && Ctx->isRecord()) || Ctx->isTransparentContext())
2004     Ctx = Ctx->getParent();
2005   return Ctx;
2006 }
2007 
2008 DeclContext *DeclContext::getEnclosingNamespaceContext() {
2009   DeclContext *Ctx = this;
2010   // Skip through non-namespace, non-translation-unit contexts.
2011   while (!Ctx->isFileContext())
2012     Ctx = Ctx->getParent();
2013   return Ctx->getPrimaryContext();
2014 }
2015 
2016 RecordDecl *DeclContext::getOuterLexicalRecordContext() {
2017   // Loop until we find a non-record context.
2018   RecordDecl *OutermostRD = nullptr;
2019   DeclContext *DC = this;
2020   while (DC->isRecord()) {
2021     OutermostRD = cast<RecordDecl>(DC);
2022     DC = DC->getLexicalParent();
2023   }
2024   return OutermostRD;
2025 }
2026 
2027 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
2028   // For non-file contexts, this is equivalent to Equals.
2029   if (!isFileContext())
2030     return O->Equals(this);
2031 
2032   do {
2033     if (O->Equals(this))
2034       return true;
2035 
2036     const auto *NS = dyn_cast<NamespaceDecl>(O);
2037     if (!NS || !NS->isInline())
2038       break;
2039     O = NS->getParent();
2040   } while (O);
2041 
2042   return false;
2043 }
2044 
2045 void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
2046   DeclContext *PrimaryDC = this->getPrimaryContext();
2047   DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
2048   // If the decl is being added outside of its semantic decl context, we
2049   // need to ensure that we eagerly build the lookup information for it.
2050   PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
2051 }
2052 
2053 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
2054                                                     bool Recoverable) {
2055   assert(this == getPrimaryContext() && "expected a primary DC");
2056 
2057   if (!isLookupContext()) {
2058     if (isTransparentContext())
2059       getParent()->getPrimaryContext()
2060         ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
2061     return;
2062   }
2063 
2064   // Skip declarations which should be invisible to name lookup.
2065   if (shouldBeHidden(D))
2066     return;
2067 
2068   // If we already have a lookup data structure, perform the insertion into
2069   // it. If we might have externally-stored decls with this name, look them
2070   // up and perform the insertion. If this decl was declared outside its
2071   // semantic context, buildLookup won't add it, so add it now.
2072   //
2073   // FIXME: As a performance hack, don't add such decls into the translation
2074   // unit unless we're in C++, since qualified lookup into the TU is never
2075   // performed.
2076   if (LookupPtr || hasExternalVisibleStorage() ||
2077       ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
2078        (getParentASTContext().getLangOpts().CPlusPlus ||
2079         !isTranslationUnit()))) {
2080     // If we have lazily omitted any decls, they might have the same name as
2081     // the decl which we are adding, so build a full lookup table before adding
2082     // this decl.
2083     buildLookup();
2084     makeDeclVisibleInContextImpl(D, Internal);
2085   } else {
2086     setHasLazyLocalLexicalLookups(true);
2087   }
2088 
2089   // If we are a transparent context or inline namespace, insert into our
2090   // parent context, too. This operation is recursive.
2091   if (isTransparentContext() || isInlineNamespace())
2092     getParent()->getPrimaryContext()->
2093         makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
2094 
2095   auto *DCAsDecl = cast<Decl>(this);
2096   // Notify that a decl was made visible unless we are a Tag being defined.
2097   if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
2098     if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
2099       L->AddedVisibleDecl(this, D);
2100 }
2101 
2102 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
2103   // Find or create the stored declaration map.
2104   StoredDeclsMap *Map = LookupPtr;
2105   if (!Map) {
2106     ASTContext *C = &getParentASTContext();
2107     Map = CreateStoredDeclsMap(*C);
2108   }
2109 
2110   // If there is an external AST source, load any declarations it knows about
2111   // with this declaration's name.
2112   // If the lookup table contains an entry about this name it means that we
2113   // have already checked the external source.
2114   if (!Internal)
2115     if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
2116       if (hasExternalVisibleStorage() &&
2117           Map->find(D->getDeclName()) == Map->end())
2118         Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
2119 
2120   // Insert this declaration into the map.
2121   StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
2122 
2123   if (Internal) {
2124     // If this is being added as part of loading an external declaration,
2125     // this may not be the only external declaration with this name.
2126     // In this case, we never try to replace an existing declaration; we'll
2127     // handle that when we finalize the list of declarations for this name.
2128     DeclNameEntries.setHasExternalDecls();
2129     DeclNameEntries.prependDeclNoReplace(D);
2130     return;
2131   }
2132 
2133   DeclNameEntries.addOrReplaceDecl(D);
2134 }
2135 
2136 UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
2137   return cast<UsingDirectiveDecl>(*I);
2138 }
2139 
2140 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
2141 /// this context.
2142 DeclContext::udir_range DeclContext::using_directives() const {
2143   // FIXME: Use something more efficient than normal lookup for using
2144   // directives. In C++, using directives are looked up more than anything else.
2145   lookup_result Result = lookup(UsingDirectiveDecl::getName());
2146   return udir_range(Result.begin(), Result.end());
2147 }
2148 
2149 //===----------------------------------------------------------------------===//
2150 // Creation and Destruction of StoredDeclsMaps.                               //
2151 //===----------------------------------------------------------------------===//
2152 
2153 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
2154   assert(!LookupPtr && "context already has a decls map");
2155   assert(getPrimaryContext() == this &&
2156          "creating decls map on non-primary context");
2157 
2158   StoredDeclsMap *M;
2159   bool Dependent = isDependentContext();
2160   if (Dependent)
2161     M = new DependentStoredDeclsMap();
2162   else
2163     M = new StoredDeclsMap();
2164   M->Previous = C.LastSDM;
2165   C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
2166   LookupPtr = M;
2167   return M;
2168 }
2169 
2170 void ASTContext::ReleaseDeclContextMaps() {
2171   // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
2172   // pointer because the subclass doesn't add anything that needs to
2173   // be deleted.
2174   StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
2175   LastSDM.setPointer(nullptr);
2176 }
2177 
2178 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
2179   while (Map) {
2180     // Advance the iteration before we invalidate memory.
2181     llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
2182 
2183     if (Dependent)
2184       delete static_cast<DependentStoredDeclsMap*>(Map);
2185     else
2186       delete Map;
2187 
2188     Map = Next.getPointer();
2189     Dependent = Next.getInt();
2190   }
2191 }
2192 
2193 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
2194                                                  DeclContext *Parent,
2195                                            const PartialDiagnostic &PDiag) {
2196   assert(Parent->isDependentContext()
2197          && "cannot iterate dependent diagnostics of non-dependent context");
2198   Parent = Parent->getPrimaryContext();
2199   if (!Parent->LookupPtr)
2200     Parent->CreateStoredDeclsMap(C);
2201 
2202   auto *Map = static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
2203 
2204   // Allocate the copy of the PartialDiagnostic via the ASTContext's
2205   // BumpPtrAllocator, rather than the ASTContext itself.
2206   DiagnosticStorage *DiagStorage = nullptr;
2207   if (PDiag.hasStorage())
2208     DiagStorage = new (C) DiagnosticStorage;
2209 
2210   auto *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
2211 
2212   // TODO: Maybe we shouldn't reverse the order during insertion.
2213   DD->NextDiagnostic = Map->FirstDiagnostic;
2214   Map->FirstDiagnostic = DD;
2215 
2216   return DD;
2217 }
2218 
2219 unsigned DeclIDBase::getLocalDeclIndex() const {
2220   return ID & llvm::maskTrailingOnes<DeclID>(32);
2221 }
2222