blob: bc7ac569fc01ac87aa36e9e394984e0289b59260 [file] [log] [blame]
Eli Friedman56d29372008-06-07 16:52:53 +00001//===--- 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"
Douglas Gregor64650af2009-02-02 23:39:07 +000015#include "clang/AST/Decl.h"
Argyrios Kyrtzidisd3bb44f2008-06-09 21:05:31 +000016#include "clang/AST/DeclCXX.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000017#include "clang/AST/DeclObjC.h"
18#include "clang/AST/DeclTemplate.h"
Eli Friedman56d29372008-06-07 16:52:53 +000019#include "clang/AST/ASTContext.h"
Douglas Gregor44b43212008-12-11 16:49:14 +000020#include "clang/AST/Type.h"
Eli Friedman56d29372008-06-07 16:52:53 +000021#include "llvm/ADT/DenseMap.h"
Chris Lattner49f28ca2009-03-05 08:00:35 +000022#include "llvm/Support/raw_ostream.h"
Douglas Gregor6ed40e32008-12-23 21:05:05 +000023#include <algorithm>
Chris Lattner3daed522009-03-02 22:20:04 +000024#include <cstdio>
Douglas Gregor6ed40e32008-12-23 21:05:05 +000025#include <functional>
Douglas Gregor3fc749d2008-12-23 00:26:44 +000026#include <vector>
Eli Friedman56d29372008-06-07 16:52:53 +000027using namespace clang;
28
29//===----------------------------------------------------------------------===//
30// Statistics
31//===----------------------------------------------------------------------===//
32
Douglas Gregor64650af2009-02-02 23:39:07 +000033#define DECL(Derived, Base) static int n##Derived##s = 0;
34#include "clang/AST/DeclNodes.def"
Eli Friedman56d29372008-06-07 16:52:53 +000035
36static bool StatSwitch = false;
37
38// This keeps track of all decl attributes. Since so few decls have attrs, we
39// keep them in a hash map instead of wasting space in the Decl class.
40typedef llvm::DenseMap<const Decl*, Attr*> DeclAttrMapTy;
41
42static DeclAttrMapTy *DeclAttrs = 0;
43
44const char *Decl::getDeclKindName() const {
45 switch (DeclKind) {
Douglas Gregor64650af2009-02-02 23:39:07 +000046 default: assert(0 && "Declaration not in DeclNodes.def!");
47#define DECL(Derived, Base) case Derived: return #Derived;
48#include "clang/AST/DeclNodes.def"
Eli Friedman56d29372008-06-07 16:52:53 +000049 }
50}
51
Steve Naroff0a473932009-01-20 19:53:53 +000052const char *DeclContext::getDeclKindName() const {
53 switch (DeclKind) {
Douglas Gregor64650af2009-02-02 23:39:07 +000054 default: assert(0 && "Declaration context not in DeclNodes.def!");
Argyrios Kyrtzidis1ad4dd72009-02-16 14:28:33 +000055#define DECL(Derived, Base) case Decl::Derived: return #Derived;
Douglas Gregor64650af2009-02-02 23:39:07 +000056#include "clang/AST/DeclNodes.def"
Steve Naroff0a473932009-01-20 19:53:53 +000057 }
58}
59
Eli Friedman56d29372008-06-07 16:52:53 +000060bool Decl::CollectingStats(bool Enable) {
61 if (Enable)
62 StatSwitch = true;
63 return StatSwitch;
64}
65
66void Decl::PrintStats() {
67 fprintf(stderr, "*** Decl Stats:\n");
Eli Friedman56d29372008-06-07 16:52:53 +000068
Douglas Gregor64650af2009-02-02 23:39:07 +000069 int totalDecls = 0;
70#define DECL(Derived, Base) totalDecls += n##Derived##s;
71#include "clang/AST/DeclNodes.def"
72 fprintf(stderr, " %d decls total.\n", totalDecls);
73
74 int totalBytes = 0;
75#define DECL(Derived, Base) \
76 if (n##Derived##s > 0) { \
77 totalBytes += (int)(n##Derived##s * sizeof(Derived##Decl)); \
78 fprintf(stderr, " %d " #Derived " decls, %d each (%d bytes)\n", \
79 n##Derived##s, (int)sizeof(Derived##Decl), \
80 (int)(n##Derived##s * sizeof(Derived##Decl))); \
81 }
82#include "clang/AST/DeclNodes.def"
Eli Friedman56d29372008-06-07 16:52:53 +000083
Douglas Gregor64650af2009-02-02 23:39:07 +000084 fprintf(stderr, "Total bytes = %d\n", totalBytes);
Eli Friedman56d29372008-06-07 16:52:53 +000085}
86
87void Decl::addDeclKind(Kind k) {
88 switch (k) {
Douglas Gregor64650af2009-02-02 23:39:07 +000089 default: assert(0 && "Declaration not in DeclNodes.def!");
90#define DECL(Derived, Base) case Derived: ++n##Derived##s; break;
91#include "clang/AST/DeclNodes.def"
Eli Friedman56d29372008-06-07 16:52:53 +000092 }
93}
94
95//===----------------------------------------------------------------------===//
Chris Lattner49f28ca2009-03-05 08:00:35 +000096// PrettyStackTraceDecl Implementation
97//===----------------------------------------------------------------------===//
98
99void PrettyStackTraceDecl::print(llvm::raw_ostream &OS) const {
100 SourceLocation TheLoc = Loc;
101 if (TheLoc.isInvalid() && TheDecl)
102 TheLoc = TheDecl->getLocation();
103
104 if (TheLoc.isValid()) {
105 TheLoc.print(OS, SM);
106 OS << ": ";
107 }
108
109 OS << Message;
110
111 if (NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl))
112 OS << " '" << DN->getQualifiedNameAsString() << '\'';
113 OS << '\n';
114}
115
116//===----------------------------------------------------------------------===//
Eli Friedman56d29372008-06-07 16:52:53 +0000117// Decl Implementation
118//===----------------------------------------------------------------------===//
119
Chris Lattner769dbdf2009-03-27 20:18:19 +0000120// Out-of-line virtual method providing a home for Decl.
121Decl::~Decl() {
122 if (isOutOfSemaDC())
123 delete getMultipleDC();
124
125 assert(!HasAttrs && "attributes should have been freed by Destroy");
126}
127
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000128void Decl::setDeclContext(DeclContext *DC) {
129 if (isOutOfSemaDC())
130 delete getMultipleDC();
131
Chris Lattner10d83792009-03-27 18:46:15 +0000132 DeclCtx.setPointer(DC);
133 DeclCtx.setInt(false);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000134}
135
136void Decl::setLexicalDeclContext(DeclContext *DC) {
137 if (DC == getLexicalDeclContext())
138 return;
139
140 if (isInSemaDC()) {
141 MultipleDC *MDC = new MultipleDC();
142 MDC->SemanticDC = getDeclContext();
143 MDC->LexicalDC = DC;
Chris Lattner10d83792009-03-27 18:46:15 +0000144 DeclCtx.setPointer(MDC);
145 DeclCtx.setInt(true);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000146 } else {
147 getMultipleDC()->LexicalDC = DC;
148 }
149}
150
Chris Lattner769dbdf2009-03-27 20:18:19 +0000151unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
152 switch (DeclKind) {
153 default:
154 if (DeclKind >= FunctionFirst && DeclKind <= FunctionLast)
155 return IDNS_Ordinary;
156 assert(0 && "Unknown decl kind!");
157 case OverloadedFunction:
158 case Typedef:
159 case EnumConstant:
160 case Var:
161 case ImplicitParam:
162 case ParmVar:
163 case OriginalParmVar:
164 case NonTypeTemplateParm:
165 case ObjCMethod:
166 case ObjCContainer:
167 case ObjCCategory:
168 case ObjCInterface:
169 case ObjCCategoryImpl:
170 case ObjCProperty:
171 case ObjCCompatibleAlias:
172 return IDNS_Ordinary;
173
174 case ObjCProtocol:
175 return IDNS_Protocol;
176
177 case Field:
178 case ObjCAtDefsField:
179 case ObjCIvar:
180 return IDNS_Member;
181
182 case Record:
183 case CXXRecord:
184 case Enum:
185 case TemplateTypeParm:
186 return IDNS_Tag;
187
188 case Namespace:
189 case Template:
190 case FunctionTemplate:
191 case ClassTemplate:
192 case TemplateTemplateParm:
Anders Carlssonfaf0e872009-03-28 23:02:53 +0000193 case NamespaceAlias:
Chris Lattner769dbdf2009-03-27 20:18:19 +0000194 return IDNS_Tag | IDNS_Ordinary;
195
196 // Never have names.
197 case LinkageSpec:
198 case FileScopeAsm:
199 case StaticAssert:
200 case ObjCClass:
201 case ObjCImplementation:
202 case ObjCPropertyImpl:
203 case ObjCForwardProtocol:
204 case Block:
205 case TranslationUnit:
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000206
Chris Lattner769dbdf2009-03-27 20:18:19 +0000207 // Aren't looked up?
208 case UsingDirective:
209 case ClassTemplateSpecialization:
210 return 0;
211 }
Eli Friedman56d29372008-06-07 16:52:53 +0000212}
213
214void Decl::addAttr(Attr *NewAttr) {
215 if (!DeclAttrs)
216 DeclAttrs = new DeclAttrMapTy();
217
218 Attr *&ExistingAttr = (*DeclAttrs)[this];
219
220 NewAttr->setNext(ExistingAttr);
221 ExistingAttr = NewAttr;
222
223 HasAttrs = true;
224}
225
226void Decl::invalidateAttrs() {
227 if (!HasAttrs) return;
228
229 HasAttrs = false;
230 (*DeclAttrs)[this] = 0;
231 DeclAttrs->erase(this);
232
233 if (DeclAttrs->empty()) {
234 delete DeclAttrs;
235 DeclAttrs = 0;
236 }
237}
238
Chris Lattner81abbdd2009-03-21 06:27:31 +0000239const Attr *Decl::getAttrsImpl() const {
240 assert(HasAttrs && "getAttrs() should verify this!");
Eli Friedman56d29372008-06-07 16:52:53 +0000241 return (*DeclAttrs)[this];
242}
243
244void Decl::swapAttrs(Decl *RHS) {
245 bool HasLHSAttr = this->HasAttrs;
246 bool HasRHSAttr = RHS->HasAttrs;
247
248 // Usually, neither decl has attrs, nothing to do.
249 if (!HasLHSAttr && !HasRHSAttr) return;
250
251 // If 'this' has no attrs, swap the other way.
252 if (!HasLHSAttr)
253 return RHS->swapAttrs(this);
254
255 // Handle the case when both decls have attrs.
256 if (HasRHSAttr) {
257 std::swap((*DeclAttrs)[this], (*DeclAttrs)[RHS]);
258 return;
259 }
260
261 // Otherwise, LHS has an attr and RHS doesn't.
262 (*DeclAttrs)[RHS] = (*DeclAttrs)[this];
263 (*DeclAttrs).erase(this);
264 this->HasAttrs = false;
265 RHS->HasAttrs = true;
266}
267
268
Chris Lattnercc581472009-03-04 06:05:19 +0000269void Decl::Destroy(ASTContext &C) {
270 // Free attributes for this decl.
271 if (HasAttrs) {
272 DeclAttrMapTy::iterator it = DeclAttrs->find(this);
273 assert(it != DeclAttrs->end() && "No attrs found but HasAttrs is true!");
274
275 // release attributes.
276 it->second->Destroy(C);
277 invalidateAttrs();
278 HasAttrs = false;
279 }
280
Douglas Gregora0fc55f2009-01-13 19:47:12 +0000281#if 0
Douglas Gregor00ad0ef2009-01-20 04:25:11 +0000282 // FIXME: Once ownership is fully understood, we can enable this code
283 if (DeclContext *DC = dyn_cast<DeclContext>(this))
284 DC->decls_begin()->Destroy(C);
Eli Friedman56d29372008-06-07 16:52:53 +0000285
Chris Lattner244a67d2009-03-28 06:04:26 +0000286 // Observe the unrolled recursion. By setting N->NextDeclInContext = 0x0
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000287 // within the loop, only the Destroy method for the first Decl
288 // will deallocate all of the Decls in a chain.
289
Chris Lattner244a67d2009-03-28 06:04:26 +0000290 Decl* N = getNextDeclInContext();
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000291
292 while (N) {
Chris Lattner244a67d2009-03-28 06:04:26 +0000293 Decl* Tmp = N->getNextDeclInContext();
294 N->NextDeclInContext = 0;
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000295 N->Destroy(C);
296 N = Tmp;
Eli Friedman56d29372008-06-07 16:52:53 +0000297 }
Douglas Gregora0fc55f2009-01-13 19:47:12 +0000298
Eli Friedman56d29372008-06-07 16:52:53 +0000299 this->~Decl();
Steve Naroff3e970492009-01-27 21:25:57 +0000300 C.Deallocate((void *)this);
Douglas Gregor00ad0ef2009-01-20 04:25:11 +0000301#endif
Eli Friedman56d29372008-06-07 16:52:53 +0000302}
303
Argyrios Kyrtzidis42220c52008-10-12 16:14:48 +0000304Decl *Decl::castFromDeclContext (const DeclContext *D) {
Argyrios Kyrtzidis3d7641e2009-02-16 14:29:28 +0000305 Decl::Kind DK = D->getDeclKind();
306 switch(DK) {
307#define DECL_CONTEXT(Name) \
308 case Decl::Name: \
309 return static_cast<Name##Decl*>(const_cast<DeclContext*>(D));
310#define DECL_CONTEXT_BASE(Name)
311#include "clang/AST/DeclNodes.def"
312 default:
313#define DECL_CONTEXT_BASE(Name) \
314 if (DK >= Decl::Name##First && DK <= Decl::Name##Last) \
315 return static_cast<Name##Decl*>(const_cast<DeclContext*>(D));
316#include "clang/AST/DeclNodes.def"
317 assert(false && "a decl that inherits DeclContext isn't handled");
318 return 0;
319 }
Argyrios Kyrtzidis42220c52008-10-12 16:14:48 +0000320}
321
322DeclContext *Decl::castToDeclContext(const Decl *D) {
Argyrios Kyrtzidis3d7641e2009-02-16 14:29:28 +0000323 Decl::Kind DK = D->getKind();
324 switch(DK) {
325#define DECL_CONTEXT(Name) \
326 case Decl::Name: \
327 return static_cast<Name##Decl*>(const_cast<Decl*>(D));
328#define DECL_CONTEXT_BASE(Name)
329#include "clang/AST/DeclNodes.def"
330 default:
331#define DECL_CONTEXT_BASE(Name) \
332 if (DK >= Decl::Name##First && DK <= Decl::Name##Last) \
333 return static_cast<Name##Decl*>(const_cast<Decl*>(D));
334#include "clang/AST/DeclNodes.def"
335 assert(false && "a decl that inherits DeclContext isn't handled");
336 return 0;
337 }
Argyrios Kyrtzidis42220c52008-10-12 16:14:48 +0000338}
339
Anders Carlsson1329c272009-03-25 23:38:06 +0000340#ifndef NDEBUG
341void Decl::CheckAccessDeclContext() const {
342 assert((Access != AS_none || !isa<CXXRecordDecl>(getDeclContext())) &&
343 "Access specifier is AS_none inside a record decl");
344}
345
346#endif
347
Eli Friedman56d29372008-06-07 16:52:53 +0000348//===----------------------------------------------------------------------===//
349// DeclContext Implementation
350//===----------------------------------------------------------------------===//
351
Argyrios Kyrtzidis3d7641e2009-02-16 14:29:28 +0000352bool DeclContext::classof(const Decl *D) {
353 switch (D->getKind()) {
354#define DECL_CONTEXT(Name) case Decl::Name:
355#define DECL_CONTEXT_BASE(Name)
356#include "clang/AST/DeclNodes.def"
357 return true;
358 default:
359#define DECL_CONTEXT_BASE(Name) \
360 if (D->getKind() >= Decl::Name##First && \
361 D->getKind() <= Decl::Name##Last) \
362 return true;
363#include "clang/AST/DeclNodes.def"
364 return false;
365 }
366}
367
Chris Lattner67762a32009-02-20 01:44:05 +0000368/// StoredDeclsList - This is an array of decls optimized a common case of only
369/// containing one entry.
370struct StoredDeclsList {
371 /// Data - If the integer is 0, then the pointer is a NamedDecl*. If the
372 /// integer is 1, then it is a VectorTy;
373 llvm::PointerIntPair<void*, 1, bool> Data;
374
375 /// VectorTy - When in vector form, this is what the Data pointer points to.
376 typedef llvm::SmallVector<NamedDecl*, 4> VectorTy;
377public:
378 StoredDeclsList() {}
379 StoredDeclsList(const StoredDeclsList &RHS) : Data(RHS.Data) {
380 if (isVector())
381 Data.setPointer(new VectorTy(getVector()));
382 }
383
384 ~StoredDeclsList() {
385 // If this is a vector-form, free the vector.
386 if (isVector())
387 delete &getVector();
388 }
389
Chris Lattner01011d42009-02-23 18:17:44 +0000390 StoredDeclsList &operator=(const StoredDeclsList &RHS) {
391 if (isVector())
392 delete &getVector();
393 Data = RHS.Data;
394 if (isVector())
395 Data.setPointer(new VectorTy(getVector()));
396 return *this;
397 }
398
Chris Lattner67762a32009-02-20 01:44:05 +0000399 bool isVector() const { return Data.getInt() != 0; }
400 bool isInline() const { return Data.getInt() == 0; }
401 bool isNull() const { return Data.getPointer() == 0; }
402
403 void setOnlyValue(NamedDecl *ND) {
404 assert(isInline() && "Not inline");
405 Data.setPointer(ND);
406 }
407
408 /// getLookupResult - Return an array of all the decls that this list
409 /// represents.
410 DeclContext::lookup_result getLookupResult() {
411 // If we have a single inline unit, return it.
412 if (isInline()) {
413 assert(!isNull() && "Empty list isn't allowed");
414
415 // Data is a raw pointer to a NamedDecl*, return it.
416 void *Ptr = &Data;
417 return DeclContext::lookup_result((NamedDecl**)Ptr, (NamedDecl**)Ptr+1);
418 }
419
420 // Otherwise, we have a range result.
421 VectorTy &V = getVector();
422 return DeclContext::lookup_result(&V[0], &V[0]+V.size());
423 }
424
425 /// HandleRedeclaration - If this is a redeclaration of an existing decl,
426 /// replace the old one with D and return true. Otherwise return false.
427 bool HandleRedeclaration(NamedDecl *D) {
428 // Most decls only have one entry in their list, special case it.
429 if (isInline()) {
430 if (!D->declarationReplaces(getInlineValue()))
431 return false;
432 setOnlyValue(D);
433 return true;
434 }
435
436 // Determine if this declaration is actually a redeclaration.
437 VectorTy &Vec = getVector();
438 VectorTy::iterator RDI
439 = std::find_if(Vec.begin(), Vec.end(),
440 std::bind1st(std::mem_fun(&NamedDecl::declarationReplaces),
441 D));
442 if (RDI == Vec.end())
443 return false;
444 *RDI = D;
445 return true;
446 }
447
448 /// AddSubsequentDecl - This is called on the second and later decl when it is
449 /// not a redeclaration to merge it into the appropriate place in our list.
450 ///
451 void AddSubsequentDecl(NamedDecl *D) {
452 // If this is the second decl added to the list, convert this to vector
453 // form.
454 if (isInline()) {
455 NamedDecl *OldD = getInlineValue();
456 Data.setInt(1);
457 VectorTy *VT = new VectorTy();
458 VT->push_back(OldD);
459 Data.setPointer(VT);
460 }
461
462 VectorTy &Vec = getVector();
463 if (isa<UsingDirectiveDecl>(D) ||
464 D->getIdentifierNamespace() == Decl::IDNS_Tag)
465 Vec.push_back(D);
466 else if (Vec.back()->getIdentifierNamespace() == Decl::IDNS_Tag) {
467 NamedDecl *TagD = Vec.back();
468 Vec.back() = D;
469 Vec.push_back(TagD);
470 } else
471 Vec.push_back(D);
472 }
473
474
475private:
476 VectorTy &getVector() const {
477 assert(isVector() && "Not in vector form");
478 return *static_cast<VectorTy*>(Data.getPointer());
479 }
480
481 NamedDecl *getInlineValue() const {
482 assert(isInline() && "Not in inline form");
483 return (NamedDecl*)Data.getPointer();
484 }
485};
486
487
488
489typedef llvm::DenseMap<DeclarationName, StoredDeclsList> StoredDeclsMap;
Douglas Gregor44b43212008-12-11 16:49:14 +0000490
491DeclContext::~DeclContext() {
Chris Lattner769dbdf2009-03-27 20:18:19 +0000492 if (isLookupMap())
Chris Lattner91942502009-02-20 00:55:03 +0000493 delete static_cast<StoredDeclsMap*>(LookupPtr.getPointer());
494 else
495 delete [] static_cast<NamedDecl**>(LookupPtr.getPointer());
Douglas Gregor44b43212008-12-11 16:49:14 +0000496}
497
498void DeclContext::DestroyDecls(ASTContext &C) {
Douglas Gregor00ad0ef2009-01-20 04:25:11 +0000499 for (decl_iterator D = decls_begin(); D != decls_end(); )
500 (*D++)->Destroy(C);
Douglas Gregor44b43212008-12-11 16:49:14 +0000501}
502
Douglas Gregor074149e2009-01-05 19:45:36 +0000503bool DeclContext::isTransparentContext() const {
504 if (DeclKind == Decl::Enum)
505 return true; // FIXME: Check for C++0x scoped enums
506 else if (DeclKind == Decl::LinkageSpec)
507 return true;
Douglas Gregor65100792009-02-26 00:02:51 +0000508 else if (DeclKind >= Decl::RecordFirst && DeclKind <= Decl::RecordLast)
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000509 return cast<RecordDecl>(this)->isAnonymousStructOrUnion();
Douglas Gregor074149e2009-01-05 19:45:36 +0000510 else if (DeclKind == Decl::Namespace)
511 return false; // FIXME: Check for C++0x inline namespaces
512
513 return false;
514}
515
Steve Naroff0701bbb2009-01-08 17:28:14 +0000516DeclContext *DeclContext::getPrimaryContext() {
Douglas Gregor44b43212008-12-11 16:49:14 +0000517 switch (DeclKind) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000518 case Decl::TranslationUnit:
Douglas Gregor074149e2009-01-05 19:45:36 +0000519 case Decl::LinkageSpec:
520 case Decl::Block:
Douglas Gregor44b43212008-12-11 16:49:14 +0000521 // There is only one DeclContext for these entities.
522 return this;
523
524 case Decl::Namespace:
525 // The original namespace is our primary context.
526 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
527
Douglas Gregor44b43212008-12-11 16:49:14 +0000528 case Decl::ObjCMethod:
529 return this;
530
531 case Decl::ObjCInterface:
Steve Naroff0701bbb2009-01-08 17:28:14 +0000532 case Decl::ObjCProtocol:
533 case Decl::ObjCCategory:
Douglas Gregor44b43212008-12-11 16:49:14 +0000534 // FIXME: Can Objective-C interfaces be forward-declared?
535 return this;
536
Steve Naroff0701bbb2009-01-08 17:28:14 +0000537 case Decl::ObjCImplementation:
538 case Decl::ObjCCategoryImpl:
539 return this;
540
Douglas Gregor44b43212008-12-11 16:49:14 +0000541 default:
Douglas Gregorcc636682009-02-17 23:15:12 +0000542 if (DeclKind >= Decl::TagFirst && DeclKind <= Decl::TagLast) {
543 // If this is a tag type that has a definition or is currently
544 // being defined, that definition is our primary context.
Chris Lattner244a67d2009-03-28 06:04:26 +0000545 if (const TagType *TagT =cast<TagDecl>(this)->TypeForDecl->getAsTagType())
Douglas Gregorcc636682009-02-17 23:15:12 +0000546 if (TagT->isBeingDefined() ||
547 (TagT->getDecl() && TagT->getDecl()->isDefinition()))
548 return TagT->getDecl();
549 return this;
550 }
551
Douglas Gregor44b43212008-12-11 16:49:14 +0000552 assert(DeclKind >= Decl::FunctionFirst && DeclKind <= Decl::FunctionLast &&
553 "Unknown DeclContext kind");
554 return this;
555 }
556}
557
558DeclContext *DeclContext::getNextContext() {
559 switch (DeclKind) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000560 case Decl::Namespace:
561 // Return the next namespace
562 return static_cast<NamespaceDecl*>(this)->getNextNamespace();
563
564 default:
Douglas Gregor44b43212008-12-11 16:49:14 +0000565 return 0;
566 }
567}
568
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000569void DeclContext::addDecl(Decl *D) {
Chris Lattner7f0be132009-02-20 00:56:18 +0000570 assert(D->getLexicalDeclContext() == this &&
571 "Decl inserted into wrong lexical context");
Chris Lattner244a67d2009-03-28 06:04:26 +0000572 assert(!D->getNextDeclInContext() && D != LastDecl &&
Douglas Gregor6037fcb2009-01-09 19:42:16 +0000573 "Decl already inserted into a DeclContext");
574
575 if (FirstDecl) {
Chris Lattner244a67d2009-03-28 06:04:26 +0000576 LastDecl->NextDeclInContext = D;
Douglas Gregor6037fcb2009-01-09 19:42:16 +0000577 LastDecl = D;
578 } else {
579 FirstDecl = LastDecl = D;
580 }
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000581
582 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Douglas Gregor40f4e692009-01-20 16:54:50 +0000583 ND->getDeclContext()->makeDeclVisibleInContext(ND);
Douglas Gregor44b43212008-12-11 16:49:14 +0000584}
585
Douglas Gregor074149e2009-01-05 19:45:36 +0000586/// buildLookup - Build the lookup data structure with all of the
587/// declarations in DCtx (and any other contexts linked to it or
588/// transparent contexts nested within it).
Steve Naroff0701bbb2009-01-08 17:28:14 +0000589void DeclContext::buildLookup(DeclContext *DCtx) {
Douglas Gregor074149e2009-01-05 19:45:36 +0000590 for (; DCtx; DCtx = DCtx->getNextContext()) {
Douglas Gregor4f3b8f82009-01-06 07:17:58 +0000591 for (decl_iterator D = DCtx->decls_begin(), DEnd = DCtx->decls_end();
592 D != DEnd; ++D) {
Douglas Gregor074149e2009-01-05 19:45:36 +0000593 // Insert this declaration into the lookup structure
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000594 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor40f4e692009-01-20 16:54:50 +0000595 makeDeclVisibleInContextImpl(ND);
Douglas Gregor074149e2009-01-05 19:45:36 +0000596
597 // If this declaration is itself a transparent declaration context,
598 // add its members (recursively).
599 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D))
600 if (InnerCtx->isTransparentContext())
Steve Naroff0701bbb2009-01-08 17:28:14 +0000601 buildLookup(InnerCtx->getPrimaryContext());
Douglas Gregor074149e2009-01-05 19:45:36 +0000602 }
603 }
604}
605
Douglas Gregor44b43212008-12-11 16:49:14 +0000606DeclContext::lookup_result
Steve Naroff0701bbb2009-01-08 17:28:14 +0000607DeclContext::lookup(DeclarationName Name) {
608 DeclContext *PrimaryContext = getPrimaryContext();
Douglas Gregor44b43212008-12-11 16:49:14 +0000609 if (PrimaryContext != this)
Steve Naroff0701bbb2009-01-08 17:28:14 +0000610 return PrimaryContext->lookup(Name);
Douglas Gregor44b43212008-12-11 16:49:14 +0000611
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000612 /// If there is no lookup data structure, build one now by walking
Douglas Gregor44b43212008-12-11 16:49:14 +0000613 /// all of the linked DeclContexts (in declaration order!) and
614 /// inserting their values.
Douglas Gregor074149e2009-01-05 19:45:36 +0000615 if (LookupPtr.getPointer() == 0)
Steve Naroff0701bbb2009-01-08 17:28:14 +0000616 buildLookup(this);
Douglas Gregor44b43212008-12-11 16:49:14 +0000617
Douglas Gregor44b43212008-12-11 16:49:14 +0000618 if (isLookupMap()) {
619 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(LookupPtr.getPointer());
620 StoredDeclsMap::iterator Pos = Map->find(Name);
Chris Lattner91942502009-02-20 00:55:03 +0000621 if (Pos == Map->end())
622 return lookup_result(0, 0);
Chris Lattner67762a32009-02-20 01:44:05 +0000623 return Pos->second.getLookupResult();
Douglas Gregor44b43212008-12-11 16:49:14 +0000624 }
625
626 // We have a small array. Look into it.
627 unsigned Size = LookupPtr.getInt();
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000628 NamedDecl **Array = static_cast<NamedDecl**>(LookupPtr.getPointer());
Douglas Gregore267ff32008-12-11 20:41:00 +0000629 for (unsigned Idx = 0; Idx != Size; ++Idx)
Douglas Gregor44b43212008-12-11 16:49:14 +0000630 if (Array[Idx]->getDeclName() == Name) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000631 unsigned Last = Idx + 1;
632 while (Last != Size && Array[Last]->getDeclName() == Name)
633 ++Last;
634 return lookup_result(&Array[Idx], &Array[Last]);
Douglas Gregor44b43212008-12-11 16:49:14 +0000635 }
636
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000637 return lookup_result(0, 0);
Douglas Gregor44b43212008-12-11 16:49:14 +0000638}
639
640DeclContext::lookup_const_result
Steve Naroff0701bbb2009-01-08 17:28:14 +0000641DeclContext::lookup(DeclarationName Name) const {
642 return const_cast<DeclContext*>(this)->lookup(Name);
Douglas Gregor44b43212008-12-11 16:49:14 +0000643}
644
Chris Lattner0cf2b192009-03-27 19:19:59 +0000645DeclContext *DeclContext::getLookupContext() {
646 DeclContext *Ctx = this;
Douglas Gregor72de6672009-01-08 20:45:30 +0000647 // Skip through transparent contexts.
Douglas Gregorce356072009-01-06 23:51:29 +0000648 while (Ctx->isTransparentContext())
649 Ctx = Ctx->getParent();
650 return Ctx;
651}
652
Douglas Gregor88b70942009-02-25 22:02:03 +0000653DeclContext *DeclContext::getEnclosingNamespaceContext() {
654 DeclContext *Ctx = this;
655 // Skip through non-namespace, non-translation-unit contexts.
656 while (!Ctx->isFileContext() || Ctx->isTransparentContext())
657 Ctx = Ctx->getParent();
658 return Ctx->getPrimaryContext();
659}
660
Douglas Gregor40f4e692009-01-20 16:54:50 +0000661void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
Douglas Gregorcc636682009-02-17 23:15:12 +0000662 // FIXME: This feels like a hack. Should DeclarationName support
663 // template-ids, or is there a better way to keep specializations
664 // from being visible?
665 if (isa<ClassTemplateSpecializationDecl>(D))
666 return;
667
Steve Naroff0701bbb2009-01-08 17:28:14 +0000668 DeclContext *PrimaryContext = getPrimaryContext();
Douglas Gregor44b43212008-12-11 16:49:14 +0000669 if (PrimaryContext != this) {
Douglas Gregor40f4e692009-01-20 16:54:50 +0000670 PrimaryContext->makeDeclVisibleInContext(D);
Douglas Gregor44b43212008-12-11 16:49:14 +0000671 return;
672 }
673
674 // If we already have a lookup data structure, perform the insertion
675 // into it. Otherwise, be lazy and don't build that structure until
676 // someone asks for it.
677 if (LookupPtr.getPointer())
Douglas Gregor40f4e692009-01-20 16:54:50 +0000678 makeDeclVisibleInContextImpl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +0000679
Douglas Gregor074149e2009-01-05 19:45:36 +0000680 // If we are a transparent context, insert into our parent context,
681 // too. This operation is recursive.
682 if (isTransparentContext())
Douglas Gregor40f4e692009-01-20 16:54:50 +0000683 getParent()->makeDeclVisibleInContext(D);
Douglas Gregor44b43212008-12-11 16:49:14 +0000684}
685
Douglas Gregor40f4e692009-01-20 16:54:50 +0000686void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D) {
Douglas Gregor074149e2009-01-05 19:45:36 +0000687 // Skip unnamed declarations.
688 if (!D->getDeclName())
689 return;
690
Douglas Gregorcc636682009-02-17 23:15:12 +0000691 // FIXME: This feels like a hack. Should DeclarationName support
692 // template-ids, or is there a better way to keep specializations
693 // from being visible?
694 if (isa<ClassTemplateSpecializationDecl>(D))
695 return;
696
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000697 bool MayBeRedeclaration = true;
698
Douglas Gregor44b43212008-12-11 16:49:14 +0000699 if (!isLookupMap()) {
700 unsigned Size = LookupPtr.getInt();
701
702 // The lookup data is stored as an array. Search through the array
703 // to find the insertion location.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000704 NamedDecl **Array;
Douglas Gregor44b43212008-12-11 16:49:14 +0000705 if (Size == 0) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000706 Array = new NamedDecl*[LookupIsMap - 1];
Douglas Gregor44b43212008-12-11 16:49:14 +0000707 LookupPtr.setPointer(Array);
708 } else {
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000709 Array = static_cast<NamedDecl **>(LookupPtr.getPointer());
Douglas Gregor44b43212008-12-11 16:49:14 +0000710 }
711
712 // We always keep declarations of the same name next to each other
713 // in the array, so that it is easy to return multiple results
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000714 // from lookup().
715 unsigned FirstMatch;
716 for (FirstMatch = 0; FirstMatch != Size; ++FirstMatch)
717 if (Array[FirstMatch]->getDeclName() == D->getDeclName())
Douglas Gregore267ff32008-12-11 20:41:00 +0000718 break;
Douglas Gregor44b43212008-12-11 16:49:14 +0000719
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000720 unsigned InsertPos = FirstMatch;
721 if (FirstMatch != Size) {
722 // We found another declaration with the same name. First
723 // determine whether this is a redeclaration of an existing
724 // declaration in this scope, in which case we will replace the
725 // existing declaration.
726 unsigned LastMatch = FirstMatch;
727 for (; LastMatch != Size; ++LastMatch) {
728 if (Array[LastMatch]->getDeclName() != D->getDeclName())
729 break;
730
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000731 if (D->declarationReplaces(Array[LastMatch])) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000732 // D is a redeclaration of an existing element in the
733 // array. Replace that element with D.
734 Array[LastMatch] = D;
735 return;
736 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000737 }
738
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000739 // [FirstMatch, LastMatch) contains the set of declarations that
740 // have the same name as this declaration. Determine where the
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000741 // declaration D will be inserted into this range.
742 if (D->getKind() == Decl::UsingDirective ||
743 D->getIdentifierNamespace() == Decl::IDNS_Tag)
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000744 InsertPos = LastMatch;
745 else if (Array[LastMatch-1]->getIdentifierNamespace() == Decl::IDNS_Tag)
746 InsertPos = LastMatch - 1;
747 else
748 InsertPos = LastMatch;
Douglas Gregor44b43212008-12-11 16:49:14 +0000749 }
750
751 if (Size < LookupIsMap - 1) {
752 // The new declaration will fit in the array. Insert the new
753 // declaration at the position Match in the array.
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000754 for (unsigned Idx = Size; Idx > InsertPos; --Idx)
Douglas Gregor44b43212008-12-11 16:49:14 +0000755 Array[Idx] = Array[Idx-1];
756
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000757 Array[InsertPos] = D;
Douglas Gregor44b43212008-12-11 16:49:14 +0000758 LookupPtr.setInt(Size + 1);
759 return;
760 }
761
762 // We've reached capacity in this array. Create a map and copy in
763 // all of the declarations that were stored in the array.
764 StoredDeclsMap *Map = new StoredDeclsMap(16);
765 LookupPtr.setPointer(Map);
766 LookupPtr.setInt(LookupIsMap);
Douglas Gregore267ff32008-12-11 20:41:00 +0000767 for (unsigned Idx = 0; Idx != LookupIsMap - 1; ++Idx)
Douglas Gregor40f4e692009-01-20 16:54:50 +0000768 makeDeclVisibleInContextImpl(Array[Idx]);
Douglas Gregor44b43212008-12-11 16:49:14 +0000769 delete [] Array;
770
771 // Fall through to perform insertion into the map.
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000772 MayBeRedeclaration = false;
773 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000774
775 // Insert this declaration into the map.
Chris Lattner67762a32009-02-20 01:44:05 +0000776 StoredDeclsMap &Map = *static_cast<StoredDeclsMap*>(LookupPtr.getPointer());
777 StoredDeclsList &DeclNameEntries = Map[D->getDeclName()];
778 if (DeclNameEntries.isNull()) {
779 DeclNameEntries.setOnlyValue(D);
Chris Lattnerbd6c8002009-02-19 07:00:44 +0000780 return;
Douglas Gregor44b43212008-12-11 16:49:14 +0000781 }
Chris Lattner91942502009-02-20 00:55:03 +0000782
Chris Lattnerbdc3d002009-02-20 01:10:07 +0000783 // If it is possible that this is a redeclaration, check to see if there is
784 // already a decl for which declarationReplaces returns true. If there is
785 // one, just replace it and return.
Chris Lattner67762a32009-02-20 01:44:05 +0000786 if (MayBeRedeclaration && DeclNameEntries.HandleRedeclaration(D))
787 return;
Chris Lattner91942502009-02-20 00:55:03 +0000788
Chris Lattnerbd6c8002009-02-19 07:00:44 +0000789 // Put this declaration into the appropriate slot.
Chris Lattner67762a32009-02-20 01:44:05 +0000790 DeclNameEntries.AddSubsequentDecl(D);
Douglas Gregor44b43212008-12-11 16:49:14 +0000791}
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000792
793/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
794/// this context.
795DeclContext::udir_iterator_range DeclContext::getUsingDirectives() const {
796 lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
797 return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.first),
798 reinterpret_cast<udir_iterator>(Result.second));
799}
800