blob: ef9dc7622f1638002a863ba49330b0a0d631a85d [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
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000120void Decl::setDeclContext(DeclContext *DC) {
121 if (isOutOfSemaDC())
122 delete getMultipleDC();
123
Chris Lattner10d83792009-03-27 18:46:15 +0000124 DeclCtx.setPointer(DC);
125 DeclCtx.setInt(false);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000126}
127
128void Decl::setLexicalDeclContext(DeclContext *DC) {
129 if (DC == getLexicalDeclContext())
130 return;
131
132 if (isInSemaDC()) {
133 MultipleDC *MDC = new MultipleDC();
134 MDC->SemanticDC = getDeclContext();
135 MDC->LexicalDC = DC;
Chris Lattner10d83792009-03-27 18:46:15 +0000136 DeclCtx.setPointer(MDC);
137 DeclCtx.setInt(true);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000138 } else {
139 getMultipleDC()->LexicalDC = DC;
140 }
141}
142
Eli Friedman56d29372008-06-07 16:52:53 +0000143// Out-of-line virtual method providing a home for Decl.
144Decl::~Decl() {
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000145 if (isOutOfSemaDC())
146 delete getMultipleDC();
147
Chris Lattnercc581472009-03-04 06:05:19 +0000148 assert(!HasAttrs && "attributes should have been freed by Destroy");
Eli Friedman56d29372008-06-07 16:52:53 +0000149}
150
151void Decl::addAttr(Attr *NewAttr) {
152 if (!DeclAttrs)
153 DeclAttrs = new DeclAttrMapTy();
154
155 Attr *&ExistingAttr = (*DeclAttrs)[this];
156
157 NewAttr->setNext(ExistingAttr);
158 ExistingAttr = NewAttr;
159
160 HasAttrs = true;
161}
162
163void Decl::invalidateAttrs() {
164 if (!HasAttrs) return;
165
166 HasAttrs = false;
167 (*DeclAttrs)[this] = 0;
168 DeclAttrs->erase(this);
169
170 if (DeclAttrs->empty()) {
171 delete DeclAttrs;
172 DeclAttrs = 0;
173 }
174}
175
Chris Lattner81abbdd2009-03-21 06:27:31 +0000176const Attr *Decl::getAttrsImpl() const {
177 assert(HasAttrs && "getAttrs() should verify this!");
Eli Friedman56d29372008-06-07 16:52:53 +0000178 return (*DeclAttrs)[this];
179}
180
181void Decl::swapAttrs(Decl *RHS) {
182 bool HasLHSAttr = this->HasAttrs;
183 bool HasRHSAttr = RHS->HasAttrs;
184
185 // Usually, neither decl has attrs, nothing to do.
186 if (!HasLHSAttr && !HasRHSAttr) return;
187
188 // If 'this' has no attrs, swap the other way.
189 if (!HasLHSAttr)
190 return RHS->swapAttrs(this);
191
192 // Handle the case when both decls have attrs.
193 if (HasRHSAttr) {
194 std::swap((*DeclAttrs)[this], (*DeclAttrs)[RHS]);
195 return;
196 }
197
198 // Otherwise, LHS has an attr and RHS doesn't.
199 (*DeclAttrs)[RHS] = (*DeclAttrs)[this];
200 (*DeclAttrs).erase(this);
201 this->HasAttrs = false;
202 RHS->HasAttrs = true;
203}
204
205
Chris Lattnercc581472009-03-04 06:05:19 +0000206void Decl::Destroy(ASTContext &C) {
207 // Free attributes for this decl.
208 if (HasAttrs) {
209 DeclAttrMapTy::iterator it = DeclAttrs->find(this);
210 assert(it != DeclAttrs->end() && "No attrs found but HasAttrs is true!");
211
212 // release attributes.
213 it->second->Destroy(C);
214 invalidateAttrs();
215 HasAttrs = false;
216 }
217
Douglas Gregora0fc55f2009-01-13 19:47:12 +0000218#if 0
Douglas Gregor00ad0ef2009-01-20 04:25:11 +0000219 // FIXME: Once ownership is fully understood, we can enable this code
220 if (DeclContext *DC = dyn_cast<DeclContext>(this))
221 DC->decls_begin()->Destroy(C);
Eli Friedman56d29372008-06-07 16:52:53 +0000222
Douglas Gregor00ad0ef2009-01-20 04:25:11 +0000223 // Observe the unrolled recursion. By setting N->NextDeclInScope = 0x0
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000224 // within the loop, only the Destroy method for the first Decl
225 // will deallocate all of the Decls in a chain.
226
Douglas Gregor00ad0ef2009-01-20 04:25:11 +0000227 Decl* N = NextDeclInScope;
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000228
229 while (N) {
Douglas Gregor00ad0ef2009-01-20 04:25:11 +0000230 Decl* Tmp = N->NextDeclInScope;
231 N->NextDeclInScope = 0;
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000232 N->Destroy(C);
233 N = Tmp;
Eli Friedman56d29372008-06-07 16:52:53 +0000234 }
Douglas Gregora0fc55f2009-01-13 19:47:12 +0000235
Eli Friedman56d29372008-06-07 16:52:53 +0000236 this->~Decl();
Steve Naroff3e970492009-01-27 21:25:57 +0000237 C.Deallocate((void *)this);
Douglas Gregor00ad0ef2009-01-20 04:25:11 +0000238#endif
Eli Friedman56d29372008-06-07 16:52:53 +0000239}
240
Argyrios Kyrtzidis42220c52008-10-12 16:14:48 +0000241Decl *Decl::castFromDeclContext (const DeclContext *D) {
Argyrios Kyrtzidis3d7641e2009-02-16 14:29:28 +0000242 Decl::Kind DK = D->getDeclKind();
243 switch(DK) {
244#define DECL_CONTEXT(Name) \
245 case Decl::Name: \
246 return static_cast<Name##Decl*>(const_cast<DeclContext*>(D));
247#define DECL_CONTEXT_BASE(Name)
248#include "clang/AST/DeclNodes.def"
249 default:
250#define DECL_CONTEXT_BASE(Name) \
251 if (DK >= Decl::Name##First && DK <= Decl::Name##Last) \
252 return static_cast<Name##Decl*>(const_cast<DeclContext*>(D));
253#include "clang/AST/DeclNodes.def"
254 assert(false && "a decl that inherits DeclContext isn't handled");
255 return 0;
256 }
Argyrios Kyrtzidis42220c52008-10-12 16:14:48 +0000257}
258
259DeclContext *Decl::castToDeclContext(const Decl *D) {
Argyrios Kyrtzidis3d7641e2009-02-16 14:29:28 +0000260 Decl::Kind DK = D->getKind();
261 switch(DK) {
262#define DECL_CONTEXT(Name) \
263 case Decl::Name: \
264 return static_cast<Name##Decl*>(const_cast<Decl*>(D));
265#define DECL_CONTEXT_BASE(Name)
266#include "clang/AST/DeclNodes.def"
267 default:
268#define DECL_CONTEXT_BASE(Name) \
269 if (DK >= Decl::Name##First && DK <= Decl::Name##Last) \
270 return static_cast<Name##Decl*>(const_cast<Decl*>(D));
271#include "clang/AST/DeclNodes.def"
272 assert(false && "a decl that inherits DeclContext isn't handled");
273 return 0;
274 }
Argyrios Kyrtzidis42220c52008-10-12 16:14:48 +0000275}
276
Anders Carlsson1329c272009-03-25 23:38:06 +0000277#ifndef NDEBUG
278void Decl::CheckAccessDeclContext() const {
279 assert((Access != AS_none || !isa<CXXRecordDecl>(getDeclContext())) &&
280 "Access specifier is AS_none inside a record decl");
281}
282
283#endif
284
Eli Friedman56d29372008-06-07 16:52:53 +0000285//===----------------------------------------------------------------------===//
286// DeclContext Implementation
287//===----------------------------------------------------------------------===//
288
Argyrios Kyrtzidis3d7641e2009-02-16 14:29:28 +0000289bool DeclContext::classof(const Decl *D) {
290 switch (D->getKind()) {
291#define DECL_CONTEXT(Name) case Decl::Name:
292#define DECL_CONTEXT_BASE(Name)
293#include "clang/AST/DeclNodes.def"
294 return true;
295 default:
296#define DECL_CONTEXT_BASE(Name) \
297 if (D->getKind() >= Decl::Name##First && \
298 D->getKind() <= Decl::Name##Last) \
299 return true;
300#include "clang/AST/DeclNodes.def"
301 return false;
302 }
303}
304
Chris Lattner67762a32009-02-20 01:44:05 +0000305/// StoredDeclsList - This is an array of decls optimized a common case of only
306/// containing one entry.
307struct StoredDeclsList {
308 /// Data - If the integer is 0, then the pointer is a NamedDecl*. If the
309 /// integer is 1, then it is a VectorTy;
310 llvm::PointerIntPair<void*, 1, bool> Data;
311
312 /// VectorTy - When in vector form, this is what the Data pointer points to.
313 typedef llvm::SmallVector<NamedDecl*, 4> VectorTy;
314public:
315 StoredDeclsList() {}
316 StoredDeclsList(const StoredDeclsList &RHS) : Data(RHS.Data) {
317 if (isVector())
318 Data.setPointer(new VectorTy(getVector()));
319 }
320
321 ~StoredDeclsList() {
322 // If this is a vector-form, free the vector.
323 if (isVector())
324 delete &getVector();
325 }
326
Chris Lattner01011d42009-02-23 18:17:44 +0000327 StoredDeclsList &operator=(const StoredDeclsList &RHS) {
328 if (isVector())
329 delete &getVector();
330 Data = RHS.Data;
331 if (isVector())
332 Data.setPointer(new VectorTy(getVector()));
333 return *this;
334 }
335
Chris Lattner67762a32009-02-20 01:44:05 +0000336 bool isVector() const { return Data.getInt() != 0; }
337 bool isInline() const { return Data.getInt() == 0; }
338 bool isNull() const { return Data.getPointer() == 0; }
339
340 void setOnlyValue(NamedDecl *ND) {
341 assert(isInline() && "Not inline");
342 Data.setPointer(ND);
343 }
344
345 /// getLookupResult - Return an array of all the decls that this list
346 /// represents.
347 DeclContext::lookup_result getLookupResult() {
348 // If we have a single inline unit, return it.
349 if (isInline()) {
350 assert(!isNull() && "Empty list isn't allowed");
351
352 // Data is a raw pointer to a NamedDecl*, return it.
353 void *Ptr = &Data;
354 return DeclContext::lookup_result((NamedDecl**)Ptr, (NamedDecl**)Ptr+1);
355 }
356
357 // Otherwise, we have a range result.
358 VectorTy &V = getVector();
359 return DeclContext::lookup_result(&V[0], &V[0]+V.size());
360 }
361
362 /// HandleRedeclaration - If this is a redeclaration of an existing decl,
363 /// replace the old one with D and return true. Otherwise return false.
364 bool HandleRedeclaration(NamedDecl *D) {
365 // Most decls only have one entry in their list, special case it.
366 if (isInline()) {
367 if (!D->declarationReplaces(getInlineValue()))
368 return false;
369 setOnlyValue(D);
370 return true;
371 }
372
373 // Determine if this declaration is actually a redeclaration.
374 VectorTy &Vec = getVector();
375 VectorTy::iterator RDI
376 = std::find_if(Vec.begin(), Vec.end(),
377 std::bind1st(std::mem_fun(&NamedDecl::declarationReplaces),
378 D));
379 if (RDI == Vec.end())
380 return false;
381 *RDI = D;
382 return true;
383 }
384
385 /// AddSubsequentDecl - This is called on the second and later decl when it is
386 /// not a redeclaration to merge it into the appropriate place in our list.
387 ///
388 void AddSubsequentDecl(NamedDecl *D) {
389 // If this is the second decl added to the list, convert this to vector
390 // form.
391 if (isInline()) {
392 NamedDecl *OldD = getInlineValue();
393 Data.setInt(1);
394 VectorTy *VT = new VectorTy();
395 VT->push_back(OldD);
396 Data.setPointer(VT);
397 }
398
399 VectorTy &Vec = getVector();
400 if (isa<UsingDirectiveDecl>(D) ||
401 D->getIdentifierNamespace() == Decl::IDNS_Tag)
402 Vec.push_back(D);
403 else if (Vec.back()->getIdentifierNamespace() == Decl::IDNS_Tag) {
404 NamedDecl *TagD = Vec.back();
405 Vec.back() = D;
406 Vec.push_back(TagD);
407 } else
408 Vec.push_back(D);
409 }
410
411
412private:
413 VectorTy &getVector() const {
414 assert(isVector() && "Not in vector form");
415 return *static_cast<VectorTy*>(Data.getPointer());
416 }
417
418 NamedDecl *getInlineValue() const {
419 assert(isInline() && "Not in inline form");
420 return (NamedDecl*)Data.getPointer();
421 }
422};
423
424
425
426typedef llvm::DenseMap<DeclarationName, StoredDeclsList> StoredDeclsMap;
Douglas Gregor44b43212008-12-11 16:49:14 +0000427
428DeclContext::~DeclContext() {
429 unsigned Size = LookupPtr.getInt();
Chris Lattner91942502009-02-20 00:55:03 +0000430 if (Size == LookupIsMap)
431 delete static_cast<StoredDeclsMap*>(LookupPtr.getPointer());
432 else
433 delete [] static_cast<NamedDecl**>(LookupPtr.getPointer());
Douglas Gregor44b43212008-12-11 16:49:14 +0000434}
435
436void DeclContext::DestroyDecls(ASTContext &C) {
Douglas Gregor00ad0ef2009-01-20 04:25:11 +0000437 for (decl_iterator D = decls_begin(); D != decls_end(); )
438 (*D++)->Destroy(C);
Douglas Gregor44b43212008-12-11 16:49:14 +0000439}
440
Douglas Gregor074149e2009-01-05 19:45:36 +0000441bool DeclContext::isTransparentContext() const {
442 if (DeclKind == Decl::Enum)
443 return true; // FIXME: Check for C++0x scoped enums
444 else if (DeclKind == Decl::LinkageSpec)
445 return true;
Douglas Gregor65100792009-02-26 00:02:51 +0000446 else if (DeclKind >= Decl::RecordFirst && DeclKind <= Decl::RecordLast)
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000447 return cast<RecordDecl>(this)->isAnonymousStructOrUnion();
Douglas Gregor074149e2009-01-05 19:45:36 +0000448 else if (DeclKind == Decl::Namespace)
449 return false; // FIXME: Check for C++0x inline namespaces
450
451 return false;
452}
453
Steve Naroff0701bbb2009-01-08 17:28:14 +0000454DeclContext *DeclContext::getPrimaryContext() {
Douglas Gregor44b43212008-12-11 16:49:14 +0000455 switch (DeclKind) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000456 case Decl::TranslationUnit:
Douglas Gregor074149e2009-01-05 19:45:36 +0000457 case Decl::LinkageSpec:
458 case Decl::Block:
Douglas Gregor44b43212008-12-11 16:49:14 +0000459 // There is only one DeclContext for these entities.
460 return this;
461
462 case Decl::Namespace:
463 // The original namespace is our primary context.
464 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
465
Douglas Gregor44b43212008-12-11 16:49:14 +0000466 case Decl::ObjCMethod:
467 return this;
468
469 case Decl::ObjCInterface:
Steve Naroff0701bbb2009-01-08 17:28:14 +0000470 case Decl::ObjCProtocol:
471 case Decl::ObjCCategory:
Douglas Gregor44b43212008-12-11 16:49:14 +0000472 // FIXME: Can Objective-C interfaces be forward-declared?
473 return this;
474
Steve Naroff0701bbb2009-01-08 17:28:14 +0000475 case Decl::ObjCImplementation:
476 case Decl::ObjCCategoryImpl:
477 return this;
478
Douglas Gregor44b43212008-12-11 16:49:14 +0000479 default:
Douglas Gregorcc636682009-02-17 23:15:12 +0000480 if (DeclKind >= Decl::TagFirst && DeclKind <= Decl::TagLast) {
481 // If this is a tag type that has a definition or is currently
482 // being defined, that definition is our primary context.
Douglas Gregorfc705b82009-02-26 22:19:44 +0000483 if (const TagType *TagT = cast<TagDecl>(this)->TypeForDecl->getAsTagType())
Douglas Gregorcc636682009-02-17 23:15:12 +0000484 if (TagT->isBeingDefined() ||
485 (TagT->getDecl() && TagT->getDecl()->isDefinition()))
486 return TagT->getDecl();
487 return this;
488 }
489
Douglas Gregor44b43212008-12-11 16:49:14 +0000490 assert(DeclKind >= Decl::FunctionFirst && DeclKind <= Decl::FunctionLast &&
491 "Unknown DeclContext kind");
492 return this;
493 }
494}
495
496DeclContext *DeclContext::getNextContext() {
497 switch (DeclKind) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000498 case Decl::Namespace:
499 // Return the next namespace
500 return static_cast<NamespaceDecl*>(this)->getNextNamespace();
501
502 default:
Douglas Gregor44b43212008-12-11 16:49:14 +0000503 return 0;
504 }
505}
506
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000507void DeclContext::addDecl(Decl *D) {
Chris Lattner7f0be132009-02-20 00:56:18 +0000508 assert(D->getLexicalDeclContext() == this &&
509 "Decl inserted into wrong lexical context");
Douglas Gregor6037fcb2009-01-09 19:42:16 +0000510 assert(!D->NextDeclInScope && D != LastDecl &&
511 "Decl already inserted into a DeclContext");
512
513 if (FirstDecl) {
514 LastDecl->NextDeclInScope = D;
515 LastDecl = D;
516 } else {
517 FirstDecl = LastDecl = D;
518 }
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000519
520 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Douglas Gregor40f4e692009-01-20 16:54:50 +0000521 ND->getDeclContext()->makeDeclVisibleInContext(ND);
Douglas Gregor44b43212008-12-11 16:49:14 +0000522}
523
Douglas Gregor074149e2009-01-05 19:45:36 +0000524/// buildLookup - Build the lookup data structure with all of the
525/// declarations in DCtx (and any other contexts linked to it or
526/// transparent contexts nested within it).
Steve Naroff0701bbb2009-01-08 17:28:14 +0000527void DeclContext::buildLookup(DeclContext *DCtx) {
Douglas Gregor074149e2009-01-05 19:45:36 +0000528 for (; DCtx; DCtx = DCtx->getNextContext()) {
Douglas Gregor4f3b8f82009-01-06 07:17:58 +0000529 for (decl_iterator D = DCtx->decls_begin(), DEnd = DCtx->decls_end();
530 D != DEnd; ++D) {
Douglas Gregor074149e2009-01-05 19:45:36 +0000531 // Insert this declaration into the lookup structure
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000532 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor40f4e692009-01-20 16:54:50 +0000533 makeDeclVisibleInContextImpl(ND);
Douglas Gregor074149e2009-01-05 19:45:36 +0000534
535 // If this declaration is itself a transparent declaration context,
536 // add its members (recursively).
537 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D))
538 if (InnerCtx->isTransparentContext())
Steve Naroff0701bbb2009-01-08 17:28:14 +0000539 buildLookup(InnerCtx->getPrimaryContext());
Douglas Gregor074149e2009-01-05 19:45:36 +0000540 }
541 }
542}
543
Douglas Gregor44b43212008-12-11 16:49:14 +0000544DeclContext::lookup_result
Steve Naroff0701bbb2009-01-08 17:28:14 +0000545DeclContext::lookup(DeclarationName Name) {
546 DeclContext *PrimaryContext = getPrimaryContext();
Douglas Gregor44b43212008-12-11 16:49:14 +0000547 if (PrimaryContext != this)
Steve Naroff0701bbb2009-01-08 17:28:14 +0000548 return PrimaryContext->lookup(Name);
Douglas Gregor44b43212008-12-11 16:49:14 +0000549
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000550 /// If there is no lookup data structure, build one now by walking
Douglas Gregor44b43212008-12-11 16:49:14 +0000551 /// all of the linked DeclContexts (in declaration order!) and
552 /// inserting their values.
Douglas Gregor074149e2009-01-05 19:45:36 +0000553 if (LookupPtr.getPointer() == 0)
Steve Naroff0701bbb2009-01-08 17:28:14 +0000554 buildLookup(this);
Douglas Gregor44b43212008-12-11 16:49:14 +0000555
Douglas Gregor44b43212008-12-11 16:49:14 +0000556 if (isLookupMap()) {
557 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(LookupPtr.getPointer());
558 StoredDeclsMap::iterator Pos = Map->find(Name);
Chris Lattner91942502009-02-20 00:55:03 +0000559 if (Pos == Map->end())
560 return lookup_result(0, 0);
Chris Lattner67762a32009-02-20 01:44:05 +0000561 return Pos->second.getLookupResult();
Douglas Gregor44b43212008-12-11 16:49:14 +0000562 }
563
564 // We have a small array. Look into it.
565 unsigned Size = LookupPtr.getInt();
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000566 NamedDecl **Array = static_cast<NamedDecl**>(LookupPtr.getPointer());
Douglas Gregore267ff32008-12-11 20:41:00 +0000567 for (unsigned Idx = 0; Idx != Size; ++Idx)
Douglas Gregor44b43212008-12-11 16:49:14 +0000568 if (Array[Idx]->getDeclName() == Name) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000569 unsigned Last = Idx + 1;
570 while (Last != Size && Array[Last]->getDeclName() == Name)
571 ++Last;
572 return lookup_result(&Array[Idx], &Array[Last]);
Douglas Gregor44b43212008-12-11 16:49:14 +0000573 }
574
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000575 return lookup_result(0, 0);
Douglas Gregor44b43212008-12-11 16:49:14 +0000576}
577
578DeclContext::lookup_const_result
Steve Naroff0701bbb2009-01-08 17:28:14 +0000579DeclContext::lookup(DeclarationName Name) const {
580 return const_cast<DeclContext*>(this)->lookup(Name);
Douglas Gregor44b43212008-12-11 16:49:14 +0000581}
582
Chris Lattner0cf2b192009-03-27 19:19:59 +0000583DeclContext *DeclContext::getLookupContext() {
584 DeclContext *Ctx = this;
Douglas Gregor72de6672009-01-08 20:45:30 +0000585 // Skip through transparent contexts.
Douglas Gregorce356072009-01-06 23:51:29 +0000586 while (Ctx->isTransparentContext())
587 Ctx = Ctx->getParent();
588 return Ctx;
589}
590
Douglas Gregor88b70942009-02-25 22:02:03 +0000591DeclContext *DeclContext::getEnclosingNamespaceContext() {
592 DeclContext *Ctx = this;
593 // Skip through non-namespace, non-translation-unit contexts.
594 while (!Ctx->isFileContext() || Ctx->isTransparentContext())
595 Ctx = Ctx->getParent();
596 return Ctx->getPrimaryContext();
597}
598
Douglas Gregor40f4e692009-01-20 16:54:50 +0000599void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
Douglas Gregorcc636682009-02-17 23:15:12 +0000600 // FIXME: This feels like a hack. Should DeclarationName support
601 // template-ids, or is there a better way to keep specializations
602 // from being visible?
603 if (isa<ClassTemplateSpecializationDecl>(D))
604 return;
605
Steve Naroff0701bbb2009-01-08 17:28:14 +0000606 DeclContext *PrimaryContext = getPrimaryContext();
Douglas Gregor44b43212008-12-11 16:49:14 +0000607 if (PrimaryContext != this) {
Douglas Gregor40f4e692009-01-20 16:54:50 +0000608 PrimaryContext->makeDeclVisibleInContext(D);
Douglas Gregor44b43212008-12-11 16:49:14 +0000609 return;
610 }
611
612 // If we already have a lookup data structure, perform the insertion
613 // into it. Otherwise, be lazy and don't build that structure until
614 // someone asks for it.
615 if (LookupPtr.getPointer())
Douglas Gregor40f4e692009-01-20 16:54:50 +0000616 makeDeclVisibleInContextImpl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +0000617
Douglas Gregor074149e2009-01-05 19:45:36 +0000618 // If we are a transparent context, insert into our parent context,
619 // too. This operation is recursive.
620 if (isTransparentContext())
Douglas Gregor40f4e692009-01-20 16:54:50 +0000621 getParent()->makeDeclVisibleInContext(D);
Douglas Gregor44b43212008-12-11 16:49:14 +0000622}
623
Douglas Gregor40f4e692009-01-20 16:54:50 +0000624void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D) {
Douglas Gregor074149e2009-01-05 19:45:36 +0000625 // Skip unnamed declarations.
626 if (!D->getDeclName())
627 return;
628
Douglas Gregorcc636682009-02-17 23:15:12 +0000629 // FIXME: This feels like a hack. Should DeclarationName support
630 // template-ids, or is there a better way to keep specializations
631 // from being visible?
632 if (isa<ClassTemplateSpecializationDecl>(D))
633 return;
634
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000635 bool MayBeRedeclaration = true;
636
Douglas Gregor44b43212008-12-11 16:49:14 +0000637 if (!isLookupMap()) {
638 unsigned Size = LookupPtr.getInt();
639
640 // The lookup data is stored as an array. Search through the array
641 // to find the insertion location.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000642 NamedDecl **Array;
Douglas Gregor44b43212008-12-11 16:49:14 +0000643 if (Size == 0) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000644 Array = new NamedDecl*[LookupIsMap - 1];
Douglas Gregor44b43212008-12-11 16:49:14 +0000645 LookupPtr.setPointer(Array);
646 } else {
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000647 Array = static_cast<NamedDecl **>(LookupPtr.getPointer());
Douglas Gregor44b43212008-12-11 16:49:14 +0000648 }
649
650 // We always keep declarations of the same name next to each other
651 // in the array, so that it is easy to return multiple results
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000652 // from lookup().
653 unsigned FirstMatch;
654 for (FirstMatch = 0; FirstMatch != Size; ++FirstMatch)
655 if (Array[FirstMatch]->getDeclName() == D->getDeclName())
Douglas Gregore267ff32008-12-11 20:41:00 +0000656 break;
Douglas Gregor44b43212008-12-11 16:49:14 +0000657
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000658 unsigned InsertPos = FirstMatch;
659 if (FirstMatch != Size) {
660 // We found another declaration with the same name. First
661 // determine whether this is a redeclaration of an existing
662 // declaration in this scope, in which case we will replace the
663 // existing declaration.
664 unsigned LastMatch = FirstMatch;
665 for (; LastMatch != Size; ++LastMatch) {
666 if (Array[LastMatch]->getDeclName() != D->getDeclName())
667 break;
668
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000669 if (D->declarationReplaces(Array[LastMatch])) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000670 // D is a redeclaration of an existing element in the
671 // array. Replace that element with D.
672 Array[LastMatch] = D;
673 return;
674 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000675 }
676
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000677 // [FirstMatch, LastMatch) contains the set of declarations that
678 // have the same name as this declaration. Determine where the
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000679 // declaration D will be inserted into this range.
680 if (D->getKind() == Decl::UsingDirective ||
681 D->getIdentifierNamespace() == Decl::IDNS_Tag)
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000682 InsertPos = LastMatch;
683 else if (Array[LastMatch-1]->getIdentifierNamespace() == Decl::IDNS_Tag)
684 InsertPos = LastMatch - 1;
685 else
686 InsertPos = LastMatch;
Douglas Gregor44b43212008-12-11 16:49:14 +0000687 }
688
689 if (Size < LookupIsMap - 1) {
690 // The new declaration will fit in the array. Insert the new
691 // declaration at the position Match in the array.
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000692 for (unsigned Idx = Size; Idx > InsertPos; --Idx)
Douglas Gregor44b43212008-12-11 16:49:14 +0000693 Array[Idx] = Array[Idx-1];
694
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000695 Array[InsertPos] = D;
Douglas Gregor44b43212008-12-11 16:49:14 +0000696 LookupPtr.setInt(Size + 1);
697 return;
698 }
699
700 // We've reached capacity in this array. Create a map and copy in
701 // all of the declarations that were stored in the array.
702 StoredDeclsMap *Map = new StoredDeclsMap(16);
703 LookupPtr.setPointer(Map);
704 LookupPtr.setInt(LookupIsMap);
Douglas Gregore267ff32008-12-11 20:41:00 +0000705 for (unsigned Idx = 0; Idx != LookupIsMap - 1; ++Idx)
Douglas Gregor40f4e692009-01-20 16:54:50 +0000706 makeDeclVisibleInContextImpl(Array[Idx]);
Douglas Gregor44b43212008-12-11 16:49:14 +0000707 delete [] Array;
708
709 // Fall through to perform insertion into the map.
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000710 MayBeRedeclaration = false;
711 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000712
713 // Insert this declaration into the map.
Chris Lattner67762a32009-02-20 01:44:05 +0000714 StoredDeclsMap &Map = *static_cast<StoredDeclsMap*>(LookupPtr.getPointer());
715 StoredDeclsList &DeclNameEntries = Map[D->getDeclName()];
716 if (DeclNameEntries.isNull()) {
717 DeclNameEntries.setOnlyValue(D);
Chris Lattnerbd6c8002009-02-19 07:00:44 +0000718 return;
Douglas Gregor44b43212008-12-11 16:49:14 +0000719 }
Chris Lattner91942502009-02-20 00:55:03 +0000720
Chris Lattnerbdc3d002009-02-20 01:10:07 +0000721 // If it is possible that this is a redeclaration, check to see if there is
722 // already a decl for which declarationReplaces returns true. If there is
723 // one, just replace it and return.
Chris Lattner67762a32009-02-20 01:44:05 +0000724 if (MayBeRedeclaration && DeclNameEntries.HandleRedeclaration(D))
725 return;
Chris Lattner91942502009-02-20 00:55:03 +0000726
Chris Lattnerbd6c8002009-02-19 07:00:44 +0000727 // Put this declaration into the appropriate slot.
Chris Lattner67762a32009-02-20 01:44:05 +0000728 DeclNameEntries.AddSubsequentDecl(D);
Douglas Gregor44b43212008-12-11 16:49:14 +0000729}
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000730
731/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
732/// this context.
733DeclContext::udir_iterator_range DeclContext::getUsingDirectives() const {
734 lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
735 return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.first),
736 reinterpret_cast<udir_iterator>(Result.second));
737}
738