blob: 8e7373631dbbbea7437216defd76b3b15b02662e [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;
Alp Tokera5d64592013-12-21 01:10:54 +000088 assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
Argyrios Kyrtzidisb7d1ca22012-03-09 21:09:04 +000089 if (Invalid && !isa<ParmVarDecl>(this)) {
Douglas Gregor90d47172010-03-05 00:26:45 +000090 // Defensive maneuver for ill-formed code: we're likely not to make it to
91 // a point where we set the access specifier, so default it to "public"
92 // to avoid triggering asserts elsewhere in the front end.
93 setAccess(AS_public);
94 }
95}
96
Steve Naroff5faaef72009-01-20 19:53:53 +000097const char *DeclContext::getDeclKindName() const {
98 switch (DeclKind) {
David Blaikie83d382b2011-09-23 05:06:16 +000099 default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
Alexis Hunted053252010-05-30 07:21:58 +0000100#define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
101#define ABSTRACT_DECL(DECL)
102#include "clang/AST/DeclNodes.inc"
Steve Naroff5faaef72009-01-20 19:53:53 +0000103 }
104}
105
Daniel Dunbar62905572012-03-05 21:42:49 +0000106bool Decl::StatisticsEnabled = false;
107void Decl::EnableStatistics() {
108 StatisticsEnabled = true;
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000109}
110
111void Decl::PrintStats() {
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000112 llvm::errs() << "\n*** Decl Stats:\n";
Mike Stump11289f42009-09-09 15:08:12 +0000113
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000114 int totalDecls = 0;
Alexis Hunted053252010-05-30 07:21:58 +0000115#define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
116#define ABSTRACT_DECL(DECL)
117#include "clang/AST/DeclNodes.inc"
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000118 llvm::errs() << " " << totalDecls << " decls total.\n";
Mike Stump11289f42009-09-09 15:08:12 +0000119
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000120 int totalBytes = 0;
Alexis Hunted053252010-05-30 07:21:58 +0000121#define DECL(DERIVED, BASE) \
122 if (n##DERIVED##s > 0) { \
123 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000124 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
125 << sizeof(DERIVED##Decl) << " each (" \
126 << n##DERIVED##s * sizeof(DERIVED##Decl) \
127 << " bytes)\n"; \
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000128 }
Alexis Hunted053252010-05-30 07:21:58 +0000129#define ABSTRACT_DECL(DECL)
130#include "clang/AST/DeclNodes.inc"
Mike Stump11289f42009-09-09 15:08:12 +0000131
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000132 llvm::errs() << "Total bytes = " << totalBytes << "\n";
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000133}
134
Alexis Hunted053252010-05-30 07:21:58 +0000135void Decl::add(Kind k) {
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000136 switch (k) {
Alexis Hunted053252010-05-30 07:21:58 +0000137#define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
138#define ABSTRACT_DECL(DECL)
139#include "clang/AST/DeclNodes.inc"
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000140 }
141}
142
Anders Carlssonaa73b912009-06-13 00:08:58 +0000143bool Decl::isTemplateParameterPack() const {
144 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
145 return TTP->isParameterPack();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000146 if (const NonTypeTemplateParmDecl *NTTP
Douglas Gregorf5500772011-01-05 15:48:55 +0000147 = dyn_cast<NonTypeTemplateParmDecl>(this))
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000148 return NTTP->isParameterPack();
Douglas Gregorf5500772011-01-05 15:48:55 +0000149 if (const TemplateTemplateParmDecl *TTP
150 = dyn_cast<TemplateTemplateParmDecl>(this))
151 return TTP->isParameterPack();
Anders Carlssonaa73b912009-06-13 00:08:58 +0000152 return false;
153}
154
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +0000155bool Decl::isParameterPack() const {
156 if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
157 return Parm->isParameterPack();
158
159 return isTemplateParameterPack();
160}
161
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000162bool Decl::isFunctionOrFunctionTemplate() const {
John McCall3f746822009-11-17 05:59:44 +0000163 if (const UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(this))
Anders Carlssonf057cb22009-06-26 05:26:50 +0000164 return UD->getTargetDecl()->isFunctionOrFunctionTemplate();
Mike Stump11289f42009-09-09 15:08:12 +0000165
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000166 return isa<FunctionDecl>(this) || isa<FunctionTemplateDecl>(this);
167}
168
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000169bool Decl::isTemplateDecl() const {
170 return isa<TemplateDecl>(this);
171}
172
Argyrios Kyrtzidis0ce4c9a2011-09-28 02:45:33 +0000173const DeclContext *Decl::getParentFunctionOrMethod() const {
174 for (const DeclContext *DC = getDeclContext();
175 DC && !DC->isTranslationUnit() && !DC->isNamespace();
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000176 DC = DC->getParent())
177 if (DC->isFunctionOrMethod())
Argyrios Kyrtzidis0ce4c9a2011-09-28 02:45:33 +0000178 return DC;
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000179
Argyrios Kyrtzidis0ce4c9a2011-09-28 02:45:33 +0000180 return 0;
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000181}
182
Douglas Gregor133eddd2011-02-17 08:47:29 +0000183
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000184//===----------------------------------------------------------------------===//
Chris Lattnereae6cb62009-03-05 08:00:35 +0000185// PrettyStackTraceDecl Implementation
186//===----------------------------------------------------------------------===//
Mike Stump11289f42009-09-09 15:08:12 +0000187
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000188void PrettyStackTraceDecl::print(raw_ostream &OS) const {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000189 SourceLocation TheLoc = Loc;
190 if (TheLoc.isInvalid() && TheDecl)
191 TheLoc = TheDecl->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000192
Chris Lattnereae6cb62009-03-05 08:00:35 +0000193 if (TheLoc.isValid()) {
194 TheLoc.print(OS, SM);
195 OS << ": ";
196 }
197
198 OS << Message;
199
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +0000200 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
201 OS << " '";
202 DN->printQualifiedName(OS);
203 OS << '\'';
204 }
Chris Lattnereae6cb62009-03-05 08:00:35 +0000205 OS << '\n';
206}
Mike Stump11289f42009-09-09 15:08:12 +0000207
Chris Lattnereae6cb62009-03-05 08:00:35 +0000208//===----------------------------------------------------------------------===//
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000209// Decl Implementation
210//===----------------------------------------------------------------------===//
211
Douglas Gregorb11aad82011-02-19 18:51:44 +0000212// Out-of-line virtual method providing a home for Decl.
213Decl::~Decl() { }
Douglas Gregora43942a2011-02-17 07:02:32 +0000214
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000215void Decl::setDeclContext(DeclContext *DC) {
Chris Lattnerb81eb052009-03-29 06:06:59 +0000216 DeclCtx = DC;
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000217}
218
219void Decl::setLexicalDeclContext(DeclContext *DC) {
220 if (DC == getLexicalDeclContext())
221 return;
222
223 if (isInSemaDC()) {
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000224 setDeclContextsImpl(getDeclContext(), DC, getASTContext());
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000225 } else {
226 getMultipleDC()->LexicalDC = DC;
227 }
228}
229
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000230void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
231 ASTContext &Ctx) {
232 if (SemaDC == LexicalDC) {
233 DeclCtx = SemaDC;
234 } else {
235 Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
236 MDC->SemanticDC = SemaDC;
237 MDC->LexicalDC = LexicalDC;
238 DeclCtx = MDC;
239 }
240}
241
John McCall4fa53422009-10-01 00:25:31 +0000242bool Decl::isInAnonymousNamespace() const {
243 const DeclContext *DC = getDeclContext();
244 do {
245 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
246 if (ND->isAnonymousNamespace())
247 return true;
248 } while ((DC = DC->getParent()));
249
250 return false;
251}
252
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000253TranslationUnitDecl *Decl::getTranslationUnitDecl() {
Argyrios Kyrtzidis4e1a72b2009-06-30 02:34:53 +0000254 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
255 return TUD;
256
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000257 DeclContext *DC = getDeclContext();
258 assert(DC && "This decl is not contained in a translation unit!");
Mike Stump11289f42009-09-09 15:08:12 +0000259
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000260 while (!DC->isTranslationUnit()) {
261 DC = DC->getParent();
262 assert(DC && "This decl is not contained in a translation unit!");
263 }
Mike Stump11289f42009-09-09 15:08:12 +0000264
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000265 return cast<TranslationUnitDecl>(DC);
266}
267
268ASTContext &Decl::getASTContext() const {
Mike Stump11289f42009-09-09 15:08:12 +0000269 return getTranslationUnitDecl()->getASTContext();
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000270}
271
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +0000272ASTMutationListener *Decl::getASTMutationListener() const {
273 return getASTContext().getASTMutationListener();
274}
275
Benjamin Kramerea70eb32012-12-01 15:09:41 +0000276unsigned Decl::getMaxAlignment() const {
277 if (!hasAttrs())
278 return 0;
279
280 unsigned Align = 0;
281 const AttrVec &V = getAttrs();
282 ASTContext &Ctx = getASTContext();
283 specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
284 for (; I != E; ++I)
285 Align = std::max(Align, I->getAlignment(Ctx));
286 return Align;
287}
288
Douglas Gregorebada0772010-06-17 23:14:26 +0000289bool Decl::isUsed(bool CheckUsedAttr) const {
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000290 if (Used)
291 return true;
292
293 // Check for used attribute.
Douglas Gregorebada0772010-06-17 23:14:26 +0000294 if (CheckUsedAttr && hasAttr<UsedAttr>())
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000295 return true;
Rafael Espindola99e3bfb2012-11-23 16:26:30 +0000296
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000297 return false;
298}
299
Eli Friedman276dd182013-09-05 00:02:25 +0000300void Decl::markUsed(ASTContext &C) {
301 if (Used)
302 return;
303
304 if (C.getASTMutationListener())
305 C.getASTMutationListener()->DeclarationMarkedUsed(this);
306
307 Used = true;
308}
309
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +0000310bool Decl::isReferenced() const {
311 if (Referenced)
312 return true;
313
314 // Check redeclarations.
315 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
316 if (I->Referenced)
317 return true;
318
319 return false;
320}
321
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000322/// \brief Determine the availability of the given declaration based on
323/// the target platform.
324///
325/// When it returns an availability result other than \c AR_Available,
326/// if the \p Message parameter is non-NULL, it will be set to a
327/// string describing why the entity is unavailable.
328///
329/// FIXME: Make these strings localizable, since they end up in
330/// diagnostics.
331static AvailabilityResult CheckAvailability(ASTContext &Context,
332 const AvailabilityAttr *A,
333 std::string *Message) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000334 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000335 StringRef PrettyPlatformName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000336 = AvailabilityAttr::getPrettyPlatformName(TargetPlatform);
337 if (PrettyPlatformName.empty())
338 PrettyPlatformName = TargetPlatform;
339
Douglas Gregore8bbc122011-09-02 00:18:52 +0000340 VersionTuple TargetMinVersion = Context.getTargetInfo().getPlatformMinVersion();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000341 if (TargetMinVersion.empty())
342 return AR_Available;
343
344 // Match the platform name.
345 if (A->getPlatform()->getName() != TargetPlatform)
346 return AR_Available;
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000347
348 std::string HintMessage;
349 if (!A->getMessage().empty()) {
350 HintMessage = " - ";
351 HintMessage += A->getMessage();
352 }
353
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000354 // Make sure that this declaration has not been marked 'unavailable'.
355 if (A->getUnavailable()) {
356 if (Message) {
357 Message->clear();
358 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000359 Out << "not available on " << PrettyPlatformName
360 << HintMessage;
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000361 }
362
363 return AR_Unavailable;
364 }
365
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000366 // Make sure that this declaration has already been introduced.
367 if (!A->getIntroduced().empty() &&
368 TargetMinVersion < A->getIntroduced()) {
369 if (Message) {
370 Message->clear();
371 llvm::raw_string_ostream Out(*Message);
372 Out << "introduced in " << PrettyPlatformName << ' '
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000373 << A->getIntroduced() << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000374 }
375
376 return AR_NotYetIntroduced;
377 }
378
379 // Make sure that this declaration hasn't been obsoleted.
380 if (!A->getObsoleted().empty() && TargetMinVersion >= A->getObsoleted()) {
381 if (Message) {
382 Message->clear();
383 llvm::raw_string_ostream Out(*Message);
384 Out << "obsoleted in " << PrettyPlatformName << ' '
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000385 << A->getObsoleted() << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000386 }
387
388 return AR_Unavailable;
389 }
390
391 // Make sure that this declaration hasn't been deprecated.
392 if (!A->getDeprecated().empty() && TargetMinVersion >= A->getDeprecated()) {
393 if (Message) {
394 Message->clear();
395 llvm::raw_string_ostream Out(*Message);
396 Out << "first deprecated in " << PrettyPlatformName << ' '
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000397 << A->getDeprecated() << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000398 }
399
400 return AR_Deprecated;
401 }
402
403 return AR_Available;
404}
405
406AvailabilityResult Decl::getAvailability(std::string *Message) const {
407 AvailabilityResult Result = AR_Available;
408 std::string ResultMessage;
409
410 for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) {
411 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(*A)) {
412 if (Result >= AR_Deprecated)
413 continue;
414
415 if (Message)
416 ResultMessage = Deprecated->getMessage();
417
418 Result = AR_Deprecated;
419 continue;
420 }
421
422 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(*A)) {
423 if (Message)
424 *Message = Unavailable->getMessage();
425 return AR_Unavailable;
426 }
427
428 if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) {
429 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
430 Message);
431
432 if (AR == AR_Unavailable)
433 return AR_Unavailable;
434
435 if (AR > Result) {
436 Result = AR;
437 if (Message)
438 ResultMessage.swap(*Message);
439 }
440 continue;
441 }
442 }
443
444 if (Message)
445 Message->swap(ResultMessage);
446 return Result;
447}
448
449bool Decl::canBeWeakImported(bool &IsDefinition) const {
450 IsDefinition = false;
John McCall5fb5df92012-06-20 06:18:46 +0000451
452 // Variables, if they aren't definitions.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000453 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000454 if (Var->isThisDeclarationADefinition()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000455 IsDefinition = true;
456 return false;
457 }
John McCall5fb5df92012-06-20 06:18:46 +0000458 return true;
459
460 // Functions, if they aren't definitions.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000461 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
462 if (FD->hasBody()) {
463 IsDefinition = true;
464 return false;
465 }
John McCall5fb5df92012-06-20 06:18:46 +0000466 return true;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000467
John McCall5fb5df92012-06-20 06:18:46 +0000468 // Objective-C classes, if this is the non-fragile runtime.
469 } else if (isa<ObjCInterfaceDecl>(this) &&
John McCall18ac1632012-06-20 21:58:02 +0000470 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
John McCall5fb5df92012-06-20 06:18:46 +0000471 return true;
472
473 // Nothing else.
474 } else {
475 return false;
476 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000477}
478
479bool Decl::isWeakImported() const {
480 bool IsDefinition;
481 if (!canBeWeakImported(IsDefinition))
482 return false;
483
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000484 for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) {
485 if (isa<WeakImportAttr>(*A))
486 return true;
487
488 if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) {
489 if (CheckAvailability(getASTContext(), Availability, 0)
490 == AR_NotYetIntroduced)
491 return true;
492 }
493 }
494
495 return false;
496}
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000497
Chris Lattner8e097192009-03-27 20:18:19 +0000498unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
499 switch (DeclKind) {
John McCall3f746822009-11-17 05:59:44 +0000500 case Function:
501 case CXXMethod:
502 case CXXConstructor:
503 case CXXDestructor:
504 case CXXConversion:
Chris Lattner8e097192009-03-27 20:18:19 +0000505 case EnumConstant:
506 case Var:
507 case ImplicitParam:
508 case ParmVar:
Chris Lattner8e097192009-03-27 20:18:19 +0000509 case NonTypeTemplateParm:
510 case ObjCMethod:
Daniel Dunbar45b2d8a2010-04-23 13:07:39 +0000511 case ObjCProperty:
John McCall5e77d762013-04-16 07:28:30 +0000512 case MSProperty:
Daniel Dunbar45b2d8a2010-04-23 13:07:39 +0000513 return IDNS_Ordinary;
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000514 case Label:
515 return IDNS_Label;
Francois Pichet783dd6e2010-11-21 06:08:52 +0000516 case IndirectField:
517 return IDNS_Ordinary | IDNS_Member;
518
John McCalle87beb22010-04-23 18:46:30 +0000519 case ObjCCompatibleAlias:
520 case ObjCInterface:
521 return IDNS_Ordinary | IDNS_Type;
522
523 case Typedef:
Richard Smithdda56e42011-04-15 14:24:37 +0000524 case TypeAlias:
Richard Smith3f1b5d02011-05-05 21:57:07 +0000525 case TypeAliasTemplate:
John McCalle87beb22010-04-23 18:46:30 +0000526 case UnresolvedUsingTypename:
527 case TemplateTypeParm:
528 return IDNS_Ordinary | IDNS_Type;
529
John McCall3f746822009-11-17 05:59:44 +0000530 case UsingShadow:
531 return 0; // we'll actually overwrite this later
532
John McCalle61f2ba2009-11-18 02:36:19 +0000533 case UnresolvedUsingValue:
John McCalle61f2ba2009-11-18 02:36:19 +0000534 return IDNS_Ordinary | IDNS_Using;
John McCall3f746822009-11-17 05:59:44 +0000535
536 case Using:
537 return IDNS_Using;
538
Chris Lattner8e097192009-03-27 20:18:19 +0000539 case ObjCProtocol:
Douglas Gregor79947a22009-04-24 00:11:27 +0000540 return IDNS_ObjCProtocol;
Mike Stump11289f42009-09-09 15:08:12 +0000541
Chris Lattner8e097192009-03-27 20:18:19 +0000542 case Field:
543 case ObjCAtDefsField:
544 case ObjCIvar:
545 return IDNS_Member;
Mike Stump11289f42009-09-09 15:08:12 +0000546
Chris Lattner8e097192009-03-27 20:18:19 +0000547 case Record:
548 case CXXRecord:
549 case Enum:
John McCalle87beb22010-04-23 18:46:30 +0000550 return IDNS_Tag | IDNS_Type;
Mike Stump11289f42009-09-09 15:08:12 +0000551
Chris Lattner8e097192009-03-27 20:18:19 +0000552 case Namespace:
John McCalle87beb22010-04-23 18:46:30 +0000553 case NamespaceAlias:
554 return IDNS_Namespace;
555
Chris Lattner8e097192009-03-27 20:18:19 +0000556 case FunctionTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +0000557 case VarTemplate:
John McCalle87beb22010-04-23 18:46:30 +0000558 return IDNS_Ordinary;
559
Chris Lattner8e097192009-03-27 20:18:19 +0000560 case ClassTemplate:
561 case TemplateTemplateParm:
John McCalle87beb22010-04-23 18:46:30 +0000562 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
Mike Stump11289f42009-09-09 15:08:12 +0000563
Chris Lattner8e097192009-03-27 20:18:19 +0000564 // Never have names.
John McCallaa74a0c2009-08-28 07:59:38 +0000565 case Friend:
John McCall11083da2009-09-16 22:47:08 +0000566 case FriendTemplate:
Abramo Bagnarad7340582010-06-05 05:09:32 +0000567 case AccessSpec:
Chris Lattner8e097192009-03-27 20:18:19 +0000568 case LinkageSpec:
569 case FileScopeAsm:
570 case StaticAssert:
Chris Lattner8e097192009-03-27 20:18:19 +0000571 case ObjCPropertyImpl:
Chris Lattner8e097192009-03-27 20:18:19 +0000572 case Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +0000573 case Captured:
Chris Lattner8e097192009-03-27 20:18:19 +0000574 case TranslationUnit:
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000575
Chris Lattner8e097192009-03-27 20:18:19 +0000576 case UsingDirective:
577 case ClassTemplateSpecialization:
Douglas Gregor2373c592009-05-31 09:31:02 +0000578 case ClassTemplatePartialSpecialization:
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000579 case ClassScopeFunctionSpecialization:
Larisse Voufo39a1e502013-08-06 01:03:05 +0000580 case VarTemplateSpecialization:
581 case VarTemplatePartialSpecialization:
Douglas Gregore93525e2010-04-22 23:19:50 +0000582 case ObjCImplementation:
583 case ObjCCategory:
584 case ObjCCategoryImpl:
Douglas Gregorba345522011-12-02 23:23:56 +0000585 case Import:
Alexey Bataeva769e072013-03-22 06:34:35 +0000586 case OMPThreadPrivate:
Michael Han84324352013-02-22 17:15:32 +0000587 case Empty:
Douglas Gregore93525e2010-04-22 23:19:50 +0000588 // Never looked up by name.
Chris Lattner8e097192009-03-27 20:18:19 +0000589 return 0;
590 }
John McCall3f746822009-11-17 05:59:44 +0000591
David Blaikiee4d798f2012-01-20 21:50:17 +0000592 llvm_unreachable("Invalid DeclKind!");
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000593}
594
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000595void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
Argyrios Kyrtzidis91167172010-06-11 23:09:25 +0000596 assert(!HasAttrs && "Decl already contains attrs.");
597
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000598 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000599 assert(AttrBlank.empty() && "HasAttrs was wrong?");
Argyrios Kyrtzidis91167172010-06-11 23:09:25 +0000600
601 AttrBlank = attrs;
602 HasAttrs = true;
603}
604
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000605void Decl::dropAttrs() {
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000606 if (!HasAttrs) return;
Mike Stump11289f42009-09-09 15:08:12 +0000607
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000608 HasAttrs = false;
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000609 getASTContext().eraseDeclAttrs(this);
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000610}
611
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000612const AttrVec &Decl::getAttrs() const {
613 assert(HasAttrs && "No attrs to get!");
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000614 return getASTContext().getDeclAttrs(this);
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000615}
616
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000617Decl *Decl::castFromDeclContext (const DeclContext *D) {
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000618 Decl::Kind DK = D->getDeclKind();
619 switch(DK) {
Alexis Hunted053252010-05-30 07:21:58 +0000620#define DECL(NAME, BASE)
621#define DECL_CONTEXT(NAME) \
622 case Decl::NAME: \
623 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
624#define DECL_CONTEXT_BASE(NAME)
625#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000626 default:
Alexis Hunted053252010-05-30 07:21:58 +0000627#define DECL(NAME, BASE)
628#define DECL_CONTEXT_BASE(NAME) \
629 if (DK >= first##NAME && DK <= last##NAME) \
630 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
631#include "clang/AST/DeclNodes.inc"
David Blaikie83d382b2011-09-23 05:06:16 +0000632 llvm_unreachable("a decl that inherits DeclContext isn't handled");
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000633 }
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000634}
635
636DeclContext *Decl::castToDeclContext(const Decl *D) {
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000637 Decl::Kind DK = D->getKind();
638 switch(DK) {
Alexis Hunted053252010-05-30 07:21:58 +0000639#define DECL(NAME, BASE)
640#define DECL_CONTEXT(NAME) \
641 case Decl::NAME: \
642 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
643#define DECL_CONTEXT_BASE(NAME)
644#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000645 default:
Alexis Hunted053252010-05-30 07:21:58 +0000646#define DECL(NAME, BASE)
647#define DECL_CONTEXT_BASE(NAME) \
648 if (DK >= first##NAME && DK <= last##NAME) \
649 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
650#include "clang/AST/DeclNodes.inc"
David Blaikie83d382b2011-09-23 05:06:16 +0000651 llvm_unreachable("a decl that inherits DeclContext isn't handled");
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000652 }
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000653}
654
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000655SourceLocation Decl::getBodyRBrace() const {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +0000656 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
657 // FunctionDecl stores EndRangeLoc for this purpose.
658 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
659 const FunctionDecl *Definition;
660 if (FD->hasBody(Definition))
661 return Definition->getSourceRange().getEnd();
662 return SourceLocation();
663 }
664
Argyrios Kyrtzidis6fbc8fa2010-07-07 11:31:27 +0000665 if (Stmt *Body = getBody())
666 return Body->getSourceRange().getEnd();
667
668 return SourceLocation();
Sebastian Redla7b98a72009-04-26 20:35:05 +0000669}
670
Alp Tokerc1086762013-12-07 13:51:35 +0000671bool Decl::AccessDeclContextSanity() const {
Douglas Gregor4b00d3b2010-12-02 00:22:25 +0000672#ifndef NDEBUG
John McCall401982f2010-01-20 21:53:11 +0000673 // Suppress this check if any of the following hold:
674 // 1. this is the translation unit (and thus has no parent)
675 // 2. this is a template parameter (and thus doesn't belong to its context)
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000676 // 3. this is a non-type template parameter
677 // 4. the context is not a record
678 // 5. it's invalid
679 // 6. it's a C++0x static_assert.
Anders Carlssonadf36b22009-08-29 20:47:47 +0000680 if (isa<TranslationUnitDecl>(this) ||
Argyrios Kyrtzidisa45855f2010-07-02 11:55:44 +0000681 isa<TemplateTypeParmDecl>(this) ||
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000682 isa<NonTypeTemplateParmDecl>(this) ||
Douglas Gregor2b76dd92010-02-22 17:53:38 +0000683 !isa<CXXRecordDecl>(getDeclContext()) ||
Argyrios Kyrtzidis260b4a82010-09-08 21:32:35 +0000684 isInvalidDecl() ||
685 isa<StaticAssertDecl>(this) ||
686 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
687 // as DeclContext (?).
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000688 isa<ParmVarDecl>(this) ||
689 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
690 // AS_none as access specifier.
Francois Pichet09af8c32011-08-17 01:06:54 +0000691 isa<CXXRecordDecl>(this) ||
692 isa<ClassScopeFunctionSpecializationDecl>(this))
Alp Tokerc1086762013-12-07 13:51:35 +0000693 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000694
695 assert(Access != AS_none &&
Anders Carlssona28908d2009-03-25 23:38:06 +0000696 "Access specifier is AS_none inside a record decl");
Douglas Gregor4b00d3b2010-12-02 00:22:25 +0000697#endif
Alp Tokerc1086762013-12-07 13:51:35 +0000698 return true;
Anders Carlssona28908d2009-03-25 23:38:06 +0000699}
700
John McCalldec348f72013-05-03 07:33:41 +0000701static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
702static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
703
704/// Starting at a given context (a Decl or DeclContext), look for a
705/// code context that is not a closure (a lambda, block, etc.).
706template <class T> static Decl *getNonClosureContext(T *D) {
707 if (getKind(D) == Decl::CXXMethod) {
708 CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
John McCall55c0cee2013-05-03 17:11:14 +0000709 if (MD->getOverloadedOperator() == OO_Call &&
710 MD->getParent()->isLambda())
John McCalldec348f72013-05-03 07:33:41 +0000711 return getNonClosureContext(MD->getParent()->getParent());
712 return MD;
713 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
714 return FD;
715 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
716 return MD;
717 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
718 return getNonClosureContext(BD->getParent());
719 } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
720 return getNonClosureContext(CD->getParent());
721 } else {
722 return 0;
723 }
John McCallfe96e0b2011-11-06 09:01:30 +0000724}
725
John McCalldec348f72013-05-03 07:33:41 +0000726Decl *Decl::getNonClosureContext() {
727 return ::getNonClosureContext(this);
728}
John McCallb67608f2011-02-22 22:25:23 +0000729
John McCalldec348f72013-05-03 07:33:41 +0000730Decl *DeclContext::getNonClosureAncestor() {
731 return ::getNonClosureContext(this);
John McCallb67608f2011-02-22 22:25:23 +0000732}
Anders Carlssona28908d2009-03-25 23:38:06 +0000733
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000734//===----------------------------------------------------------------------===//
735// DeclContext Implementation
736//===----------------------------------------------------------------------===//
737
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000738bool DeclContext::classof(const Decl *D) {
739 switch (D->getKind()) {
Alexis Hunted053252010-05-30 07:21:58 +0000740#define DECL(NAME, BASE)
741#define DECL_CONTEXT(NAME) case Decl::NAME:
742#define DECL_CONTEXT_BASE(NAME)
743#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000744 return true;
745 default:
Alexis Hunted053252010-05-30 07:21:58 +0000746#define DECL(NAME, BASE)
747#define DECL_CONTEXT_BASE(NAME) \
748 if (D->getKind() >= Decl::first##NAME && \
749 D->getKind() <= Decl::last##NAME) \
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000750 return true;
Alexis Hunted053252010-05-30 07:21:58 +0000751#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000752 return false;
753 }
754}
755
Douglas Gregor9c832f72010-07-25 18:38:02 +0000756DeclContext::~DeclContext() { }
Douglas Gregor91f84212008-12-11 16:49:14 +0000757
Douglas Gregor7f737c02009-09-10 16:57:35 +0000758/// \brief Find the parent context of this context that will be
759/// used for unqualified name lookup.
760///
761/// Generally, the parent lookup context is the semantic context. However, for
762/// a friend function the parent lookup context is the lexical context, which
763/// is the class in which the friend is declared.
764DeclContext *DeclContext::getLookupParent() {
765 // FIXME: Find a better way to identify friends
766 if (isa<FunctionDecl>(this))
Sebastian Redl50c68252010-08-31 00:36:30 +0000767 if (getParent()->getRedeclContext()->isFileContext() &&
768 getLexicalParent()->getRedeclContext()->isRecord())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000769 return getLexicalParent();
770
771 return getParent();
772}
773
Sebastian Redlbd595762010-08-31 20:53:31 +0000774bool DeclContext::isInlineNamespace() const {
775 return isNamespace() &&
776 cast<NamespaceDecl>(this)->isInline();
777}
778
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000779bool DeclContext::isDependentContext() const {
780 if (isFileContext())
781 return false;
782
Douglas Gregor2373c592009-05-31 09:31:02 +0000783 if (isa<ClassTemplatePartialSpecializationDecl>(this))
784 return true;
785
Douglas Gregor680e9e02012-02-21 19:11:17 +0000786 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000787 if (Record->getDescribedClassTemplate())
788 return true;
Douglas Gregor680e9e02012-02-21 19:11:17 +0000789
790 if (Record->isDependentLambda())
791 return true;
792 }
793
John McCallc62bb642010-03-24 05:22:00 +0000794 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000795 if (Function->getDescribedFunctionTemplate())
796 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000797
John McCallc62bb642010-03-24 05:22:00 +0000798 // Friend function declarations are dependent if their *lexical*
799 // context is dependent.
800 if (cast<Decl>(this)->getFriendObjectKind())
801 return getLexicalParent()->isDependentContext();
802 }
803
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000804 return getParent() && getParent()->isDependentContext();
805}
806
Douglas Gregor07665a62009-01-05 19:45:36 +0000807bool DeclContext::isTransparentContext() const {
808 if (DeclKind == Decl::Enum)
Douglas Gregor0bf31402010-10-08 23:50:27 +0000809 return !cast<EnumDecl>(this)->isScoped();
Douglas Gregor07665a62009-01-05 19:45:36 +0000810 else if (DeclKind == Decl::LinkageSpec)
811 return true;
Douglas Gregor07665a62009-01-05 19:45:36 +0000812
813 return false;
814}
815
Serge Pavlov3cb80222013-11-14 02:13:03 +0000816static bool isLinkageSpecContext(const DeclContext *DC,
817 LinkageSpecDecl::LanguageIDs ID) {
818 while (DC->getDeclKind() != Decl::TranslationUnit) {
819 if (DC->getDeclKind() == Decl::LinkageSpec)
820 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
821 DC = DC->getParent();
822 }
823 return false;
824}
825
826bool DeclContext::isExternCContext() const {
827 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_c);
828}
829
830bool DeclContext::isExternCXXContext() const {
831 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_cxx);
832}
833
Sebastian Redl50c68252010-08-31 00:36:30 +0000834bool DeclContext::Encloses(const DeclContext *DC) const {
Douglas Gregore985a3b2009-08-27 06:03:53 +0000835 if (getPrimaryContext() != this)
836 return getPrimaryContext()->Encloses(DC);
Mike Stump11289f42009-09-09 15:08:12 +0000837
Douglas Gregore985a3b2009-08-27 06:03:53 +0000838 for (; DC; DC = DC->getParent())
839 if (DC->getPrimaryContext() == this)
840 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000841 return false;
Douglas Gregore985a3b2009-08-27 06:03:53 +0000842}
843
Steve Naroff35c62ae2009-01-08 17:28:14 +0000844DeclContext *DeclContext::getPrimaryContext() {
Douglas Gregor91f84212008-12-11 16:49:14 +0000845 switch (DeclKind) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000846 case Decl::TranslationUnit:
Douglas Gregor07665a62009-01-05 19:45:36 +0000847 case Decl::LinkageSpec:
Mike Stump11289f42009-09-09 15:08:12 +0000848 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +0000849 case Decl::Captured:
Douglas Gregor91f84212008-12-11 16:49:14 +0000850 // There is only one DeclContext for these entities.
851 return this;
852
853 case Decl::Namespace:
854 // The original namespace is our primary context.
855 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
856
Douglas Gregor91f84212008-12-11 16:49:14 +0000857 case Decl::ObjCMethod:
858 return this;
859
860 case Decl::ObjCInterface:
Douglas Gregor66b310c2011-12-15 18:03:09 +0000861 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
862 return Def;
863
864 return this;
865
Steve Naroff35c62ae2009-01-08 17:28:14 +0000866 case Decl::ObjCProtocol:
Douglas Gregora715bff2012-01-01 19:51:50 +0000867 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
868 return Def;
869
870 return this;
Douglas Gregor66b310c2011-12-15 18:03:09 +0000871
Steve Naroff35c62ae2009-01-08 17:28:14 +0000872 case Decl::ObjCCategory:
Douglas Gregor91f84212008-12-11 16:49:14 +0000873 return this;
874
Steve Naroff35c62ae2009-01-08 17:28:14 +0000875 case Decl::ObjCImplementation:
876 case Decl::ObjCCategoryImpl:
877 return this;
878
Douglas Gregor91f84212008-12-11 16:49:14 +0000879 default:
Alexis Hunted053252010-05-30 07:21:58 +0000880 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
Douglas Gregor67a65642009-02-17 23:15:12 +0000881 // If this is a tag type that has a definition or is currently
882 // being defined, that definition is our primary context.
John McCalle78aac42010-03-10 03:28:59 +0000883 TagDecl *Tag = cast<TagDecl>(this);
884 assert(isa<TagType>(Tag->TypeForDecl) ||
885 isa<InjectedClassNameType>(Tag->TypeForDecl));
886
887 if (TagDecl *Def = Tag->getDefinition())
888 return Def;
889
890 if (!isa<InjectedClassNameType>(Tag->TypeForDecl)) {
891 const TagType *TagTy = cast<TagType>(Tag->TypeForDecl);
892 if (TagTy->isBeingDefined())
893 // FIXME: is it necessarily being defined in the decl
894 // that owns the type?
895 return TagTy->getDecl();
896 }
897
898 return Tag;
Douglas Gregor67a65642009-02-17 23:15:12 +0000899 }
900
Alexis Hunted053252010-05-30 07:21:58 +0000901 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
Douglas Gregor91f84212008-12-11 16:49:14 +0000902 "Unknown DeclContext kind");
903 return this;
904 }
905}
906
Douglas Gregore57e7522012-01-07 09:11:48 +0000907void
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000908DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
Douglas Gregore57e7522012-01-07 09:11:48 +0000909 Contexts.clear();
910
911 if (DeclKind != Decl::Namespace) {
912 Contexts.push_back(this);
913 return;
Douglas Gregor91f84212008-12-11 16:49:14 +0000914 }
Douglas Gregore57e7522012-01-07 09:11:48 +0000915
916 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
Douglas Gregorec9fd132012-01-14 16:38:05 +0000917 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
918 N = N->getPreviousDecl())
Douglas Gregore57e7522012-01-07 09:11:48 +0000919 Contexts.push_back(N);
920
921 std::reverse(Contexts.begin(), Contexts.end());
Douglas Gregor91f84212008-12-11 16:49:14 +0000922}
923
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000924std::pair<Decl *, Decl *>
Bill Wendling8eb771d2012-02-22 09:51:33 +0000925DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +0000926 bool FieldsAlreadyLoaded) {
Douglas Gregor781f7132012-01-06 16:59:53 +0000927 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000928 Decl *FirstNewDecl = 0;
929 Decl *PrevDecl = 0;
930 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +0000931 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
932 continue;
933
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000934 Decl *D = Decls[I];
935 if (PrevDecl)
Douglas Gregor781f7132012-01-06 16:59:53 +0000936 PrevDecl->NextInContextAndBits.setPointer(D);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000937 else
938 FirstNewDecl = D;
939
940 PrevDecl = D;
941 }
942
943 return std::make_pair(FirstNewDecl, PrevDecl);
944}
945
Richard Smith645d7552013-02-07 03:37:08 +0000946/// \brief We have just acquired external visible storage, and we already have
947/// built a lookup map. For every name in the map, pull in the new names from
948/// the external storage.
949void DeclContext::reconcileExternalVisibleStorage() {
Richard Smith86a12012013-02-11 22:02:16 +0000950 assert(NeedToReconcileExternalVisibleStorage && LookupPtr.getPointer());
Richard Smith645d7552013-02-07 03:37:08 +0000951 NeedToReconcileExternalVisibleStorage = false;
952
953 StoredDeclsMap &Map = *LookupPtr.getPointer();
Richard Smith4abe0a82013-09-09 07:34:56 +0000954 for (StoredDeclsMap::iterator I = Map.begin(); I != Map.end(); ++I)
955 I->second.setHasExternalDecls();
Richard Smith645d7552013-02-07 03:37:08 +0000956}
957
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000958/// \brief Load the declarations within this lexical storage from an
959/// external source.
Mike Stump11289f42009-09-09 15:08:12 +0000960void
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000961DeclContext::LoadLexicalDeclsFromExternalStorage() const {
962 ExternalASTSource *Source = getParentASTContext().getExternalSource();
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000963 assert(hasExternalLexicalStorage() && Source && "No external storage?");
964
Argyrios Kyrtzidis98d045e2010-07-30 10:03:23 +0000965 // Notify that we have a DeclContext that is initializing.
966 ExternalASTSource::Deserializing ADeclContext(Source);
Douglas Gregorf337ae92011-08-26 21:23:06 +0000967
Douglas Gregor3d0adb32011-07-15 21:46:17 +0000968 // Load the external declarations, if any.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000969 SmallVector<Decl*, 64> Decls;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000970 ExternalLexicalStorage = false;
Douglas Gregor3d0adb32011-07-15 21:46:17 +0000971 switch (Source->FindExternalLexicalDecls(this, Decls)) {
972 case ELR_Success:
973 break;
974
975 case ELR_Failure:
976 case ELR_AlreadyLoaded:
977 return;
978 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000979
980 if (Decls.empty())
981 return;
982
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +0000983 // We may have already loaded just the fields of this record, in which case
984 // we need to ignore them.
985 bool FieldsAlreadyLoaded = false;
986 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
987 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
988
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000989 // Splice the newly-read declarations into the beginning of the list
990 // of declarations.
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000991 Decl *ExternalFirst, *ExternalLast;
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +0000992 llvm::tie(ExternalFirst, ExternalLast) = BuildDeclChain(Decls,
993 FieldsAlreadyLoaded);
Douglas Gregor781f7132012-01-06 16:59:53 +0000994 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000995 FirstDecl = ExternalFirst;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000996 if (!LastDecl)
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000997 LastDecl = ExternalLast;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000998}
999
John McCall75b960e2010-06-01 09:23:16 +00001000DeclContext::lookup_result
1001ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1002 DeclarationName Name) {
1003 ASTContext &Context = DC->getParentASTContext();
1004 StoredDeclsMap *Map;
Richard Smithf634c902012-03-16 06:12:59 +00001005 if (!(Map = DC->LookupPtr.getPointer()))
John McCall75b960e2010-06-01 09:23:16 +00001006 Map = DC->CreateStoredDeclsMap(Context);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001007
Richard Smith4abe0a82013-09-09 07:34:56 +00001008 (*Map)[Name].removeExternalDecls();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001009
John McCall75b960e2010-06-01 09:23:16 +00001010 return DeclContext::lookup_result();
1011}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001012
John McCall75b960e2010-06-01 09:23:16 +00001013DeclContext::lookup_result
1014ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
John McCall75b960e2010-06-01 09:23:16 +00001015 DeclarationName Name,
Argyrios Kyrtzidis94d3f9d2011-09-09 06:44:14 +00001016 ArrayRef<NamedDecl*> Decls) {
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00001017 ASTContext &Context = DC->getParentASTContext();
John McCall75b960e2010-06-01 09:23:16 +00001018 StoredDeclsMap *Map;
Richard Smithf634c902012-03-16 06:12:59 +00001019 if (!(Map = DC->LookupPtr.getPointer()))
John McCall75b960e2010-06-01 09:23:16 +00001020 Map = DC->CreateStoredDeclsMap(Context);
1021
1022 StoredDeclsList &List = (*Map)[Name];
Richard Smith51445cd2013-06-24 01:46:41 +00001023
1024 // Clear out any old external visible declarations, to avoid quadratic
1025 // performance in the redeclaration checks below.
1026 List.removeExternalDecls();
1027
1028 if (!List.isNull()) {
1029 // We have both existing declarations and new declarations for this name.
1030 // Some of the declarations may simply replace existing ones. Handle those
1031 // first.
1032 llvm::SmallVector<unsigned, 8> Skip;
1033 for (unsigned I = 0, N = Decls.size(); I != N; ++I)
1034 if (List.HandleRedeclaration(Decls[I]))
1035 Skip.push_back(I);
1036 Skip.push_back(Decls.size());
1037
1038 // Add in any new declarations.
1039 unsigned SkipPos = 0;
1040 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1041 if (I == Skip[SkipPos])
1042 ++SkipPos;
1043 else
1044 List.AddSubsequentDecl(Decls[I]);
1045 }
1046 } else {
1047 // Convert the array to a StoredDeclsList.
1048 for (ArrayRef<NamedDecl*>::iterator
1049 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1050 if (List.isNull())
1051 List.setOnlyValue(*I);
1052 else
1053 List.AddSubsequentDecl(*I);
1054 }
John McCall75b960e2010-06-01 09:23:16 +00001055 }
1056
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001057 return List.getLookupResult();
John McCall75b960e2010-06-01 09:23:16 +00001058}
1059
Sebastian Redl66c5eef2010-07-27 00:17:23 +00001060DeclContext::decl_iterator DeclContext::noload_decls_begin() const {
1061 return decl_iterator(FirstDecl);
1062}
1063
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001064DeclContext::decl_iterator DeclContext::decls_begin() const {
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001065 if (hasExternalLexicalStorage())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001066 LoadLexicalDeclsFromExternalStorage();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001067
Mike Stump11289f42009-09-09 15:08:12 +00001068 return decl_iterator(FirstDecl);
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001069}
1070
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001071bool DeclContext::decls_empty() const {
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001072 if (hasExternalLexicalStorage())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001073 LoadLexicalDeclsFromExternalStorage();
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001074
1075 return !FirstDecl;
1076}
1077
Sean Callanan0325fb82013-05-04 02:04:27 +00001078bool DeclContext::containsDecl(Decl *D) const {
1079 return (D->getLexicalDeclContext() == this &&
1080 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1081}
1082
John McCall84d87672009-12-10 09:41:52 +00001083void DeclContext::removeDecl(Decl *D) {
1084 assert(D->getLexicalDeclContext() == this &&
1085 "decl being removed from non-lexical context");
Douglas Gregor781f7132012-01-06 16:59:53 +00001086 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
John McCall84d87672009-12-10 09:41:52 +00001087 "decl is not in decls list");
1088
1089 // Remove D from the decl chain. This is O(n) but hopefully rare.
1090 if (D == FirstDecl) {
1091 if (D == LastDecl)
1092 FirstDecl = LastDecl = 0;
1093 else
Douglas Gregor781f7132012-01-06 16:59:53 +00001094 FirstDecl = D->NextInContextAndBits.getPointer();
John McCall84d87672009-12-10 09:41:52 +00001095 } else {
Douglas Gregor781f7132012-01-06 16:59:53 +00001096 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
John McCall84d87672009-12-10 09:41:52 +00001097 assert(I && "decl not found in linked list");
Douglas Gregor781f7132012-01-06 16:59:53 +00001098 if (I->NextInContextAndBits.getPointer() == D) {
1099 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
John McCall84d87672009-12-10 09:41:52 +00001100 if (D == LastDecl) LastDecl = I;
1101 break;
1102 }
1103 }
1104 }
1105
1106 // Mark that D is no longer in the decl chain.
Douglas Gregor781f7132012-01-06 16:59:53 +00001107 D->NextInContextAndBits.setPointer(0);
John McCall84d87672009-12-10 09:41:52 +00001108
1109 // Remove D from the lookup table if necessary.
1110 if (isa<NamedDecl>(D)) {
1111 NamedDecl *ND = cast<NamedDecl>(D);
1112
Axel Naumanncb2c52f2011-08-26 14:06:12 +00001113 // Remove only decls that have a name
1114 if (!ND->getDeclName()) return;
1115
Richard Smithf634c902012-03-16 06:12:59 +00001116 StoredDeclsMap *Map = getPrimaryContext()->LookupPtr.getPointer();
John McCallc62bb642010-03-24 05:22:00 +00001117 if (!Map) return;
John McCall84d87672009-12-10 09:41:52 +00001118
John McCall84d87672009-12-10 09:41:52 +00001119 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1120 assert(Pos != Map->end() && "no lookup entry for decl");
Axel Naumannfbc7b982011-11-08 18:21:06 +00001121 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1122 Pos->second.remove(ND);
John McCall84d87672009-12-10 09:41:52 +00001123 }
1124}
1125
John McCalld1e9d832009-08-11 06:59:38 +00001126void DeclContext::addHiddenDecl(Decl *D) {
Chris Lattner33f219d2009-02-20 00:56:18 +00001127 assert(D->getLexicalDeclContext() == this &&
1128 "Decl inserted into wrong lexical context");
Mike Stump11289f42009-09-09 15:08:12 +00001129 assert(!D->getNextDeclInContext() && D != LastDecl &&
Douglas Gregor020713e2009-01-09 19:42:16 +00001130 "Decl already inserted into a DeclContext");
1131
1132 if (FirstDecl) {
Douglas Gregor781f7132012-01-06 16:59:53 +00001133 LastDecl->NextInContextAndBits.setPointer(D);
Douglas Gregor020713e2009-01-09 19:42:16 +00001134 LastDecl = D;
1135 } else {
1136 FirstDecl = LastDecl = D;
1137 }
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001138
1139 // Notify a C++ record declaration that we've added a member, so it can
1140 // update it's class-specific state.
1141 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1142 Record->addedMember(D);
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001143
1144 // If this is a newly-created (not de-serialized) import declaration, wire
1145 // it in to the list of local import declarations.
1146 if (!D->isFromASTFile()) {
1147 if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1148 D->getASTContext().addedLocalImportDecl(Import);
1149 }
John McCalld1e9d832009-08-11 06:59:38 +00001150}
1151
1152void DeclContext::addDecl(Decl *D) {
1153 addHiddenDecl(D);
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001154
1155 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithf634c902012-03-16 06:12:59 +00001156 ND->getDeclContext()->getPrimaryContext()->
1157 makeDeclVisibleInContextWithFlags(ND, false, true);
Douglas Gregor91f84212008-12-11 16:49:14 +00001158}
1159
Sean Callanan95e74be2011-10-21 02:57:43 +00001160void DeclContext::addDeclInternal(Decl *D) {
1161 addHiddenDecl(D);
1162
1163 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithf634c902012-03-16 06:12:59 +00001164 ND->getDeclContext()->getPrimaryContext()->
1165 makeDeclVisibleInContextWithFlags(ND, true, true);
1166}
1167
1168/// shouldBeHidden - Determine whether a declaration which was declared
1169/// within its semantic context should be invisible to qualified name lookup.
1170static bool shouldBeHidden(NamedDecl *D) {
1171 // Skip unnamed declarations.
1172 if (!D->getDeclName())
1173 return true;
1174
1175 // Skip entities that can't be found by name lookup into a particular
1176 // context.
1177 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1178 D->isTemplateParameter())
1179 return true;
1180
1181 // Skip template specializations.
1182 // FIXME: This feels like a hack. Should DeclarationName support
1183 // template-ids, or is there a better way to keep specializations
1184 // from being visible?
1185 if (isa<ClassTemplateSpecializationDecl>(D))
1186 return true;
1187 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1188 if (FD->isFunctionTemplateSpecialization())
1189 return true;
1190
1191 return false;
1192}
1193
1194/// buildLookup - Build the lookup data structure with all of the
1195/// declarations in this DeclContext (and any other contexts linked
1196/// to it or transparent contexts nested within it) and return it.
1197StoredDeclsMap *DeclContext::buildLookup() {
1198 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1199
Richard Smith86a12012013-02-11 22:02:16 +00001200 // FIXME: Should we keep going if hasExternalVisibleStorage?
Richard Smithf634c902012-03-16 06:12:59 +00001201 if (!LookupPtr.getInt())
1202 return LookupPtr.getPointer();
1203
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001204 SmallVector<DeclContext *, 2> Contexts;
Richard Smithf634c902012-03-16 06:12:59 +00001205 collectAllContexts(Contexts);
1206 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
Richard Smith95d99302013-07-13 02:00:19 +00001207 buildLookupImpl<&DeclContext::decls_begin,
1208 &DeclContext::decls_end>(Contexts[I]);
Richard Smithf634c902012-03-16 06:12:59 +00001209
1210 // We no longer have any lazy decls.
1211 LookupPtr.setInt(false);
Richard Smith86a12012013-02-11 22:02:16 +00001212 NeedToReconcileExternalVisibleStorage = false;
Richard Smithf634c902012-03-16 06:12:59 +00001213 return LookupPtr.getPointer();
1214}
1215
1216/// buildLookupImpl - Build part of the lookup data structure for the
1217/// declarations contained within DCtx, which will either be this
1218/// DeclContext, a DeclContext linked to it, or a transparent context
1219/// nested within it.
Richard Smith95d99302013-07-13 02:00:19 +00001220template<DeclContext::decl_iterator (DeclContext::*Begin)() const,
1221 DeclContext::decl_iterator (DeclContext::*End)() const>
Richard Smithf634c902012-03-16 06:12:59 +00001222void DeclContext::buildLookupImpl(DeclContext *DCtx) {
Richard Smith95d99302013-07-13 02:00:19 +00001223 for (decl_iterator I = (DCtx->*Begin)(), E = (DCtx->*End)();
Richard Smithf634c902012-03-16 06:12:59 +00001224 I != E; ++I) {
1225 Decl *D = *I;
1226
1227 // Insert this declaration into the lookup structure, but only if
1228 // it's semantically within its decl context. Any other decls which
1229 // should be found in this context are added eagerly.
Richard Smithcf4ab522013-06-24 07:20:36 +00001230 //
1231 // If it's from an AST file, don't add it now. It'll get handled by
1232 // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1233 // in C++, we do not track external visible decls for the TU, so in
1234 // that case we need to collect them all here.
Richard Smithf634c902012-03-16 06:12:59 +00001235 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithcf4ab522013-06-24 07:20:36 +00001236 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1237 (!ND->isFromASTFile() ||
1238 (isTranslationUnit() &&
1239 !getParentASTContext().getLangOpts().CPlusPlus)))
Richard Smithf634c902012-03-16 06:12:59 +00001240 makeDeclVisibleInContextImpl(ND, false);
1241
1242 // If this declaration is itself a transparent declaration context
1243 // or inline namespace, add the members of this declaration of that
1244 // context (recursively).
1245 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1246 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Richard Smith95d99302013-07-13 02:00:19 +00001247 buildLookupImpl<Begin, End>(InnerCtx);
Richard Smithf634c902012-03-16 06:12:59 +00001248 }
Sean Callanan95e74be2011-10-21 02:57:43 +00001249}
1250
Mike Stump11289f42009-09-09 15:08:12 +00001251DeclContext::lookup_result
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001252DeclContext::lookup(DeclarationName Name) {
Nick Lewycky2bd636f2012-03-13 04:12:34 +00001253 assert(DeclKind != Decl::LinkageSpec &&
1254 "Should not perform lookups into linkage specs!");
1255
Steve Naroff35c62ae2009-01-08 17:28:14 +00001256 DeclContext *PrimaryContext = getPrimaryContext();
Douglas Gregor91f84212008-12-11 16:49:14 +00001257 if (PrimaryContext != this)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001258 return PrimaryContext->lookup(Name);
Douglas Gregor91f84212008-12-11 16:49:14 +00001259
Richard Smith05afe5e2012-03-13 03:12:56 +00001260 if (hasExternalVisibleStorage()) {
Richard Smith645d7552013-02-07 03:37:08 +00001261 StoredDeclsMap *Map = LookupPtr.getPointer();
1262 if (LookupPtr.getInt())
1263 Map = buildLookup();
Richard Smith86a12012013-02-11 22:02:16 +00001264 else if (NeedToReconcileExternalVisibleStorage)
1265 reconcileExternalVisibleStorage();
Richard Smith645d7552013-02-07 03:37:08 +00001266
Richard Smith75fc3bf2013-02-08 00:37:45 +00001267 if (!Map)
1268 Map = CreateStoredDeclsMap(getParentASTContext());
1269
Richard Smith4abe0a82013-09-09 07:34:56 +00001270 // If we have a lookup result with no external decls, we are done.
Richard Smith75fc3bf2013-02-08 00:37:45 +00001271 std::pair<StoredDeclsMap::iterator, bool> R =
1272 Map->insert(std::make_pair(Name, StoredDeclsList()));
Richard Smith4abe0a82013-09-09 07:34:56 +00001273 if (!R.second && !R.first->second.hasExternalDecls())
Richard Smith75fc3bf2013-02-08 00:37:45 +00001274 return R.first->second.getLookupResult();
Richard Smithf634c902012-03-16 06:12:59 +00001275
John McCall75b960e2010-06-01 09:23:16 +00001276 ExternalASTSource *Source = getParentASTContext().getExternalSource();
Richard Smith4abe0a82013-09-09 07:34:56 +00001277 if (Source->FindExternalVisibleDeclsByName(this, Name) || R.second) {
Richard Smith9ce12e32013-02-07 03:30:24 +00001278 if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
1279 StoredDeclsMap::iterator I = Map->find(Name);
1280 if (I != Map->end())
1281 return I->second.getLookupResult();
1282 }
1283 }
1284
1285 return lookup_result(lookup_iterator(0), lookup_iterator(0));
John McCall75b960e2010-06-01 09:23:16 +00001286 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001287
Richard Smithf634c902012-03-16 06:12:59 +00001288 StoredDeclsMap *Map = LookupPtr.getPointer();
1289 if (LookupPtr.getInt())
1290 Map = buildLookup();
1291
1292 if (!Map)
1293 return lookup_result(lookup_iterator(0), lookup_iterator(0));
1294
1295 StoredDeclsMap::iterator I = Map->find(Name);
1296 if (I == Map->end())
1297 return lookup_result(lookup_iterator(0), lookup_iterator(0));
1298
1299 return I->second.getLookupResult();
Douglas Gregor91f84212008-12-11 16:49:14 +00001300}
1301
Richard Smith95d99302013-07-13 02:00:19 +00001302DeclContext::lookup_result
1303DeclContext::noload_lookup(DeclarationName Name) {
1304 assert(DeclKind != Decl::LinkageSpec &&
1305 "Should not perform lookups into linkage specs!");
1306 if (!hasExternalVisibleStorage())
1307 return lookup(Name);
1308
1309 DeclContext *PrimaryContext = getPrimaryContext();
1310 if (PrimaryContext != this)
1311 return PrimaryContext->noload_lookup(Name);
1312
1313 StoredDeclsMap *Map = LookupPtr.getPointer();
1314 if (LookupPtr.getInt()) {
1315 // Carefully build the lookup map, without deserializing anything.
1316 SmallVector<DeclContext *, 2> Contexts;
1317 collectAllContexts(Contexts);
1318 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1319 buildLookupImpl<&DeclContext::noload_decls_begin,
1320 &DeclContext::noload_decls_end>(Contexts[I]);
1321
1322 // We no longer have any lazy decls.
1323 LookupPtr.setInt(false);
1324
1325 // There may now be names for which we have local decls but are
Richard Smith4abe0a82013-09-09 07:34:56 +00001326 // missing the external decls. FIXME: Just set the hasExternalDecls
1327 // flag on those names that have external decls.
Richard Smith95d99302013-07-13 02:00:19 +00001328 NeedToReconcileExternalVisibleStorage = true;
1329
1330 Map = LookupPtr.getPointer();
1331 }
1332
1333 if (!Map)
1334 return lookup_result(lookup_iterator(0), lookup_iterator(0));
1335
1336 StoredDeclsMap::iterator I = Map->find(Name);
1337 return I != Map->end()
1338 ? I->second.getLookupResult()
1339 : lookup_result(lookup_iterator(0), lookup_iterator(0));
1340}
1341
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001342void DeclContext::localUncachedLookup(DeclarationName Name,
1343 SmallVectorImpl<NamedDecl *> &Results) {
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001344 Results.clear();
1345
1346 // If there's no external storage, just perform a normal lookup and copy
1347 // the results.
Douglas Gregordd6006f2012-07-17 21:16:27 +00001348 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001349 lookup_result LookupResults = lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00001350 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001351 return;
1352 }
1353
1354 // If we have a lookup table, check there first. Maybe we'll get lucky.
Richard Smith645d7552013-02-07 03:37:08 +00001355 if (Name && !LookupPtr.getInt()) {
Douglas Gregordd6006f2012-07-17 21:16:27 +00001356 if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
1357 StoredDeclsMap::iterator Pos = Map->find(Name);
1358 if (Pos != Map->end()) {
1359 Results.insert(Results.end(),
David Blaikieff7d47a2012-12-19 00:45:41 +00001360 Pos->second.getLookupResult().begin(),
1361 Pos->second.getLookupResult().end());
Douglas Gregordd6006f2012-07-17 21:16:27 +00001362 return;
1363 }
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001364 }
1365 }
Douglas Gregordd6006f2012-07-17 21:16:27 +00001366
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001367 // Slow case: grovel through the declarations in our chain looking for
1368 // matches.
1369 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1370 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1371 if (ND->getDeclName() == Name)
1372 Results.push_back(ND);
1373 }
1374}
1375
Sebastian Redl50c68252010-08-31 00:36:30 +00001376DeclContext *DeclContext::getRedeclContext() {
Chris Lattner17a1bfa2009-03-27 19:19:59 +00001377 DeclContext *Ctx = this;
Sebastian Redlbd595762010-08-31 20:53:31 +00001378 // Skip through transparent contexts.
1379 while (Ctx->isTransparentContext())
Douglas Gregor6ad0ef52009-01-06 23:51:29 +00001380 Ctx = Ctx->getParent();
1381 return Ctx;
1382}
1383
Douglas Gregorf47b9112009-02-25 22:02:03 +00001384DeclContext *DeclContext::getEnclosingNamespaceContext() {
1385 DeclContext *Ctx = this;
1386 // Skip through non-namespace, non-translation-unit contexts.
Sebastian Redl4f08c962010-08-31 00:36:23 +00001387 while (!Ctx->isFileContext())
Douglas Gregorf47b9112009-02-25 22:02:03 +00001388 Ctx = Ctx->getParent();
1389 return Ctx->getPrimaryContext();
1390}
1391
Sebastian Redl50c68252010-08-31 00:36:30 +00001392bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1393 // For non-file contexts, this is equivalent to Equals.
1394 if (!isFileContext())
1395 return O->Equals(this);
1396
1397 do {
1398 if (O->Equals(this))
1399 return true;
1400
1401 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1402 if (!NS || !NS->isInline())
1403 break;
1404 O = NS->getParent();
1405 } while (O);
1406
1407 return false;
1408}
1409
Richard Smithf634c902012-03-16 06:12:59 +00001410void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1411 DeclContext *PrimaryDC = this->getPrimaryContext();
1412 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1413 // If the decl is being added outside of its semantic decl context, we
1414 // need to ensure that we eagerly build the lookup information for it.
1415 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
Sean Callanan95e74be2011-10-21 02:57:43 +00001416}
1417
Richard Smithf634c902012-03-16 06:12:59 +00001418void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1419 bool Recoverable) {
1420 assert(this == getPrimaryContext() && "expected a primary DC");
Sean Callanan95e74be2011-10-21 02:57:43 +00001421
Richard Smith05afe5e2012-03-13 03:12:56 +00001422 // Skip declarations within functions.
Richard Smith114394f2013-08-09 04:35:01 +00001423 if (isFunctionOrMethod())
Richard Smith05afe5e2012-03-13 03:12:56 +00001424 return;
1425
Richard Smithf634c902012-03-16 06:12:59 +00001426 // Skip declarations which should be invisible to name lookup.
1427 if (shouldBeHidden(D))
1428 return;
1429
1430 // If we already have a lookup data structure, perform the insertion into
1431 // it. If we might have externally-stored decls with this name, look them
1432 // up and perform the insertion. If this decl was declared outside its
1433 // semantic context, buildLookup won't add it, so add it now.
1434 //
1435 // FIXME: As a performance hack, don't add such decls into the translation
1436 // unit unless we're in C++, since qualified lookup into the TU is never
1437 // performed.
1438 if (LookupPtr.getPointer() || hasExternalVisibleStorage() ||
1439 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1440 (getParentASTContext().getLangOpts().CPlusPlus ||
1441 !isTranslationUnit()))) {
1442 // If we have lazily omitted any decls, they might have the same name as
1443 // the decl which we are adding, so build a full lookup table before adding
1444 // this decl.
1445 buildLookup();
1446 makeDeclVisibleInContextImpl(D, Internal);
1447 } else {
1448 LookupPtr.setInt(true);
1449 }
1450
1451 // If we are a transparent context or inline namespace, insert into our
1452 // parent context, too. This operation is recursive.
1453 if (isTransparentContext() || isInlineNamespace())
1454 getParent()->getPrimaryContext()->
1455 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1456
1457 Decl *DCAsDecl = cast<Decl>(this);
1458 // Notify that a decl was made visible unless we are a Tag being defined.
1459 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1460 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1461 L->AddedVisibleDecl(this, D);
1462}
1463
1464void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1465 // Find or create the stored declaration map.
1466 StoredDeclsMap *Map = LookupPtr.getPointer();
1467 if (!Map) {
1468 ASTContext *C = &getParentASTContext();
1469 Map = CreateStoredDeclsMap(*C);
Argyrios Kyrtzidise51e5542010-07-04 21:44:25 +00001470 }
1471
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001472 // If there is an external AST source, load any declarations it knows about
1473 // with this declaration's name.
1474 // If the lookup table contains an entry about this name it means that we
1475 // have already checked the external source.
Sean Callanan95e74be2011-10-21 02:57:43 +00001476 if (!Internal)
1477 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1478 if (hasExternalVisibleStorage() &&
Richard Smithf634c902012-03-16 06:12:59 +00001479 Map->find(D->getDeclName()) == Map->end())
Sean Callanan95e74be2011-10-21 02:57:43 +00001480 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001481
Douglas Gregor91f84212008-12-11 16:49:14 +00001482 // Insert this declaration into the map.
Richard Smithf634c902012-03-16 06:12:59 +00001483 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
Richard Smith4abe0a82013-09-09 07:34:56 +00001484
1485 if (Internal) {
1486 // If this is being added as part of loading an external declaration,
1487 // this may not be the only external declaration with this name.
1488 // In this case, we never try to replace an existing declaration; we'll
1489 // handle that when we finalize the list of declarations for this name.
1490 DeclNameEntries.setHasExternalDecls();
1491 DeclNameEntries.AddSubsequentDecl(D);
1492 return;
1493 }
1494
1495 else if (DeclNameEntries.isNull()) {
Chris Lattnercaae7162009-02-20 01:44:05 +00001496 DeclNameEntries.setOnlyValue(D);
Richard Smithf634c902012-03-16 06:12:59 +00001497 return;
Douglas Gregor91f84212008-12-11 16:49:14 +00001498 }
Chris Lattner24e24d52009-02-20 00:55:03 +00001499
Richard Smithf634c902012-03-16 06:12:59 +00001500 if (DeclNameEntries.HandleRedeclaration(D)) {
1501 // This declaration has replaced an existing one for which
1502 // declarationReplaces returns true.
1503 return;
1504 }
Mike Stump11289f42009-09-09 15:08:12 +00001505
Richard Smithf634c902012-03-16 06:12:59 +00001506 // Put this declaration into the appropriate slot.
1507 DeclNameEntries.AddSubsequentDecl(D);
Douglas Gregor91f84212008-12-11 16:49:14 +00001508}
Douglas Gregor889ceb72009-02-03 19:21:40 +00001509
1510/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1511/// this context.
Mike Stump11289f42009-09-09 15:08:12 +00001512DeclContext::udir_iterator_range
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001513DeclContext::getUsingDirectives() const {
Richard Smith05afe5e2012-03-13 03:12:56 +00001514 // FIXME: Use something more efficient than normal lookup for using
1515 // directives. In C++, using directives are looked up more than anything else.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001516 lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
David Blaikieff7d47a2012-12-19 00:45:41 +00001517 return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.begin()),
1518 reinterpret_cast<udir_iterator>(Result.end()));
Douglas Gregor889ceb72009-02-03 19:21:40 +00001519}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001520
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001521//===----------------------------------------------------------------------===//
1522// Creation and Destruction of StoredDeclsMaps. //
1523//===----------------------------------------------------------------------===//
1524
John McCallc62bb642010-03-24 05:22:00 +00001525StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
Richard Smithf634c902012-03-16 06:12:59 +00001526 assert(!LookupPtr.getPointer() && "context already has a decls map");
John McCallc62bb642010-03-24 05:22:00 +00001527 assert(getPrimaryContext() == this &&
1528 "creating decls map on non-primary context");
1529
1530 StoredDeclsMap *M;
1531 bool Dependent = isDependentContext();
1532 if (Dependent)
1533 M = new DependentStoredDeclsMap();
1534 else
1535 M = new StoredDeclsMap();
1536 M->Previous = C.LastSDM;
1537 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
Richard Smithf634c902012-03-16 06:12:59 +00001538 LookupPtr.setPointer(M);
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001539 return M;
1540}
1541
1542void ASTContext::ReleaseDeclContextMaps() {
John McCallc62bb642010-03-24 05:22:00 +00001543 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1544 // pointer because the subclass doesn't add anything that needs to
1545 // be deleted.
John McCallc62bb642010-03-24 05:22:00 +00001546 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1547}
1548
1549void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1550 while (Map) {
1551 // Advance the iteration before we invalidate memory.
1552 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1553
1554 if (Dependent)
1555 delete static_cast<DependentStoredDeclsMap*>(Map);
1556 else
1557 delete Map;
1558
1559 Map = Next.getPointer();
1560 Dependent = Next.getInt();
1561 }
1562}
1563
John McCallc62bb642010-03-24 05:22:00 +00001564DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1565 DeclContext *Parent,
1566 const PartialDiagnostic &PDiag) {
1567 assert(Parent->isDependentContext()
1568 && "cannot iterate dependent diagnostics of non-dependent context");
1569 Parent = Parent->getPrimaryContext();
Richard Smithf634c902012-03-16 06:12:59 +00001570 if (!Parent->LookupPtr.getPointer())
John McCallc62bb642010-03-24 05:22:00 +00001571 Parent->CreateStoredDeclsMap(C);
1572
1573 DependentStoredDeclsMap *Map
Richard Smithf634c902012-03-16 06:12:59 +00001574 = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr.getPointer());
John McCallc62bb642010-03-24 05:22:00 +00001575
Douglas Gregora55530e2010-03-29 23:56:53 +00001576 // Allocate the copy of the PartialDiagnostic via the ASTContext's
Douglas Gregor89336232010-03-29 23:34:08 +00001577 // BumpPtrAllocator, rather than the ASTContext itself.
Douglas Gregora55530e2010-03-29 23:56:53 +00001578 PartialDiagnostic::Storage *DiagStorage = 0;
1579 if (PDiag.hasStorage())
1580 DiagStorage = new (C) PartialDiagnostic::Storage;
1581
1582 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
John McCallc62bb642010-03-24 05:22:00 +00001583
1584 // TODO: Maybe we shouldn't reverse the order during insertion.
1585 DD->NextDiagnostic = Map->FirstDiagnostic;
1586 Map->FirstDiagnostic = DD;
1587
1588 return DD;
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001589}