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