blob: be1992a4d545e6bebb4e78ad3addb1c6fee99b77 [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"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Douglas Gregor64650af2009-02-02 23:39:07 +000018#include "clang/AST/Decl.h"
Argyrios Kyrtzidisd3bb44f2008-06-09 21:05:31 +000019#include "clang/AST/DeclCXX.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/AST/DeclContextInternals.h"
John McCall92b7f702010-03-11 07:50:04 +000021#include "clang/AST/DeclFriend.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000022#include "clang/AST/DeclObjC.h"
Alexey Bataevc6400582013-03-22 06:34:35 +000023#include "clang/AST/DeclOpenMP.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000024#include "clang/AST/DeclTemplate.h"
John McCall0c01d182010-03-24 05:22:00 +000025#include "clang/AST/DependentDiagnostic.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000026#include "clang/AST/ExternalASTSource.h"
Sebastian Redld3a413d2009-04-26 20:35:05 +000027#include "clang/AST/Stmt.h"
28#include "clang/AST/StmtCXX.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000029#include "clang/AST/Type.h"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000030#include "clang/Basic/TargetInfo.h"
Eli Friedman56d29372008-06-07 16:52:53 +000031#include "llvm/ADT/DenseMap.h"
Chris Lattner49f28ca2009-03-05 08:00:35 +000032#include "llvm/Support/raw_ostream.h"
Douglas Gregor6ed40e32008-12-23 21:05:05 +000033#include <algorithm>
Eli Friedman56d29372008-06-07 16:52:53 +000034using namespace clang;
35
36//===----------------------------------------------------------------------===//
37// Statistics
38//===----------------------------------------------------------------------===//
39
Sean Hunt9a555912010-05-30 07:21:58 +000040#define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
41#define ABSTRACT_DECL(DECL)
42#include "clang/AST/DeclNodes.inc"
Eli Friedman56d29372008-06-07 16:52:53 +000043
Douglas Gregor6bd99292013-02-09 01:35:03 +000044void Decl::updateOutOfDate(IdentifierInfo &II) const {
45 getASTContext().getExternalSource()->updateOutOfDateIdentifier(II);
46}
47
Douglas Gregor1e68ecc2012-01-05 21:55:30 +000048void *Decl::AllocateDeserializedDecl(const ASTContext &Context,
49 unsigned ID,
50 unsigned Size) {
Douglas Gregor5d1f4962012-01-05 23:49:36 +000051 // Allocate an extra 8 bytes worth of storage, which ensures that the
Douglas Gregorc6c8e0e2012-01-09 17:30:44 +000052 // resulting pointer will still be 8-byte aligned.
Douglas Gregor5d1f4962012-01-05 23:49:36 +000053 void *Start = Context.Allocate(Size + 8);
54 void *Result = (char*)Start + 8;
Douglas Gregorb6b60c12012-01-05 22:27:05 +000055
Douglas Gregorc6c8e0e2012-01-09 17:30:44 +000056 unsigned *PrefixPtr = (unsigned *)Result - 2;
57
58 // Zero out the first 4 bytes; this is used to store the owning module ID.
59 PrefixPtr[0] = 0;
60
61 // Store the global declaration ID in the second 4 bytes.
62 PrefixPtr[1] = ID;
Douglas Gregorb6b60c12012-01-05 22:27:05 +000063
64 return Result;
Douglas Gregor1e68ecc2012-01-05 21:55:30 +000065}
66
Douglas Gregorca2ab452013-01-12 01:29:50 +000067Module *Decl::getOwningModuleSlow() const {
68 assert(isFromASTFile() && "Not from AST file?");
69 return getASTContext().getExternalSource()->getModule(getOwningModuleID());
70}
71
Eli Friedman56d29372008-06-07 16:52:53 +000072const char *Decl::getDeclKindName() const {
73 switch (DeclKind) {
David Blaikieb219cfc2011-09-23 05:06:16 +000074 default: llvm_unreachable("Declaration not in DeclNodes.inc!");
Sean Hunt9a555912010-05-30 07:21:58 +000075#define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
76#define ABSTRACT_DECL(DECL)
77#include "clang/AST/DeclNodes.inc"
Eli Friedman56d29372008-06-07 16:52:53 +000078 }
79}
80
Douglas Gregor42738572010-03-05 00:26:45 +000081void Decl::setInvalidDecl(bool Invalid) {
82 InvalidDecl = Invalid;
Argyrios Kyrtzidisba50b3e2012-03-09 21:09:04 +000083 if (Invalid && !isa<ParmVarDecl>(this)) {
Douglas Gregor42738572010-03-05 00:26:45 +000084 // Defensive maneuver for ill-formed code: we're likely not to make it to
85 // a point where we set the access specifier, so default it to "public"
86 // to avoid triggering asserts elsewhere in the front end.
87 setAccess(AS_public);
88 }
89}
90
Steve Naroff0a473932009-01-20 19:53:53 +000091const char *DeclContext::getDeclKindName() const {
92 switch (DeclKind) {
David Blaikieb219cfc2011-09-23 05:06:16 +000093 default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
Sean Hunt9a555912010-05-30 07:21:58 +000094#define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
95#define ABSTRACT_DECL(DECL)
96#include "clang/AST/DeclNodes.inc"
Steve Naroff0a473932009-01-20 19:53:53 +000097 }
98}
99
Daniel Dunbar02892a62012-03-05 21:42:49 +0000100bool Decl::StatisticsEnabled = false;
101void Decl::EnableStatistics() {
102 StatisticsEnabled = true;
Eli Friedman56d29372008-06-07 16:52:53 +0000103}
104
105void Decl::PrintStats() {
Chandler Carruthb43c8ec2011-07-04 06:13:27 +0000106 llvm::errs() << "\n*** Decl Stats:\n";
Mike Stump1eb44332009-09-09 15:08:12 +0000107
Douglas Gregor64650af2009-02-02 23:39:07 +0000108 int totalDecls = 0;
Sean Hunt9a555912010-05-30 07:21:58 +0000109#define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
110#define ABSTRACT_DECL(DECL)
111#include "clang/AST/DeclNodes.inc"
Chandler Carruthb43c8ec2011-07-04 06:13:27 +0000112 llvm::errs() << " " << totalDecls << " decls total.\n";
Mike Stump1eb44332009-09-09 15:08:12 +0000113
Douglas Gregor64650af2009-02-02 23:39:07 +0000114 int totalBytes = 0;
Sean Hunt9a555912010-05-30 07:21:58 +0000115#define DECL(DERIVED, BASE) \
116 if (n##DERIVED##s > 0) { \
117 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
Chandler Carruthb43c8ec2011-07-04 06:13:27 +0000118 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
119 << sizeof(DERIVED##Decl) << " each (" \
120 << n##DERIVED##s * sizeof(DERIVED##Decl) \
121 << " bytes)\n"; \
Douglas Gregor64650af2009-02-02 23:39:07 +0000122 }
Sean Hunt9a555912010-05-30 07:21:58 +0000123#define ABSTRACT_DECL(DECL)
124#include "clang/AST/DeclNodes.inc"
Mike Stump1eb44332009-09-09 15:08:12 +0000125
Chandler Carruthb43c8ec2011-07-04 06:13:27 +0000126 llvm::errs() << "Total bytes = " << totalBytes << "\n";
Eli Friedman56d29372008-06-07 16:52:53 +0000127}
128
Sean Hunt9a555912010-05-30 07:21:58 +0000129void Decl::add(Kind k) {
Eli Friedman56d29372008-06-07 16:52:53 +0000130 switch (k) {
Sean Hunt9a555912010-05-30 07:21:58 +0000131#define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
132#define ABSTRACT_DECL(DECL)
133#include "clang/AST/DeclNodes.inc"
Eli Friedman56d29372008-06-07 16:52:53 +0000134 }
135}
136
Anders Carlsson67e33202009-06-13 00:08:58 +0000137bool Decl::isTemplateParameterPack() const {
138 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
139 return TTP->isParameterPack();
Douglas Gregor10738d32010-12-23 23:51:58 +0000140 if (const NonTypeTemplateParmDecl *NTTP
Douglas Gregor61c4d282011-01-05 15:48:55 +0000141 = dyn_cast<NonTypeTemplateParmDecl>(this))
Douglas Gregor10738d32010-12-23 23:51:58 +0000142 return NTTP->isParameterPack();
Douglas Gregor61c4d282011-01-05 15:48:55 +0000143 if (const TemplateTemplateParmDecl *TTP
144 = dyn_cast<TemplateTemplateParmDecl>(this))
145 return TTP->isParameterPack();
Anders Carlsson67e33202009-06-13 00:08:58 +0000146 return false;
147}
148
Douglas Gregor1fe85ea2011-01-05 21:11:38 +0000149bool Decl::isParameterPack() const {
150 if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
151 return Parm->isParameterPack();
152
153 return isTemplateParameterPack();
154}
155
Douglas Gregore53060f2009-06-25 22:08:12 +0000156bool Decl::isFunctionOrFunctionTemplate() const {
John McCall9488ea12009-11-17 05:59:44 +0000157 if (const UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(this))
Anders Carlsson58badb72009-06-26 05:26:50 +0000158 return UD->getTargetDecl()->isFunctionOrFunctionTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +0000159
Douglas Gregore53060f2009-06-25 22:08:12 +0000160 return isa<FunctionDecl>(this) || isa<FunctionTemplateDecl>(this);
161}
162
Caitlin Sadowskied9d84a2011-09-08 17:42:31 +0000163bool Decl::isTemplateDecl() const {
164 return isa<TemplateDecl>(this);
165}
166
Argyrios Kyrtzidisc8680f42011-09-28 02:45:33 +0000167const DeclContext *Decl::getParentFunctionOrMethod() const {
168 for (const DeclContext *DC = getDeclContext();
169 DC && !DC->isTranslationUnit() && !DC->isNamespace();
Douglas Gregor79c22782010-01-16 20:21:20 +0000170 DC = DC->getParent())
171 if (DC->isFunctionOrMethod())
Argyrios Kyrtzidisc8680f42011-09-28 02:45:33 +0000172 return DC;
Douglas Gregor79c22782010-01-16 20:21:20 +0000173
Argyrios Kyrtzidisc8680f42011-09-28 02:45:33 +0000174 return 0;
Douglas Gregor79c22782010-01-16 20:21:20 +0000175}
176
Douglas Gregor4c3e0ee2011-02-17 08:47:29 +0000177
Eli Friedman56d29372008-06-07 16:52:53 +0000178//===----------------------------------------------------------------------===//
Chris Lattner49f28ca2009-03-05 08:00:35 +0000179// PrettyStackTraceDecl Implementation
180//===----------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Chris Lattner5f9e2722011-07-23 10:55:15 +0000182void PrettyStackTraceDecl::print(raw_ostream &OS) const {
Chris Lattner49f28ca2009-03-05 08:00:35 +0000183 SourceLocation TheLoc = Loc;
184 if (TheLoc.isInvalid() && TheDecl)
185 TheLoc = TheDecl->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000186
Chris Lattner49f28ca2009-03-05 08:00:35 +0000187 if (TheLoc.isValid()) {
188 TheLoc.print(OS, SM);
189 OS << ": ";
190 }
191
192 OS << Message;
193
Benjamin Kramerb063ef02013-02-23 13:53:57 +0000194 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
195 OS << " '";
196 DN->printQualifiedName(OS);
197 OS << '\'';
198 }
Chris Lattner49f28ca2009-03-05 08:00:35 +0000199 OS << '\n';
200}
Mike Stump1eb44332009-09-09 15:08:12 +0000201
Chris Lattner49f28ca2009-03-05 08:00:35 +0000202//===----------------------------------------------------------------------===//
Eli Friedman56d29372008-06-07 16:52:53 +0000203// Decl Implementation
204//===----------------------------------------------------------------------===//
205
Douglas Gregorda2142f2011-02-19 18:51:44 +0000206// Out-of-line virtual method providing a home for Decl.
207Decl::~Decl() { }
Douglas Gregorf4a03cc2011-02-17 07:02:32 +0000208
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000209void Decl::setDeclContext(DeclContext *DC) {
Chris Lattneree219fd2009-03-29 06:06:59 +0000210 DeclCtx = DC;
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000211}
212
213void Decl::setLexicalDeclContext(DeclContext *DC) {
214 if (DC == getLexicalDeclContext())
215 return;
216
217 if (isInSemaDC()) {
Argyrios Kyrtzidis4bbb8502012-02-09 02:44:08 +0000218 setDeclContextsImpl(getDeclContext(), DC, getASTContext());
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000219 } else {
220 getMultipleDC()->LexicalDC = DC;
221 }
222}
223
Argyrios Kyrtzidis4bbb8502012-02-09 02:44:08 +0000224void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
225 ASTContext &Ctx) {
226 if (SemaDC == LexicalDC) {
227 DeclCtx = SemaDC;
228 } else {
229 Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
230 MDC->SemanticDC = SemaDC;
231 MDC->LexicalDC = LexicalDC;
232 DeclCtx = MDC;
233 }
234}
235
John McCall9aeed322009-10-01 00:25:31 +0000236bool Decl::isInAnonymousNamespace() const {
237 const DeclContext *DC = getDeclContext();
238 do {
239 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
240 if (ND->isAnonymousNamespace())
241 return true;
242 } while ((DC = DC->getParent()));
243
244 return false;
245}
246
Argyrios Kyrtzidis3708b3d2009-06-29 17:38:40 +0000247TranslationUnitDecl *Decl::getTranslationUnitDecl() {
Argyrios Kyrtzidis9b346692009-06-30 02:34:53 +0000248 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
249 return TUD;
250
Argyrios Kyrtzidis3708b3d2009-06-29 17:38:40 +0000251 DeclContext *DC = getDeclContext();
252 assert(DC && "This decl is not contained in a translation unit!");
Mike Stump1eb44332009-09-09 15:08:12 +0000253
Argyrios Kyrtzidis3708b3d2009-06-29 17:38:40 +0000254 while (!DC->isTranslationUnit()) {
255 DC = DC->getParent();
256 assert(DC && "This decl is not contained in a translation unit!");
257 }
Mike Stump1eb44332009-09-09 15:08:12 +0000258
Argyrios Kyrtzidis3708b3d2009-06-29 17:38:40 +0000259 return cast<TranslationUnitDecl>(DC);
260}
261
262ASTContext &Decl::getASTContext() const {
Mike Stump1eb44332009-09-09 15:08:12 +0000263 return getTranslationUnitDecl()->getASTContext();
Argyrios Kyrtzidis3708b3d2009-06-29 17:38:40 +0000264}
265
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +0000266ASTMutationListener *Decl::getASTMutationListener() const {
267 return getASTContext().getASTMutationListener();
268}
269
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +0000270unsigned Decl::getMaxAlignment() const {
271 if (!hasAttrs())
272 return 0;
273
274 unsigned Align = 0;
275 const AttrVec &V = getAttrs();
276 ASTContext &Ctx = getASTContext();
277 specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
278 for (; I != E; ++I)
279 Align = std::max(Align, I->getAlignment(Ctx));
280 return Align;
281}
282
Douglas Gregorc070cc62010-06-17 23:14:26 +0000283bool Decl::isUsed(bool CheckUsedAttr) const {
Tanya Lattner12ead492010-02-17 02:17:21 +0000284 if (Used)
285 return true;
286
287 // Check for used attribute.
Douglas Gregorc070cc62010-06-17 23:14:26 +0000288 if (CheckUsedAttr && hasAttr<UsedAttr>())
Tanya Lattner12ead492010-02-17 02:17:21 +0000289 return true;
Rafael Espindola919b7e62012-11-23 16:26:30 +0000290
Tanya Lattner12ead492010-02-17 02:17:21 +0000291 return false;
292}
293
Eli Friedman86164e82013-09-05 00:02:25 +0000294void Decl::markUsed(ASTContext &C) {
295 if (Used)
296 return;
297
298 if (C.getASTMutationListener())
299 C.getASTMutationListener()->DeclarationMarkedUsed(this);
300
301 Used = true;
302}
303
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +0000304bool Decl::isReferenced() const {
305 if (Referenced)
306 return true;
307
308 // Check redeclarations.
309 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
310 if (I->Referenced)
311 return true;
312
313 return false;
314}
315
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000316/// \brief Determine the availability of the given declaration based on
317/// the target platform.
318///
319/// When it returns an availability result other than \c AR_Available,
320/// if the \p Message parameter is non-NULL, it will be set to a
321/// string describing why the entity is unavailable.
322///
323/// FIXME: Make these strings localizable, since they end up in
324/// diagnostics.
325static AvailabilityResult CheckAvailability(ASTContext &Context,
326 const AvailabilityAttr *A,
327 std::string *Message) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000328 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000329 StringRef PrettyPlatformName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000330 = AvailabilityAttr::getPrettyPlatformName(TargetPlatform);
331 if (PrettyPlatformName.empty())
332 PrettyPlatformName = TargetPlatform;
333
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000334 VersionTuple TargetMinVersion = Context.getTargetInfo().getPlatformMinVersion();
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000335 if (TargetMinVersion.empty())
336 return AR_Available;
337
338 // Match the platform name.
339 if (A->getPlatform()->getName() != TargetPlatform)
340 return AR_Available;
Fariborz Jahanian006e42f2011-12-10 00:28:41 +0000341
342 std::string HintMessage;
343 if (!A->getMessage().empty()) {
344 HintMessage = " - ";
345 HintMessage += A->getMessage();
346 }
347
Douglas Gregorb53e4172011-03-26 03:35:55 +0000348 // Make sure that this declaration has not been marked 'unavailable'.
349 if (A->getUnavailable()) {
350 if (Message) {
351 Message->clear();
352 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian006e42f2011-12-10 00:28:41 +0000353 Out << "not available on " << PrettyPlatformName
354 << HintMessage;
Douglas Gregorb53e4172011-03-26 03:35:55 +0000355 }
356
357 return AR_Unavailable;
358 }
359
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000360 // Make sure that this declaration has already been introduced.
361 if (!A->getIntroduced().empty() &&
362 TargetMinVersion < A->getIntroduced()) {
363 if (Message) {
364 Message->clear();
365 llvm::raw_string_ostream Out(*Message);
366 Out << "introduced in " << PrettyPlatformName << ' '
Fariborz Jahanian006e42f2011-12-10 00:28:41 +0000367 << A->getIntroduced() << HintMessage;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000368 }
369
370 return AR_NotYetIntroduced;
371 }
372
373 // Make sure that this declaration hasn't been obsoleted.
374 if (!A->getObsoleted().empty() && TargetMinVersion >= A->getObsoleted()) {
375 if (Message) {
376 Message->clear();
377 llvm::raw_string_ostream Out(*Message);
378 Out << "obsoleted in " << PrettyPlatformName << ' '
Fariborz Jahanian006e42f2011-12-10 00:28:41 +0000379 << A->getObsoleted() << HintMessage;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000380 }
381
382 return AR_Unavailable;
383 }
384
385 // Make sure that this declaration hasn't been deprecated.
386 if (!A->getDeprecated().empty() && TargetMinVersion >= A->getDeprecated()) {
387 if (Message) {
388 Message->clear();
389 llvm::raw_string_ostream Out(*Message);
390 Out << "first deprecated in " << PrettyPlatformName << ' '
Fariborz Jahanian006e42f2011-12-10 00:28:41 +0000391 << A->getDeprecated() << HintMessage;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000392 }
393
394 return AR_Deprecated;
395 }
396
397 return AR_Available;
398}
399
400AvailabilityResult Decl::getAvailability(std::string *Message) const {
401 AvailabilityResult Result = AR_Available;
402 std::string ResultMessage;
403
404 for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) {
405 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(*A)) {
406 if (Result >= AR_Deprecated)
407 continue;
408
409 if (Message)
410 ResultMessage = Deprecated->getMessage();
411
412 Result = AR_Deprecated;
413 continue;
414 }
415
416 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(*A)) {
417 if (Message)
418 *Message = Unavailable->getMessage();
419 return AR_Unavailable;
420 }
421
422 if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) {
423 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
424 Message);
425
426 if (AR == AR_Unavailable)
427 return AR_Unavailable;
428
429 if (AR > Result) {
430 Result = AR;
431 if (Message)
432 ResultMessage.swap(*Message);
433 }
434 continue;
435 }
436 }
437
438 if (Message)
439 Message->swap(ResultMessage);
440 return Result;
441}
442
443bool Decl::canBeWeakImported(bool &IsDefinition) const {
444 IsDefinition = false;
John McCall260611a2012-06-20 06:18:46 +0000445
446 // Variables, if they aren't definitions.
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000447 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000448 if (Var->isThisDeclarationADefinition()) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000449 IsDefinition = true;
450 return false;
451 }
John McCall260611a2012-06-20 06:18:46 +0000452 return true;
453
454 // Functions, if they aren't definitions.
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000455 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
456 if (FD->hasBody()) {
457 IsDefinition = true;
458 return false;
459 }
John McCall260611a2012-06-20 06:18:46 +0000460 return true;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000461
John McCall260611a2012-06-20 06:18:46 +0000462 // Objective-C classes, if this is the non-fragile runtime.
463 } else if (isa<ObjCInterfaceDecl>(this) &&
John McCall0b92fcb2012-06-20 21:58:02 +0000464 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
John McCall260611a2012-06-20 06:18:46 +0000465 return true;
466
467 // Nothing else.
468 } else {
469 return false;
470 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000471}
472
473bool Decl::isWeakImported() const {
474 bool IsDefinition;
475 if (!canBeWeakImported(IsDefinition))
476 return false;
477
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000478 for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) {
479 if (isa<WeakImportAttr>(*A))
480 return true;
481
482 if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) {
483 if (CheckAvailability(getASTContext(), Availability, 0)
484 == AR_NotYetIntroduced)
485 return true;
486 }
487 }
488
489 return false;
490}
Tanya Lattner12ead492010-02-17 02:17:21 +0000491
Chris Lattner769dbdf2009-03-27 20:18:19 +0000492unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
493 switch (DeclKind) {
John McCall9488ea12009-11-17 05:59:44 +0000494 case Function:
495 case CXXMethod:
496 case CXXConstructor:
497 case CXXDestructor:
498 case CXXConversion:
Chris Lattner769dbdf2009-03-27 20:18:19 +0000499 case EnumConstant:
500 case Var:
501 case ImplicitParam:
502 case ParmVar:
Chris Lattner769dbdf2009-03-27 20:18:19 +0000503 case NonTypeTemplateParm:
504 case ObjCMethod:
Daniel Dunbar00b40d32010-04-23 13:07:39 +0000505 case ObjCProperty:
John McCall76da55d2013-04-16 07:28:30 +0000506 case MSProperty:
Daniel Dunbar00b40d32010-04-23 13:07:39 +0000507 return IDNS_Ordinary;
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000508 case Label:
509 return IDNS_Label;
Francois Pichet87c2e122010-11-21 06:08:52 +0000510 case IndirectField:
511 return IDNS_Ordinary | IDNS_Member;
512
John McCall0d6b1642010-04-23 18:46:30 +0000513 case ObjCCompatibleAlias:
514 case ObjCInterface:
515 return IDNS_Ordinary | IDNS_Type;
516
517 case Typedef:
Richard Smith162e1c12011-04-15 14:24:37 +0000518 case TypeAlias:
Richard Smith3e4c6c42011-05-05 21:57:07 +0000519 case TypeAliasTemplate:
John McCall0d6b1642010-04-23 18:46:30 +0000520 case UnresolvedUsingTypename:
521 case TemplateTypeParm:
522 return IDNS_Ordinary | IDNS_Type;
523
John McCall9488ea12009-11-17 05:59:44 +0000524 case UsingShadow:
525 return 0; // we'll actually overwrite this later
526
John McCall7ba107a2009-11-18 02:36:19 +0000527 case UnresolvedUsingValue:
John McCall7ba107a2009-11-18 02:36:19 +0000528 return IDNS_Ordinary | IDNS_Using;
John McCall9488ea12009-11-17 05:59:44 +0000529
530 case Using:
531 return IDNS_Using;
532
Chris Lattner769dbdf2009-03-27 20:18:19 +0000533 case ObjCProtocol:
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000534 return IDNS_ObjCProtocol;
Mike Stump1eb44332009-09-09 15:08:12 +0000535
Chris Lattner769dbdf2009-03-27 20:18:19 +0000536 case Field:
537 case ObjCAtDefsField:
538 case ObjCIvar:
539 return IDNS_Member;
Mike Stump1eb44332009-09-09 15:08:12 +0000540
Chris Lattner769dbdf2009-03-27 20:18:19 +0000541 case Record:
542 case CXXRecord:
543 case Enum:
John McCall0d6b1642010-04-23 18:46:30 +0000544 return IDNS_Tag | IDNS_Type;
Mike Stump1eb44332009-09-09 15:08:12 +0000545
Chris Lattner769dbdf2009-03-27 20:18:19 +0000546 case Namespace:
John McCall0d6b1642010-04-23 18:46:30 +0000547 case NamespaceAlias:
548 return IDNS_Namespace;
549
Chris Lattner769dbdf2009-03-27 20:18:19 +0000550 case FunctionTemplate:
Larisse Voufoef4579c2013-08-06 01:03:05 +0000551 case VarTemplate:
John McCall0d6b1642010-04-23 18:46:30 +0000552 return IDNS_Ordinary;
553
Chris Lattner769dbdf2009-03-27 20:18:19 +0000554 case ClassTemplate:
555 case TemplateTemplateParm:
John McCall0d6b1642010-04-23 18:46:30 +0000556 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
Mike Stump1eb44332009-09-09 15:08:12 +0000557
Chris Lattner769dbdf2009-03-27 20:18:19 +0000558 // Never have names.
John McCall02cace72009-08-28 07:59:38 +0000559 case Friend:
John McCalldd4a3b02009-09-16 22:47:08 +0000560 case FriendTemplate:
Abramo Bagnara6206d532010-06-05 05:09:32 +0000561 case AccessSpec:
Chris Lattner769dbdf2009-03-27 20:18:19 +0000562 case LinkageSpec:
563 case FileScopeAsm:
564 case StaticAssert:
Chris Lattner769dbdf2009-03-27 20:18:19 +0000565 case ObjCPropertyImpl:
Chris Lattner769dbdf2009-03-27 20:18:19 +0000566 case Block:
Tareq A. Siraj6afcf882013-04-16 19:37:38 +0000567 case Captured:
Chris Lattner769dbdf2009-03-27 20:18:19 +0000568 case TranslationUnit:
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000569
Chris Lattner769dbdf2009-03-27 20:18:19 +0000570 case UsingDirective:
571 case ClassTemplateSpecialization:
Douglas Gregorc8ab2562009-05-31 09:31:02 +0000572 case ClassTemplatePartialSpecialization:
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000573 case ClassScopeFunctionSpecialization:
Larisse Voufoef4579c2013-08-06 01:03:05 +0000574 case VarTemplateSpecialization:
575 case VarTemplatePartialSpecialization:
Douglas Gregorbd4187b2010-04-22 23:19:50 +0000576 case ObjCImplementation:
577 case ObjCCategory:
578 case ObjCCategoryImpl:
Douglas Gregor15de72c2011-12-02 23:23:56 +0000579 case Import:
Alexey Bataevc6400582013-03-22 06:34:35 +0000580 case OMPThreadPrivate:
Michael Han684aa732013-02-22 17:15:32 +0000581 case Empty:
Douglas Gregorbd4187b2010-04-22 23:19:50 +0000582 // Never looked up by name.
Chris Lattner769dbdf2009-03-27 20:18:19 +0000583 return 0;
584 }
John McCall9488ea12009-11-17 05:59:44 +0000585
David Blaikie30263482012-01-20 21:50:17 +0000586 llvm_unreachable("Invalid DeclKind!");
Eli Friedman56d29372008-06-07 16:52:53 +0000587}
588
Argyrios Kyrtzidis4bbb8502012-02-09 02:44:08 +0000589void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
Argyrios Kyrtzidis1715bf52010-06-11 23:09:25 +0000590 assert(!HasAttrs && "Decl already contains attrs.");
591
Argyrios Kyrtzidis4bbb8502012-02-09 02:44:08 +0000592 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
Sean Huntcf807c42010-08-18 23:23:40 +0000593 assert(AttrBlank.empty() && "HasAttrs was wrong?");
Argyrios Kyrtzidis1715bf52010-06-11 23:09:25 +0000594
595 AttrBlank = attrs;
596 HasAttrs = true;
597}
598
Sean Huntcf807c42010-08-18 23:23:40 +0000599void Decl::dropAttrs() {
Eli Friedman56d29372008-06-07 16:52:53 +0000600 if (!HasAttrs) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000601
Eli Friedman56d29372008-06-07 16:52:53 +0000602 HasAttrs = false;
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000603 getASTContext().eraseDeclAttrs(this);
Eli Friedman56d29372008-06-07 16:52:53 +0000604}
605
Sean Huntcf807c42010-08-18 23:23:40 +0000606const AttrVec &Decl::getAttrs() const {
607 assert(HasAttrs && "No attrs to get!");
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000608 return getASTContext().getDeclAttrs(this);
Eli Friedman56d29372008-06-07 16:52:53 +0000609}
610
Argyrios Kyrtzidis42220c52008-10-12 16:14:48 +0000611Decl *Decl::castFromDeclContext (const DeclContext *D) {
Argyrios Kyrtzidis3d7641e2009-02-16 14:29:28 +0000612 Decl::Kind DK = D->getDeclKind();
613 switch(DK) {
Sean Hunt9a555912010-05-30 07:21:58 +0000614#define DECL(NAME, BASE)
615#define DECL_CONTEXT(NAME) \
616 case Decl::NAME: \
617 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
618#define DECL_CONTEXT_BASE(NAME)
619#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidis3d7641e2009-02-16 14:29:28 +0000620 default:
Sean Hunt9a555912010-05-30 07:21:58 +0000621#define DECL(NAME, BASE)
622#define DECL_CONTEXT_BASE(NAME) \
623 if (DK >= first##NAME && DK <= last##NAME) \
624 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
625#include "clang/AST/DeclNodes.inc"
David Blaikieb219cfc2011-09-23 05:06:16 +0000626 llvm_unreachable("a decl that inherits DeclContext isn't handled");
Argyrios Kyrtzidis3d7641e2009-02-16 14:29:28 +0000627 }
Argyrios Kyrtzidis42220c52008-10-12 16:14:48 +0000628}
629
630DeclContext *Decl::castToDeclContext(const Decl *D) {
Argyrios Kyrtzidis3d7641e2009-02-16 14:29:28 +0000631 Decl::Kind DK = D->getKind();
632 switch(DK) {
Sean Hunt9a555912010-05-30 07:21:58 +0000633#define DECL(NAME, BASE)
634#define DECL_CONTEXT(NAME) \
635 case Decl::NAME: \
636 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
637#define DECL_CONTEXT_BASE(NAME)
638#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidis3d7641e2009-02-16 14:29:28 +0000639 default:
Sean Hunt9a555912010-05-30 07:21:58 +0000640#define DECL(NAME, BASE)
641#define DECL_CONTEXT_BASE(NAME) \
642 if (DK >= first##NAME && DK <= last##NAME) \
643 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
644#include "clang/AST/DeclNodes.inc"
David Blaikieb219cfc2011-09-23 05:06:16 +0000645 llvm_unreachable("a decl that inherits DeclContext isn't handled");
Argyrios Kyrtzidis3d7641e2009-02-16 14:29:28 +0000646 }
Argyrios Kyrtzidis42220c52008-10-12 16:14:48 +0000647}
648
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000649SourceLocation Decl::getBodyRBrace() const {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +0000650 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
651 // FunctionDecl stores EndRangeLoc for this purpose.
652 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
653 const FunctionDecl *Definition;
654 if (FD->hasBody(Definition))
655 return Definition->getSourceRange().getEnd();
656 return SourceLocation();
657 }
658
Argyrios Kyrtzidis6717ef42010-07-07 11:31:27 +0000659 if (Stmt *Body = getBody())
660 return Body->getSourceRange().getEnd();
661
662 return SourceLocation();
Sebastian Redld3a413d2009-04-26 20:35:05 +0000663}
664
Anders Carlsson1329c272009-03-25 23:38:06 +0000665void Decl::CheckAccessDeclContext() const {
Douglas Gregor3a1c36c2010-12-02 00:22:25 +0000666#ifndef NDEBUG
John McCall46460a62010-01-20 21:53:11 +0000667 // Suppress this check if any of the following hold:
668 // 1. this is the translation unit (and thus has no parent)
669 // 2. this is a template parameter (and thus doesn't belong to its context)
Argyrios Kyrtzidisd580e562010-09-08 21:58:42 +0000670 // 3. this is a non-type template parameter
671 // 4. the context is not a record
672 // 5. it's invalid
673 // 6. it's a C++0x static_assert.
Anders Carlsson35eda442009-08-29 20:47:47 +0000674 if (isa<TranslationUnitDecl>(this) ||
Argyrios Kyrtzidis04aed0e2010-07-02 11:55:44 +0000675 isa<TemplateTypeParmDecl>(this) ||
Argyrios Kyrtzidisd580e562010-09-08 21:58:42 +0000676 isa<NonTypeTemplateParmDecl>(this) ||
Douglas Gregorfdd8ab12010-02-22 17:53:38 +0000677 !isa<CXXRecordDecl>(getDeclContext()) ||
Argyrios Kyrtzidis65b63ec2010-09-08 21:32:35 +0000678 isInvalidDecl() ||
679 isa<StaticAssertDecl>(this) ||
680 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
681 // as DeclContext (?).
Argyrios Kyrtzidisd580e562010-09-08 21:58:42 +0000682 isa<ParmVarDecl>(this) ||
683 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
684 // AS_none as access specifier.
Francois Pichetbc845322011-08-17 01:06:54 +0000685 isa<CXXRecordDecl>(this) ||
686 isa<ClassScopeFunctionSpecializationDecl>(this))
Anders Carlsson35eda442009-08-29 20:47:47 +0000687 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000688
689 assert(Access != AS_none &&
Anders Carlsson1329c272009-03-25 23:38:06 +0000690 "Access specifier is AS_none inside a record decl");
Douglas Gregor3a1c36c2010-12-02 00:22:25 +0000691#endif
Anders Carlsson1329c272009-03-25 23:38:06 +0000692}
693
John McCallf5ebf9b2013-05-03 07:33:41 +0000694static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
695static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
696
697/// Starting at a given context (a Decl or DeclContext), look for a
698/// code context that is not a closure (a lambda, block, etc.).
699template <class T> static Decl *getNonClosureContext(T *D) {
700 if (getKind(D) == Decl::CXXMethod) {
701 CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
John McCall000817b2013-05-03 17:11:14 +0000702 if (MD->getOverloadedOperator() == OO_Call &&
703 MD->getParent()->isLambda())
John McCallf5ebf9b2013-05-03 07:33:41 +0000704 return getNonClosureContext(MD->getParent()->getParent());
705 return MD;
706 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
707 return FD;
708 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
709 return MD;
710 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
711 return getNonClosureContext(BD->getParent());
712 } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
713 return getNonClosureContext(CD->getParent());
714 } else {
715 return 0;
716 }
John McCall4b9c2d22011-11-06 09:01:30 +0000717}
718
John McCallf5ebf9b2013-05-03 07:33:41 +0000719Decl *Decl::getNonClosureContext() {
720 return ::getNonClosureContext(this);
721}
John McCallaab9e312011-02-22 22:25:23 +0000722
John McCallf5ebf9b2013-05-03 07:33:41 +0000723Decl *DeclContext::getNonClosureAncestor() {
724 return ::getNonClosureContext(this);
John McCallaab9e312011-02-22 22:25:23 +0000725}
Anders Carlsson1329c272009-03-25 23:38:06 +0000726
Eli Friedman56d29372008-06-07 16:52:53 +0000727//===----------------------------------------------------------------------===//
728// DeclContext Implementation
729//===----------------------------------------------------------------------===//
730
Argyrios Kyrtzidis3d7641e2009-02-16 14:29:28 +0000731bool DeclContext::classof(const Decl *D) {
732 switch (D->getKind()) {
Sean Hunt9a555912010-05-30 07:21:58 +0000733#define DECL(NAME, BASE)
734#define DECL_CONTEXT(NAME) case Decl::NAME:
735#define DECL_CONTEXT_BASE(NAME)
736#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidis3d7641e2009-02-16 14:29:28 +0000737 return true;
738 default:
Sean Hunt9a555912010-05-30 07:21:58 +0000739#define DECL(NAME, BASE)
740#define DECL_CONTEXT_BASE(NAME) \
741 if (D->getKind() >= Decl::first##NAME && \
742 D->getKind() <= Decl::last##NAME) \
Argyrios Kyrtzidis3d7641e2009-02-16 14:29:28 +0000743 return true;
Sean Hunt9a555912010-05-30 07:21:58 +0000744#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidis3d7641e2009-02-16 14:29:28 +0000745 return false;
746 }
747}
748
Douglas Gregora2da7802010-07-25 18:38:02 +0000749DeclContext::~DeclContext() { }
Douglas Gregor44b43212008-12-11 16:49:14 +0000750
Douglas Gregore942bbe2009-09-10 16:57:35 +0000751/// \brief Find the parent context of this context that will be
752/// used for unqualified name lookup.
753///
754/// Generally, the parent lookup context is the semantic context. However, for
755/// a friend function the parent lookup context is the lexical context, which
756/// is the class in which the friend is declared.
757DeclContext *DeclContext::getLookupParent() {
758 // FIXME: Find a better way to identify friends
759 if (isa<FunctionDecl>(this))
Sebastian Redl7a126a42010-08-31 00:36:30 +0000760 if (getParent()->getRedeclContext()->isFileContext() &&
761 getLexicalParent()->getRedeclContext()->isRecord())
Douglas Gregore942bbe2009-09-10 16:57:35 +0000762 return getLexicalParent();
763
764 return getParent();
765}
766
Sebastian Redl410c4f22010-08-31 20:53:31 +0000767bool DeclContext::isInlineNamespace() const {
768 return isNamespace() &&
769 cast<NamespaceDecl>(this)->isInline();
770}
771
Douglas Gregorbc221632009-05-28 16:34:51 +0000772bool DeclContext::isDependentContext() const {
773 if (isFileContext())
774 return false;
775
Douglas Gregorc8ab2562009-05-31 09:31:02 +0000776 if (isa<ClassTemplatePartialSpecializationDecl>(this))
777 return true;
778
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000779 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
Douglas Gregorbc221632009-05-28 16:34:51 +0000780 if (Record->getDescribedClassTemplate())
781 return true;
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000782
783 if (Record->isDependentLambda())
784 return true;
785 }
786
John McCall0c01d182010-03-24 05:22:00 +0000787 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
Douglas Gregorbc221632009-05-28 16:34:51 +0000788 if (Function->getDescribedFunctionTemplate())
789 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000790
John McCall0c01d182010-03-24 05:22:00 +0000791 // Friend function declarations are dependent if their *lexical*
792 // context is dependent.
793 if (cast<Decl>(this)->getFriendObjectKind())
794 return getLexicalParent()->isDependentContext();
795 }
796
Douglas Gregorbc221632009-05-28 16:34:51 +0000797 return getParent() && getParent()->isDependentContext();
798}
799
Douglas Gregor074149e2009-01-05 19:45:36 +0000800bool DeclContext::isTransparentContext() const {
801 if (DeclKind == Decl::Enum)
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000802 return !cast<EnumDecl>(this)->isScoped();
Douglas Gregor074149e2009-01-05 19:45:36 +0000803 else if (DeclKind == Decl::LinkageSpec)
804 return true;
Douglas Gregor074149e2009-01-05 19:45:36 +0000805
806 return false;
807}
808
Sebastian Redl7a126a42010-08-31 00:36:30 +0000809bool DeclContext::Encloses(const DeclContext *DC) const {
Douglas Gregor6dd38da2009-08-27 06:03:53 +0000810 if (getPrimaryContext() != this)
811 return getPrimaryContext()->Encloses(DC);
Mike Stump1eb44332009-09-09 15:08:12 +0000812
Douglas Gregor6dd38da2009-08-27 06:03:53 +0000813 for (; DC; DC = DC->getParent())
814 if (DC->getPrimaryContext() == this)
815 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000816 return false;
Douglas Gregor6dd38da2009-08-27 06:03:53 +0000817}
818
Steve Naroff0701bbb2009-01-08 17:28:14 +0000819DeclContext *DeclContext::getPrimaryContext() {
Douglas Gregor44b43212008-12-11 16:49:14 +0000820 switch (DeclKind) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000821 case Decl::TranslationUnit:
Douglas Gregor074149e2009-01-05 19:45:36 +0000822 case Decl::LinkageSpec:
Mike Stump1eb44332009-09-09 15:08:12 +0000823 case Decl::Block:
Tareq A. Siraj6afcf882013-04-16 19:37:38 +0000824 case Decl::Captured:
Douglas Gregor44b43212008-12-11 16:49:14 +0000825 // There is only one DeclContext for these entities.
826 return this;
827
828 case Decl::Namespace:
829 // The original namespace is our primary context.
830 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
831
Douglas Gregor44b43212008-12-11 16:49:14 +0000832 case Decl::ObjCMethod:
833 return this;
834
835 case Decl::ObjCInterface:
Douglas Gregor53df7a12011-12-15 18:03:09 +0000836 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
837 return Def;
838
839 return this;
840
Steve Naroff0701bbb2009-01-08 17:28:14 +0000841 case Decl::ObjCProtocol:
Douglas Gregor1d784b22012-01-01 19:51:50 +0000842 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
843 return Def;
844
845 return this;
Douglas Gregor53df7a12011-12-15 18:03:09 +0000846
Steve Naroff0701bbb2009-01-08 17:28:14 +0000847 case Decl::ObjCCategory:
Douglas Gregor44b43212008-12-11 16:49:14 +0000848 return this;
849
Steve Naroff0701bbb2009-01-08 17:28:14 +0000850 case Decl::ObjCImplementation:
851 case Decl::ObjCCategoryImpl:
852 return this;
853
Douglas Gregor44b43212008-12-11 16:49:14 +0000854 default:
Sean Hunt9a555912010-05-30 07:21:58 +0000855 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
Douglas Gregorcc636682009-02-17 23:15:12 +0000856 // If this is a tag type that has a definition or is currently
857 // being defined, that definition is our primary context.
John McCall3cb0ebd2010-03-10 03:28:59 +0000858 TagDecl *Tag = cast<TagDecl>(this);
859 assert(isa<TagType>(Tag->TypeForDecl) ||
860 isa<InjectedClassNameType>(Tag->TypeForDecl));
861
862 if (TagDecl *Def = Tag->getDefinition())
863 return Def;
864
865 if (!isa<InjectedClassNameType>(Tag->TypeForDecl)) {
866 const TagType *TagTy = cast<TagType>(Tag->TypeForDecl);
867 if (TagTy->isBeingDefined())
868 // FIXME: is it necessarily being defined in the decl
869 // that owns the type?
870 return TagTy->getDecl();
871 }
872
873 return Tag;
Douglas Gregorcc636682009-02-17 23:15:12 +0000874 }
875
Sean Hunt9a555912010-05-30 07:21:58 +0000876 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
Douglas Gregor44b43212008-12-11 16:49:14 +0000877 "Unknown DeclContext kind");
878 return this;
879 }
880}
881
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +0000882void
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000883DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +0000884 Contexts.clear();
885
886 if (DeclKind != Decl::Namespace) {
887 Contexts.push_back(this);
888 return;
Douglas Gregor44b43212008-12-11 16:49:14 +0000889 }
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +0000890
891 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
Douglas Gregoref96ee02012-01-14 16:38:05 +0000892 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
893 N = N->getPreviousDecl())
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +0000894 Contexts.push_back(N);
895
896 std::reverse(Contexts.begin(), Contexts.end());
Douglas Gregor44b43212008-12-11 16:49:14 +0000897}
898
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +0000899std::pair<Decl *, Decl *>
Bill Wendling341785e2012-02-22 09:51:33 +0000900DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
Argyrios Kyrtzidisec2ec1f2011-10-07 21:55:43 +0000901 bool FieldsAlreadyLoaded) {
Douglas Gregor46cd2182012-01-06 16:59:53 +0000902 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +0000903 Decl *FirstNewDecl = 0;
904 Decl *PrevDecl = 0;
905 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
Argyrios Kyrtzidisec2ec1f2011-10-07 21:55:43 +0000906 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
907 continue;
908
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +0000909 Decl *D = Decls[I];
910 if (PrevDecl)
Douglas Gregor46cd2182012-01-06 16:59:53 +0000911 PrevDecl->NextInContextAndBits.setPointer(D);
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +0000912 else
913 FirstNewDecl = D;
914
915 PrevDecl = D;
916 }
917
918 return std::make_pair(FirstNewDecl, PrevDecl);
919}
920
Richard Smithbbcd0f32013-02-07 03:37:08 +0000921/// \brief We have just acquired external visible storage, and we already have
922/// built a lookup map. For every name in the map, pull in the new names from
923/// the external storage.
924void DeclContext::reconcileExternalVisibleStorage() {
Richard Smith88963392013-02-11 22:02:16 +0000925 assert(NeedToReconcileExternalVisibleStorage && LookupPtr.getPointer());
Richard Smithbbcd0f32013-02-07 03:37:08 +0000926 NeedToReconcileExternalVisibleStorage = false;
927
928 StoredDeclsMap &Map = *LookupPtr.getPointer();
Richard Smithb7165582013-09-09 07:34:56 +0000929 for (StoredDeclsMap::iterator I = Map.begin(); I != Map.end(); ++I)
930 I->second.setHasExternalDecls();
Richard Smithbbcd0f32013-02-07 03:37:08 +0000931}
932
Douglas Gregor2cf26342009-04-09 22:27:44 +0000933/// \brief Load the declarations within this lexical storage from an
934/// external source.
Mike Stump1eb44332009-09-09 15:08:12 +0000935void
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000936DeclContext::LoadLexicalDeclsFromExternalStorage() const {
937 ExternalASTSource *Source = getParentASTContext().getExternalSource();
Douglas Gregor2cf26342009-04-09 22:27:44 +0000938 assert(hasExternalLexicalStorage() && Source && "No external storage?");
939
Argyrios Kyrtzidis0dbbc042010-07-30 10:03:23 +0000940 // Notify that we have a DeclContext that is initializing.
941 ExternalASTSource::Deserializing ADeclContext(Source);
Douglas Gregor9fc18c92011-08-26 21:23:06 +0000942
Douglas Gregorba6ffaf2011-07-15 21:46:17 +0000943 // Load the external declarations, if any.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000944 SmallVector<Decl*, 64> Decls;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000945 ExternalLexicalStorage = false;
Douglas Gregorba6ffaf2011-07-15 21:46:17 +0000946 switch (Source->FindExternalLexicalDecls(this, Decls)) {
947 case ELR_Success:
948 break;
949
950 case ELR_Failure:
951 case ELR_AlreadyLoaded:
952 return;
953 }
Douglas Gregor2cf26342009-04-09 22:27:44 +0000954
955 if (Decls.empty())
956 return;
957
Argyrios Kyrtzidisec2ec1f2011-10-07 21:55:43 +0000958 // We may have already loaded just the fields of this record, in which case
959 // we need to ignore them.
960 bool FieldsAlreadyLoaded = false;
961 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
962 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
963
Douglas Gregor2cf26342009-04-09 22:27:44 +0000964 // Splice the newly-read declarations into the beginning of the list
965 // of declarations.
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +0000966 Decl *ExternalFirst, *ExternalLast;
Argyrios Kyrtzidisec2ec1f2011-10-07 21:55:43 +0000967 llvm::tie(ExternalFirst, ExternalLast) = BuildDeclChain(Decls,
968 FieldsAlreadyLoaded);
Douglas Gregor46cd2182012-01-06 16:59:53 +0000969 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +0000970 FirstDecl = ExternalFirst;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000971 if (!LastDecl)
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +0000972 LastDecl = ExternalLast;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000973}
974
John McCall76bd1f32010-06-01 09:23:16 +0000975DeclContext::lookup_result
976ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
977 DeclarationName Name) {
978 ASTContext &Context = DC->getParentASTContext();
979 StoredDeclsMap *Map;
Richard Smithc5d3e802012-03-16 06:12:59 +0000980 if (!(Map = DC->LookupPtr.getPointer()))
John McCall76bd1f32010-06-01 09:23:16 +0000981 Map = DC->CreateStoredDeclsMap(Context);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000982
Richard Smithb7165582013-09-09 07:34:56 +0000983 (*Map)[Name].removeExternalDecls();
Douglas Gregor2cf26342009-04-09 22:27:44 +0000984
John McCall76bd1f32010-06-01 09:23:16 +0000985 return DeclContext::lookup_result();
986}
Douglas Gregor2cf26342009-04-09 22:27:44 +0000987
John McCall76bd1f32010-06-01 09:23:16 +0000988DeclContext::lookup_result
989ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
John McCall76bd1f32010-06-01 09:23:16 +0000990 DeclarationName Name,
Argyrios Kyrtzidis45df9c62011-09-09 06:44:14 +0000991 ArrayRef<NamedDecl*> Decls) {
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +0000992 ASTContext &Context = DC->getParentASTContext();
John McCall76bd1f32010-06-01 09:23:16 +0000993 StoredDeclsMap *Map;
Richard Smithc5d3e802012-03-16 06:12:59 +0000994 if (!(Map = DC->LookupPtr.getPointer()))
John McCall76bd1f32010-06-01 09:23:16 +0000995 Map = DC->CreateStoredDeclsMap(Context);
996
997 StoredDeclsList &List = (*Map)[Name];
Richard Smithddb10f72013-06-24 01:46:41 +0000998
999 // Clear out any old external visible declarations, to avoid quadratic
1000 // performance in the redeclaration checks below.
1001 List.removeExternalDecls();
1002
1003 if (!List.isNull()) {
1004 // We have both existing declarations and new declarations for this name.
1005 // Some of the declarations may simply replace existing ones. Handle those
1006 // first.
1007 llvm::SmallVector<unsigned, 8> Skip;
1008 for (unsigned I = 0, N = Decls.size(); I != N; ++I)
1009 if (List.HandleRedeclaration(Decls[I]))
1010 Skip.push_back(I);
1011 Skip.push_back(Decls.size());
1012
1013 // Add in any new declarations.
1014 unsigned SkipPos = 0;
1015 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1016 if (I == Skip[SkipPos])
1017 ++SkipPos;
1018 else
1019 List.AddSubsequentDecl(Decls[I]);
1020 }
1021 } else {
1022 // Convert the array to a StoredDeclsList.
1023 for (ArrayRef<NamedDecl*>::iterator
1024 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1025 if (List.isNull())
1026 List.setOnlyValue(*I);
1027 else
1028 List.AddSubsequentDecl(*I);
1029 }
John McCall76bd1f32010-06-01 09:23:16 +00001030 }
1031
Argyrios Kyrtzidis074dcc82010-08-20 16:04:35 +00001032 return List.getLookupResult();
John McCall76bd1f32010-06-01 09:23:16 +00001033}
1034
Sebastian Redl681d7232010-07-27 00:17:23 +00001035DeclContext::decl_iterator DeclContext::noload_decls_begin() const {
1036 return decl_iterator(FirstDecl);
1037}
1038
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001039DeclContext::decl_iterator DeclContext::decls_begin() const {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001040 if (hasExternalLexicalStorage())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001041 LoadLexicalDeclsFromExternalStorage();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001042
Mike Stump1eb44332009-09-09 15:08:12 +00001043 return decl_iterator(FirstDecl);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001044}
1045
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001046bool DeclContext::decls_empty() const {
Douglas Gregor8038d512009-04-10 17:25:41 +00001047 if (hasExternalLexicalStorage())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001048 LoadLexicalDeclsFromExternalStorage();
Douglas Gregor8038d512009-04-10 17:25:41 +00001049
1050 return !FirstDecl;
1051}
1052
Sean Callanancd904e82013-05-04 02:04:27 +00001053bool DeclContext::containsDecl(Decl *D) const {
1054 return (D->getLexicalDeclContext() == this &&
1055 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1056}
1057
John McCall9f54ad42009-12-10 09:41:52 +00001058void DeclContext::removeDecl(Decl *D) {
1059 assert(D->getLexicalDeclContext() == this &&
1060 "decl being removed from non-lexical context");
Douglas Gregor46cd2182012-01-06 16:59:53 +00001061 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
John McCall9f54ad42009-12-10 09:41:52 +00001062 "decl is not in decls list");
1063
1064 // Remove D from the decl chain. This is O(n) but hopefully rare.
1065 if (D == FirstDecl) {
1066 if (D == LastDecl)
1067 FirstDecl = LastDecl = 0;
1068 else
Douglas Gregor46cd2182012-01-06 16:59:53 +00001069 FirstDecl = D->NextInContextAndBits.getPointer();
John McCall9f54ad42009-12-10 09:41:52 +00001070 } else {
Douglas Gregor46cd2182012-01-06 16:59:53 +00001071 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
John McCall9f54ad42009-12-10 09:41:52 +00001072 assert(I && "decl not found in linked list");
Douglas Gregor46cd2182012-01-06 16:59:53 +00001073 if (I->NextInContextAndBits.getPointer() == D) {
1074 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
John McCall9f54ad42009-12-10 09:41:52 +00001075 if (D == LastDecl) LastDecl = I;
1076 break;
1077 }
1078 }
1079 }
1080
1081 // Mark that D is no longer in the decl chain.
Douglas Gregor46cd2182012-01-06 16:59:53 +00001082 D->NextInContextAndBits.setPointer(0);
John McCall9f54ad42009-12-10 09:41:52 +00001083
1084 // Remove D from the lookup table if necessary.
1085 if (isa<NamedDecl>(D)) {
1086 NamedDecl *ND = cast<NamedDecl>(D);
1087
Axel Naumann02368d02011-08-26 14:06:12 +00001088 // Remove only decls that have a name
1089 if (!ND->getDeclName()) return;
1090
Richard Smithc5d3e802012-03-16 06:12:59 +00001091 StoredDeclsMap *Map = getPrimaryContext()->LookupPtr.getPointer();
John McCall0c01d182010-03-24 05:22:00 +00001092 if (!Map) return;
John McCall9f54ad42009-12-10 09:41:52 +00001093
John McCall9f54ad42009-12-10 09:41:52 +00001094 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1095 assert(Pos != Map->end() && "no lookup entry for decl");
Axel Naumannd9d137e2011-11-08 18:21:06 +00001096 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1097 Pos->second.remove(ND);
John McCall9f54ad42009-12-10 09:41:52 +00001098 }
1099}
1100
John McCall3f9a8a62009-08-11 06:59:38 +00001101void DeclContext::addHiddenDecl(Decl *D) {
Chris Lattner7f0be132009-02-20 00:56:18 +00001102 assert(D->getLexicalDeclContext() == this &&
1103 "Decl inserted into wrong lexical context");
Mike Stump1eb44332009-09-09 15:08:12 +00001104 assert(!D->getNextDeclInContext() && D != LastDecl &&
Douglas Gregor6037fcb2009-01-09 19:42:16 +00001105 "Decl already inserted into a DeclContext");
1106
1107 if (FirstDecl) {
Douglas Gregor46cd2182012-01-06 16:59:53 +00001108 LastDecl->NextInContextAndBits.setPointer(D);
Douglas Gregor6037fcb2009-01-09 19:42:16 +00001109 LastDecl = D;
1110 } else {
1111 FirstDecl = LastDecl = D;
1112 }
Douglas Gregor27c08ab2010-09-27 22:06:20 +00001113
1114 // Notify a C++ record declaration that we've added a member, so it can
1115 // update it's class-specific state.
1116 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1117 Record->addedMember(D);
Douglas Gregore6649772011-12-03 00:30:27 +00001118
1119 // If this is a newly-created (not de-serialized) import declaration, wire
1120 // it in to the list of local import declarations.
1121 if (!D->isFromASTFile()) {
1122 if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1123 D->getASTContext().addedLocalImportDecl(Import);
1124 }
John McCall3f9a8a62009-08-11 06:59:38 +00001125}
1126
1127void DeclContext::addDecl(Decl *D) {
1128 addHiddenDecl(D);
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001129
1130 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithc5d3e802012-03-16 06:12:59 +00001131 ND->getDeclContext()->getPrimaryContext()->
1132 makeDeclVisibleInContextWithFlags(ND, false, true);
Douglas Gregor44b43212008-12-11 16:49:14 +00001133}
1134
Sean Callanan9faf8102011-10-21 02:57:43 +00001135void DeclContext::addDeclInternal(Decl *D) {
1136 addHiddenDecl(D);
1137
1138 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithc5d3e802012-03-16 06:12:59 +00001139 ND->getDeclContext()->getPrimaryContext()->
1140 makeDeclVisibleInContextWithFlags(ND, true, true);
1141}
1142
1143/// shouldBeHidden - Determine whether a declaration which was declared
1144/// within its semantic context should be invisible to qualified name lookup.
1145static bool shouldBeHidden(NamedDecl *D) {
1146 // Skip unnamed declarations.
1147 if (!D->getDeclName())
1148 return true;
1149
1150 // Skip entities that can't be found by name lookup into a particular
1151 // context.
1152 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1153 D->isTemplateParameter())
1154 return true;
1155
1156 // Skip template specializations.
1157 // FIXME: This feels like a hack. Should DeclarationName support
1158 // template-ids, or is there a better way to keep specializations
1159 // from being visible?
1160 if (isa<ClassTemplateSpecializationDecl>(D))
1161 return true;
1162 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1163 if (FD->isFunctionTemplateSpecialization())
1164 return true;
1165
1166 return false;
1167}
1168
1169/// buildLookup - Build the lookup data structure with all of the
1170/// declarations in this DeclContext (and any other contexts linked
1171/// to it or transparent contexts nested within it) and return it.
1172StoredDeclsMap *DeclContext::buildLookup() {
1173 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1174
Richard Smith88963392013-02-11 22:02:16 +00001175 // FIXME: Should we keep going if hasExternalVisibleStorage?
Richard Smithc5d3e802012-03-16 06:12:59 +00001176 if (!LookupPtr.getInt())
1177 return LookupPtr.getPointer();
1178
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001179 SmallVector<DeclContext *, 2> Contexts;
Richard Smithc5d3e802012-03-16 06:12:59 +00001180 collectAllContexts(Contexts);
1181 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
Richard Smithe7bae152013-07-13 02:00:19 +00001182 buildLookupImpl<&DeclContext::decls_begin,
1183 &DeclContext::decls_end>(Contexts[I]);
Richard Smithc5d3e802012-03-16 06:12:59 +00001184
1185 // We no longer have any lazy decls.
1186 LookupPtr.setInt(false);
Richard Smith88963392013-02-11 22:02:16 +00001187 NeedToReconcileExternalVisibleStorage = false;
Richard Smithc5d3e802012-03-16 06:12:59 +00001188 return LookupPtr.getPointer();
1189}
1190
1191/// buildLookupImpl - Build part of the lookup data structure for the
1192/// declarations contained within DCtx, which will either be this
1193/// DeclContext, a DeclContext linked to it, or a transparent context
1194/// nested within it.
Richard Smithe7bae152013-07-13 02:00:19 +00001195template<DeclContext::decl_iterator (DeclContext::*Begin)() const,
1196 DeclContext::decl_iterator (DeclContext::*End)() const>
Richard Smithc5d3e802012-03-16 06:12:59 +00001197void DeclContext::buildLookupImpl(DeclContext *DCtx) {
Richard Smithe7bae152013-07-13 02:00:19 +00001198 for (decl_iterator I = (DCtx->*Begin)(), E = (DCtx->*End)();
Richard Smithc5d3e802012-03-16 06:12:59 +00001199 I != E; ++I) {
1200 Decl *D = *I;
1201
1202 // Insert this declaration into the lookup structure, but only if
1203 // it's semantically within its decl context. Any other decls which
1204 // should be found in this context are added eagerly.
Richard Smith096a3942013-06-24 07:20:36 +00001205 //
1206 // If it's from an AST file, don't add it now. It'll get handled by
1207 // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1208 // in C++, we do not track external visible decls for the TU, so in
1209 // that case we need to collect them all here.
Richard Smithc5d3e802012-03-16 06:12:59 +00001210 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smith096a3942013-06-24 07:20:36 +00001211 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1212 (!ND->isFromASTFile() ||
1213 (isTranslationUnit() &&
1214 !getParentASTContext().getLangOpts().CPlusPlus)))
Richard Smithc5d3e802012-03-16 06:12:59 +00001215 makeDeclVisibleInContextImpl(ND, false);
1216
1217 // If this declaration is itself a transparent declaration context
1218 // or inline namespace, add the members of this declaration of that
1219 // context (recursively).
1220 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1221 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Richard Smithe7bae152013-07-13 02:00:19 +00001222 buildLookupImpl<Begin, End>(InnerCtx);
Richard Smithc5d3e802012-03-16 06:12:59 +00001223 }
Sean Callanan9faf8102011-10-21 02:57:43 +00001224}
1225
Mike Stump1eb44332009-09-09 15:08:12 +00001226DeclContext::lookup_result
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001227DeclContext::lookup(DeclarationName Name) {
Nick Lewycky65daef12012-03-13 04:12:34 +00001228 assert(DeclKind != Decl::LinkageSpec &&
1229 "Should not perform lookups into linkage specs!");
1230
Steve Naroff0701bbb2009-01-08 17:28:14 +00001231 DeclContext *PrimaryContext = getPrimaryContext();
Douglas Gregor44b43212008-12-11 16:49:14 +00001232 if (PrimaryContext != this)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001233 return PrimaryContext->lookup(Name);
Douglas Gregor44b43212008-12-11 16:49:14 +00001234
Richard Smith1b7f9cb2012-03-13 03:12:56 +00001235 if (hasExternalVisibleStorage()) {
Richard Smithbbcd0f32013-02-07 03:37:08 +00001236 StoredDeclsMap *Map = LookupPtr.getPointer();
1237 if (LookupPtr.getInt())
1238 Map = buildLookup();
Richard Smith88963392013-02-11 22:02:16 +00001239 else if (NeedToReconcileExternalVisibleStorage)
1240 reconcileExternalVisibleStorage();
Richard Smithbbcd0f32013-02-07 03:37:08 +00001241
Richard Smith2bb07c12013-02-08 00:37:45 +00001242 if (!Map)
1243 Map = CreateStoredDeclsMap(getParentASTContext());
1244
Richard Smithb7165582013-09-09 07:34:56 +00001245 // If we have a lookup result with no external decls, we are done.
Richard Smith2bb07c12013-02-08 00:37:45 +00001246 std::pair<StoredDeclsMap::iterator, bool> R =
1247 Map->insert(std::make_pair(Name, StoredDeclsList()));
Richard Smithb7165582013-09-09 07:34:56 +00001248 if (!R.second && !R.first->second.hasExternalDecls())
Richard Smith2bb07c12013-02-08 00:37:45 +00001249 return R.first->second.getLookupResult();
Richard Smithc5d3e802012-03-16 06:12:59 +00001250
John McCall76bd1f32010-06-01 09:23:16 +00001251 ExternalASTSource *Source = getParentASTContext().getExternalSource();
Richard Smithb7165582013-09-09 07:34:56 +00001252 if (Source->FindExternalVisibleDeclsByName(this, Name) || R.second) {
Richard Smith3646c682013-02-07 03:30:24 +00001253 if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
1254 StoredDeclsMap::iterator I = Map->find(Name);
1255 if (I != Map->end())
1256 return I->second.getLookupResult();
1257 }
1258 }
1259
1260 return lookup_result(lookup_iterator(0), lookup_iterator(0));
John McCall76bd1f32010-06-01 09:23:16 +00001261 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001262
Richard Smithc5d3e802012-03-16 06:12:59 +00001263 StoredDeclsMap *Map = LookupPtr.getPointer();
1264 if (LookupPtr.getInt())
1265 Map = buildLookup();
1266
1267 if (!Map)
1268 return lookup_result(lookup_iterator(0), lookup_iterator(0));
1269
1270 StoredDeclsMap::iterator I = Map->find(Name);
1271 if (I == Map->end())
1272 return lookup_result(lookup_iterator(0), lookup_iterator(0));
1273
1274 return I->second.getLookupResult();
Douglas Gregor44b43212008-12-11 16:49:14 +00001275}
1276
Richard Smithe7bae152013-07-13 02:00:19 +00001277DeclContext::lookup_result
1278DeclContext::noload_lookup(DeclarationName Name) {
1279 assert(DeclKind != Decl::LinkageSpec &&
1280 "Should not perform lookups into linkage specs!");
1281 if (!hasExternalVisibleStorage())
1282 return lookup(Name);
1283
1284 DeclContext *PrimaryContext = getPrimaryContext();
1285 if (PrimaryContext != this)
1286 return PrimaryContext->noload_lookup(Name);
1287
1288 StoredDeclsMap *Map = LookupPtr.getPointer();
1289 if (LookupPtr.getInt()) {
1290 // Carefully build the lookup map, without deserializing anything.
1291 SmallVector<DeclContext *, 2> Contexts;
1292 collectAllContexts(Contexts);
1293 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1294 buildLookupImpl<&DeclContext::noload_decls_begin,
1295 &DeclContext::noload_decls_end>(Contexts[I]);
1296
1297 // We no longer have any lazy decls.
1298 LookupPtr.setInt(false);
1299
1300 // There may now be names for which we have local decls but are
Richard Smithb7165582013-09-09 07:34:56 +00001301 // missing the external decls. FIXME: Just set the hasExternalDecls
1302 // flag on those names that have external decls.
Richard Smithe7bae152013-07-13 02:00:19 +00001303 NeedToReconcileExternalVisibleStorage = true;
1304
1305 Map = LookupPtr.getPointer();
1306 }
1307
1308 if (!Map)
1309 return lookup_result(lookup_iterator(0), lookup_iterator(0));
1310
1311 StoredDeclsMap::iterator I = Map->find(Name);
1312 return I != Map->end()
1313 ? I->second.getLookupResult()
1314 : lookup_result(lookup_iterator(0), lookup_iterator(0));
1315}
1316
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001317void DeclContext::localUncachedLookup(DeclarationName Name,
1318 SmallVectorImpl<NamedDecl *> &Results) {
Douglas Gregorb75a3452011-10-15 00:10:27 +00001319 Results.clear();
1320
1321 // If there's no external storage, just perform a normal lookup and copy
1322 // the results.
Douglas Gregor93ed7cf2012-07-17 21:16:27 +00001323 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
Douglas Gregorb75a3452011-10-15 00:10:27 +00001324 lookup_result LookupResults = lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00001325 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
Douglas Gregorb75a3452011-10-15 00:10:27 +00001326 return;
1327 }
1328
1329 // If we have a lookup table, check there first. Maybe we'll get lucky.
Richard Smithbbcd0f32013-02-07 03:37:08 +00001330 if (Name && !LookupPtr.getInt()) {
Douglas Gregor93ed7cf2012-07-17 21:16:27 +00001331 if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
1332 StoredDeclsMap::iterator Pos = Map->find(Name);
1333 if (Pos != Map->end()) {
1334 Results.insert(Results.end(),
David Blaikie3bc93e32012-12-19 00:45:41 +00001335 Pos->second.getLookupResult().begin(),
1336 Pos->second.getLookupResult().end());
Douglas Gregor93ed7cf2012-07-17 21:16:27 +00001337 return;
1338 }
Douglas Gregorb75a3452011-10-15 00:10:27 +00001339 }
1340 }
Douglas Gregor93ed7cf2012-07-17 21:16:27 +00001341
Douglas Gregorb75a3452011-10-15 00:10:27 +00001342 // Slow case: grovel through the declarations in our chain looking for
1343 // matches.
1344 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1345 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1346 if (ND->getDeclName() == Name)
1347 Results.push_back(ND);
1348 }
1349}
1350
Sebastian Redl7a126a42010-08-31 00:36:30 +00001351DeclContext *DeclContext::getRedeclContext() {
Chris Lattner0cf2b192009-03-27 19:19:59 +00001352 DeclContext *Ctx = this;
Sebastian Redl410c4f22010-08-31 20:53:31 +00001353 // Skip through transparent contexts.
1354 while (Ctx->isTransparentContext())
Douglas Gregorce356072009-01-06 23:51:29 +00001355 Ctx = Ctx->getParent();
1356 return Ctx;
1357}
1358
Douglas Gregor88b70942009-02-25 22:02:03 +00001359DeclContext *DeclContext::getEnclosingNamespaceContext() {
1360 DeclContext *Ctx = this;
1361 // Skip through non-namespace, non-translation-unit contexts.
Sebastian Redl51a8a372010-08-31 00:36:23 +00001362 while (!Ctx->isFileContext())
Douglas Gregor88b70942009-02-25 22:02:03 +00001363 Ctx = Ctx->getParent();
1364 return Ctx->getPrimaryContext();
1365}
1366
Sebastian Redl7a126a42010-08-31 00:36:30 +00001367bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1368 // For non-file contexts, this is equivalent to Equals.
1369 if (!isFileContext())
1370 return O->Equals(this);
1371
1372 do {
1373 if (O->Equals(this))
1374 return true;
1375
1376 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1377 if (!NS || !NS->isInline())
1378 break;
1379 O = NS->getParent();
1380 } while (O);
1381
1382 return false;
1383}
1384
Richard Smithc5d3e802012-03-16 06:12:59 +00001385void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1386 DeclContext *PrimaryDC = this->getPrimaryContext();
1387 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1388 // If the decl is being added outside of its semantic decl context, we
1389 // need to ensure that we eagerly build the lookup information for it.
1390 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
Sean Callanan9faf8102011-10-21 02:57:43 +00001391}
1392
Richard Smithc5d3e802012-03-16 06:12:59 +00001393void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1394 bool Recoverable) {
1395 assert(this == getPrimaryContext() && "expected a primary DC");
Sean Callanan9faf8102011-10-21 02:57:43 +00001396
Richard Smith1b7f9cb2012-03-13 03:12:56 +00001397 // Skip declarations within functions.
Richard Smith4e9686b2013-08-09 04:35:01 +00001398 if (isFunctionOrMethod())
Richard Smith1b7f9cb2012-03-13 03:12:56 +00001399 return;
1400
Richard Smithc5d3e802012-03-16 06:12:59 +00001401 // Skip declarations which should be invisible to name lookup.
1402 if (shouldBeHidden(D))
1403 return;
1404
1405 // If we already have a lookup data structure, perform the insertion into
1406 // it. If we might have externally-stored decls with this name, look them
1407 // up and perform the insertion. If this decl was declared outside its
1408 // semantic context, buildLookup won't add it, so add it now.
1409 //
1410 // FIXME: As a performance hack, don't add such decls into the translation
1411 // unit unless we're in C++, since qualified lookup into the TU is never
1412 // performed.
1413 if (LookupPtr.getPointer() || hasExternalVisibleStorage() ||
1414 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1415 (getParentASTContext().getLangOpts().CPlusPlus ||
1416 !isTranslationUnit()))) {
1417 // If we have lazily omitted any decls, they might have the same name as
1418 // the decl which we are adding, so build a full lookup table before adding
1419 // this decl.
1420 buildLookup();
1421 makeDeclVisibleInContextImpl(D, Internal);
1422 } else {
1423 LookupPtr.setInt(true);
1424 }
1425
1426 // If we are a transparent context or inline namespace, insert into our
1427 // parent context, too. This operation is recursive.
1428 if (isTransparentContext() || isInlineNamespace())
1429 getParent()->getPrimaryContext()->
1430 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1431
1432 Decl *DCAsDecl = cast<Decl>(this);
1433 // Notify that a decl was made visible unless we are a Tag being defined.
1434 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1435 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1436 L->AddedVisibleDecl(this, D);
1437}
1438
1439void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1440 // Find or create the stored declaration map.
1441 StoredDeclsMap *Map = LookupPtr.getPointer();
1442 if (!Map) {
1443 ASTContext *C = &getParentASTContext();
1444 Map = CreateStoredDeclsMap(*C);
Argyrios Kyrtzidis5586b012010-07-04 21:44:25 +00001445 }
1446
Argyrios Kyrtzidis074dcc82010-08-20 16:04:35 +00001447 // If there is an external AST source, load any declarations it knows about
1448 // with this declaration's name.
1449 // If the lookup table contains an entry about this name it means that we
1450 // have already checked the external source.
Sean Callanan9faf8102011-10-21 02:57:43 +00001451 if (!Internal)
1452 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1453 if (hasExternalVisibleStorage() &&
Richard Smithc5d3e802012-03-16 06:12:59 +00001454 Map->find(D->getDeclName()) == Map->end())
Sean Callanan9faf8102011-10-21 02:57:43 +00001455 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
Argyrios Kyrtzidis074dcc82010-08-20 16:04:35 +00001456
Douglas Gregor44b43212008-12-11 16:49:14 +00001457 // Insert this declaration into the map.
Richard Smithc5d3e802012-03-16 06:12:59 +00001458 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
Richard Smithb7165582013-09-09 07:34:56 +00001459
1460 if (Internal) {
1461 // If this is being added as part of loading an external declaration,
1462 // this may not be the only external declaration with this name.
1463 // In this case, we never try to replace an existing declaration; we'll
1464 // handle that when we finalize the list of declarations for this name.
1465 DeclNameEntries.setHasExternalDecls();
1466 DeclNameEntries.AddSubsequentDecl(D);
1467 return;
1468 }
1469
1470 else if (DeclNameEntries.isNull()) {
Chris Lattner67762a32009-02-20 01:44:05 +00001471 DeclNameEntries.setOnlyValue(D);
Richard Smithc5d3e802012-03-16 06:12:59 +00001472 return;
Douglas Gregor44b43212008-12-11 16:49:14 +00001473 }
Chris Lattner91942502009-02-20 00:55:03 +00001474
Richard Smithc5d3e802012-03-16 06:12:59 +00001475 if (DeclNameEntries.HandleRedeclaration(D)) {
1476 // This declaration has replaced an existing one for which
1477 // declarationReplaces returns true.
1478 return;
1479 }
Mike Stump1eb44332009-09-09 15:08:12 +00001480
Richard Smithc5d3e802012-03-16 06:12:59 +00001481 // Put this declaration into the appropriate slot.
1482 DeclNameEntries.AddSubsequentDecl(D);
Douglas Gregor44b43212008-12-11 16:49:14 +00001483}
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001484
1485/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1486/// this context.
Mike Stump1eb44332009-09-09 15:08:12 +00001487DeclContext::udir_iterator_range
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001488DeclContext::getUsingDirectives() const {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00001489 // FIXME: Use something more efficient than normal lookup for using
1490 // directives. In C++, using directives are looked up more than anything else.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001491 lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
David Blaikie3bc93e32012-12-19 00:45:41 +00001492 return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.begin()),
1493 reinterpret_cast<udir_iterator>(Result.end()));
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001494}
Douglas Gregor2cf26342009-04-09 22:27:44 +00001495
Ted Kremenek3478eb62010-02-11 07:12:28 +00001496//===----------------------------------------------------------------------===//
1497// Creation and Destruction of StoredDeclsMaps. //
1498//===----------------------------------------------------------------------===//
1499
John McCall0c01d182010-03-24 05:22:00 +00001500StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
Richard Smithc5d3e802012-03-16 06:12:59 +00001501 assert(!LookupPtr.getPointer() && "context already has a decls map");
John McCall0c01d182010-03-24 05:22:00 +00001502 assert(getPrimaryContext() == this &&
1503 "creating decls map on non-primary context");
1504
1505 StoredDeclsMap *M;
1506 bool Dependent = isDependentContext();
1507 if (Dependent)
1508 M = new DependentStoredDeclsMap();
1509 else
1510 M = new StoredDeclsMap();
1511 M->Previous = C.LastSDM;
1512 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
Richard Smithc5d3e802012-03-16 06:12:59 +00001513 LookupPtr.setPointer(M);
Ted Kremenek3478eb62010-02-11 07:12:28 +00001514 return M;
1515}
1516
1517void ASTContext::ReleaseDeclContextMaps() {
John McCall0c01d182010-03-24 05:22:00 +00001518 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1519 // pointer because the subclass doesn't add anything that needs to
1520 // be deleted.
John McCall0c01d182010-03-24 05:22:00 +00001521 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1522}
1523
1524void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1525 while (Map) {
1526 // Advance the iteration before we invalidate memory.
1527 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1528
1529 if (Dependent)
1530 delete static_cast<DependentStoredDeclsMap*>(Map);
1531 else
1532 delete Map;
1533
1534 Map = Next.getPointer();
1535 Dependent = Next.getInt();
1536 }
1537}
1538
John McCall0c01d182010-03-24 05:22:00 +00001539DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1540 DeclContext *Parent,
1541 const PartialDiagnostic &PDiag) {
1542 assert(Parent->isDependentContext()
1543 && "cannot iterate dependent diagnostics of non-dependent context");
1544 Parent = Parent->getPrimaryContext();
Richard Smithc5d3e802012-03-16 06:12:59 +00001545 if (!Parent->LookupPtr.getPointer())
John McCall0c01d182010-03-24 05:22:00 +00001546 Parent->CreateStoredDeclsMap(C);
1547
1548 DependentStoredDeclsMap *Map
Richard Smithc5d3e802012-03-16 06:12:59 +00001549 = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr.getPointer());
John McCall0c01d182010-03-24 05:22:00 +00001550
Douglas Gregorb8365182010-03-29 23:56:53 +00001551 // Allocate the copy of the PartialDiagnostic via the ASTContext's
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00001552 // BumpPtrAllocator, rather than the ASTContext itself.
Douglas Gregorb8365182010-03-29 23:56:53 +00001553 PartialDiagnostic::Storage *DiagStorage = 0;
1554 if (PDiag.hasStorage())
1555 DiagStorage = new (C) PartialDiagnostic::Storage;
1556
1557 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
John McCall0c01d182010-03-24 05:22:00 +00001558
1559 // TODO: Maybe we shouldn't reverse the order during insertion.
1560 DD->NextDiagnostic = Map->FirstDiagnostic;
1561 Map->FirstDiagnostic = DD;
1562
1563 return DD;
Ted Kremenek3478eb62010-02-11 07:12:28 +00001564}