blob: 121c5a671a29a9f5b8601b31bcd4943e4314117c [file] [log] [blame]
Eli Friedman7dbab8a2008-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 Carruth3a022472012-12-04 09:13:33 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +000018#include "clang/AST/Decl.h"
Argyrios Kyrtzidis2951e142008-06-09 21:05:31 +000019#include "clang/AST/DeclCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/DeclContextInternals.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000021#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000022#include "clang/AST/DeclObjC.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000023#include "clang/AST/DeclOpenMP.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000024#include "clang/AST/DeclTemplate.h"
John McCallc62bb642010-03-24 05:22:00 +000025#include "clang/AST/DependentDiagnostic.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000026#include "clang/AST/ExternalASTSource.h"
Sebastian Redla7b98a72009-04-26 20:35:05 +000027#include "clang/AST/Stmt.h"
28#include "clang/AST/StmtCXX.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000029#include "clang/AST/Type.h"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000030#include "clang/Basic/TargetInfo.h"
Eli Friedman7dbab8a2008-06-07 16:52:53 +000031#include "llvm/ADT/DenseMap.h"
Chris Lattnereae6cb62009-03-05 08:00:35 +000032#include "llvm/Support/raw_ostream.h"
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000033#include <algorithm>
Eli Friedman7dbab8a2008-06-07 16:52:53 +000034using namespace clang;
35
36//===----------------------------------------------------------------------===//
37// Statistics
38//===----------------------------------------------------------------------===//
39
Alexis Hunted053252010-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 Friedman7dbab8a2008-06-07 16:52:53 +000043
Douglas Gregor7dab26b2013-02-09 01:35:03 +000044void Decl::updateOutOfDate(IdentifierInfo &II) const {
45 getASTContext().getExternalSource()->updateOutOfDateIdentifier(II);
46}
47
Douglas Gregor72172e92012-01-05 21:55:30 +000048void *Decl::AllocateDeserializedDecl(const ASTContext &Context,
49 unsigned ID,
50 unsigned Size) {
Douglas Gregor52261fd2012-01-05 23:49:36 +000051 // Allocate an extra 8 bytes worth of storage, which ensures that the
Douglas Gregorcfe7dc62012-01-09 17:30:44 +000052 // resulting pointer will still be 8-byte aligned.
Douglas Gregor52261fd2012-01-05 23:49:36 +000053 void *Start = Context.Allocate(Size + 8);
54 void *Result = (char*)Start + 8;
Douglas Gregor64af53c2012-01-05 22:27:05 +000055
Douglas Gregorcfe7dc62012-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 Gregor64af53c2012-01-05 22:27:05 +000063
64 return Result;
Douglas Gregor72172e92012-01-05 21:55:30 +000065}
66
Douglas Gregorc147b0b2013-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 Friedman7dbab8a2008-06-07 16:52:53 +000072const char *Decl::getDeclKindName() const {
73 switch (DeclKind) {
David Blaikie83d382b2011-09-23 05:06:16 +000074 default: llvm_unreachable("Declaration not in DeclNodes.inc!");
Alexis Hunted053252010-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 Friedman7dbab8a2008-06-07 16:52:53 +000078 }
79}
80
Douglas Gregor90d47172010-03-05 00:26:45 +000081void Decl::setInvalidDecl(bool Invalid) {
82 InvalidDecl = Invalid;
Argyrios Kyrtzidisb7d1ca22012-03-09 21:09:04 +000083 if (Invalid && !isa<ParmVarDecl>(this)) {
Douglas Gregor90d47172010-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 Naroff5faaef72009-01-20 19:53:53 +000091const char *DeclContext::getDeclKindName() const {
92 switch (DeclKind) {
David Blaikie83d382b2011-09-23 05:06:16 +000093 default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
Alexis Hunted053252010-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 Naroff5faaef72009-01-20 19:53:53 +000097 }
98}
99
Daniel Dunbar62905572012-03-05 21:42:49 +0000100bool Decl::StatisticsEnabled = false;
101void Decl::EnableStatistics() {
102 StatisticsEnabled = true;
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000103}
104
105void Decl::PrintStats() {
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000106 llvm::errs() << "\n*** Decl Stats:\n";
Mike Stump11289f42009-09-09 15:08:12 +0000107
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000108 int totalDecls = 0;
Alexis Hunted053252010-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 Carruthbfb154a2011-07-04 06:13:27 +0000112 llvm::errs() << " " << totalDecls << " decls total.\n";
Mike Stump11289f42009-09-09 15:08:12 +0000113
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000114 int totalBytes = 0;
Alexis Hunted053252010-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 Carruthbfb154a2011-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 Gregor8bd3c2e2009-02-02 23:39:07 +0000122 }
Alexis Hunted053252010-05-30 07:21:58 +0000123#define ABSTRACT_DECL(DECL)
124#include "clang/AST/DeclNodes.inc"
Mike Stump11289f42009-09-09 15:08:12 +0000125
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000126 llvm::errs() << "Total bytes = " << totalBytes << "\n";
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000127}
128
Alexis Hunted053252010-05-30 07:21:58 +0000129void Decl::add(Kind k) {
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000130 switch (k) {
Alexis Hunted053252010-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 Friedman7dbab8a2008-06-07 16:52:53 +0000134 }
135}
136
Anders Carlssonaa73b912009-06-13 00:08:58 +0000137bool Decl::isTemplateParameterPack() const {
138 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
139 return TTP->isParameterPack();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000140 if (const NonTypeTemplateParmDecl *NTTP
Douglas Gregorf5500772011-01-05 15:48:55 +0000141 = dyn_cast<NonTypeTemplateParmDecl>(this))
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000142 return NTTP->isParameterPack();
Douglas Gregorf5500772011-01-05 15:48:55 +0000143 if (const TemplateTemplateParmDecl *TTP
144 = dyn_cast<TemplateTemplateParmDecl>(this))
145 return TTP->isParameterPack();
Anders Carlssonaa73b912009-06-13 00:08:58 +0000146 return false;
147}
148
Douglas Gregor3c6bd2a2011-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 Gregorad3f2fc2009-06-25 22:08:12 +0000156bool Decl::isFunctionOrFunctionTemplate() const {
John McCall3f746822009-11-17 05:59:44 +0000157 if (const UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(this))
Anders Carlssonf057cb22009-06-26 05:26:50 +0000158 return UD->getTargetDecl()->isFunctionOrFunctionTemplate();
Mike Stump11289f42009-09-09 15:08:12 +0000159
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000160 return isa<FunctionDecl>(this) || isa<FunctionTemplateDecl>(this);
161}
162
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000163bool Decl::isTemplateDecl() const {
164 return isa<TemplateDecl>(this);
165}
166
Argyrios Kyrtzidis0ce4c9a2011-09-28 02:45:33 +0000167const DeclContext *Decl::getParentFunctionOrMethod() const {
168 for (const DeclContext *DC = getDeclContext();
169 DC && !DC->isTranslationUnit() && !DC->isNamespace();
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000170 DC = DC->getParent())
171 if (DC->isFunctionOrMethod())
Argyrios Kyrtzidis0ce4c9a2011-09-28 02:45:33 +0000172 return DC;
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000173
Argyrios Kyrtzidis0ce4c9a2011-09-28 02:45:33 +0000174 return 0;
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000175}
176
Douglas Gregor133eddd2011-02-17 08:47:29 +0000177
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000178//===----------------------------------------------------------------------===//
Chris Lattnereae6cb62009-03-05 08:00:35 +0000179// PrettyStackTraceDecl Implementation
180//===----------------------------------------------------------------------===//
Mike Stump11289f42009-09-09 15:08:12 +0000181
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000182void PrettyStackTraceDecl::print(raw_ostream &OS) const {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000183 SourceLocation TheLoc = Loc;
184 if (TheLoc.isInvalid() && TheDecl)
185 TheLoc = TheDecl->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000186
Chris Lattnereae6cb62009-03-05 08:00:35 +0000187 if (TheLoc.isValid()) {
188 TheLoc.print(OS, SM);
189 OS << ": ";
190 }
191
192 OS << Message;
193
Benjamin Kramer24ebf7c2013-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 Lattnereae6cb62009-03-05 08:00:35 +0000199 OS << '\n';
200}
Mike Stump11289f42009-09-09 15:08:12 +0000201
Chris Lattnereae6cb62009-03-05 08:00:35 +0000202//===----------------------------------------------------------------------===//
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000203// Decl Implementation
204//===----------------------------------------------------------------------===//
205
Douglas Gregorb11aad82011-02-19 18:51:44 +0000206// Out-of-line virtual method providing a home for Decl.
207Decl::~Decl() { }
Douglas Gregora43942a2011-02-17 07:02:32 +0000208
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000209void Decl::setDeclContext(DeclContext *DC) {
Chris Lattnerb81eb052009-03-29 06:06:59 +0000210 DeclCtx = DC;
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000211}
212
213void Decl::setLexicalDeclContext(DeclContext *DC) {
214 if (DC == getLexicalDeclContext())
215 return;
216
217 if (isInSemaDC()) {
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000218 setDeclContextsImpl(getDeclContext(), DC, getASTContext());
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000219 } else {
220 getMultipleDC()->LexicalDC = DC;
221 }
222}
223
Argyrios Kyrtzidis6f40eb72012-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 McCall4fa53422009-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 Kyrtzidis743e7db2009-06-29 17:38:40 +0000247TranslationUnitDecl *Decl::getTranslationUnitDecl() {
Argyrios Kyrtzidis4e1a72b2009-06-30 02:34:53 +0000248 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
249 return TUD;
250
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000251 DeclContext *DC = getDeclContext();
252 assert(DC && "This decl is not contained in a translation unit!");
Mike Stump11289f42009-09-09 15:08:12 +0000253
Argyrios Kyrtzidis743e7db2009-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 Stump11289f42009-09-09 15:08:12 +0000258
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000259 return cast<TranslationUnitDecl>(DC);
260}
261
262ASTContext &Decl::getASTContext() const {
Mike Stump11289f42009-09-09 15:08:12 +0000263 return getTranslationUnitDecl()->getASTContext();
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000264}
265
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +0000266ASTMutationListener *Decl::getASTMutationListener() const {
267 return getASTContext().getASTMutationListener();
268}
269
Benjamin Kramerea70eb32012-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 Gregorebada0772010-06-17 23:14:26 +0000283bool Decl::isUsed(bool CheckUsedAttr) const {
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000284 if (Used)
285 return true;
286
287 // Check for used attribute.
Douglas Gregorebada0772010-06-17 23:14:26 +0000288 if (CheckUsedAttr && hasAttr<UsedAttr>())
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000289 return true;
Rafael Espindola99e3bfb2012-11-23 16:26:30 +0000290
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000291 return false;
292}
293
Eli Friedman276dd182013-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 Kyrtzidis16180232011-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 Gregor20b2ebd2011-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 Gregore8bbc122011-09-02 00:18:52 +0000328 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000329 StringRef PrettyPlatformName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000330 = AvailabilityAttr::getPrettyPlatformName(TargetPlatform);
331 if (PrettyPlatformName.empty())
332 PrettyPlatformName = TargetPlatform;
333
Douglas Gregore8bbc122011-09-02 00:18:52 +0000334 VersionTuple TargetMinVersion = Context.getTargetInfo().getPlatformMinVersion();
Douglas Gregor20b2ebd2011-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 Jahanian88d510d2011-12-10 00:28:41 +0000341
342 std::string HintMessage;
343 if (!A->getMessage().empty()) {
344 HintMessage = " - ";
345 HintMessage += A->getMessage();
346 }
347
Douglas Gregor7ab142b2011-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 Jahanian88d510d2011-12-10 00:28:41 +0000353 Out << "not available on " << PrettyPlatformName
354 << HintMessage;
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000355 }
356
357 return AR_Unavailable;
358 }
359
Douglas Gregor20b2ebd2011-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 Jahanian88d510d2011-12-10 00:28:41 +0000367 << A->getIntroduced() << HintMessage;
Douglas Gregor20b2ebd2011-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 Jahanian88d510d2011-12-10 00:28:41 +0000379 << A->getObsoleted() << HintMessage;
Douglas Gregor20b2ebd2011-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 Jahanian88d510d2011-12-10 00:28:41 +0000391 << A->getDeprecated() << HintMessage;
Douglas Gregor20b2ebd2011-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 McCall5fb5df92012-06-20 06:18:46 +0000445
446 // Variables, if they aren't definitions.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000447 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000448 if (Var->isThisDeclarationADefinition()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000449 IsDefinition = true;
450 return false;
451 }
John McCall5fb5df92012-06-20 06:18:46 +0000452 return true;
453
454 // Functions, if they aren't definitions.
Douglas Gregor20b2ebd2011-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 McCall5fb5df92012-06-20 06:18:46 +0000460 return true;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000461
John McCall5fb5df92012-06-20 06:18:46 +0000462 // Objective-C classes, if this is the non-fragile runtime.
463 } else if (isa<ObjCInterfaceDecl>(this) &&
John McCall18ac1632012-06-20 21:58:02 +0000464 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
John McCall5fb5df92012-06-20 06:18:46 +0000465 return true;
466
467 // Nothing else.
468 } else {
469 return false;
470 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000471}
472
473bool Decl::isWeakImported() const {
474 bool IsDefinition;
475 if (!canBeWeakImported(IsDefinition))
476 return false;
477
Douglas Gregor20b2ebd2011-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 Lattner8aefcbe2010-02-17 02:17:21 +0000491
Chris Lattner8e097192009-03-27 20:18:19 +0000492unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
493 switch (DeclKind) {
John McCall3f746822009-11-17 05:59:44 +0000494 case Function:
495 case CXXMethod:
496 case CXXConstructor:
497 case CXXDestructor:
498 case CXXConversion:
Chris Lattner8e097192009-03-27 20:18:19 +0000499 case EnumConstant:
500 case Var:
501 case ImplicitParam:
502 case ParmVar:
Chris Lattner8e097192009-03-27 20:18:19 +0000503 case NonTypeTemplateParm:
504 case ObjCMethod:
Daniel Dunbar45b2d8a2010-04-23 13:07:39 +0000505 case ObjCProperty:
John McCall5e77d762013-04-16 07:28:30 +0000506 case MSProperty:
Daniel Dunbar45b2d8a2010-04-23 13:07:39 +0000507 return IDNS_Ordinary;
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000508 case Label:
509 return IDNS_Label;
Francois Pichet783dd6e2010-11-21 06:08:52 +0000510 case IndirectField:
511 return IDNS_Ordinary | IDNS_Member;
512
John McCalle87beb22010-04-23 18:46:30 +0000513 case ObjCCompatibleAlias:
514 case ObjCInterface:
515 return IDNS_Ordinary | IDNS_Type;
516
517 case Typedef:
Richard Smithdda56e42011-04-15 14:24:37 +0000518 case TypeAlias:
Richard Smith3f1b5d02011-05-05 21:57:07 +0000519 case TypeAliasTemplate:
John McCalle87beb22010-04-23 18:46:30 +0000520 case UnresolvedUsingTypename:
521 case TemplateTypeParm:
522 return IDNS_Ordinary | IDNS_Type;
523
John McCall3f746822009-11-17 05:59:44 +0000524 case UsingShadow:
525 return 0; // we'll actually overwrite this later
526
John McCalle61f2ba2009-11-18 02:36:19 +0000527 case UnresolvedUsingValue:
John McCalle61f2ba2009-11-18 02:36:19 +0000528 return IDNS_Ordinary | IDNS_Using;
John McCall3f746822009-11-17 05:59:44 +0000529
530 case Using:
531 return IDNS_Using;
532
Chris Lattner8e097192009-03-27 20:18:19 +0000533 case ObjCProtocol:
Douglas Gregor79947a22009-04-24 00:11:27 +0000534 return IDNS_ObjCProtocol;
Mike Stump11289f42009-09-09 15:08:12 +0000535
Chris Lattner8e097192009-03-27 20:18:19 +0000536 case Field:
537 case ObjCAtDefsField:
538 case ObjCIvar:
539 return IDNS_Member;
Mike Stump11289f42009-09-09 15:08:12 +0000540
Chris Lattner8e097192009-03-27 20:18:19 +0000541 case Record:
542 case CXXRecord:
543 case Enum:
John McCalle87beb22010-04-23 18:46:30 +0000544 return IDNS_Tag | IDNS_Type;
Mike Stump11289f42009-09-09 15:08:12 +0000545
Chris Lattner8e097192009-03-27 20:18:19 +0000546 case Namespace:
John McCalle87beb22010-04-23 18:46:30 +0000547 case NamespaceAlias:
548 return IDNS_Namespace;
549
Chris Lattner8e097192009-03-27 20:18:19 +0000550 case FunctionTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +0000551 case VarTemplate:
John McCalle87beb22010-04-23 18:46:30 +0000552 return IDNS_Ordinary;
553
Chris Lattner8e097192009-03-27 20:18:19 +0000554 case ClassTemplate:
555 case TemplateTemplateParm:
John McCalle87beb22010-04-23 18:46:30 +0000556 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
Mike Stump11289f42009-09-09 15:08:12 +0000557
Chris Lattner8e097192009-03-27 20:18:19 +0000558 // Never have names.
John McCallaa74a0c2009-08-28 07:59:38 +0000559 case Friend:
John McCall11083da2009-09-16 22:47:08 +0000560 case FriendTemplate:
Abramo Bagnarad7340582010-06-05 05:09:32 +0000561 case AccessSpec:
Chris Lattner8e097192009-03-27 20:18:19 +0000562 case LinkageSpec:
563 case FileScopeAsm:
564 case StaticAssert:
Chris Lattner8e097192009-03-27 20:18:19 +0000565 case ObjCPropertyImpl:
Chris Lattner8e097192009-03-27 20:18:19 +0000566 case Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +0000567 case Captured:
Chris Lattner8e097192009-03-27 20:18:19 +0000568 case TranslationUnit:
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000569
Chris Lattner8e097192009-03-27 20:18:19 +0000570 case UsingDirective:
571 case ClassTemplateSpecialization:
Douglas Gregor2373c592009-05-31 09:31:02 +0000572 case ClassTemplatePartialSpecialization:
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000573 case ClassScopeFunctionSpecialization:
Larisse Voufo39a1e502013-08-06 01:03:05 +0000574 case VarTemplateSpecialization:
575 case VarTemplatePartialSpecialization:
Douglas Gregore93525e2010-04-22 23:19:50 +0000576 case ObjCImplementation:
577 case ObjCCategory:
578 case ObjCCategoryImpl:
Douglas Gregorba345522011-12-02 23:23:56 +0000579 case Import:
Alexey Bataeva769e072013-03-22 06:34:35 +0000580 case OMPThreadPrivate:
Michael Han84324352013-02-22 17:15:32 +0000581 case Empty:
Douglas Gregore93525e2010-04-22 23:19:50 +0000582 // Never looked up by name.
Chris Lattner8e097192009-03-27 20:18:19 +0000583 return 0;
584 }
John McCall3f746822009-11-17 05:59:44 +0000585
David Blaikiee4d798f2012-01-20 21:50:17 +0000586 llvm_unreachable("Invalid DeclKind!");
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000587}
588
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000589void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
Argyrios Kyrtzidis91167172010-06-11 23:09:25 +0000590 assert(!HasAttrs && "Decl already contains attrs.");
591
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000592 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000593 assert(AttrBlank.empty() && "HasAttrs was wrong?");
Argyrios Kyrtzidis91167172010-06-11 23:09:25 +0000594
595 AttrBlank = attrs;
596 HasAttrs = true;
597}
598
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000599void Decl::dropAttrs() {
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000600 if (!HasAttrs) return;
Mike Stump11289f42009-09-09 15:08:12 +0000601
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000602 HasAttrs = false;
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000603 getASTContext().eraseDeclAttrs(this);
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000604}
605
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000606const AttrVec &Decl::getAttrs() const {
607 assert(HasAttrs && "No attrs to get!");
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000608 return getASTContext().getDeclAttrs(this);
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000609}
610
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000611Decl *Decl::castFromDeclContext (const DeclContext *D) {
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000612 Decl::Kind DK = D->getDeclKind();
613 switch(DK) {
Alexis Hunted053252010-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 Kyrtzidisafe24c82009-02-16 14:29:28 +0000620 default:
Alexis Hunted053252010-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 Blaikie83d382b2011-09-23 05:06:16 +0000626 llvm_unreachable("a decl that inherits DeclContext isn't handled");
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000627 }
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000628}
629
630DeclContext *Decl::castToDeclContext(const Decl *D) {
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000631 Decl::Kind DK = D->getKind();
632 switch(DK) {
Alexis Hunted053252010-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 Kyrtzidisafe24c82009-02-16 14:29:28 +0000639 default:
Alexis Hunted053252010-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 Blaikie83d382b2011-09-23 05:06:16 +0000645 llvm_unreachable("a decl that inherits DeclContext isn't handled");
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000646 }
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000647}
648
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000649SourceLocation Decl::getBodyRBrace() const {
Argyrios Kyrtzidis36ea3222010-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 Kyrtzidis6fbc8fa2010-07-07 11:31:27 +0000659 if (Stmt *Body = getBody())
660 return Body->getSourceRange().getEnd();
661
662 return SourceLocation();
Sebastian Redla7b98a72009-04-26 20:35:05 +0000663}
664
Anders Carlssona28908d2009-03-25 23:38:06 +0000665void Decl::CheckAccessDeclContext() const {
Douglas Gregor4b00d3b2010-12-02 00:22:25 +0000666#ifndef NDEBUG
John McCall401982f2010-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 Kyrtzidise1778632010-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 Carlssonadf36b22009-08-29 20:47:47 +0000674 if (isa<TranslationUnitDecl>(this) ||
Argyrios Kyrtzidisa45855f2010-07-02 11:55:44 +0000675 isa<TemplateTypeParmDecl>(this) ||
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000676 isa<NonTypeTemplateParmDecl>(this) ||
Douglas Gregor2b76dd92010-02-22 17:53:38 +0000677 !isa<CXXRecordDecl>(getDeclContext()) ||
Argyrios Kyrtzidis260b4a82010-09-08 21:32:35 +0000678 isInvalidDecl() ||
679 isa<StaticAssertDecl>(this) ||
680 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
681 // as DeclContext (?).
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000682 isa<ParmVarDecl>(this) ||
683 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
684 // AS_none as access specifier.
Francois Pichet09af8c32011-08-17 01:06:54 +0000685 isa<CXXRecordDecl>(this) ||
686 isa<ClassScopeFunctionSpecializationDecl>(this))
Anders Carlssonadf36b22009-08-29 20:47:47 +0000687 return;
Mike Stump11289f42009-09-09 15:08:12 +0000688
689 assert(Access != AS_none &&
Anders Carlssona28908d2009-03-25 23:38:06 +0000690 "Access specifier is AS_none inside a record decl");
Douglas Gregor4b00d3b2010-12-02 00:22:25 +0000691#endif
Anders Carlssona28908d2009-03-25 23:38:06 +0000692}
693
John McCalldec348f72013-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 McCall55c0cee2013-05-03 17:11:14 +0000702 if (MD->getOverloadedOperator() == OO_Call &&
703 MD->getParent()->isLambda())
John McCalldec348f72013-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 McCallfe96e0b2011-11-06 09:01:30 +0000717}
718
John McCalldec348f72013-05-03 07:33:41 +0000719Decl *Decl::getNonClosureContext() {
720 return ::getNonClosureContext(this);
721}
John McCallb67608f2011-02-22 22:25:23 +0000722
John McCalldec348f72013-05-03 07:33:41 +0000723Decl *DeclContext::getNonClosureAncestor() {
724 return ::getNonClosureContext(this);
John McCallb67608f2011-02-22 22:25:23 +0000725}
Anders Carlssona28908d2009-03-25 23:38:06 +0000726
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000727//===----------------------------------------------------------------------===//
728// DeclContext Implementation
729//===----------------------------------------------------------------------===//
730
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000731bool DeclContext::classof(const Decl *D) {
732 switch (D->getKind()) {
Alexis Hunted053252010-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 Kyrtzidisafe24c82009-02-16 14:29:28 +0000737 return true;
738 default:
Alexis Hunted053252010-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 Kyrtzidisafe24c82009-02-16 14:29:28 +0000743 return true;
Alexis Hunted053252010-05-30 07:21:58 +0000744#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000745 return false;
746 }
747}
748
Douglas Gregor9c832f72010-07-25 18:38:02 +0000749DeclContext::~DeclContext() { }
Douglas Gregor91f84212008-12-11 16:49:14 +0000750
Douglas Gregor7f737c02009-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 Redl50c68252010-08-31 00:36:30 +0000760 if (getParent()->getRedeclContext()->isFileContext() &&
761 getLexicalParent()->getRedeclContext()->isRecord())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000762 return getLexicalParent();
763
764 return getParent();
765}
766
Sebastian Redlbd595762010-08-31 20:53:31 +0000767bool DeclContext::isInlineNamespace() const {
768 return isNamespace() &&
769 cast<NamespaceDecl>(this)->isInline();
770}
771
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000772bool DeclContext::isDependentContext() const {
773 if (isFileContext())
774 return false;
775
Douglas Gregor2373c592009-05-31 09:31:02 +0000776 if (isa<ClassTemplatePartialSpecializationDecl>(this))
777 return true;
778
Douglas Gregor680e9e02012-02-21 19:11:17 +0000779 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000780 if (Record->getDescribedClassTemplate())
781 return true;
Douglas Gregor680e9e02012-02-21 19:11:17 +0000782
783 if (Record->isDependentLambda())
784 return true;
785 }
786
John McCallc62bb642010-03-24 05:22:00 +0000787 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000788 if (Function->getDescribedFunctionTemplate())
789 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000790
John McCallc62bb642010-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 Gregor9e927ab2009-05-28 16:34:51 +0000797 return getParent() && getParent()->isDependentContext();
798}
799
Douglas Gregor07665a62009-01-05 19:45:36 +0000800bool DeclContext::isTransparentContext() const {
801 if (DeclKind == Decl::Enum)
Douglas Gregor0bf31402010-10-08 23:50:27 +0000802 return !cast<EnumDecl>(this)->isScoped();
Douglas Gregor07665a62009-01-05 19:45:36 +0000803 else if (DeclKind == Decl::LinkageSpec)
804 return true;
Douglas Gregor07665a62009-01-05 19:45:36 +0000805
806 return false;
807}
808
Serge Pavlov3cb80222013-11-14 02:13:03 +0000809static bool isLinkageSpecContext(const DeclContext *DC,
810 LinkageSpecDecl::LanguageIDs ID) {
811 while (DC->getDeclKind() != Decl::TranslationUnit) {
812 if (DC->getDeclKind() == Decl::LinkageSpec)
813 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
814 DC = DC->getParent();
815 }
816 return false;
817}
818
819bool DeclContext::isExternCContext() const {
820 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_c);
821}
822
823bool DeclContext::isExternCXXContext() const {
824 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_cxx);
825}
826
Sebastian Redl50c68252010-08-31 00:36:30 +0000827bool DeclContext::Encloses(const DeclContext *DC) const {
Douglas Gregore985a3b2009-08-27 06:03:53 +0000828 if (getPrimaryContext() != this)
829 return getPrimaryContext()->Encloses(DC);
Mike Stump11289f42009-09-09 15:08:12 +0000830
Douglas Gregore985a3b2009-08-27 06:03:53 +0000831 for (; DC; DC = DC->getParent())
832 if (DC->getPrimaryContext() == this)
833 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000834 return false;
Douglas Gregore985a3b2009-08-27 06:03:53 +0000835}
836
Steve Naroff35c62ae2009-01-08 17:28:14 +0000837DeclContext *DeclContext::getPrimaryContext() {
Douglas Gregor91f84212008-12-11 16:49:14 +0000838 switch (DeclKind) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000839 case Decl::TranslationUnit:
Douglas Gregor07665a62009-01-05 19:45:36 +0000840 case Decl::LinkageSpec:
Mike Stump11289f42009-09-09 15:08:12 +0000841 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +0000842 case Decl::Captured:
Douglas Gregor91f84212008-12-11 16:49:14 +0000843 // There is only one DeclContext for these entities.
844 return this;
845
846 case Decl::Namespace:
847 // The original namespace is our primary context.
848 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
849
Douglas Gregor91f84212008-12-11 16:49:14 +0000850 case Decl::ObjCMethod:
851 return this;
852
853 case Decl::ObjCInterface:
Douglas Gregor66b310c2011-12-15 18:03:09 +0000854 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
855 return Def;
856
857 return this;
858
Steve Naroff35c62ae2009-01-08 17:28:14 +0000859 case Decl::ObjCProtocol:
Douglas Gregora715bff2012-01-01 19:51:50 +0000860 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
861 return Def;
862
863 return this;
Douglas Gregor66b310c2011-12-15 18:03:09 +0000864
Steve Naroff35c62ae2009-01-08 17:28:14 +0000865 case Decl::ObjCCategory:
Douglas Gregor91f84212008-12-11 16:49:14 +0000866 return this;
867
Steve Naroff35c62ae2009-01-08 17:28:14 +0000868 case Decl::ObjCImplementation:
869 case Decl::ObjCCategoryImpl:
870 return this;
871
Douglas Gregor91f84212008-12-11 16:49:14 +0000872 default:
Alexis Hunted053252010-05-30 07:21:58 +0000873 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
Douglas Gregor67a65642009-02-17 23:15:12 +0000874 // If this is a tag type that has a definition or is currently
875 // being defined, that definition is our primary context.
John McCalle78aac42010-03-10 03:28:59 +0000876 TagDecl *Tag = cast<TagDecl>(this);
877 assert(isa<TagType>(Tag->TypeForDecl) ||
878 isa<InjectedClassNameType>(Tag->TypeForDecl));
879
880 if (TagDecl *Def = Tag->getDefinition())
881 return Def;
882
883 if (!isa<InjectedClassNameType>(Tag->TypeForDecl)) {
884 const TagType *TagTy = cast<TagType>(Tag->TypeForDecl);
885 if (TagTy->isBeingDefined())
886 // FIXME: is it necessarily being defined in the decl
887 // that owns the type?
888 return TagTy->getDecl();
889 }
890
891 return Tag;
Douglas Gregor67a65642009-02-17 23:15:12 +0000892 }
893
Alexis Hunted053252010-05-30 07:21:58 +0000894 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
Douglas Gregor91f84212008-12-11 16:49:14 +0000895 "Unknown DeclContext kind");
896 return this;
897 }
898}
899
Douglas Gregore57e7522012-01-07 09:11:48 +0000900void
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000901DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
Douglas Gregore57e7522012-01-07 09:11:48 +0000902 Contexts.clear();
903
904 if (DeclKind != Decl::Namespace) {
905 Contexts.push_back(this);
906 return;
Douglas Gregor91f84212008-12-11 16:49:14 +0000907 }
Douglas Gregore57e7522012-01-07 09:11:48 +0000908
909 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
Douglas Gregorec9fd132012-01-14 16:38:05 +0000910 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
911 N = N->getPreviousDecl())
Douglas Gregore57e7522012-01-07 09:11:48 +0000912 Contexts.push_back(N);
913
914 std::reverse(Contexts.begin(), Contexts.end());
Douglas Gregor91f84212008-12-11 16:49:14 +0000915}
916
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000917std::pair<Decl *, Decl *>
Bill Wendling8eb771d2012-02-22 09:51:33 +0000918DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +0000919 bool FieldsAlreadyLoaded) {
Douglas Gregor781f7132012-01-06 16:59:53 +0000920 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000921 Decl *FirstNewDecl = 0;
922 Decl *PrevDecl = 0;
923 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +0000924 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
925 continue;
926
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000927 Decl *D = Decls[I];
928 if (PrevDecl)
Douglas Gregor781f7132012-01-06 16:59:53 +0000929 PrevDecl->NextInContextAndBits.setPointer(D);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000930 else
931 FirstNewDecl = D;
932
933 PrevDecl = D;
934 }
935
936 return std::make_pair(FirstNewDecl, PrevDecl);
937}
938
Richard Smith645d7552013-02-07 03:37:08 +0000939/// \brief We have just acquired external visible storage, and we already have
940/// built a lookup map. For every name in the map, pull in the new names from
941/// the external storage.
942void DeclContext::reconcileExternalVisibleStorage() {
Richard Smith86a12012013-02-11 22:02:16 +0000943 assert(NeedToReconcileExternalVisibleStorage && LookupPtr.getPointer());
Richard Smith645d7552013-02-07 03:37:08 +0000944 NeedToReconcileExternalVisibleStorage = false;
945
946 StoredDeclsMap &Map = *LookupPtr.getPointer();
Richard Smith4abe0a82013-09-09 07:34:56 +0000947 for (StoredDeclsMap::iterator I = Map.begin(); I != Map.end(); ++I)
948 I->second.setHasExternalDecls();
Richard Smith645d7552013-02-07 03:37:08 +0000949}
950
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000951/// \brief Load the declarations within this lexical storage from an
952/// external source.
Mike Stump11289f42009-09-09 15:08:12 +0000953void
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000954DeclContext::LoadLexicalDeclsFromExternalStorage() const {
955 ExternalASTSource *Source = getParentASTContext().getExternalSource();
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000956 assert(hasExternalLexicalStorage() && Source && "No external storage?");
957
Argyrios Kyrtzidis98d045e2010-07-30 10:03:23 +0000958 // Notify that we have a DeclContext that is initializing.
959 ExternalASTSource::Deserializing ADeclContext(Source);
Douglas Gregorf337ae92011-08-26 21:23:06 +0000960
Douglas Gregor3d0adb32011-07-15 21:46:17 +0000961 // Load the external declarations, if any.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000962 SmallVector<Decl*, 64> Decls;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000963 ExternalLexicalStorage = false;
Douglas Gregor3d0adb32011-07-15 21:46:17 +0000964 switch (Source->FindExternalLexicalDecls(this, Decls)) {
965 case ELR_Success:
966 break;
967
968 case ELR_Failure:
969 case ELR_AlreadyLoaded:
970 return;
971 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000972
973 if (Decls.empty())
974 return;
975
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +0000976 // We may have already loaded just the fields of this record, in which case
977 // we need to ignore them.
978 bool FieldsAlreadyLoaded = false;
979 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
980 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
981
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000982 // Splice the newly-read declarations into the beginning of the list
983 // of declarations.
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000984 Decl *ExternalFirst, *ExternalLast;
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +0000985 llvm::tie(ExternalFirst, ExternalLast) = BuildDeclChain(Decls,
986 FieldsAlreadyLoaded);
Douglas Gregor781f7132012-01-06 16:59:53 +0000987 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000988 FirstDecl = ExternalFirst;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000989 if (!LastDecl)
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000990 LastDecl = ExternalLast;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000991}
992
John McCall75b960e2010-06-01 09:23:16 +0000993DeclContext::lookup_result
994ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
995 DeclarationName Name) {
996 ASTContext &Context = DC->getParentASTContext();
997 StoredDeclsMap *Map;
Richard Smithf634c902012-03-16 06:12:59 +0000998 if (!(Map = DC->LookupPtr.getPointer()))
John McCall75b960e2010-06-01 09:23:16 +0000999 Map = DC->CreateStoredDeclsMap(Context);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001000
Richard Smith4abe0a82013-09-09 07:34:56 +00001001 (*Map)[Name].removeExternalDecls();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001002
John McCall75b960e2010-06-01 09:23:16 +00001003 return DeclContext::lookup_result();
1004}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001005
John McCall75b960e2010-06-01 09:23:16 +00001006DeclContext::lookup_result
1007ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
John McCall75b960e2010-06-01 09:23:16 +00001008 DeclarationName Name,
Argyrios Kyrtzidis94d3f9d2011-09-09 06:44:14 +00001009 ArrayRef<NamedDecl*> Decls) {
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00001010 ASTContext &Context = DC->getParentASTContext();
John McCall75b960e2010-06-01 09:23:16 +00001011 StoredDeclsMap *Map;
Richard Smithf634c902012-03-16 06:12:59 +00001012 if (!(Map = DC->LookupPtr.getPointer()))
John McCall75b960e2010-06-01 09:23:16 +00001013 Map = DC->CreateStoredDeclsMap(Context);
1014
1015 StoredDeclsList &List = (*Map)[Name];
Richard Smith51445cd2013-06-24 01:46:41 +00001016
1017 // Clear out any old external visible declarations, to avoid quadratic
1018 // performance in the redeclaration checks below.
1019 List.removeExternalDecls();
1020
1021 if (!List.isNull()) {
1022 // We have both existing declarations and new declarations for this name.
1023 // Some of the declarations may simply replace existing ones. Handle those
1024 // first.
1025 llvm::SmallVector<unsigned, 8> Skip;
1026 for (unsigned I = 0, N = Decls.size(); I != N; ++I)
1027 if (List.HandleRedeclaration(Decls[I]))
1028 Skip.push_back(I);
1029 Skip.push_back(Decls.size());
1030
1031 // Add in any new declarations.
1032 unsigned SkipPos = 0;
1033 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1034 if (I == Skip[SkipPos])
1035 ++SkipPos;
1036 else
1037 List.AddSubsequentDecl(Decls[I]);
1038 }
1039 } else {
1040 // Convert the array to a StoredDeclsList.
1041 for (ArrayRef<NamedDecl*>::iterator
1042 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1043 if (List.isNull())
1044 List.setOnlyValue(*I);
1045 else
1046 List.AddSubsequentDecl(*I);
1047 }
John McCall75b960e2010-06-01 09:23:16 +00001048 }
1049
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001050 return List.getLookupResult();
John McCall75b960e2010-06-01 09:23:16 +00001051}
1052
Sebastian Redl66c5eef2010-07-27 00:17:23 +00001053DeclContext::decl_iterator DeclContext::noload_decls_begin() const {
1054 return decl_iterator(FirstDecl);
1055}
1056
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001057DeclContext::decl_iterator DeclContext::decls_begin() const {
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001058 if (hasExternalLexicalStorage())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001059 LoadLexicalDeclsFromExternalStorage();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001060
Mike Stump11289f42009-09-09 15:08:12 +00001061 return decl_iterator(FirstDecl);
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001062}
1063
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001064bool DeclContext::decls_empty() const {
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001065 if (hasExternalLexicalStorage())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001066 LoadLexicalDeclsFromExternalStorage();
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001067
1068 return !FirstDecl;
1069}
1070
Sean Callanan0325fb82013-05-04 02:04:27 +00001071bool DeclContext::containsDecl(Decl *D) const {
1072 return (D->getLexicalDeclContext() == this &&
1073 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1074}
1075
John McCall84d87672009-12-10 09:41:52 +00001076void DeclContext::removeDecl(Decl *D) {
1077 assert(D->getLexicalDeclContext() == this &&
1078 "decl being removed from non-lexical context");
Douglas Gregor781f7132012-01-06 16:59:53 +00001079 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
John McCall84d87672009-12-10 09:41:52 +00001080 "decl is not in decls list");
1081
1082 // Remove D from the decl chain. This is O(n) but hopefully rare.
1083 if (D == FirstDecl) {
1084 if (D == LastDecl)
1085 FirstDecl = LastDecl = 0;
1086 else
Douglas Gregor781f7132012-01-06 16:59:53 +00001087 FirstDecl = D->NextInContextAndBits.getPointer();
John McCall84d87672009-12-10 09:41:52 +00001088 } else {
Douglas Gregor781f7132012-01-06 16:59:53 +00001089 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
John McCall84d87672009-12-10 09:41:52 +00001090 assert(I && "decl not found in linked list");
Douglas Gregor781f7132012-01-06 16:59:53 +00001091 if (I->NextInContextAndBits.getPointer() == D) {
1092 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
John McCall84d87672009-12-10 09:41:52 +00001093 if (D == LastDecl) LastDecl = I;
1094 break;
1095 }
1096 }
1097 }
1098
1099 // Mark that D is no longer in the decl chain.
Douglas Gregor781f7132012-01-06 16:59:53 +00001100 D->NextInContextAndBits.setPointer(0);
John McCall84d87672009-12-10 09:41:52 +00001101
1102 // Remove D from the lookup table if necessary.
1103 if (isa<NamedDecl>(D)) {
1104 NamedDecl *ND = cast<NamedDecl>(D);
1105
Axel Naumanncb2c52f2011-08-26 14:06:12 +00001106 // Remove only decls that have a name
1107 if (!ND->getDeclName()) return;
1108
Richard Smithf634c902012-03-16 06:12:59 +00001109 StoredDeclsMap *Map = getPrimaryContext()->LookupPtr.getPointer();
John McCallc62bb642010-03-24 05:22:00 +00001110 if (!Map) return;
John McCall84d87672009-12-10 09:41:52 +00001111
John McCall84d87672009-12-10 09:41:52 +00001112 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1113 assert(Pos != Map->end() && "no lookup entry for decl");
Axel Naumannfbc7b982011-11-08 18:21:06 +00001114 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1115 Pos->second.remove(ND);
John McCall84d87672009-12-10 09:41:52 +00001116 }
1117}
1118
John McCalld1e9d832009-08-11 06:59:38 +00001119void DeclContext::addHiddenDecl(Decl *D) {
Chris Lattner33f219d2009-02-20 00:56:18 +00001120 assert(D->getLexicalDeclContext() == this &&
1121 "Decl inserted into wrong lexical context");
Mike Stump11289f42009-09-09 15:08:12 +00001122 assert(!D->getNextDeclInContext() && D != LastDecl &&
Douglas Gregor020713e2009-01-09 19:42:16 +00001123 "Decl already inserted into a DeclContext");
1124
1125 if (FirstDecl) {
Douglas Gregor781f7132012-01-06 16:59:53 +00001126 LastDecl->NextInContextAndBits.setPointer(D);
Douglas Gregor020713e2009-01-09 19:42:16 +00001127 LastDecl = D;
1128 } else {
1129 FirstDecl = LastDecl = D;
1130 }
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001131
1132 // Notify a C++ record declaration that we've added a member, so it can
1133 // update it's class-specific state.
1134 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1135 Record->addedMember(D);
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001136
1137 // If this is a newly-created (not de-serialized) import declaration, wire
1138 // it in to the list of local import declarations.
1139 if (!D->isFromASTFile()) {
1140 if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1141 D->getASTContext().addedLocalImportDecl(Import);
1142 }
John McCalld1e9d832009-08-11 06:59:38 +00001143}
1144
1145void DeclContext::addDecl(Decl *D) {
1146 addHiddenDecl(D);
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001147
1148 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithf634c902012-03-16 06:12:59 +00001149 ND->getDeclContext()->getPrimaryContext()->
1150 makeDeclVisibleInContextWithFlags(ND, false, true);
Douglas Gregor91f84212008-12-11 16:49:14 +00001151}
1152
Sean Callanan95e74be2011-10-21 02:57:43 +00001153void DeclContext::addDeclInternal(Decl *D) {
1154 addHiddenDecl(D);
1155
1156 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithf634c902012-03-16 06:12:59 +00001157 ND->getDeclContext()->getPrimaryContext()->
1158 makeDeclVisibleInContextWithFlags(ND, true, true);
1159}
1160
1161/// shouldBeHidden - Determine whether a declaration which was declared
1162/// within its semantic context should be invisible to qualified name lookup.
1163static bool shouldBeHidden(NamedDecl *D) {
1164 // Skip unnamed declarations.
1165 if (!D->getDeclName())
1166 return true;
1167
1168 // Skip entities that can't be found by name lookup into a particular
1169 // context.
1170 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1171 D->isTemplateParameter())
1172 return true;
1173
1174 // Skip template specializations.
1175 // FIXME: This feels like a hack. Should DeclarationName support
1176 // template-ids, or is there a better way to keep specializations
1177 // from being visible?
1178 if (isa<ClassTemplateSpecializationDecl>(D))
1179 return true;
1180 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1181 if (FD->isFunctionTemplateSpecialization())
1182 return true;
1183
1184 return false;
1185}
1186
1187/// buildLookup - Build the lookup data structure with all of the
1188/// declarations in this DeclContext (and any other contexts linked
1189/// to it or transparent contexts nested within it) and return it.
1190StoredDeclsMap *DeclContext::buildLookup() {
1191 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1192
Richard Smith86a12012013-02-11 22:02:16 +00001193 // FIXME: Should we keep going if hasExternalVisibleStorage?
Richard Smithf634c902012-03-16 06:12:59 +00001194 if (!LookupPtr.getInt())
1195 return LookupPtr.getPointer();
1196
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001197 SmallVector<DeclContext *, 2> Contexts;
Richard Smithf634c902012-03-16 06:12:59 +00001198 collectAllContexts(Contexts);
1199 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
Richard Smith95d99302013-07-13 02:00:19 +00001200 buildLookupImpl<&DeclContext::decls_begin,
1201 &DeclContext::decls_end>(Contexts[I]);
Richard Smithf634c902012-03-16 06:12:59 +00001202
1203 // We no longer have any lazy decls.
1204 LookupPtr.setInt(false);
Richard Smith86a12012013-02-11 22:02:16 +00001205 NeedToReconcileExternalVisibleStorage = false;
Richard Smithf634c902012-03-16 06:12:59 +00001206 return LookupPtr.getPointer();
1207}
1208
1209/// buildLookupImpl - Build part of the lookup data structure for the
1210/// declarations contained within DCtx, which will either be this
1211/// DeclContext, a DeclContext linked to it, or a transparent context
1212/// nested within it.
Richard Smith95d99302013-07-13 02:00:19 +00001213template<DeclContext::decl_iterator (DeclContext::*Begin)() const,
1214 DeclContext::decl_iterator (DeclContext::*End)() const>
Richard Smithf634c902012-03-16 06:12:59 +00001215void DeclContext::buildLookupImpl(DeclContext *DCtx) {
Richard Smith95d99302013-07-13 02:00:19 +00001216 for (decl_iterator I = (DCtx->*Begin)(), E = (DCtx->*End)();
Richard Smithf634c902012-03-16 06:12:59 +00001217 I != E; ++I) {
1218 Decl *D = *I;
1219
1220 // Insert this declaration into the lookup structure, but only if
1221 // it's semantically within its decl context. Any other decls which
1222 // should be found in this context are added eagerly.
Richard Smithcf4ab522013-06-24 07:20:36 +00001223 //
1224 // If it's from an AST file, don't add it now. It'll get handled by
1225 // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1226 // in C++, we do not track external visible decls for the TU, so in
1227 // that case we need to collect them all here.
Richard Smithf634c902012-03-16 06:12:59 +00001228 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithcf4ab522013-06-24 07:20:36 +00001229 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1230 (!ND->isFromASTFile() ||
1231 (isTranslationUnit() &&
1232 !getParentASTContext().getLangOpts().CPlusPlus)))
Richard Smithf634c902012-03-16 06:12:59 +00001233 makeDeclVisibleInContextImpl(ND, false);
1234
1235 // If this declaration is itself a transparent declaration context
1236 // or inline namespace, add the members of this declaration of that
1237 // context (recursively).
1238 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1239 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Richard Smith95d99302013-07-13 02:00:19 +00001240 buildLookupImpl<Begin, End>(InnerCtx);
Richard Smithf634c902012-03-16 06:12:59 +00001241 }
Sean Callanan95e74be2011-10-21 02:57:43 +00001242}
1243
Mike Stump11289f42009-09-09 15:08:12 +00001244DeclContext::lookup_result
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001245DeclContext::lookup(DeclarationName Name) {
Nick Lewycky2bd636f2012-03-13 04:12:34 +00001246 assert(DeclKind != Decl::LinkageSpec &&
1247 "Should not perform lookups into linkage specs!");
1248
Steve Naroff35c62ae2009-01-08 17:28:14 +00001249 DeclContext *PrimaryContext = getPrimaryContext();
Douglas Gregor91f84212008-12-11 16:49:14 +00001250 if (PrimaryContext != this)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001251 return PrimaryContext->lookup(Name);
Douglas Gregor91f84212008-12-11 16:49:14 +00001252
Richard Smith05afe5e2012-03-13 03:12:56 +00001253 if (hasExternalVisibleStorage()) {
Richard Smith645d7552013-02-07 03:37:08 +00001254 StoredDeclsMap *Map = LookupPtr.getPointer();
1255 if (LookupPtr.getInt())
1256 Map = buildLookup();
Richard Smith86a12012013-02-11 22:02:16 +00001257 else if (NeedToReconcileExternalVisibleStorage)
1258 reconcileExternalVisibleStorage();
Richard Smith645d7552013-02-07 03:37:08 +00001259
Richard Smith75fc3bf2013-02-08 00:37:45 +00001260 if (!Map)
1261 Map = CreateStoredDeclsMap(getParentASTContext());
1262
Richard Smith4abe0a82013-09-09 07:34:56 +00001263 // If we have a lookup result with no external decls, we are done.
Richard Smith75fc3bf2013-02-08 00:37:45 +00001264 std::pair<StoredDeclsMap::iterator, bool> R =
1265 Map->insert(std::make_pair(Name, StoredDeclsList()));
Richard Smith4abe0a82013-09-09 07:34:56 +00001266 if (!R.second && !R.first->second.hasExternalDecls())
Richard Smith75fc3bf2013-02-08 00:37:45 +00001267 return R.first->second.getLookupResult();
Richard Smithf634c902012-03-16 06:12:59 +00001268
John McCall75b960e2010-06-01 09:23:16 +00001269 ExternalASTSource *Source = getParentASTContext().getExternalSource();
Richard Smith4abe0a82013-09-09 07:34:56 +00001270 if (Source->FindExternalVisibleDeclsByName(this, Name) || R.second) {
Richard Smith9ce12e32013-02-07 03:30:24 +00001271 if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
1272 StoredDeclsMap::iterator I = Map->find(Name);
1273 if (I != Map->end())
1274 return I->second.getLookupResult();
1275 }
1276 }
1277
1278 return lookup_result(lookup_iterator(0), lookup_iterator(0));
John McCall75b960e2010-06-01 09:23:16 +00001279 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001280
Richard Smithf634c902012-03-16 06:12:59 +00001281 StoredDeclsMap *Map = LookupPtr.getPointer();
1282 if (LookupPtr.getInt())
1283 Map = buildLookup();
1284
1285 if (!Map)
1286 return lookup_result(lookup_iterator(0), lookup_iterator(0));
1287
1288 StoredDeclsMap::iterator I = Map->find(Name);
1289 if (I == Map->end())
1290 return lookup_result(lookup_iterator(0), lookup_iterator(0));
1291
1292 return I->second.getLookupResult();
Douglas Gregor91f84212008-12-11 16:49:14 +00001293}
1294
Richard Smith95d99302013-07-13 02:00:19 +00001295DeclContext::lookup_result
1296DeclContext::noload_lookup(DeclarationName Name) {
1297 assert(DeclKind != Decl::LinkageSpec &&
1298 "Should not perform lookups into linkage specs!");
1299 if (!hasExternalVisibleStorage())
1300 return lookup(Name);
1301
1302 DeclContext *PrimaryContext = getPrimaryContext();
1303 if (PrimaryContext != this)
1304 return PrimaryContext->noload_lookup(Name);
1305
1306 StoredDeclsMap *Map = LookupPtr.getPointer();
1307 if (LookupPtr.getInt()) {
1308 // Carefully build the lookup map, without deserializing anything.
1309 SmallVector<DeclContext *, 2> Contexts;
1310 collectAllContexts(Contexts);
1311 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1312 buildLookupImpl<&DeclContext::noload_decls_begin,
1313 &DeclContext::noload_decls_end>(Contexts[I]);
1314
1315 // We no longer have any lazy decls.
1316 LookupPtr.setInt(false);
1317
1318 // There may now be names for which we have local decls but are
Richard Smith4abe0a82013-09-09 07:34:56 +00001319 // missing the external decls. FIXME: Just set the hasExternalDecls
1320 // flag on those names that have external decls.
Richard Smith95d99302013-07-13 02:00:19 +00001321 NeedToReconcileExternalVisibleStorage = true;
1322
1323 Map = LookupPtr.getPointer();
1324 }
1325
1326 if (!Map)
1327 return lookup_result(lookup_iterator(0), lookup_iterator(0));
1328
1329 StoredDeclsMap::iterator I = Map->find(Name);
1330 return I != Map->end()
1331 ? I->second.getLookupResult()
1332 : lookup_result(lookup_iterator(0), lookup_iterator(0));
1333}
1334
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001335void DeclContext::localUncachedLookup(DeclarationName Name,
1336 SmallVectorImpl<NamedDecl *> &Results) {
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001337 Results.clear();
1338
1339 // If there's no external storage, just perform a normal lookup and copy
1340 // the results.
Douglas Gregordd6006f2012-07-17 21:16:27 +00001341 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001342 lookup_result LookupResults = lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00001343 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001344 return;
1345 }
1346
1347 // If we have a lookup table, check there first. Maybe we'll get lucky.
Richard Smith645d7552013-02-07 03:37:08 +00001348 if (Name && !LookupPtr.getInt()) {
Douglas Gregordd6006f2012-07-17 21:16:27 +00001349 if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
1350 StoredDeclsMap::iterator Pos = Map->find(Name);
1351 if (Pos != Map->end()) {
1352 Results.insert(Results.end(),
David Blaikieff7d47a2012-12-19 00:45:41 +00001353 Pos->second.getLookupResult().begin(),
1354 Pos->second.getLookupResult().end());
Douglas Gregordd6006f2012-07-17 21:16:27 +00001355 return;
1356 }
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001357 }
1358 }
Douglas Gregordd6006f2012-07-17 21:16:27 +00001359
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001360 // Slow case: grovel through the declarations in our chain looking for
1361 // matches.
1362 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1363 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1364 if (ND->getDeclName() == Name)
1365 Results.push_back(ND);
1366 }
1367}
1368
Sebastian Redl50c68252010-08-31 00:36:30 +00001369DeclContext *DeclContext::getRedeclContext() {
Chris Lattner17a1bfa2009-03-27 19:19:59 +00001370 DeclContext *Ctx = this;
Sebastian Redlbd595762010-08-31 20:53:31 +00001371 // Skip through transparent contexts.
1372 while (Ctx->isTransparentContext())
Douglas Gregor6ad0ef52009-01-06 23:51:29 +00001373 Ctx = Ctx->getParent();
1374 return Ctx;
1375}
1376
Douglas Gregorf47b9112009-02-25 22:02:03 +00001377DeclContext *DeclContext::getEnclosingNamespaceContext() {
1378 DeclContext *Ctx = this;
1379 // Skip through non-namespace, non-translation-unit contexts.
Sebastian Redl4f08c962010-08-31 00:36:23 +00001380 while (!Ctx->isFileContext())
Douglas Gregorf47b9112009-02-25 22:02:03 +00001381 Ctx = Ctx->getParent();
1382 return Ctx->getPrimaryContext();
1383}
1384
Sebastian Redl50c68252010-08-31 00:36:30 +00001385bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1386 // For non-file contexts, this is equivalent to Equals.
1387 if (!isFileContext())
1388 return O->Equals(this);
1389
1390 do {
1391 if (O->Equals(this))
1392 return true;
1393
1394 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1395 if (!NS || !NS->isInline())
1396 break;
1397 O = NS->getParent();
1398 } while (O);
1399
1400 return false;
1401}
1402
Richard Smithf634c902012-03-16 06:12:59 +00001403void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1404 DeclContext *PrimaryDC = this->getPrimaryContext();
1405 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1406 // If the decl is being added outside of its semantic decl context, we
1407 // need to ensure that we eagerly build the lookup information for it.
1408 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
Sean Callanan95e74be2011-10-21 02:57:43 +00001409}
1410
Richard Smithf634c902012-03-16 06:12:59 +00001411void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1412 bool Recoverable) {
1413 assert(this == getPrimaryContext() && "expected a primary DC");
Sean Callanan95e74be2011-10-21 02:57:43 +00001414
Richard Smith05afe5e2012-03-13 03:12:56 +00001415 // Skip declarations within functions.
Richard Smith114394f2013-08-09 04:35:01 +00001416 if (isFunctionOrMethod())
Richard Smith05afe5e2012-03-13 03:12:56 +00001417 return;
1418
Richard Smithf634c902012-03-16 06:12:59 +00001419 // Skip declarations which should be invisible to name lookup.
1420 if (shouldBeHidden(D))
1421 return;
1422
1423 // If we already have a lookup data structure, perform the insertion into
1424 // it. If we might have externally-stored decls with this name, look them
1425 // up and perform the insertion. If this decl was declared outside its
1426 // semantic context, buildLookup won't add it, so add it now.
1427 //
1428 // FIXME: As a performance hack, don't add such decls into the translation
1429 // unit unless we're in C++, since qualified lookup into the TU is never
1430 // performed.
1431 if (LookupPtr.getPointer() || hasExternalVisibleStorage() ||
1432 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1433 (getParentASTContext().getLangOpts().CPlusPlus ||
1434 !isTranslationUnit()))) {
1435 // If we have lazily omitted any decls, they might have the same name as
1436 // the decl which we are adding, so build a full lookup table before adding
1437 // this decl.
1438 buildLookup();
1439 makeDeclVisibleInContextImpl(D, Internal);
1440 } else {
1441 LookupPtr.setInt(true);
1442 }
1443
1444 // If we are a transparent context or inline namespace, insert into our
1445 // parent context, too. This operation is recursive.
1446 if (isTransparentContext() || isInlineNamespace())
1447 getParent()->getPrimaryContext()->
1448 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1449
1450 Decl *DCAsDecl = cast<Decl>(this);
1451 // Notify that a decl was made visible unless we are a Tag being defined.
1452 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1453 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1454 L->AddedVisibleDecl(this, D);
1455}
1456
1457void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1458 // Find or create the stored declaration map.
1459 StoredDeclsMap *Map = LookupPtr.getPointer();
1460 if (!Map) {
1461 ASTContext *C = &getParentASTContext();
1462 Map = CreateStoredDeclsMap(*C);
Argyrios Kyrtzidise51e5542010-07-04 21:44:25 +00001463 }
1464
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001465 // If there is an external AST source, load any declarations it knows about
1466 // with this declaration's name.
1467 // If the lookup table contains an entry about this name it means that we
1468 // have already checked the external source.
Sean Callanan95e74be2011-10-21 02:57:43 +00001469 if (!Internal)
1470 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1471 if (hasExternalVisibleStorage() &&
Richard Smithf634c902012-03-16 06:12:59 +00001472 Map->find(D->getDeclName()) == Map->end())
Sean Callanan95e74be2011-10-21 02:57:43 +00001473 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001474
Douglas Gregor91f84212008-12-11 16:49:14 +00001475 // Insert this declaration into the map.
Richard Smithf634c902012-03-16 06:12:59 +00001476 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
Richard Smith4abe0a82013-09-09 07:34:56 +00001477
1478 if (Internal) {
1479 // If this is being added as part of loading an external declaration,
1480 // this may not be the only external declaration with this name.
1481 // In this case, we never try to replace an existing declaration; we'll
1482 // handle that when we finalize the list of declarations for this name.
1483 DeclNameEntries.setHasExternalDecls();
1484 DeclNameEntries.AddSubsequentDecl(D);
1485 return;
1486 }
1487
1488 else if (DeclNameEntries.isNull()) {
Chris Lattnercaae7162009-02-20 01:44:05 +00001489 DeclNameEntries.setOnlyValue(D);
Richard Smithf634c902012-03-16 06:12:59 +00001490 return;
Douglas Gregor91f84212008-12-11 16:49:14 +00001491 }
Chris Lattner24e24d52009-02-20 00:55:03 +00001492
Richard Smithf634c902012-03-16 06:12:59 +00001493 if (DeclNameEntries.HandleRedeclaration(D)) {
1494 // This declaration has replaced an existing one for which
1495 // declarationReplaces returns true.
1496 return;
1497 }
Mike Stump11289f42009-09-09 15:08:12 +00001498
Richard Smithf634c902012-03-16 06:12:59 +00001499 // Put this declaration into the appropriate slot.
1500 DeclNameEntries.AddSubsequentDecl(D);
Douglas Gregor91f84212008-12-11 16:49:14 +00001501}
Douglas Gregor889ceb72009-02-03 19:21:40 +00001502
1503/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1504/// this context.
Mike Stump11289f42009-09-09 15:08:12 +00001505DeclContext::udir_iterator_range
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001506DeclContext::getUsingDirectives() const {
Richard Smith05afe5e2012-03-13 03:12:56 +00001507 // FIXME: Use something more efficient than normal lookup for using
1508 // directives. In C++, using directives are looked up more than anything else.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001509 lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
David Blaikieff7d47a2012-12-19 00:45:41 +00001510 return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.begin()),
1511 reinterpret_cast<udir_iterator>(Result.end()));
Douglas Gregor889ceb72009-02-03 19:21:40 +00001512}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001513
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001514//===----------------------------------------------------------------------===//
1515// Creation and Destruction of StoredDeclsMaps. //
1516//===----------------------------------------------------------------------===//
1517
John McCallc62bb642010-03-24 05:22:00 +00001518StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
Richard Smithf634c902012-03-16 06:12:59 +00001519 assert(!LookupPtr.getPointer() && "context already has a decls map");
John McCallc62bb642010-03-24 05:22:00 +00001520 assert(getPrimaryContext() == this &&
1521 "creating decls map on non-primary context");
1522
1523 StoredDeclsMap *M;
1524 bool Dependent = isDependentContext();
1525 if (Dependent)
1526 M = new DependentStoredDeclsMap();
1527 else
1528 M = new StoredDeclsMap();
1529 M->Previous = C.LastSDM;
1530 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
Richard Smithf634c902012-03-16 06:12:59 +00001531 LookupPtr.setPointer(M);
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001532 return M;
1533}
1534
1535void ASTContext::ReleaseDeclContextMaps() {
John McCallc62bb642010-03-24 05:22:00 +00001536 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1537 // pointer because the subclass doesn't add anything that needs to
1538 // be deleted.
John McCallc62bb642010-03-24 05:22:00 +00001539 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1540}
1541
1542void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1543 while (Map) {
1544 // Advance the iteration before we invalidate memory.
1545 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1546
1547 if (Dependent)
1548 delete static_cast<DependentStoredDeclsMap*>(Map);
1549 else
1550 delete Map;
1551
1552 Map = Next.getPointer();
1553 Dependent = Next.getInt();
1554 }
1555}
1556
John McCallc62bb642010-03-24 05:22:00 +00001557DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1558 DeclContext *Parent,
1559 const PartialDiagnostic &PDiag) {
1560 assert(Parent->isDependentContext()
1561 && "cannot iterate dependent diagnostics of non-dependent context");
1562 Parent = Parent->getPrimaryContext();
Richard Smithf634c902012-03-16 06:12:59 +00001563 if (!Parent->LookupPtr.getPointer())
John McCallc62bb642010-03-24 05:22:00 +00001564 Parent->CreateStoredDeclsMap(C);
1565
1566 DependentStoredDeclsMap *Map
Richard Smithf634c902012-03-16 06:12:59 +00001567 = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr.getPointer());
John McCallc62bb642010-03-24 05:22:00 +00001568
Douglas Gregora55530e2010-03-29 23:56:53 +00001569 // Allocate the copy of the PartialDiagnostic via the ASTContext's
Douglas Gregor89336232010-03-29 23:34:08 +00001570 // BumpPtrAllocator, rather than the ASTContext itself.
Douglas Gregora55530e2010-03-29 23:56:53 +00001571 PartialDiagnostic::Storage *DiagStorage = 0;
1572 if (PDiag.hasStorage())
1573 DiagStorage = new (C) PartialDiagnostic::Storage;
1574
1575 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
John McCallc62bb642010-03-24 05:22:00 +00001576
1577 // TODO: Maybe we shouldn't reverse the order during insertion.
1578 DD->NextDiagnostic = Map->FirstDiagnostic;
1579 Map->FirstDiagnostic = DD;
1580
1581 return DD;
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001582}