blob: 4eceda4fac0f616a3cfa4c1fa3adec794405ce0f [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
Richard Smithf7981722013-11-22 09:01:48 +000048void *Decl::operator new(std::size_t Size, const ASTContext &Context,
49 unsigned ID, std::size_t Extra) {
Douglas Gregor52261fd2012-01-05 23:49:36 +000050 // Allocate an extra 8 bytes worth of storage, which ensures that the
Douglas Gregorcfe7dc62012-01-09 17:30:44 +000051 // resulting pointer will still be 8-byte aligned.
Richard Smithf7981722013-11-22 09:01:48 +000052 void *Start = Context.Allocate(Size + Extra + 8);
Douglas Gregor52261fd2012-01-05 23:49:36 +000053 void *Result = (char*)Start + 8;
Richard Smithf7981722013-11-22 09:01:48 +000054
Douglas Gregorcfe7dc62012-01-09 17:30:44 +000055 unsigned *PrefixPtr = (unsigned *)Result - 2;
Richard Smithf7981722013-11-22 09:01:48 +000056
Douglas Gregorcfe7dc62012-01-09 17:30:44 +000057 // Zero out the first 4 bytes; this is used to store the owning module ID.
58 PrefixPtr[0] = 0;
Richard Smithf7981722013-11-22 09:01:48 +000059
Douglas Gregorcfe7dc62012-01-09 17:30:44 +000060 // Store the global declaration ID in the second 4 bytes.
61 PrefixPtr[1] = ID;
Richard Smithf7981722013-11-22 09:01:48 +000062
Douglas Gregor64af53c2012-01-05 22:27:05 +000063 return Result;
Douglas Gregor72172e92012-01-05 21:55:30 +000064}
65
Richard Smithf7981722013-11-22 09:01:48 +000066void *Decl::operator new(std::size_t Size, const ASTContext &Ctx,
67 DeclContext *Parent, std::size_t Extra) {
68 assert(!Parent || &Parent->getParentASTContext() == &Ctx);
69 return ::operator new(Size + Extra, Ctx);
70}
71
Douglas Gregorc147b0b2013-01-12 01:29:50 +000072Module *Decl::getOwningModuleSlow() const {
73 assert(isFromASTFile() && "Not from AST file?");
74 return getASTContext().getExternalSource()->getModule(getOwningModuleID());
75}
76
Eli Friedman7dbab8a2008-06-07 16:52:53 +000077const char *Decl::getDeclKindName() const {
78 switch (DeclKind) {
David Blaikie83d382b2011-09-23 05:06:16 +000079 default: llvm_unreachable("Declaration not in DeclNodes.inc!");
Alexis Hunted053252010-05-30 07:21:58 +000080#define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
81#define ABSTRACT_DECL(DECL)
82#include "clang/AST/DeclNodes.inc"
Eli Friedman7dbab8a2008-06-07 16:52:53 +000083 }
84}
85
Douglas Gregor90d47172010-03-05 00:26:45 +000086void Decl::setInvalidDecl(bool Invalid) {
87 InvalidDecl = Invalid;
Argyrios Kyrtzidisb7d1ca22012-03-09 21:09:04 +000088 if (Invalid && !isa<ParmVarDecl>(this)) {
Douglas Gregor90d47172010-03-05 00:26:45 +000089 // Defensive maneuver for ill-formed code: we're likely not to make it to
90 // a point where we set the access specifier, so default it to "public"
91 // to avoid triggering asserts elsewhere in the front end.
92 setAccess(AS_public);
93 }
94}
95
Steve Naroff5faaef72009-01-20 19:53:53 +000096const char *DeclContext::getDeclKindName() const {
97 switch (DeclKind) {
David Blaikie83d382b2011-09-23 05:06:16 +000098 default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
Alexis Hunted053252010-05-30 07:21:58 +000099#define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
100#define ABSTRACT_DECL(DECL)
101#include "clang/AST/DeclNodes.inc"
Steve Naroff5faaef72009-01-20 19:53:53 +0000102 }
103}
104
Daniel Dunbar62905572012-03-05 21:42:49 +0000105bool Decl::StatisticsEnabled = false;
106void Decl::EnableStatistics() {
107 StatisticsEnabled = true;
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000108}
109
110void Decl::PrintStats() {
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000111 llvm::errs() << "\n*** Decl Stats:\n";
Mike Stump11289f42009-09-09 15:08:12 +0000112
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000113 int totalDecls = 0;
Alexis Hunted053252010-05-30 07:21:58 +0000114#define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
115#define ABSTRACT_DECL(DECL)
116#include "clang/AST/DeclNodes.inc"
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000117 llvm::errs() << " " << totalDecls << " decls total.\n";
Mike Stump11289f42009-09-09 15:08:12 +0000118
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000119 int totalBytes = 0;
Alexis Hunted053252010-05-30 07:21:58 +0000120#define DECL(DERIVED, BASE) \
121 if (n##DERIVED##s > 0) { \
122 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000123 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
124 << sizeof(DERIVED##Decl) << " each (" \
125 << n##DERIVED##s * sizeof(DERIVED##Decl) \
126 << " bytes)\n"; \
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000127 }
Alexis Hunted053252010-05-30 07:21:58 +0000128#define ABSTRACT_DECL(DECL)
129#include "clang/AST/DeclNodes.inc"
Mike Stump11289f42009-09-09 15:08:12 +0000130
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000131 llvm::errs() << "Total bytes = " << totalBytes << "\n";
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000132}
133
Alexis Hunted053252010-05-30 07:21:58 +0000134void Decl::add(Kind k) {
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000135 switch (k) {
Alexis Hunted053252010-05-30 07:21:58 +0000136#define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
137#define ABSTRACT_DECL(DECL)
138#include "clang/AST/DeclNodes.inc"
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000139 }
140}
141
Anders Carlssonaa73b912009-06-13 00:08:58 +0000142bool Decl::isTemplateParameterPack() const {
143 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
144 return TTP->isParameterPack();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000145 if (const NonTypeTemplateParmDecl *NTTP
Douglas Gregorf5500772011-01-05 15:48:55 +0000146 = dyn_cast<NonTypeTemplateParmDecl>(this))
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000147 return NTTP->isParameterPack();
Douglas Gregorf5500772011-01-05 15:48:55 +0000148 if (const TemplateTemplateParmDecl *TTP
149 = dyn_cast<TemplateTemplateParmDecl>(this))
150 return TTP->isParameterPack();
Anders Carlssonaa73b912009-06-13 00:08:58 +0000151 return false;
152}
153
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +0000154bool Decl::isParameterPack() const {
155 if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
156 return Parm->isParameterPack();
157
158 return isTemplateParameterPack();
159}
160
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000161bool Decl::isFunctionOrFunctionTemplate() const {
John McCall3f746822009-11-17 05:59:44 +0000162 if (const UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(this))
Anders Carlssonf057cb22009-06-26 05:26:50 +0000163 return UD->getTargetDecl()->isFunctionOrFunctionTemplate();
Mike Stump11289f42009-09-09 15:08:12 +0000164
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000165 return isa<FunctionDecl>(this) || isa<FunctionTemplateDecl>(this);
166}
167
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000168bool Decl::isTemplateDecl() const {
169 return isa<TemplateDecl>(this);
170}
171
Argyrios Kyrtzidis0ce4c9a2011-09-28 02:45:33 +0000172const DeclContext *Decl::getParentFunctionOrMethod() const {
173 for (const DeclContext *DC = getDeclContext();
174 DC && !DC->isTranslationUnit() && !DC->isNamespace();
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000175 DC = DC->getParent())
176 if (DC->isFunctionOrMethod())
Argyrios Kyrtzidis0ce4c9a2011-09-28 02:45:33 +0000177 return DC;
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000178
Argyrios Kyrtzidis0ce4c9a2011-09-28 02:45:33 +0000179 return 0;
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000180}
181
Douglas Gregor133eddd2011-02-17 08:47:29 +0000182
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000183//===----------------------------------------------------------------------===//
Chris Lattnereae6cb62009-03-05 08:00:35 +0000184// PrettyStackTraceDecl Implementation
185//===----------------------------------------------------------------------===//
Mike Stump11289f42009-09-09 15:08:12 +0000186
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000187void PrettyStackTraceDecl::print(raw_ostream &OS) const {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000188 SourceLocation TheLoc = Loc;
189 if (TheLoc.isInvalid() && TheDecl)
190 TheLoc = TheDecl->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000191
Chris Lattnereae6cb62009-03-05 08:00:35 +0000192 if (TheLoc.isValid()) {
193 TheLoc.print(OS, SM);
194 OS << ": ";
195 }
196
197 OS << Message;
198
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +0000199 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
200 OS << " '";
201 DN->printQualifiedName(OS);
202 OS << '\'';
203 }
Chris Lattnereae6cb62009-03-05 08:00:35 +0000204 OS << '\n';
205}
Mike Stump11289f42009-09-09 15:08:12 +0000206
Chris Lattnereae6cb62009-03-05 08:00:35 +0000207//===----------------------------------------------------------------------===//
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000208// Decl Implementation
209//===----------------------------------------------------------------------===//
210
Douglas Gregorb11aad82011-02-19 18:51:44 +0000211// Out-of-line virtual method providing a home for Decl.
212Decl::~Decl() { }
Douglas Gregora43942a2011-02-17 07:02:32 +0000213
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000214void Decl::setDeclContext(DeclContext *DC) {
Chris Lattnerb81eb052009-03-29 06:06:59 +0000215 DeclCtx = DC;
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000216}
217
218void Decl::setLexicalDeclContext(DeclContext *DC) {
219 if (DC == getLexicalDeclContext())
220 return;
221
222 if (isInSemaDC()) {
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000223 setDeclContextsImpl(getDeclContext(), DC, getASTContext());
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000224 } else {
225 getMultipleDC()->LexicalDC = DC;
226 }
227}
228
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000229void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
230 ASTContext &Ctx) {
231 if (SemaDC == LexicalDC) {
232 DeclCtx = SemaDC;
233 } else {
234 Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
235 MDC->SemanticDC = SemaDC;
236 MDC->LexicalDC = LexicalDC;
237 DeclCtx = MDC;
238 }
239}
240
John McCall4fa53422009-10-01 00:25:31 +0000241bool Decl::isInAnonymousNamespace() const {
242 const DeclContext *DC = getDeclContext();
243 do {
244 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
245 if (ND->isAnonymousNamespace())
246 return true;
247 } while ((DC = DC->getParent()));
248
249 return false;
250}
251
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000252TranslationUnitDecl *Decl::getTranslationUnitDecl() {
Argyrios Kyrtzidis4e1a72b2009-06-30 02:34:53 +0000253 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
254 return TUD;
255
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000256 DeclContext *DC = getDeclContext();
257 assert(DC && "This decl is not contained in a translation unit!");
Mike Stump11289f42009-09-09 15:08:12 +0000258
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000259 while (!DC->isTranslationUnit()) {
260 DC = DC->getParent();
261 assert(DC && "This decl is not contained in a translation unit!");
262 }
Mike Stump11289f42009-09-09 15:08:12 +0000263
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000264 return cast<TranslationUnitDecl>(DC);
265}
266
267ASTContext &Decl::getASTContext() const {
Mike Stump11289f42009-09-09 15:08:12 +0000268 return getTranslationUnitDecl()->getASTContext();
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000269}
270
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +0000271ASTMutationListener *Decl::getASTMutationListener() const {
272 return getASTContext().getASTMutationListener();
273}
274
Benjamin Kramerea70eb32012-12-01 15:09:41 +0000275unsigned Decl::getMaxAlignment() const {
276 if (!hasAttrs())
277 return 0;
278
279 unsigned Align = 0;
280 const AttrVec &V = getAttrs();
281 ASTContext &Ctx = getASTContext();
282 specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
283 for (; I != E; ++I)
284 Align = std::max(Align, I->getAlignment(Ctx));
285 return Align;
286}
287
Douglas Gregorebada0772010-06-17 23:14:26 +0000288bool Decl::isUsed(bool CheckUsedAttr) const {
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000289 if (Used)
290 return true;
291
292 // Check for used attribute.
Douglas Gregorebada0772010-06-17 23:14:26 +0000293 if (CheckUsedAttr && hasAttr<UsedAttr>())
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000294 return true;
Rafael Espindola99e3bfb2012-11-23 16:26:30 +0000295
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000296 return false;
297}
298
Eli Friedman276dd182013-09-05 00:02:25 +0000299void Decl::markUsed(ASTContext &C) {
300 if (Used)
301 return;
302
303 if (C.getASTMutationListener())
304 C.getASTMutationListener()->DeclarationMarkedUsed(this);
305
306 Used = true;
307}
308
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +0000309bool Decl::isReferenced() const {
310 if (Referenced)
311 return true;
312
313 // Check redeclarations.
314 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
315 if (I->Referenced)
316 return true;
317
318 return false;
319}
320
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000321/// \brief Determine the availability of the given declaration based on
322/// the target platform.
323///
324/// When it returns an availability result other than \c AR_Available,
325/// if the \p Message parameter is non-NULL, it will be set to a
326/// string describing why the entity is unavailable.
327///
328/// FIXME: Make these strings localizable, since they end up in
329/// diagnostics.
330static AvailabilityResult CheckAvailability(ASTContext &Context,
331 const AvailabilityAttr *A,
332 std::string *Message) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000333 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000334 StringRef PrettyPlatformName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000335 = AvailabilityAttr::getPrettyPlatformName(TargetPlatform);
336 if (PrettyPlatformName.empty())
337 PrettyPlatformName = TargetPlatform;
338
Douglas Gregore8bbc122011-09-02 00:18:52 +0000339 VersionTuple TargetMinVersion = Context.getTargetInfo().getPlatformMinVersion();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000340 if (TargetMinVersion.empty())
341 return AR_Available;
342
343 // Match the platform name.
344 if (A->getPlatform()->getName() != TargetPlatform)
345 return AR_Available;
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000346
347 std::string HintMessage;
348 if (!A->getMessage().empty()) {
349 HintMessage = " - ";
350 HintMessage += A->getMessage();
351 }
352
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000353 // Make sure that this declaration has not been marked 'unavailable'.
354 if (A->getUnavailable()) {
355 if (Message) {
356 Message->clear();
357 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000358 Out << "not available on " << PrettyPlatformName
359 << HintMessage;
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000360 }
361
362 return AR_Unavailable;
363 }
364
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000365 // Make sure that this declaration has already been introduced.
366 if (!A->getIntroduced().empty() &&
367 TargetMinVersion < A->getIntroduced()) {
368 if (Message) {
369 Message->clear();
370 llvm::raw_string_ostream Out(*Message);
371 Out << "introduced in " << PrettyPlatformName << ' '
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000372 << A->getIntroduced() << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000373 }
374
375 return AR_NotYetIntroduced;
376 }
377
378 // Make sure that this declaration hasn't been obsoleted.
379 if (!A->getObsoleted().empty() && TargetMinVersion >= A->getObsoleted()) {
380 if (Message) {
381 Message->clear();
382 llvm::raw_string_ostream Out(*Message);
383 Out << "obsoleted in " << PrettyPlatformName << ' '
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000384 << A->getObsoleted() << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000385 }
386
387 return AR_Unavailable;
388 }
389
390 // Make sure that this declaration hasn't been deprecated.
391 if (!A->getDeprecated().empty() && TargetMinVersion >= A->getDeprecated()) {
392 if (Message) {
393 Message->clear();
394 llvm::raw_string_ostream Out(*Message);
395 Out << "first deprecated in " << PrettyPlatformName << ' '
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000396 << A->getDeprecated() << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000397 }
398
399 return AR_Deprecated;
400 }
401
402 return AR_Available;
403}
404
405AvailabilityResult Decl::getAvailability(std::string *Message) const {
406 AvailabilityResult Result = AR_Available;
407 std::string ResultMessage;
408
409 for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) {
410 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(*A)) {
411 if (Result >= AR_Deprecated)
412 continue;
413
414 if (Message)
415 ResultMessage = Deprecated->getMessage();
416
417 Result = AR_Deprecated;
418 continue;
419 }
420
421 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(*A)) {
422 if (Message)
423 *Message = Unavailable->getMessage();
424 return AR_Unavailable;
425 }
426
427 if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) {
428 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
429 Message);
430
431 if (AR == AR_Unavailable)
432 return AR_Unavailable;
433
434 if (AR > Result) {
435 Result = AR;
436 if (Message)
437 ResultMessage.swap(*Message);
438 }
439 continue;
440 }
441 }
442
443 if (Message)
444 Message->swap(ResultMessage);
445 return Result;
446}
447
448bool Decl::canBeWeakImported(bool &IsDefinition) const {
449 IsDefinition = false;
John McCall5fb5df92012-06-20 06:18:46 +0000450
451 // Variables, if they aren't definitions.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000452 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000453 if (Var->isThisDeclarationADefinition()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000454 IsDefinition = true;
455 return false;
456 }
John McCall5fb5df92012-06-20 06:18:46 +0000457 return true;
458
459 // Functions, if they aren't definitions.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000460 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
461 if (FD->hasBody()) {
462 IsDefinition = true;
463 return false;
464 }
John McCall5fb5df92012-06-20 06:18:46 +0000465 return true;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000466
John McCall5fb5df92012-06-20 06:18:46 +0000467 // Objective-C classes, if this is the non-fragile runtime.
468 } else if (isa<ObjCInterfaceDecl>(this) &&
John McCall18ac1632012-06-20 21:58:02 +0000469 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
John McCall5fb5df92012-06-20 06:18:46 +0000470 return true;
471
472 // Nothing else.
473 } else {
474 return false;
475 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000476}
477
478bool Decl::isWeakImported() const {
479 bool IsDefinition;
480 if (!canBeWeakImported(IsDefinition))
481 return false;
482
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000483 for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) {
484 if (isa<WeakImportAttr>(*A))
485 return true;
486
487 if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) {
488 if (CheckAvailability(getASTContext(), Availability, 0)
489 == AR_NotYetIntroduced)
490 return true;
491 }
492 }
493
494 return false;
495}
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000496
Chris Lattner8e097192009-03-27 20:18:19 +0000497unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
498 switch (DeclKind) {
John McCall3f746822009-11-17 05:59:44 +0000499 case Function:
500 case CXXMethod:
501 case CXXConstructor:
502 case CXXDestructor:
503 case CXXConversion:
Chris Lattner8e097192009-03-27 20:18:19 +0000504 case EnumConstant:
505 case Var:
506 case ImplicitParam:
507 case ParmVar:
Chris Lattner8e097192009-03-27 20:18:19 +0000508 case NonTypeTemplateParm:
509 case ObjCMethod:
Daniel Dunbar45b2d8a2010-04-23 13:07:39 +0000510 case ObjCProperty:
John McCall5e77d762013-04-16 07:28:30 +0000511 case MSProperty:
Daniel Dunbar45b2d8a2010-04-23 13:07:39 +0000512 return IDNS_Ordinary;
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000513 case Label:
514 return IDNS_Label;
Francois Pichet783dd6e2010-11-21 06:08:52 +0000515 case IndirectField:
516 return IDNS_Ordinary | IDNS_Member;
517
John McCalle87beb22010-04-23 18:46:30 +0000518 case ObjCCompatibleAlias:
519 case ObjCInterface:
520 return IDNS_Ordinary | IDNS_Type;
521
522 case Typedef:
Richard Smithdda56e42011-04-15 14:24:37 +0000523 case TypeAlias:
Richard Smith3f1b5d02011-05-05 21:57:07 +0000524 case TypeAliasTemplate:
John McCalle87beb22010-04-23 18:46:30 +0000525 case UnresolvedUsingTypename:
526 case TemplateTypeParm:
527 return IDNS_Ordinary | IDNS_Type;
528
John McCall3f746822009-11-17 05:59:44 +0000529 case UsingShadow:
530 return 0; // we'll actually overwrite this later
531
John McCalle61f2ba2009-11-18 02:36:19 +0000532 case UnresolvedUsingValue:
John McCalle61f2ba2009-11-18 02:36:19 +0000533 return IDNS_Ordinary | IDNS_Using;
John McCall3f746822009-11-17 05:59:44 +0000534
535 case Using:
536 return IDNS_Using;
537
Chris Lattner8e097192009-03-27 20:18:19 +0000538 case ObjCProtocol:
Douglas Gregor79947a22009-04-24 00:11:27 +0000539 return IDNS_ObjCProtocol;
Mike Stump11289f42009-09-09 15:08:12 +0000540
Chris Lattner8e097192009-03-27 20:18:19 +0000541 case Field:
542 case ObjCAtDefsField:
543 case ObjCIvar:
544 return IDNS_Member;
Mike Stump11289f42009-09-09 15:08:12 +0000545
Chris Lattner8e097192009-03-27 20:18:19 +0000546 case Record:
547 case CXXRecord:
548 case Enum:
John McCalle87beb22010-04-23 18:46:30 +0000549 return IDNS_Tag | IDNS_Type;
Mike Stump11289f42009-09-09 15:08:12 +0000550
Chris Lattner8e097192009-03-27 20:18:19 +0000551 case Namespace:
John McCalle87beb22010-04-23 18:46:30 +0000552 case NamespaceAlias:
553 return IDNS_Namespace;
554
Chris Lattner8e097192009-03-27 20:18:19 +0000555 case FunctionTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +0000556 case VarTemplate:
John McCalle87beb22010-04-23 18:46:30 +0000557 return IDNS_Ordinary;
558
Chris Lattner8e097192009-03-27 20:18:19 +0000559 case ClassTemplate:
560 case TemplateTemplateParm:
John McCalle87beb22010-04-23 18:46:30 +0000561 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
Mike Stump11289f42009-09-09 15:08:12 +0000562
Chris Lattner8e097192009-03-27 20:18:19 +0000563 // Never have names.
John McCallaa74a0c2009-08-28 07:59:38 +0000564 case Friend:
John McCall11083da2009-09-16 22:47:08 +0000565 case FriendTemplate:
Abramo Bagnarad7340582010-06-05 05:09:32 +0000566 case AccessSpec:
Chris Lattner8e097192009-03-27 20:18:19 +0000567 case LinkageSpec:
568 case FileScopeAsm:
569 case StaticAssert:
Chris Lattner8e097192009-03-27 20:18:19 +0000570 case ObjCPropertyImpl:
Chris Lattner8e097192009-03-27 20:18:19 +0000571 case Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +0000572 case Captured:
Chris Lattner8e097192009-03-27 20:18:19 +0000573 case TranslationUnit:
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000574
Chris Lattner8e097192009-03-27 20:18:19 +0000575 case UsingDirective:
576 case ClassTemplateSpecialization:
Douglas Gregor2373c592009-05-31 09:31:02 +0000577 case ClassTemplatePartialSpecialization:
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000578 case ClassScopeFunctionSpecialization:
Larisse Voufo39a1e502013-08-06 01:03:05 +0000579 case VarTemplateSpecialization:
580 case VarTemplatePartialSpecialization:
Douglas Gregore93525e2010-04-22 23:19:50 +0000581 case ObjCImplementation:
582 case ObjCCategory:
583 case ObjCCategoryImpl:
Douglas Gregorba345522011-12-02 23:23:56 +0000584 case Import:
Alexey Bataeva769e072013-03-22 06:34:35 +0000585 case OMPThreadPrivate:
Michael Han84324352013-02-22 17:15:32 +0000586 case Empty:
Douglas Gregore93525e2010-04-22 23:19:50 +0000587 // Never looked up by name.
Chris Lattner8e097192009-03-27 20:18:19 +0000588 return 0;
589 }
John McCall3f746822009-11-17 05:59:44 +0000590
David Blaikiee4d798f2012-01-20 21:50:17 +0000591 llvm_unreachable("Invalid DeclKind!");
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000592}
593
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000594void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
Argyrios Kyrtzidis91167172010-06-11 23:09:25 +0000595 assert(!HasAttrs && "Decl already contains attrs.");
596
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000597 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000598 assert(AttrBlank.empty() && "HasAttrs was wrong?");
Argyrios Kyrtzidis91167172010-06-11 23:09:25 +0000599
600 AttrBlank = attrs;
601 HasAttrs = true;
602}
603
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000604void Decl::dropAttrs() {
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000605 if (!HasAttrs) return;
Mike Stump11289f42009-09-09 15:08:12 +0000606
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000607 HasAttrs = false;
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000608 getASTContext().eraseDeclAttrs(this);
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000609}
610
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000611const AttrVec &Decl::getAttrs() const {
612 assert(HasAttrs && "No attrs to get!");
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000613 return getASTContext().getDeclAttrs(this);
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000614}
615
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000616Decl *Decl::castFromDeclContext (const DeclContext *D) {
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000617 Decl::Kind DK = D->getDeclKind();
618 switch(DK) {
Alexis Hunted053252010-05-30 07:21:58 +0000619#define DECL(NAME, BASE)
620#define DECL_CONTEXT(NAME) \
621 case Decl::NAME: \
622 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
623#define DECL_CONTEXT_BASE(NAME)
624#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000625 default:
Alexis Hunted053252010-05-30 07:21:58 +0000626#define DECL(NAME, BASE)
627#define DECL_CONTEXT_BASE(NAME) \
628 if (DK >= first##NAME && DK <= last##NAME) \
629 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
630#include "clang/AST/DeclNodes.inc"
David Blaikie83d382b2011-09-23 05:06:16 +0000631 llvm_unreachable("a decl that inherits DeclContext isn't handled");
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000632 }
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000633}
634
635DeclContext *Decl::castToDeclContext(const Decl *D) {
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000636 Decl::Kind DK = D->getKind();
637 switch(DK) {
Alexis Hunted053252010-05-30 07:21:58 +0000638#define DECL(NAME, BASE)
639#define DECL_CONTEXT(NAME) \
640 case Decl::NAME: \
641 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
642#define DECL_CONTEXT_BASE(NAME)
643#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000644 default:
Alexis Hunted053252010-05-30 07:21:58 +0000645#define DECL(NAME, BASE)
646#define DECL_CONTEXT_BASE(NAME) \
647 if (DK >= first##NAME && DK <= last##NAME) \
648 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
649#include "clang/AST/DeclNodes.inc"
David Blaikie83d382b2011-09-23 05:06:16 +0000650 llvm_unreachable("a decl that inherits DeclContext isn't handled");
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000651 }
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000652}
653
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000654SourceLocation Decl::getBodyRBrace() const {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +0000655 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
656 // FunctionDecl stores EndRangeLoc for this purpose.
657 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
658 const FunctionDecl *Definition;
659 if (FD->hasBody(Definition))
660 return Definition->getSourceRange().getEnd();
661 return SourceLocation();
662 }
663
Argyrios Kyrtzidis6fbc8fa2010-07-07 11:31:27 +0000664 if (Stmt *Body = getBody())
665 return Body->getSourceRange().getEnd();
666
667 return SourceLocation();
Sebastian Redla7b98a72009-04-26 20:35:05 +0000668}
669
Alp Tokerc1086762013-12-07 13:51:35 +0000670bool Decl::AccessDeclContextSanity() const {
Douglas Gregor4b00d3b2010-12-02 00:22:25 +0000671#ifndef NDEBUG
John McCall401982f2010-01-20 21:53:11 +0000672 // Suppress this check if any of the following hold:
673 // 1. this is the translation unit (and thus has no parent)
674 // 2. this is a template parameter (and thus doesn't belong to its context)
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000675 // 3. this is a non-type template parameter
676 // 4. the context is not a record
677 // 5. it's invalid
678 // 6. it's a C++0x static_assert.
Anders Carlssonadf36b22009-08-29 20:47:47 +0000679 if (isa<TranslationUnitDecl>(this) ||
Argyrios Kyrtzidisa45855f2010-07-02 11:55:44 +0000680 isa<TemplateTypeParmDecl>(this) ||
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000681 isa<NonTypeTemplateParmDecl>(this) ||
Douglas Gregor2b76dd92010-02-22 17:53:38 +0000682 !isa<CXXRecordDecl>(getDeclContext()) ||
Argyrios Kyrtzidis260b4a82010-09-08 21:32:35 +0000683 isInvalidDecl() ||
684 isa<StaticAssertDecl>(this) ||
685 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
686 // as DeclContext (?).
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000687 isa<ParmVarDecl>(this) ||
688 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
689 // AS_none as access specifier.
Francois Pichet09af8c32011-08-17 01:06:54 +0000690 isa<CXXRecordDecl>(this) ||
691 isa<ClassScopeFunctionSpecializationDecl>(this))
Alp Tokerc1086762013-12-07 13:51:35 +0000692 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000693
694 assert(Access != AS_none &&
Anders Carlssona28908d2009-03-25 23:38:06 +0000695 "Access specifier is AS_none inside a record decl");
Douglas Gregor4b00d3b2010-12-02 00:22:25 +0000696#endif
Alp Tokerc1086762013-12-07 13:51:35 +0000697 return true;
Anders Carlssona28908d2009-03-25 23:38:06 +0000698}
699
John McCalldec348f72013-05-03 07:33:41 +0000700static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
701static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
702
703/// Starting at a given context (a Decl or DeclContext), look for a
704/// code context that is not a closure (a lambda, block, etc.).
705template <class T> static Decl *getNonClosureContext(T *D) {
706 if (getKind(D) == Decl::CXXMethod) {
707 CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
John McCall55c0cee2013-05-03 17:11:14 +0000708 if (MD->getOverloadedOperator() == OO_Call &&
709 MD->getParent()->isLambda())
John McCalldec348f72013-05-03 07:33:41 +0000710 return getNonClosureContext(MD->getParent()->getParent());
711 return MD;
712 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
713 return FD;
714 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
715 return MD;
716 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
717 return getNonClosureContext(BD->getParent());
718 } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
719 return getNonClosureContext(CD->getParent());
720 } else {
721 return 0;
722 }
John McCallfe96e0b2011-11-06 09:01:30 +0000723}
724
John McCalldec348f72013-05-03 07:33:41 +0000725Decl *Decl::getNonClosureContext() {
726 return ::getNonClosureContext(this);
727}
John McCallb67608f2011-02-22 22:25:23 +0000728
John McCalldec348f72013-05-03 07:33:41 +0000729Decl *DeclContext::getNonClosureAncestor() {
730 return ::getNonClosureContext(this);
John McCallb67608f2011-02-22 22:25:23 +0000731}
Anders Carlssona28908d2009-03-25 23:38:06 +0000732
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000733//===----------------------------------------------------------------------===//
734// DeclContext Implementation
735//===----------------------------------------------------------------------===//
736
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000737bool DeclContext::classof(const Decl *D) {
738 switch (D->getKind()) {
Alexis Hunted053252010-05-30 07:21:58 +0000739#define DECL(NAME, BASE)
740#define DECL_CONTEXT(NAME) case Decl::NAME:
741#define DECL_CONTEXT_BASE(NAME)
742#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000743 return true;
744 default:
Alexis Hunted053252010-05-30 07:21:58 +0000745#define DECL(NAME, BASE)
746#define DECL_CONTEXT_BASE(NAME) \
747 if (D->getKind() >= Decl::first##NAME && \
748 D->getKind() <= Decl::last##NAME) \
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000749 return true;
Alexis Hunted053252010-05-30 07:21:58 +0000750#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000751 return false;
752 }
753}
754
Douglas Gregor9c832f72010-07-25 18:38:02 +0000755DeclContext::~DeclContext() { }
Douglas Gregor91f84212008-12-11 16:49:14 +0000756
Douglas Gregor7f737c02009-09-10 16:57:35 +0000757/// \brief Find the parent context of this context that will be
758/// used for unqualified name lookup.
759///
760/// Generally, the parent lookup context is the semantic context. However, for
761/// a friend function the parent lookup context is the lexical context, which
762/// is the class in which the friend is declared.
763DeclContext *DeclContext::getLookupParent() {
764 // FIXME: Find a better way to identify friends
765 if (isa<FunctionDecl>(this))
Sebastian Redl50c68252010-08-31 00:36:30 +0000766 if (getParent()->getRedeclContext()->isFileContext() &&
767 getLexicalParent()->getRedeclContext()->isRecord())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000768 return getLexicalParent();
769
770 return getParent();
771}
772
Sebastian Redlbd595762010-08-31 20:53:31 +0000773bool DeclContext::isInlineNamespace() const {
774 return isNamespace() &&
775 cast<NamespaceDecl>(this)->isInline();
776}
777
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000778bool DeclContext::isDependentContext() const {
779 if (isFileContext())
780 return false;
781
Douglas Gregor2373c592009-05-31 09:31:02 +0000782 if (isa<ClassTemplatePartialSpecializationDecl>(this))
783 return true;
784
Douglas Gregor680e9e02012-02-21 19:11:17 +0000785 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000786 if (Record->getDescribedClassTemplate())
787 return true;
Douglas Gregor680e9e02012-02-21 19:11:17 +0000788
789 if (Record->isDependentLambda())
790 return true;
791 }
792
John McCallc62bb642010-03-24 05:22:00 +0000793 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000794 if (Function->getDescribedFunctionTemplate())
795 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000796
John McCallc62bb642010-03-24 05:22:00 +0000797 // Friend function declarations are dependent if their *lexical*
798 // context is dependent.
799 if (cast<Decl>(this)->getFriendObjectKind())
800 return getLexicalParent()->isDependentContext();
801 }
802
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000803 return getParent() && getParent()->isDependentContext();
804}
805
Douglas Gregor07665a62009-01-05 19:45:36 +0000806bool DeclContext::isTransparentContext() const {
807 if (DeclKind == Decl::Enum)
Douglas Gregor0bf31402010-10-08 23:50:27 +0000808 return !cast<EnumDecl>(this)->isScoped();
Douglas Gregor07665a62009-01-05 19:45:36 +0000809 else if (DeclKind == Decl::LinkageSpec)
810 return true;
Douglas Gregor07665a62009-01-05 19:45:36 +0000811
812 return false;
813}
814
Serge Pavlov3cb80222013-11-14 02:13:03 +0000815static bool isLinkageSpecContext(const DeclContext *DC,
816 LinkageSpecDecl::LanguageIDs ID) {
817 while (DC->getDeclKind() != Decl::TranslationUnit) {
818 if (DC->getDeclKind() == Decl::LinkageSpec)
819 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
820 DC = DC->getParent();
821 }
822 return false;
823}
824
825bool DeclContext::isExternCContext() const {
826 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_c);
827}
828
829bool DeclContext::isExternCXXContext() const {
830 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_cxx);
831}
832
Sebastian Redl50c68252010-08-31 00:36:30 +0000833bool DeclContext::Encloses(const DeclContext *DC) const {
Douglas Gregore985a3b2009-08-27 06:03:53 +0000834 if (getPrimaryContext() != this)
835 return getPrimaryContext()->Encloses(DC);
Mike Stump11289f42009-09-09 15:08:12 +0000836
Douglas Gregore985a3b2009-08-27 06:03:53 +0000837 for (; DC; DC = DC->getParent())
838 if (DC->getPrimaryContext() == this)
839 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000840 return false;
Douglas Gregore985a3b2009-08-27 06:03:53 +0000841}
842
Steve Naroff35c62ae2009-01-08 17:28:14 +0000843DeclContext *DeclContext::getPrimaryContext() {
Douglas Gregor91f84212008-12-11 16:49:14 +0000844 switch (DeclKind) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000845 case Decl::TranslationUnit:
Douglas Gregor07665a62009-01-05 19:45:36 +0000846 case Decl::LinkageSpec:
Mike Stump11289f42009-09-09 15:08:12 +0000847 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +0000848 case Decl::Captured:
Douglas Gregor91f84212008-12-11 16:49:14 +0000849 // There is only one DeclContext for these entities.
850 return this;
851
852 case Decl::Namespace:
853 // The original namespace is our primary context.
854 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
855
Douglas Gregor91f84212008-12-11 16:49:14 +0000856 case Decl::ObjCMethod:
857 return this;
858
859 case Decl::ObjCInterface:
Douglas Gregor66b310c2011-12-15 18:03:09 +0000860 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
861 return Def;
862
863 return this;
864
Steve Naroff35c62ae2009-01-08 17:28:14 +0000865 case Decl::ObjCProtocol:
Douglas Gregora715bff2012-01-01 19:51:50 +0000866 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
867 return Def;
868
869 return this;
Douglas Gregor66b310c2011-12-15 18:03:09 +0000870
Steve Naroff35c62ae2009-01-08 17:28:14 +0000871 case Decl::ObjCCategory:
Douglas Gregor91f84212008-12-11 16:49:14 +0000872 return this;
873
Steve Naroff35c62ae2009-01-08 17:28:14 +0000874 case Decl::ObjCImplementation:
875 case Decl::ObjCCategoryImpl:
876 return this;
877
Douglas Gregor91f84212008-12-11 16:49:14 +0000878 default:
Alexis Hunted053252010-05-30 07:21:58 +0000879 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
Douglas Gregor67a65642009-02-17 23:15:12 +0000880 // If this is a tag type that has a definition or is currently
881 // being defined, that definition is our primary context.
John McCalle78aac42010-03-10 03:28:59 +0000882 TagDecl *Tag = cast<TagDecl>(this);
883 assert(isa<TagType>(Tag->TypeForDecl) ||
884 isa<InjectedClassNameType>(Tag->TypeForDecl));
885
886 if (TagDecl *Def = Tag->getDefinition())
887 return Def;
888
889 if (!isa<InjectedClassNameType>(Tag->TypeForDecl)) {
890 const TagType *TagTy = cast<TagType>(Tag->TypeForDecl);
891 if (TagTy->isBeingDefined())
892 // FIXME: is it necessarily being defined in the decl
893 // that owns the type?
894 return TagTy->getDecl();
895 }
896
897 return Tag;
Douglas Gregor67a65642009-02-17 23:15:12 +0000898 }
899
Alexis Hunted053252010-05-30 07:21:58 +0000900 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
Douglas Gregor91f84212008-12-11 16:49:14 +0000901 "Unknown DeclContext kind");
902 return this;
903 }
904}
905
Douglas Gregore57e7522012-01-07 09:11:48 +0000906void
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000907DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
Douglas Gregore57e7522012-01-07 09:11:48 +0000908 Contexts.clear();
909
910 if (DeclKind != Decl::Namespace) {
911 Contexts.push_back(this);
912 return;
Douglas Gregor91f84212008-12-11 16:49:14 +0000913 }
Douglas Gregore57e7522012-01-07 09:11:48 +0000914
915 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
Douglas Gregorec9fd132012-01-14 16:38:05 +0000916 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
917 N = N->getPreviousDecl())
Douglas Gregore57e7522012-01-07 09:11:48 +0000918 Contexts.push_back(N);
919
920 std::reverse(Contexts.begin(), Contexts.end());
Douglas Gregor91f84212008-12-11 16:49:14 +0000921}
922
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000923std::pair<Decl *, Decl *>
Bill Wendling8eb771d2012-02-22 09:51:33 +0000924DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +0000925 bool FieldsAlreadyLoaded) {
Douglas Gregor781f7132012-01-06 16:59:53 +0000926 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000927 Decl *FirstNewDecl = 0;
928 Decl *PrevDecl = 0;
929 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +0000930 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
931 continue;
932
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000933 Decl *D = Decls[I];
934 if (PrevDecl)
Douglas Gregor781f7132012-01-06 16:59:53 +0000935 PrevDecl->NextInContextAndBits.setPointer(D);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000936 else
937 FirstNewDecl = D;
938
939 PrevDecl = D;
940 }
941
942 return std::make_pair(FirstNewDecl, PrevDecl);
943}
944
Richard Smith645d7552013-02-07 03:37:08 +0000945/// \brief We have just acquired external visible storage, and we already have
946/// built a lookup map. For every name in the map, pull in the new names from
947/// the external storage.
948void DeclContext::reconcileExternalVisibleStorage() {
Richard Smith86a12012013-02-11 22:02:16 +0000949 assert(NeedToReconcileExternalVisibleStorage && LookupPtr.getPointer());
Richard Smith645d7552013-02-07 03:37:08 +0000950 NeedToReconcileExternalVisibleStorage = false;
951
952 StoredDeclsMap &Map = *LookupPtr.getPointer();
Richard Smith4abe0a82013-09-09 07:34:56 +0000953 for (StoredDeclsMap::iterator I = Map.begin(); I != Map.end(); ++I)
954 I->second.setHasExternalDecls();
Richard Smith645d7552013-02-07 03:37:08 +0000955}
956
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000957/// \brief Load the declarations within this lexical storage from an
958/// external source.
Mike Stump11289f42009-09-09 15:08:12 +0000959void
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000960DeclContext::LoadLexicalDeclsFromExternalStorage() const {
961 ExternalASTSource *Source = getParentASTContext().getExternalSource();
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000962 assert(hasExternalLexicalStorage() && Source && "No external storage?");
963
Argyrios Kyrtzidis98d045e2010-07-30 10:03:23 +0000964 // Notify that we have a DeclContext that is initializing.
965 ExternalASTSource::Deserializing ADeclContext(Source);
Douglas Gregorf337ae92011-08-26 21:23:06 +0000966
Douglas Gregor3d0adb32011-07-15 21:46:17 +0000967 // Load the external declarations, if any.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000968 SmallVector<Decl*, 64> Decls;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000969 ExternalLexicalStorage = false;
Douglas Gregor3d0adb32011-07-15 21:46:17 +0000970 switch (Source->FindExternalLexicalDecls(this, Decls)) {
971 case ELR_Success:
972 break;
973
974 case ELR_Failure:
975 case ELR_AlreadyLoaded:
976 return;
977 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000978
979 if (Decls.empty())
980 return;
981
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +0000982 // We may have already loaded just the fields of this record, in which case
983 // we need to ignore them.
984 bool FieldsAlreadyLoaded = false;
985 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
986 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
987
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000988 // Splice the newly-read declarations into the beginning of the list
989 // of declarations.
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000990 Decl *ExternalFirst, *ExternalLast;
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +0000991 llvm::tie(ExternalFirst, ExternalLast) = BuildDeclChain(Decls,
992 FieldsAlreadyLoaded);
Douglas Gregor781f7132012-01-06 16:59:53 +0000993 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000994 FirstDecl = ExternalFirst;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000995 if (!LastDecl)
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000996 LastDecl = ExternalLast;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000997}
998
John McCall75b960e2010-06-01 09:23:16 +0000999DeclContext::lookup_result
1000ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1001 DeclarationName Name) {
1002 ASTContext &Context = DC->getParentASTContext();
1003 StoredDeclsMap *Map;
Richard Smithf634c902012-03-16 06:12:59 +00001004 if (!(Map = DC->LookupPtr.getPointer()))
John McCall75b960e2010-06-01 09:23:16 +00001005 Map = DC->CreateStoredDeclsMap(Context);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001006
Richard Smith4abe0a82013-09-09 07:34:56 +00001007 (*Map)[Name].removeExternalDecls();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001008
John McCall75b960e2010-06-01 09:23:16 +00001009 return DeclContext::lookup_result();
1010}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001011
John McCall75b960e2010-06-01 09:23:16 +00001012DeclContext::lookup_result
1013ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
John McCall75b960e2010-06-01 09:23:16 +00001014 DeclarationName Name,
Argyrios Kyrtzidis94d3f9d2011-09-09 06:44:14 +00001015 ArrayRef<NamedDecl*> Decls) {
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00001016 ASTContext &Context = DC->getParentASTContext();
John McCall75b960e2010-06-01 09:23:16 +00001017 StoredDeclsMap *Map;
Richard Smithf634c902012-03-16 06:12:59 +00001018 if (!(Map = DC->LookupPtr.getPointer()))
John McCall75b960e2010-06-01 09:23:16 +00001019 Map = DC->CreateStoredDeclsMap(Context);
1020
1021 StoredDeclsList &List = (*Map)[Name];
Richard Smith51445cd2013-06-24 01:46:41 +00001022
1023 // Clear out any old external visible declarations, to avoid quadratic
1024 // performance in the redeclaration checks below.
1025 List.removeExternalDecls();
1026
1027 if (!List.isNull()) {
1028 // We have both existing declarations and new declarations for this name.
1029 // Some of the declarations may simply replace existing ones. Handle those
1030 // first.
1031 llvm::SmallVector<unsigned, 8> Skip;
1032 for (unsigned I = 0, N = Decls.size(); I != N; ++I)
1033 if (List.HandleRedeclaration(Decls[I]))
1034 Skip.push_back(I);
1035 Skip.push_back(Decls.size());
1036
1037 // Add in any new declarations.
1038 unsigned SkipPos = 0;
1039 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1040 if (I == Skip[SkipPos])
1041 ++SkipPos;
1042 else
1043 List.AddSubsequentDecl(Decls[I]);
1044 }
1045 } else {
1046 // Convert the array to a StoredDeclsList.
1047 for (ArrayRef<NamedDecl*>::iterator
1048 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1049 if (List.isNull())
1050 List.setOnlyValue(*I);
1051 else
1052 List.AddSubsequentDecl(*I);
1053 }
John McCall75b960e2010-06-01 09:23:16 +00001054 }
1055
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001056 return List.getLookupResult();
John McCall75b960e2010-06-01 09:23:16 +00001057}
1058
Sebastian Redl66c5eef2010-07-27 00:17:23 +00001059DeclContext::decl_iterator DeclContext::noload_decls_begin() const {
1060 return decl_iterator(FirstDecl);
1061}
1062
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001063DeclContext::decl_iterator DeclContext::decls_begin() const {
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001064 if (hasExternalLexicalStorage())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001065 LoadLexicalDeclsFromExternalStorage();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001066
Mike Stump11289f42009-09-09 15:08:12 +00001067 return decl_iterator(FirstDecl);
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001068}
1069
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001070bool DeclContext::decls_empty() const {
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001071 if (hasExternalLexicalStorage())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001072 LoadLexicalDeclsFromExternalStorage();
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001073
1074 return !FirstDecl;
1075}
1076
Sean Callanan0325fb82013-05-04 02:04:27 +00001077bool DeclContext::containsDecl(Decl *D) const {
1078 return (D->getLexicalDeclContext() == this &&
1079 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1080}
1081
John McCall84d87672009-12-10 09:41:52 +00001082void DeclContext::removeDecl(Decl *D) {
1083 assert(D->getLexicalDeclContext() == this &&
1084 "decl being removed from non-lexical context");
Douglas Gregor781f7132012-01-06 16:59:53 +00001085 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
John McCall84d87672009-12-10 09:41:52 +00001086 "decl is not in decls list");
1087
1088 // Remove D from the decl chain. This is O(n) but hopefully rare.
1089 if (D == FirstDecl) {
1090 if (D == LastDecl)
1091 FirstDecl = LastDecl = 0;
1092 else
Douglas Gregor781f7132012-01-06 16:59:53 +00001093 FirstDecl = D->NextInContextAndBits.getPointer();
John McCall84d87672009-12-10 09:41:52 +00001094 } else {
Douglas Gregor781f7132012-01-06 16:59:53 +00001095 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
John McCall84d87672009-12-10 09:41:52 +00001096 assert(I && "decl not found in linked list");
Douglas Gregor781f7132012-01-06 16:59:53 +00001097 if (I->NextInContextAndBits.getPointer() == D) {
1098 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
John McCall84d87672009-12-10 09:41:52 +00001099 if (D == LastDecl) LastDecl = I;
1100 break;
1101 }
1102 }
1103 }
1104
1105 // Mark that D is no longer in the decl chain.
Douglas Gregor781f7132012-01-06 16:59:53 +00001106 D->NextInContextAndBits.setPointer(0);
John McCall84d87672009-12-10 09:41:52 +00001107
1108 // Remove D from the lookup table if necessary.
1109 if (isa<NamedDecl>(D)) {
1110 NamedDecl *ND = cast<NamedDecl>(D);
1111
Axel Naumanncb2c52f2011-08-26 14:06:12 +00001112 // Remove only decls that have a name
1113 if (!ND->getDeclName()) return;
1114
Richard Smithf634c902012-03-16 06:12:59 +00001115 StoredDeclsMap *Map = getPrimaryContext()->LookupPtr.getPointer();
John McCallc62bb642010-03-24 05:22:00 +00001116 if (!Map) return;
John McCall84d87672009-12-10 09:41:52 +00001117
John McCall84d87672009-12-10 09:41:52 +00001118 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1119 assert(Pos != Map->end() && "no lookup entry for decl");
Axel Naumannfbc7b982011-11-08 18:21:06 +00001120 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1121 Pos->second.remove(ND);
John McCall84d87672009-12-10 09:41:52 +00001122 }
1123}
1124
John McCalld1e9d832009-08-11 06:59:38 +00001125void DeclContext::addHiddenDecl(Decl *D) {
Chris Lattner33f219d2009-02-20 00:56:18 +00001126 assert(D->getLexicalDeclContext() == this &&
1127 "Decl inserted into wrong lexical context");
Mike Stump11289f42009-09-09 15:08:12 +00001128 assert(!D->getNextDeclInContext() && D != LastDecl &&
Douglas Gregor020713e2009-01-09 19:42:16 +00001129 "Decl already inserted into a DeclContext");
1130
1131 if (FirstDecl) {
Douglas Gregor781f7132012-01-06 16:59:53 +00001132 LastDecl->NextInContextAndBits.setPointer(D);
Douglas Gregor020713e2009-01-09 19:42:16 +00001133 LastDecl = D;
1134 } else {
1135 FirstDecl = LastDecl = D;
1136 }
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001137
1138 // Notify a C++ record declaration that we've added a member, so it can
1139 // update it's class-specific state.
1140 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1141 Record->addedMember(D);
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001142
1143 // If this is a newly-created (not de-serialized) import declaration, wire
1144 // it in to the list of local import declarations.
1145 if (!D->isFromASTFile()) {
1146 if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1147 D->getASTContext().addedLocalImportDecl(Import);
1148 }
John McCalld1e9d832009-08-11 06:59:38 +00001149}
1150
1151void DeclContext::addDecl(Decl *D) {
1152 addHiddenDecl(D);
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001153
1154 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithf634c902012-03-16 06:12:59 +00001155 ND->getDeclContext()->getPrimaryContext()->
1156 makeDeclVisibleInContextWithFlags(ND, false, true);
Douglas Gregor91f84212008-12-11 16:49:14 +00001157}
1158
Sean Callanan95e74be2011-10-21 02:57:43 +00001159void DeclContext::addDeclInternal(Decl *D) {
1160 addHiddenDecl(D);
1161
1162 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithf634c902012-03-16 06:12:59 +00001163 ND->getDeclContext()->getPrimaryContext()->
1164 makeDeclVisibleInContextWithFlags(ND, true, true);
1165}
1166
1167/// shouldBeHidden - Determine whether a declaration which was declared
1168/// within its semantic context should be invisible to qualified name lookup.
1169static bool shouldBeHidden(NamedDecl *D) {
1170 // Skip unnamed declarations.
1171 if (!D->getDeclName())
1172 return true;
1173
1174 // Skip entities that can't be found by name lookup into a particular
1175 // context.
1176 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1177 D->isTemplateParameter())
1178 return true;
1179
1180 // Skip template specializations.
1181 // FIXME: This feels like a hack. Should DeclarationName support
1182 // template-ids, or is there a better way to keep specializations
1183 // from being visible?
1184 if (isa<ClassTemplateSpecializationDecl>(D))
1185 return true;
1186 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1187 if (FD->isFunctionTemplateSpecialization())
1188 return true;
1189
1190 return false;
1191}
1192
1193/// buildLookup - Build the lookup data structure with all of the
1194/// declarations in this DeclContext (and any other contexts linked
1195/// to it or transparent contexts nested within it) and return it.
1196StoredDeclsMap *DeclContext::buildLookup() {
1197 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1198
Richard Smith86a12012013-02-11 22:02:16 +00001199 // FIXME: Should we keep going if hasExternalVisibleStorage?
Richard Smithf634c902012-03-16 06:12:59 +00001200 if (!LookupPtr.getInt())
1201 return LookupPtr.getPointer();
1202
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001203 SmallVector<DeclContext *, 2> Contexts;
Richard Smithf634c902012-03-16 06:12:59 +00001204 collectAllContexts(Contexts);
1205 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
Richard Smith95d99302013-07-13 02:00:19 +00001206 buildLookupImpl<&DeclContext::decls_begin,
1207 &DeclContext::decls_end>(Contexts[I]);
Richard Smithf634c902012-03-16 06:12:59 +00001208
1209 // We no longer have any lazy decls.
1210 LookupPtr.setInt(false);
Richard Smith86a12012013-02-11 22:02:16 +00001211 NeedToReconcileExternalVisibleStorage = false;
Richard Smithf634c902012-03-16 06:12:59 +00001212 return LookupPtr.getPointer();
1213}
1214
1215/// buildLookupImpl - Build part of the lookup data structure for the
1216/// declarations contained within DCtx, which will either be this
1217/// DeclContext, a DeclContext linked to it, or a transparent context
1218/// nested within it.
Richard Smith95d99302013-07-13 02:00:19 +00001219template<DeclContext::decl_iterator (DeclContext::*Begin)() const,
1220 DeclContext::decl_iterator (DeclContext::*End)() const>
Richard Smithf634c902012-03-16 06:12:59 +00001221void DeclContext::buildLookupImpl(DeclContext *DCtx) {
Richard Smith95d99302013-07-13 02:00:19 +00001222 for (decl_iterator I = (DCtx->*Begin)(), E = (DCtx->*End)();
Richard Smithf634c902012-03-16 06:12:59 +00001223 I != E; ++I) {
1224 Decl *D = *I;
1225
1226 // Insert this declaration into the lookup structure, but only if
1227 // it's semantically within its decl context. Any other decls which
1228 // should be found in this context are added eagerly.
Richard Smithcf4ab522013-06-24 07:20:36 +00001229 //
1230 // If it's from an AST file, don't add it now. It'll get handled by
1231 // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1232 // in C++, we do not track external visible decls for the TU, so in
1233 // that case we need to collect them all here.
Richard Smithf634c902012-03-16 06:12:59 +00001234 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithcf4ab522013-06-24 07:20:36 +00001235 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1236 (!ND->isFromASTFile() ||
1237 (isTranslationUnit() &&
1238 !getParentASTContext().getLangOpts().CPlusPlus)))
Richard Smithf634c902012-03-16 06:12:59 +00001239 makeDeclVisibleInContextImpl(ND, false);
1240
1241 // If this declaration is itself a transparent declaration context
1242 // or inline namespace, add the members of this declaration of that
1243 // context (recursively).
1244 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1245 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Richard Smith95d99302013-07-13 02:00:19 +00001246 buildLookupImpl<Begin, End>(InnerCtx);
Richard Smithf634c902012-03-16 06:12:59 +00001247 }
Sean Callanan95e74be2011-10-21 02:57:43 +00001248}
1249
Mike Stump11289f42009-09-09 15:08:12 +00001250DeclContext::lookup_result
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001251DeclContext::lookup(DeclarationName Name) {
Nick Lewycky2bd636f2012-03-13 04:12:34 +00001252 assert(DeclKind != Decl::LinkageSpec &&
1253 "Should not perform lookups into linkage specs!");
1254
Steve Naroff35c62ae2009-01-08 17:28:14 +00001255 DeclContext *PrimaryContext = getPrimaryContext();
Douglas Gregor91f84212008-12-11 16:49:14 +00001256 if (PrimaryContext != this)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001257 return PrimaryContext->lookup(Name);
Douglas Gregor91f84212008-12-11 16:49:14 +00001258
Richard Smith05afe5e2012-03-13 03:12:56 +00001259 if (hasExternalVisibleStorage()) {
Richard Smith645d7552013-02-07 03:37:08 +00001260 StoredDeclsMap *Map = LookupPtr.getPointer();
1261 if (LookupPtr.getInt())
1262 Map = buildLookup();
Richard Smith86a12012013-02-11 22:02:16 +00001263 else if (NeedToReconcileExternalVisibleStorage)
1264 reconcileExternalVisibleStorage();
Richard Smith645d7552013-02-07 03:37:08 +00001265
Richard Smith75fc3bf2013-02-08 00:37:45 +00001266 if (!Map)
1267 Map = CreateStoredDeclsMap(getParentASTContext());
1268
Richard Smith4abe0a82013-09-09 07:34:56 +00001269 // If we have a lookup result with no external decls, we are done.
Richard Smith75fc3bf2013-02-08 00:37:45 +00001270 std::pair<StoredDeclsMap::iterator, bool> R =
1271 Map->insert(std::make_pair(Name, StoredDeclsList()));
Richard Smith4abe0a82013-09-09 07:34:56 +00001272 if (!R.second && !R.first->second.hasExternalDecls())
Richard Smith75fc3bf2013-02-08 00:37:45 +00001273 return R.first->second.getLookupResult();
Richard Smithf634c902012-03-16 06:12:59 +00001274
John McCall75b960e2010-06-01 09:23:16 +00001275 ExternalASTSource *Source = getParentASTContext().getExternalSource();
Richard Smith4abe0a82013-09-09 07:34:56 +00001276 if (Source->FindExternalVisibleDeclsByName(this, Name) || R.second) {
Richard Smith9ce12e32013-02-07 03:30:24 +00001277 if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
1278 StoredDeclsMap::iterator I = Map->find(Name);
1279 if (I != Map->end())
1280 return I->second.getLookupResult();
1281 }
1282 }
1283
1284 return lookup_result(lookup_iterator(0), lookup_iterator(0));
John McCall75b960e2010-06-01 09:23:16 +00001285 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001286
Richard Smithf634c902012-03-16 06:12:59 +00001287 StoredDeclsMap *Map = LookupPtr.getPointer();
1288 if (LookupPtr.getInt())
1289 Map = buildLookup();
1290
1291 if (!Map)
1292 return lookup_result(lookup_iterator(0), lookup_iterator(0));
1293
1294 StoredDeclsMap::iterator I = Map->find(Name);
1295 if (I == Map->end())
1296 return lookup_result(lookup_iterator(0), lookup_iterator(0));
1297
1298 return I->second.getLookupResult();
Douglas Gregor91f84212008-12-11 16:49:14 +00001299}
1300
Richard Smith95d99302013-07-13 02:00:19 +00001301DeclContext::lookup_result
1302DeclContext::noload_lookup(DeclarationName Name) {
1303 assert(DeclKind != Decl::LinkageSpec &&
1304 "Should not perform lookups into linkage specs!");
1305 if (!hasExternalVisibleStorage())
1306 return lookup(Name);
1307
1308 DeclContext *PrimaryContext = getPrimaryContext();
1309 if (PrimaryContext != this)
1310 return PrimaryContext->noload_lookup(Name);
1311
1312 StoredDeclsMap *Map = LookupPtr.getPointer();
1313 if (LookupPtr.getInt()) {
1314 // Carefully build the lookup map, without deserializing anything.
1315 SmallVector<DeclContext *, 2> Contexts;
1316 collectAllContexts(Contexts);
1317 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1318 buildLookupImpl<&DeclContext::noload_decls_begin,
1319 &DeclContext::noload_decls_end>(Contexts[I]);
1320
1321 // We no longer have any lazy decls.
1322 LookupPtr.setInt(false);
1323
1324 // There may now be names for which we have local decls but are
Richard Smith4abe0a82013-09-09 07:34:56 +00001325 // missing the external decls. FIXME: Just set the hasExternalDecls
1326 // flag on those names that have external decls.
Richard Smith95d99302013-07-13 02:00:19 +00001327 NeedToReconcileExternalVisibleStorage = true;
1328
1329 Map = LookupPtr.getPointer();
1330 }
1331
1332 if (!Map)
1333 return lookup_result(lookup_iterator(0), lookup_iterator(0));
1334
1335 StoredDeclsMap::iterator I = Map->find(Name);
1336 return I != Map->end()
1337 ? I->second.getLookupResult()
1338 : lookup_result(lookup_iterator(0), lookup_iterator(0));
1339}
1340
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001341void DeclContext::localUncachedLookup(DeclarationName Name,
1342 SmallVectorImpl<NamedDecl *> &Results) {
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001343 Results.clear();
1344
1345 // If there's no external storage, just perform a normal lookup and copy
1346 // the results.
Douglas Gregordd6006f2012-07-17 21:16:27 +00001347 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001348 lookup_result LookupResults = lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00001349 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001350 return;
1351 }
1352
1353 // If we have a lookup table, check there first. Maybe we'll get lucky.
Richard Smith645d7552013-02-07 03:37:08 +00001354 if (Name && !LookupPtr.getInt()) {
Douglas Gregordd6006f2012-07-17 21:16:27 +00001355 if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
1356 StoredDeclsMap::iterator Pos = Map->find(Name);
1357 if (Pos != Map->end()) {
1358 Results.insert(Results.end(),
David Blaikieff7d47a2012-12-19 00:45:41 +00001359 Pos->second.getLookupResult().begin(),
1360 Pos->second.getLookupResult().end());
Douglas Gregordd6006f2012-07-17 21:16:27 +00001361 return;
1362 }
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001363 }
1364 }
Douglas Gregordd6006f2012-07-17 21:16:27 +00001365
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001366 // Slow case: grovel through the declarations in our chain looking for
1367 // matches.
1368 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1369 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1370 if (ND->getDeclName() == Name)
1371 Results.push_back(ND);
1372 }
1373}
1374
Sebastian Redl50c68252010-08-31 00:36:30 +00001375DeclContext *DeclContext::getRedeclContext() {
Chris Lattner17a1bfa2009-03-27 19:19:59 +00001376 DeclContext *Ctx = this;
Sebastian Redlbd595762010-08-31 20:53:31 +00001377 // Skip through transparent contexts.
1378 while (Ctx->isTransparentContext())
Douglas Gregor6ad0ef52009-01-06 23:51:29 +00001379 Ctx = Ctx->getParent();
1380 return Ctx;
1381}
1382
Douglas Gregorf47b9112009-02-25 22:02:03 +00001383DeclContext *DeclContext::getEnclosingNamespaceContext() {
1384 DeclContext *Ctx = this;
1385 // Skip through non-namespace, non-translation-unit contexts.
Sebastian Redl4f08c962010-08-31 00:36:23 +00001386 while (!Ctx->isFileContext())
Douglas Gregorf47b9112009-02-25 22:02:03 +00001387 Ctx = Ctx->getParent();
1388 return Ctx->getPrimaryContext();
1389}
1390
Sebastian Redl50c68252010-08-31 00:36:30 +00001391bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1392 // For non-file contexts, this is equivalent to Equals.
1393 if (!isFileContext())
1394 return O->Equals(this);
1395
1396 do {
1397 if (O->Equals(this))
1398 return true;
1399
1400 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1401 if (!NS || !NS->isInline())
1402 break;
1403 O = NS->getParent();
1404 } while (O);
1405
1406 return false;
1407}
1408
Richard Smithf634c902012-03-16 06:12:59 +00001409void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1410 DeclContext *PrimaryDC = this->getPrimaryContext();
1411 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1412 // If the decl is being added outside of its semantic decl context, we
1413 // need to ensure that we eagerly build the lookup information for it.
1414 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
Sean Callanan95e74be2011-10-21 02:57:43 +00001415}
1416
Richard Smithf634c902012-03-16 06:12:59 +00001417void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1418 bool Recoverable) {
1419 assert(this == getPrimaryContext() && "expected a primary DC");
Sean Callanan95e74be2011-10-21 02:57:43 +00001420
Richard Smith05afe5e2012-03-13 03:12:56 +00001421 // Skip declarations within functions.
Richard Smith114394f2013-08-09 04:35:01 +00001422 if (isFunctionOrMethod())
Richard Smith05afe5e2012-03-13 03:12:56 +00001423 return;
1424
Richard Smithf634c902012-03-16 06:12:59 +00001425 // Skip declarations which should be invisible to name lookup.
1426 if (shouldBeHidden(D))
1427 return;
1428
1429 // If we already have a lookup data structure, perform the insertion into
1430 // it. If we might have externally-stored decls with this name, look them
1431 // up and perform the insertion. If this decl was declared outside its
1432 // semantic context, buildLookup won't add it, so add it now.
1433 //
1434 // FIXME: As a performance hack, don't add such decls into the translation
1435 // unit unless we're in C++, since qualified lookup into the TU is never
1436 // performed.
1437 if (LookupPtr.getPointer() || hasExternalVisibleStorage() ||
1438 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1439 (getParentASTContext().getLangOpts().CPlusPlus ||
1440 !isTranslationUnit()))) {
1441 // If we have lazily omitted any decls, they might have the same name as
1442 // the decl which we are adding, so build a full lookup table before adding
1443 // this decl.
1444 buildLookup();
1445 makeDeclVisibleInContextImpl(D, Internal);
1446 } else {
1447 LookupPtr.setInt(true);
1448 }
1449
1450 // If we are a transparent context or inline namespace, insert into our
1451 // parent context, too. This operation is recursive.
1452 if (isTransparentContext() || isInlineNamespace())
1453 getParent()->getPrimaryContext()->
1454 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1455
1456 Decl *DCAsDecl = cast<Decl>(this);
1457 // Notify that a decl was made visible unless we are a Tag being defined.
1458 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1459 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1460 L->AddedVisibleDecl(this, D);
1461}
1462
1463void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1464 // Find or create the stored declaration map.
1465 StoredDeclsMap *Map = LookupPtr.getPointer();
1466 if (!Map) {
1467 ASTContext *C = &getParentASTContext();
1468 Map = CreateStoredDeclsMap(*C);
Argyrios Kyrtzidise51e5542010-07-04 21:44:25 +00001469 }
1470
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001471 // If there is an external AST source, load any declarations it knows about
1472 // with this declaration's name.
1473 // If the lookup table contains an entry about this name it means that we
1474 // have already checked the external source.
Sean Callanan95e74be2011-10-21 02:57:43 +00001475 if (!Internal)
1476 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1477 if (hasExternalVisibleStorage() &&
Richard Smithf634c902012-03-16 06:12:59 +00001478 Map->find(D->getDeclName()) == Map->end())
Sean Callanan95e74be2011-10-21 02:57:43 +00001479 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001480
Douglas Gregor91f84212008-12-11 16:49:14 +00001481 // Insert this declaration into the map.
Richard Smithf634c902012-03-16 06:12:59 +00001482 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
Richard Smith4abe0a82013-09-09 07:34:56 +00001483
1484 if (Internal) {
1485 // If this is being added as part of loading an external declaration,
1486 // this may not be the only external declaration with this name.
1487 // In this case, we never try to replace an existing declaration; we'll
1488 // handle that when we finalize the list of declarations for this name.
1489 DeclNameEntries.setHasExternalDecls();
1490 DeclNameEntries.AddSubsequentDecl(D);
1491 return;
1492 }
1493
1494 else if (DeclNameEntries.isNull()) {
Chris Lattnercaae7162009-02-20 01:44:05 +00001495 DeclNameEntries.setOnlyValue(D);
Richard Smithf634c902012-03-16 06:12:59 +00001496 return;
Douglas Gregor91f84212008-12-11 16:49:14 +00001497 }
Chris Lattner24e24d52009-02-20 00:55:03 +00001498
Richard Smithf634c902012-03-16 06:12:59 +00001499 if (DeclNameEntries.HandleRedeclaration(D)) {
1500 // This declaration has replaced an existing one for which
1501 // declarationReplaces returns true.
1502 return;
1503 }
Mike Stump11289f42009-09-09 15:08:12 +00001504
Richard Smithf634c902012-03-16 06:12:59 +00001505 // Put this declaration into the appropriate slot.
1506 DeclNameEntries.AddSubsequentDecl(D);
Douglas Gregor91f84212008-12-11 16:49:14 +00001507}
Douglas Gregor889ceb72009-02-03 19:21:40 +00001508
1509/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1510/// this context.
Mike Stump11289f42009-09-09 15:08:12 +00001511DeclContext::udir_iterator_range
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001512DeclContext::getUsingDirectives() const {
Richard Smith05afe5e2012-03-13 03:12:56 +00001513 // FIXME: Use something more efficient than normal lookup for using
1514 // directives. In C++, using directives are looked up more than anything else.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001515 lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
David Blaikieff7d47a2012-12-19 00:45:41 +00001516 return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.begin()),
1517 reinterpret_cast<udir_iterator>(Result.end()));
Douglas Gregor889ceb72009-02-03 19:21:40 +00001518}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001519
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001520//===----------------------------------------------------------------------===//
1521// Creation and Destruction of StoredDeclsMaps. //
1522//===----------------------------------------------------------------------===//
1523
John McCallc62bb642010-03-24 05:22:00 +00001524StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
Richard Smithf634c902012-03-16 06:12:59 +00001525 assert(!LookupPtr.getPointer() && "context already has a decls map");
John McCallc62bb642010-03-24 05:22:00 +00001526 assert(getPrimaryContext() == this &&
1527 "creating decls map on non-primary context");
1528
1529 StoredDeclsMap *M;
1530 bool Dependent = isDependentContext();
1531 if (Dependent)
1532 M = new DependentStoredDeclsMap();
1533 else
1534 M = new StoredDeclsMap();
1535 M->Previous = C.LastSDM;
1536 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
Richard Smithf634c902012-03-16 06:12:59 +00001537 LookupPtr.setPointer(M);
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001538 return M;
1539}
1540
1541void ASTContext::ReleaseDeclContextMaps() {
John McCallc62bb642010-03-24 05:22:00 +00001542 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1543 // pointer because the subclass doesn't add anything that needs to
1544 // be deleted.
John McCallc62bb642010-03-24 05:22:00 +00001545 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1546}
1547
1548void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1549 while (Map) {
1550 // Advance the iteration before we invalidate memory.
1551 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1552
1553 if (Dependent)
1554 delete static_cast<DependentStoredDeclsMap*>(Map);
1555 else
1556 delete Map;
1557
1558 Map = Next.getPointer();
1559 Dependent = Next.getInt();
1560 }
1561}
1562
John McCallc62bb642010-03-24 05:22:00 +00001563DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1564 DeclContext *Parent,
1565 const PartialDiagnostic &PDiag) {
1566 assert(Parent->isDependentContext()
1567 && "cannot iterate dependent diagnostics of non-dependent context");
1568 Parent = Parent->getPrimaryContext();
Richard Smithf634c902012-03-16 06:12:59 +00001569 if (!Parent->LookupPtr.getPointer())
John McCallc62bb642010-03-24 05:22:00 +00001570 Parent->CreateStoredDeclsMap(C);
1571
1572 DependentStoredDeclsMap *Map
Richard Smithf634c902012-03-16 06:12:59 +00001573 = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr.getPointer());
John McCallc62bb642010-03-24 05:22:00 +00001574
Douglas Gregora55530e2010-03-29 23:56:53 +00001575 // Allocate the copy of the PartialDiagnostic via the ASTContext's
Douglas Gregor89336232010-03-29 23:34:08 +00001576 // BumpPtrAllocator, rather than the ASTContext itself.
Douglas Gregora55530e2010-03-29 23:56:53 +00001577 PartialDiagnostic::Storage *DiagStorage = 0;
1578 if (PDiag.hasStorage())
1579 DiagStorage = new (C) PartialDiagnostic::Storage;
1580
1581 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
John McCallc62bb642010-03-24 05:22:00 +00001582
1583 // TODO: Maybe we shouldn't reverse the order during insertion.
1584 DD->NextDiagnostic = Map->FirstDiagnostic;
1585 Map->FirstDiagnostic = DD;
1586
1587 return DD;
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001588}