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