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