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