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