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