blob: 085fb522932a63bdc8dcbf2ceb84dc404d417503 [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"
Chris Lattnereae6cb62009-03-05 08:00:35 +000031#include "llvm/Support/raw_ostream.h"
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000032#include <algorithm>
Eli Friedman7dbab8a2008-06-07 16:52:53 +000033using namespace clang;
34
35//===----------------------------------------------------------------------===//
36// Statistics
37//===----------------------------------------------------------------------===//
38
Alexis Hunted053252010-05-30 07:21:58 +000039#define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
40#define ABSTRACT_DECL(DECL)
41#include "clang/AST/DeclNodes.inc"
Eli Friedman7dbab8a2008-06-07 16:52:53 +000042
Douglas Gregor7dab26b2013-02-09 01:35:03 +000043void Decl::updateOutOfDate(IdentifierInfo &II) const {
44 getASTContext().getExternalSource()->updateOutOfDateIdentifier(II);
45}
46
James Y Knight53c76162015-07-17 18:21:37 +000047#define DECL(DERIVED, BASE) \
Benjamin Kramerc3f89252016-10-20 14:27:22 +000048 static_assert(alignof(Decl) >= alignof(DERIVED##Decl), \
James Y Knight53c76162015-07-17 18:21:37 +000049 "Alignment sufficient after objects prepended to " #DERIVED);
50#define ABSTRACT_DECL(DECL)
51#include "clang/AST/DeclNodes.inc"
52
Richard Smithf7981722013-11-22 09:01:48 +000053void *Decl::operator new(std::size_t Size, const ASTContext &Context,
54 unsigned ID, std::size_t Extra) {
Douglas Gregor52261fd2012-01-05 23:49:36 +000055 // Allocate an extra 8 bytes worth of storage, which ensures that the
James Y Knight53c76162015-07-17 18:21:37 +000056 // resulting pointer will still be 8-byte aligned.
Benjamin Kramerc3f89252016-10-20 14:27:22 +000057 static_assert(sizeof(unsigned) * 2 >= alignof(Decl),
James Y Knight53c76162015-07-17 18:21:37 +000058 "Decl won't be misaligned");
Richard Smithf7981722013-11-22 09:01:48 +000059 void *Start = Context.Allocate(Size + Extra + 8);
Douglas Gregor52261fd2012-01-05 23:49:36 +000060 void *Result = (char*)Start + 8;
Richard Smithf7981722013-11-22 09:01:48 +000061
Douglas Gregorcfe7dc62012-01-09 17:30:44 +000062 unsigned *PrefixPtr = (unsigned *)Result - 2;
Richard Smithf7981722013-11-22 09:01:48 +000063
Douglas Gregorcfe7dc62012-01-09 17:30:44 +000064 // Zero out the first 4 bytes; this is used to store the owning module ID.
65 PrefixPtr[0] = 0;
Richard Smithf7981722013-11-22 09:01:48 +000066
Douglas Gregorcfe7dc62012-01-09 17:30:44 +000067 // Store the global declaration ID in the second 4 bytes.
68 PrefixPtr[1] = ID;
Richard Smithf7981722013-11-22 09:01:48 +000069
Douglas Gregor64af53c2012-01-05 22:27:05 +000070 return Result;
Douglas Gregor72172e92012-01-05 21:55:30 +000071}
72
Richard Smithf7981722013-11-22 09:01:48 +000073void *Decl::operator new(std::size_t Size, const ASTContext &Ctx,
74 DeclContext *Parent, std::size_t Extra) {
75 assert(!Parent || &Parent->getParentASTContext() == &Ctx);
Richard Smith42413142015-05-15 20:05:43 +000076 // With local visibility enabled, we track the owning module even for local
77 // declarations.
Richard Smith26342f92017-05-17 00:24:14 +000078 if (Ctx.getLangOpts().trackLocalOwningModule()) {
James Y Knight53c76162015-07-17 18:21:37 +000079 // Ensure required alignment of the resulting object by adding extra
80 // padding at the start if required.
81 size_t ExtraAlign =
Benjamin Kramerc3f89252016-10-20 14:27:22 +000082 llvm::OffsetToAlignment(sizeof(Module *), alignof(Decl));
James Y Knight53c76162015-07-17 18:21:37 +000083 char *Buffer = reinterpret_cast<char *>(
84 ::operator new(ExtraAlign + sizeof(Module *) + Size + Extra, Ctx));
85 Buffer += ExtraAlign;
Richard Smith26342f92017-05-17 00:24:14 +000086 auto *ParentModule =
87 Parent ? cast<Decl>(Parent)->getOwningModule() : nullptr;
88 return new (Buffer) Module*(ParentModule) + 1;
Richard Smith42413142015-05-15 20:05:43 +000089 }
Richard Smithf7981722013-11-22 09:01:48 +000090 return ::operator new(Size + Extra, Ctx);
91}
92
Douglas Gregorc147b0b2013-01-12 01:29:50 +000093Module *Decl::getOwningModuleSlow() const {
94 assert(isFromASTFile() && "Not from AST file?");
95 return getASTContext().getExternalSource()->getModule(getOwningModuleID());
96}
97
Richard Smith87bb5692015-06-09 00:35:49 +000098bool Decl::hasLocalOwningModuleStorage() const {
Richard Smith26342f92017-05-17 00:24:14 +000099 return getASTContext().getLangOpts().trackLocalOwningModule();
Richard Smith87bb5692015-06-09 00:35:49 +0000100}
101
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000102const char *Decl::getDeclKindName() const {
103 switch (DeclKind) {
David Blaikie83d382b2011-09-23 05:06:16 +0000104 default: llvm_unreachable("Declaration not in DeclNodes.inc!");
Alexis Hunted053252010-05-30 07:21:58 +0000105#define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
106#define ABSTRACT_DECL(DECL)
107#include "clang/AST/DeclNodes.inc"
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000108 }
109}
110
Douglas Gregor90d47172010-03-05 00:26:45 +0000111void Decl::setInvalidDecl(bool Invalid) {
112 InvalidDecl = Invalid;
Alp Tokera5d64592013-12-21 01:10:54 +0000113 assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
Richard Trieucbd54302016-11-11 20:51:04 +0000114 if (!Invalid) {
115 return;
116 }
117
118 if (!isa<ParmVarDecl>(this)) {
Douglas Gregor90d47172010-03-05 00:26:45 +0000119 // Defensive maneuver for ill-formed code: we're likely not to make it to
120 // a point where we set the access specifier, so default it to "public"
121 // to avoid triggering asserts elsewhere in the front end.
122 setAccess(AS_public);
123 }
Richard Trieucbd54302016-11-11 20:51:04 +0000124
125 // Marking a DecompositionDecl as invalid implies all the child BindingDecl's
126 // are invalid too.
127 if (DecompositionDecl *DD = dyn_cast<DecompositionDecl>(this)) {
128 for (BindingDecl *Binding : DD->bindings()) {
129 Binding->setInvalidDecl();
130 }
131 }
Douglas Gregor90d47172010-03-05 00:26:45 +0000132}
133
Steve Naroff5faaef72009-01-20 19:53:53 +0000134const char *DeclContext::getDeclKindName() const {
135 switch (DeclKind) {
David Blaikie83d382b2011-09-23 05:06:16 +0000136 default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
Alexis Hunted053252010-05-30 07:21:58 +0000137#define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
138#define ABSTRACT_DECL(DECL)
139#include "clang/AST/DeclNodes.inc"
Steve Naroff5faaef72009-01-20 19:53:53 +0000140 }
141}
142
Daniel Dunbar62905572012-03-05 21:42:49 +0000143bool Decl::StatisticsEnabled = false;
144void Decl::EnableStatistics() {
145 StatisticsEnabled = true;
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000146}
147
148void Decl::PrintStats() {
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000149 llvm::errs() << "\n*** Decl Stats:\n";
Mike Stump11289f42009-09-09 15:08:12 +0000150
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000151 int totalDecls = 0;
Alexis Hunted053252010-05-30 07:21:58 +0000152#define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
153#define ABSTRACT_DECL(DECL)
154#include "clang/AST/DeclNodes.inc"
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000155 llvm::errs() << " " << totalDecls << " decls total.\n";
Mike Stump11289f42009-09-09 15:08:12 +0000156
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000157 int totalBytes = 0;
Alexis Hunted053252010-05-30 07:21:58 +0000158#define DECL(DERIVED, BASE) \
159 if (n##DERIVED##s > 0) { \
160 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000161 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
162 << sizeof(DERIVED##Decl) << " each (" \
163 << n##DERIVED##s * sizeof(DERIVED##Decl) \
164 << " bytes)\n"; \
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000165 }
Alexis Hunted053252010-05-30 07:21:58 +0000166#define ABSTRACT_DECL(DECL)
167#include "clang/AST/DeclNodes.inc"
Mike Stump11289f42009-09-09 15:08:12 +0000168
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000169 llvm::errs() << "Total bytes = " << totalBytes << "\n";
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000170}
171
Alexis Hunted053252010-05-30 07:21:58 +0000172void Decl::add(Kind k) {
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000173 switch (k) {
Alexis Hunted053252010-05-30 07:21:58 +0000174#define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
175#define ABSTRACT_DECL(DECL)
176#include "clang/AST/DeclNodes.inc"
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000177 }
178}
179
Anders Carlssonaa73b912009-06-13 00:08:58 +0000180bool Decl::isTemplateParameterPack() const {
181 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
182 return TTP->isParameterPack();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000183 if (const NonTypeTemplateParmDecl *NTTP
Douglas Gregorf5500772011-01-05 15:48:55 +0000184 = dyn_cast<NonTypeTemplateParmDecl>(this))
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000185 return NTTP->isParameterPack();
Douglas Gregorf5500772011-01-05 15:48:55 +0000186 if (const TemplateTemplateParmDecl *TTP
187 = dyn_cast<TemplateTemplateParmDecl>(this))
188 return TTP->isParameterPack();
Anders Carlssonaa73b912009-06-13 00:08:58 +0000189 return false;
190}
191
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +0000192bool Decl::isParameterPack() const {
193 if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
194 return Parm->isParameterPack();
195
196 return isTemplateParameterPack();
197}
198
Alp Tokera2794f92014-01-22 07:29:52 +0000199FunctionDecl *Decl::getAsFunction() {
200 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
201 return FD;
202 if (const FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(this))
203 return FTD->getTemplatedDecl();
Craig Topper36250ad2014-05-12 05:36:57 +0000204 return nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000205}
206
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000207bool Decl::isTemplateDecl() const {
208 return isa<TemplateDecl>(this);
209}
210
Serge Pavlov7dcc97e2016-04-19 06:19:52 +0000211TemplateDecl *Decl::getDescribedTemplate() const {
212 if (auto *FD = dyn_cast<FunctionDecl>(this))
213 return FD->getDescribedFunctionTemplate();
214 else if (auto *RD = dyn_cast<CXXRecordDecl>(this))
215 return RD->getDescribedClassTemplate();
216 else if (auto *VD = dyn_cast<VarDecl>(this))
217 return VD->getDescribedVarTemplate();
218
219 return nullptr;
220}
221
Argyrios Kyrtzidis0ce4c9a2011-09-28 02:45:33 +0000222const DeclContext *Decl::getParentFunctionOrMethod() const {
223 for (const DeclContext *DC = getDeclContext();
224 DC && !DC->isTranslationUnit() && !DC->isNamespace();
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000225 DC = DC->getParent())
226 if (DC->isFunctionOrMethod())
Argyrios Kyrtzidis0ce4c9a2011-09-28 02:45:33 +0000227 return DC;
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000228
Craig Topper36250ad2014-05-12 05:36:57 +0000229 return nullptr;
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000230}
231
Douglas Gregor133eddd2011-02-17 08:47:29 +0000232
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000233//===----------------------------------------------------------------------===//
Chris Lattnereae6cb62009-03-05 08:00:35 +0000234// PrettyStackTraceDecl Implementation
235//===----------------------------------------------------------------------===//
Mike Stump11289f42009-09-09 15:08:12 +0000236
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000237void PrettyStackTraceDecl::print(raw_ostream &OS) const {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000238 SourceLocation TheLoc = Loc;
239 if (TheLoc.isInvalid() && TheDecl)
240 TheLoc = TheDecl->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000241
Chris Lattnereae6cb62009-03-05 08:00:35 +0000242 if (TheLoc.isValid()) {
243 TheLoc.print(OS, SM);
244 OS << ": ";
245 }
246
247 OS << Message;
248
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +0000249 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
250 OS << " '";
251 DN->printQualifiedName(OS);
252 OS << '\'';
253 }
Chris Lattnereae6cb62009-03-05 08:00:35 +0000254 OS << '\n';
255}
Mike Stump11289f42009-09-09 15:08:12 +0000256
Chris Lattnereae6cb62009-03-05 08:00:35 +0000257//===----------------------------------------------------------------------===//
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000258// Decl Implementation
259//===----------------------------------------------------------------------===//
260
Douglas Gregorb11aad82011-02-19 18:51:44 +0000261// Out-of-line virtual method providing a home for Decl.
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000262Decl::~Decl() { }
Douglas Gregora43942a2011-02-17 07:02:32 +0000263
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000264void Decl::setDeclContext(DeclContext *DC) {
Chris Lattnerb81eb052009-03-29 06:06:59 +0000265 DeclCtx = DC;
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000266}
267
268void Decl::setLexicalDeclContext(DeclContext *DC) {
269 if (DC == getLexicalDeclContext())
270 return;
271
272 if (isInSemaDC()) {
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000273 setDeclContextsImpl(getDeclContext(), DC, getASTContext());
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000274 } else {
275 getMultipleDC()->LexicalDC = DC;
276 }
Richard Smithae50c562017-05-23 22:02:49 +0000277
278 // FIXME: We shouldn't be changing the lexical context of declarations
279 // imported from AST files.
280 if (!isFromASTFile()) {
281 Hidden = cast<Decl>(DC)->Hidden && hasLocalOwningModuleStorage();
282 if (Hidden)
283 setLocalOwningModule(cast<Decl>(DC)->getOwningModule());
284 }
285
286 assert((!Hidden || getOwningModule()) &&
287 "hidden declaration has no owning module");
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000288}
289
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000290void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
291 ASTContext &Ctx) {
292 if (SemaDC == LexicalDC) {
293 DeclCtx = SemaDC;
294 } else {
295 Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
296 MDC->SemanticDC = SemaDC;
297 MDC->LexicalDC = LexicalDC;
298 DeclCtx = MDC;
299 }
300}
301
Serge Pavlov73c6a242015-08-23 10:22:28 +0000302bool Decl::isLexicallyWithinFunctionOrMethod() const {
303 const DeclContext *LDC = getLexicalDeclContext();
Serge Pavlovb24a7112015-08-23 11:09:40 +0000304 while (true) {
Serge Pavlov73c6a242015-08-23 10:22:28 +0000305 if (LDC->isFunctionOrMethod())
306 return true;
307 if (!isa<TagDecl>(LDC))
308 return false;
Serge Pavlovb24a7112015-08-23 11:09:40 +0000309 LDC = LDC->getLexicalParent();
310 }
Serge Pavlov73c6a242015-08-23 10:22:28 +0000311 return false;
312}
313
John McCall4fa53422009-10-01 00:25:31 +0000314bool Decl::isInAnonymousNamespace() const {
315 const DeclContext *DC = getDeclContext();
316 do {
317 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
318 if (ND->isAnonymousNamespace())
319 return true;
320 } while ((DC = DC->getParent()));
321
322 return false;
323}
324
Richard Trieuc771d5d2014-05-28 02:16:01 +0000325bool Decl::isInStdNamespace() const {
326 return getDeclContext()->isStdNamespace();
327}
328
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000329TranslationUnitDecl *Decl::getTranslationUnitDecl() {
Argyrios Kyrtzidis4e1a72b2009-06-30 02:34:53 +0000330 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
331 return TUD;
332
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000333 DeclContext *DC = getDeclContext();
334 assert(DC && "This decl is not contained in a translation unit!");
Mike Stump11289f42009-09-09 15:08:12 +0000335
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000336 while (!DC->isTranslationUnit()) {
337 DC = DC->getParent();
338 assert(DC && "This decl is not contained in a translation unit!");
339 }
Mike Stump11289f42009-09-09 15:08:12 +0000340
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000341 return cast<TranslationUnitDecl>(DC);
342}
343
344ASTContext &Decl::getASTContext() const {
Mike Stump11289f42009-09-09 15:08:12 +0000345 return getTranslationUnitDecl()->getASTContext();
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000346}
347
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +0000348ASTMutationListener *Decl::getASTMutationListener() const {
349 return getASTContext().getASTMutationListener();
350}
351
Benjamin Kramerea70eb32012-12-01 15:09:41 +0000352unsigned Decl::getMaxAlignment() const {
353 if (!hasAttrs())
354 return 0;
355
356 unsigned Align = 0;
357 const AttrVec &V = getAttrs();
358 ASTContext &Ctx = getASTContext();
359 specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
360 for (; I != E; ++I)
361 Align = std::max(Align, I->getAlignment(Ctx));
362 return Align;
363}
364
Vassil Vassilev928c8252016-04-28 14:13:28 +0000365bool Decl::isUsed(bool CheckUsedAttr) const {
366 const Decl *CanonD = getCanonicalDecl();
367 if (CanonD->Used)
Vassil Vassileva4d7d782016-04-27 10:46:06 +0000368 return true;
369
Vassil Vassilev928c8252016-04-28 14:13:28 +0000370 // Check for used attribute.
371 // Ask the most recent decl, since attributes accumulate in the redecl chain.
372 if (CheckUsedAttr && getMostRecentDecl()->hasAttr<UsedAttr>())
373 return true;
374
375 // The information may have not been deserialized yet. Force deserialization
376 // to complete the needed information.
377 return getMostRecentDecl()->getCanonicalDecl()->Used;
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000378}
379
Eli Friedman276dd182013-09-05 00:02:25 +0000380void Decl::markUsed(ASTContext &C) {
Vassil Vassilev928c8252016-04-28 14:13:28 +0000381 if (isUsed(false))
Eli Friedman276dd182013-09-05 00:02:25 +0000382 return;
383
384 if (C.getASTMutationListener())
385 C.getASTMutationListener()->DeclarationMarkedUsed(this);
386
Vassil Vassilev928c8252016-04-28 14:13:28 +0000387 setIsUsed();
Eli Friedman276dd182013-09-05 00:02:25 +0000388}
389
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +0000390bool Decl::isReferenced() const {
391 if (Referenced)
392 return true;
393
394 // Check redeclarations.
Aaron Ballman86c93902014-03-06 23:45:36 +0000395 for (auto I : redecls())
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +0000396 if (I->Referenced)
397 return true;
398
399 return false;
400}
401
Richard Smith3b660562016-09-26 21:27:23 +0000402bool Decl::isExported() const {
403 if (isModulePrivate())
404 return false;
405 // Namespaces are always exported.
406 if (isa<TranslationUnitDecl>(this) || isa<NamespaceDecl>(this))
407 return true;
408 // Otherwise, this is a strictly lexical check.
409 for (auto *DC = getLexicalDeclContext(); DC; DC = DC->getLexicalParent()) {
410 if (cast<Decl>(DC)->isModulePrivate())
411 return false;
412 if (isa<ExportDecl>(DC))
413 return true;
414 }
415 return false;
416}
417
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +0000418ExternalSourceSymbolAttr *Decl::getExternalSourceSymbolAttr() const {
419 const Decl *Definition = nullptr;
420 if (auto ID = dyn_cast<ObjCInterfaceDecl>(this)) {
421 Definition = ID->getDefinition();
422 } else if (auto PD = dyn_cast<ObjCProtocolDecl>(this)) {
423 Definition = PD->getDefinition();
424 } else if (auto TD = dyn_cast<TagDecl>(this)) {
425 Definition = TD->getDefinition();
426 }
427 if (!Definition)
428 Definition = this;
429
430 if (auto *attr = Definition->getAttr<ExternalSourceSymbolAttr>())
431 return attr;
432 if (auto *dcd = dyn_cast<Decl>(getDeclContext())) {
433 return dcd->getAttr<ExternalSourceSymbolAttr>();
434 }
435
436 return nullptr;
437}
438
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000439bool Decl::hasDefiningAttr() const {
440 return hasAttr<AliasAttr>() || hasAttr<IFuncAttr>();
441}
442
443const Attr *Decl::getDefiningAttr() const {
444 if (AliasAttr *AA = getAttr<AliasAttr>())
445 return AA;
446 if (IFuncAttr *IFA = getAttr<IFuncAttr>())
447 return IFA;
448 return nullptr;
449}
450
Alex Lorenza8a372d2017-04-27 10:43:48 +0000451StringRef getRealizedPlatform(const AvailabilityAttr *A,
452 const ASTContext &Context) {
453 // Check if this is an App Extension "platform", and if so chop off
454 // the suffix for matching with the actual platform.
455 StringRef RealizedPlatform = A->getPlatform()->getName();
456 if (!Context.getLangOpts().AppExt)
457 return RealizedPlatform;
458 size_t suffix = RealizedPlatform.rfind("_app_extension");
459 if (suffix != StringRef::npos)
460 return RealizedPlatform.slice(0, suffix);
461 return RealizedPlatform;
462}
463
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000464/// \brief Determine the availability of the given declaration based on
465/// the target platform.
466///
467/// When it returns an availability result other than \c AR_Available,
468/// if the \p Message parameter is non-NULL, it will be set to a
469/// string describing why the entity is unavailable.
470///
471/// FIXME: Make these strings localizable, since they end up in
472/// diagnostics.
473static AvailabilityResult CheckAvailability(ASTContext &Context,
474 const AvailabilityAttr *A,
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000475 std::string *Message,
476 VersionTuple EnclosingVersion) {
477 if (EnclosingVersion.empty())
478 EnclosingVersion = Context.getTargetInfo().getPlatformMinVersion();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000479
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000480 if (EnclosingVersion.empty())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000481 return AR_Available;
482
Bob Wilsonb111ec92015-03-02 19:01:14 +0000483 StringRef ActualPlatform = A->getPlatform()->getName();
Bob Wilsonb111ec92015-03-02 19:01:14 +0000484 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
485
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000486 // Match the platform name.
Alex Lorenza8a372d2017-04-27 10:43:48 +0000487 if (getRealizedPlatform(A, Context) != TargetPlatform)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000488 return AR_Available;
Bob Wilsonb111ec92015-03-02 19:01:14 +0000489
490 StringRef PrettyPlatformName
491 = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
492
493 if (PrettyPlatformName.empty())
494 PrettyPlatformName = ActualPlatform;
495
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000496 std::string HintMessage;
497 if (!A->getMessage().empty()) {
498 HintMessage = " - ";
499 HintMessage += A->getMessage();
500 }
501
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000502 // Make sure that this declaration has not been marked 'unavailable'.
503 if (A->getUnavailable()) {
504 if (Message) {
505 Message->clear();
506 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000507 Out << "not available on " << PrettyPlatformName
508 << HintMessage;
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000509 }
510
511 return AR_Unavailable;
512 }
513
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000514 // Make sure that this declaration has already been introduced.
515 if (!A->getIntroduced().empty() &&
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000516 EnclosingVersion < A->getIntroduced()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000517 if (Message) {
518 Message->clear();
519 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000520 VersionTuple VTI(A->getIntroduced());
521 VTI.UseDotAsSeparator();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000522 Out << "introduced in " << PrettyPlatformName << ' '
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000523 << VTI << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000524 }
525
Duncan P. N. Exon Smith5d6790c2016-03-08 06:12:54 +0000526 return A->getStrict() ? AR_Unavailable : AR_NotYetIntroduced;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000527 }
528
529 // Make sure that this declaration hasn't been obsoleted.
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000530 if (!A->getObsoleted().empty() && EnclosingVersion >= A->getObsoleted()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000531 if (Message) {
532 Message->clear();
533 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000534 VersionTuple VTO(A->getObsoleted());
535 VTO.UseDotAsSeparator();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000536 Out << "obsoleted in " << PrettyPlatformName << ' '
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000537 << VTO << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000538 }
539
540 return AR_Unavailable;
541 }
542
543 // Make sure that this declaration hasn't been deprecated.
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000544 if (!A->getDeprecated().empty() && EnclosingVersion >= A->getDeprecated()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000545 if (Message) {
546 Message->clear();
547 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000548 VersionTuple VTD(A->getDeprecated());
549 VTD.UseDotAsSeparator();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000550 Out << "first deprecated in " << PrettyPlatformName << ' '
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000551 << VTD << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000552 }
553
554 return AR_Deprecated;
555 }
556
557 return AR_Available;
558}
559
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000560AvailabilityResult Decl::getAvailability(std::string *Message,
561 VersionTuple EnclosingVersion) const {
Duncan P. N. Exon Smithec599a92016-02-26 19:27:00 +0000562 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000563 return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion);
Duncan P. N. Exon Smithec599a92016-02-26 19:27:00 +0000564
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000565 AvailabilityResult Result = AR_Available;
566 std::string ResultMessage;
567
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000568 for (const auto *A : attrs()) {
569 if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000570 if (Result >= AR_Deprecated)
571 continue;
572
573 if (Message)
574 ResultMessage = Deprecated->getMessage();
575
576 Result = AR_Deprecated;
577 continue;
578 }
579
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000580 if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000581 if (Message)
582 *Message = Unavailable->getMessage();
583 return AR_Unavailable;
584 }
585
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000586 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000587 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000588 Message, EnclosingVersion);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000589
590 if (AR == AR_Unavailable)
591 return AR_Unavailable;
592
593 if (AR > Result) {
594 Result = AR;
595 if (Message)
596 ResultMessage.swap(*Message);
597 }
598 continue;
599 }
600 }
601
602 if (Message)
603 Message->swap(ResultMessage);
604 return Result;
605}
606
Alex Lorenza8a372d2017-04-27 10:43:48 +0000607VersionTuple Decl::getVersionIntroduced() const {
608 const ASTContext &Context = getASTContext();
609 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
610 for (const auto *A : attrs()) {
611 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
612 if (getRealizedPlatform(Availability, Context) != TargetPlatform)
613 continue;
614 if (!Availability->getIntroduced().empty())
615 return Availability->getIntroduced();
616 }
617 }
618 return VersionTuple();
619}
620
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000621bool Decl::canBeWeakImported(bool &IsDefinition) const {
622 IsDefinition = false;
John McCall5fb5df92012-06-20 06:18:46 +0000623
624 // Variables, if they aren't definitions.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000625 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000626 if (Var->isThisDeclarationADefinition()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000627 IsDefinition = true;
628 return false;
629 }
John McCall5fb5df92012-06-20 06:18:46 +0000630 return true;
631
632 // Functions, if they aren't definitions.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000633 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
634 if (FD->hasBody()) {
635 IsDefinition = true;
636 return false;
637 }
John McCall5fb5df92012-06-20 06:18:46 +0000638 return true;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000639
John McCall5fb5df92012-06-20 06:18:46 +0000640 // Objective-C classes, if this is the non-fragile runtime.
641 } else if (isa<ObjCInterfaceDecl>(this) &&
John McCall18ac1632012-06-20 21:58:02 +0000642 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
John McCall5fb5df92012-06-20 06:18:46 +0000643 return true;
644
645 // Nothing else.
646 } else {
647 return false;
648 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000649}
650
651bool Decl::isWeakImported() const {
652 bool IsDefinition;
653 if (!canBeWeakImported(IsDefinition))
654 return false;
655
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000656 for (const auto *A : attrs()) {
657 if (isa<WeakImportAttr>(A))
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000658 return true;
659
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000660 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000661 if (CheckAvailability(getASTContext(), Availability, nullptr,
662 VersionTuple()) == AR_NotYetIntroduced)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000663 return true;
664 }
665 }
666
667 return false;
668}
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000669
Chris Lattner8e097192009-03-27 20:18:19 +0000670unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
671 switch (DeclKind) {
John McCall3f746822009-11-17 05:59:44 +0000672 case Function:
Richard Smithbc491202017-02-17 20:05:37 +0000673 case CXXDeductionGuide:
John McCall3f746822009-11-17 05:59:44 +0000674 case CXXMethod:
675 case CXXConstructor:
Richard Smith5179eb72016-06-28 19:03:57 +0000676 case ConstructorUsingShadow:
John McCall3f746822009-11-17 05:59:44 +0000677 case CXXDestructor:
678 case CXXConversion:
Chris Lattner8e097192009-03-27 20:18:19 +0000679 case EnumConstant:
680 case Var:
Richard Smithbdb84f32016-07-22 23:36:59 +0000681 case Binding:
Chris Lattner8e097192009-03-27 20:18:19 +0000682 case ImplicitParam:
683 case ParmVar:
Chris Lattner8e097192009-03-27 20:18:19 +0000684 case ObjCMethod:
Daniel Dunbar45b2d8a2010-04-23 13:07:39 +0000685 case ObjCProperty:
John McCall5e77d762013-04-16 07:28:30 +0000686 case MSProperty:
Daniel Dunbar45b2d8a2010-04-23 13:07:39 +0000687 return IDNS_Ordinary;
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000688 case Label:
689 return IDNS_Label;
Francois Pichet783dd6e2010-11-21 06:08:52 +0000690 case IndirectField:
691 return IDNS_Ordinary | IDNS_Member;
692
Richard Smith9f951822016-01-06 22:49:11 +0000693 case NonTypeTemplateParm:
694 // Non-type template parameters are not found by lookups that ignore
695 // non-types, but they are found by redeclaration lookups for tag types,
696 // so we include them in the tag namespace.
697 return IDNS_Ordinary | IDNS_Tag;
698
John McCalle87beb22010-04-23 18:46:30 +0000699 case ObjCCompatibleAlias:
700 case ObjCInterface:
701 return IDNS_Ordinary | IDNS_Type;
702
703 case Typedef:
Richard Smithdda56e42011-04-15 14:24:37 +0000704 case TypeAlias:
Richard Smith3f1b5d02011-05-05 21:57:07 +0000705 case TypeAliasTemplate:
John McCalle87beb22010-04-23 18:46:30 +0000706 case TemplateTypeParm:
Douglas Gregor85f3f952015-07-07 03:57:15 +0000707 case ObjCTypeParam:
John McCalle87beb22010-04-23 18:46:30 +0000708 return IDNS_Ordinary | IDNS_Type;
709
Richard Smith151c4562016-12-20 21:35:28 +0000710 case UnresolvedUsingTypename:
711 return IDNS_Ordinary | IDNS_Type | IDNS_Using;
712
John McCall3f746822009-11-17 05:59:44 +0000713 case UsingShadow:
714 return 0; // we'll actually overwrite this later
715
John McCalle61f2ba2009-11-18 02:36:19 +0000716 case UnresolvedUsingValue:
John McCalle61f2ba2009-11-18 02:36:19 +0000717 return IDNS_Ordinary | IDNS_Using;
John McCall3f746822009-11-17 05:59:44 +0000718
719 case Using:
Richard Smith151c4562016-12-20 21:35:28 +0000720 case UsingPack:
John McCall3f746822009-11-17 05:59:44 +0000721 return IDNS_Using;
722
Chris Lattner8e097192009-03-27 20:18:19 +0000723 case ObjCProtocol:
Douglas Gregor79947a22009-04-24 00:11:27 +0000724 return IDNS_ObjCProtocol;
Mike Stump11289f42009-09-09 15:08:12 +0000725
Chris Lattner8e097192009-03-27 20:18:19 +0000726 case Field:
727 case ObjCAtDefsField:
728 case ObjCIvar:
729 return IDNS_Member;
Mike Stump11289f42009-09-09 15:08:12 +0000730
Chris Lattner8e097192009-03-27 20:18:19 +0000731 case Record:
732 case CXXRecord:
733 case Enum:
John McCalle87beb22010-04-23 18:46:30 +0000734 return IDNS_Tag | IDNS_Type;
Mike Stump11289f42009-09-09 15:08:12 +0000735
Chris Lattner8e097192009-03-27 20:18:19 +0000736 case Namespace:
John McCalle87beb22010-04-23 18:46:30 +0000737 case NamespaceAlias:
738 return IDNS_Namespace;
739
Chris Lattner8e097192009-03-27 20:18:19 +0000740 case FunctionTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +0000741 case VarTemplate:
John McCalle87beb22010-04-23 18:46:30 +0000742 return IDNS_Ordinary;
743
Chris Lattner8e097192009-03-27 20:18:19 +0000744 case ClassTemplate:
745 case TemplateTemplateParm:
John McCalle87beb22010-04-23 18:46:30 +0000746 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
Mike Stump11289f42009-09-09 15:08:12 +0000747
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000748 case OMPDeclareReduction:
749 return IDNS_OMPReduction;
750
Chris Lattner8e097192009-03-27 20:18:19 +0000751 // Never have names.
John McCallaa74a0c2009-08-28 07:59:38 +0000752 case Friend:
John McCall11083da2009-09-16 22:47:08 +0000753 case FriendTemplate:
Abramo Bagnarad7340582010-06-05 05:09:32 +0000754 case AccessSpec:
Chris Lattner8e097192009-03-27 20:18:19 +0000755 case LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +0000756 case Export:
Chris Lattner8e097192009-03-27 20:18:19 +0000757 case FileScopeAsm:
758 case StaticAssert:
Chris Lattner8e097192009-03-27 20:18:19 +0000759 case ObjCPropertyImpl:
Nico Weber66220292016-03-02 17:28:48 +0000760 case PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +0000761 case PragmaDetectMismatch:
Chris Lattner8e097192009-03-27 20:18:19 +0000762 case Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +0000763 case Captured:
Chris Lattner8e097192009-03-27 20:18:19 +0000764 case TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +0000765 case ExternCContext:
Richard Smithbdb84f32016-07-22 23:36:59 +0000766 case Decomposition:
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000767
Chris Lattner8e097192009-03-27 20:18:19 +0000768 case UsingDirective:
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000769 case BuiltinTemplate:
Chris Lattner8e097192009-03-27 20:18:19 +0000770 case ClassTemplateSpecialization:
Douglas Gregor2373c592009-05-31 09:31:02 +0000771 case ClassTemplatePartialSpecialization:
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000772 case ClassScopeFunctionSpecialization:
Larisse Voufo39a1e502013-08-06 01:03:05 +0000773 case VarTemplateSpecialization:
774 case VarTemplatePartialSpecialization:
Douglas Gregore93525e2010-04-22 23:19:50 +0000775 case ObjCImplementation:
776 case ObjCCategory:
777 case ObjCCategoryImpl:
Douglas Gregorba345522011-12-02 23:23:56 +0000778 case Import:
Alexey Bataeva769e072013-03-22 06:34:35 +0000779 case OMPThreadPrivate:
Alexey Bataev4244be22016-02-11 05:35:55 +0000780 case OMPCapturedExpr:
Michael Han84324352013-02-22 17:15:32 +0000781 case Empty:
Douglas Gregore93525e2010-04-22 23:19:50 +0000782 // Never looked up by name.
Chris Lattner8e097192009-03-27 20:18:19 +0000783 return 0;
784 }
John McCall3f746822009-11-17 05:59:44 +0000785
David Blaikiee4d798f2012-01-20 21:50:17 +0000786 llvm_unreachable("Invalid DeclKind!");
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000787}
788
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000789void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
Argyrios Kyrtzidis91167172010-06-11 23:09:25 +0000790 assert(!HasAttrs && "Decl already contains attrs.");
791
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000792 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000793 assert(AttrBlank.empty() && "HasAttrs was wrong?");
Argyrios Kyrtzidis91167172010-06-11 23:09:25 +0000794
795 AttrBlank = attrs;
796 HasAttrs = true;
797}
798
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000799void Decl::dropAttrs() {
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000800 if (!HasAttrs) return;
Mike Stump11289f42009-09-09 15:08:12 +0000801
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000802 HasAttrs = false;
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000803 getASTContext().eraseDeclAttrs(this);
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000804}
805
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000806const AttrVec &Decl::getAttrs() const {
807 assert(HasAttrs && "No attrs to get!");
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000808 return getASTContext().getDeclAttrs(this);
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000809}
810
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000811Decl *Decl::castFromDeclContext (const DeclContext *D) {
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000812 Decl::Kind DK = D->getDeclKind();
813 switch(DK) {
Alexis Hunted053252010-05-30 07:21:58 +0000814#define DECL(NAME, BASE)
815#define DECL_CONTEXT(NAME) \
816 case Decl::NAME: \
817 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
818#define DECL_CONTEXT_BASE(NAME)
819#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000820 default:
Alexis Hunted053252010-05-30 07:21:58 +0000821#define DECL(NAME, BASE)
822#define DECL_CONTEXT_BASE(NAME) \
823 if (DK >= first##NAME && DK <= last##NAME) \
824 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
825#include "clang/AST/DeclNodes.inc"
David Blaikie83d382b2011-09-23 05:06:16 +0000826 llvm_unreachable("a decl that inherits DeclContext isn't handled");
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000827 }
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000828}
829
830DeclContext *Decl::castToDeclContext(const Decl *D) {
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000831 Decl::Kind DK = D->getKind();
832 switch(DK) {
Alexis Hunted053252010-05-30 07:21:58 +0000833#define DECL(NAME, BASE)
834#define DECL_CONTEXT(NAME) \
835 case Decl::NAME: \
836 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
837#define DECL_CONTEXT_BASE(NAME)
838#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000839 default:
Alexis Hunted053252010-05-30 07:21:58 +0000840#define DECL(NAME, BASE)
841#define DECL_CONTEXT_BASE(NAME) \
842 if (DK >= first##NAME && DK <= last##NAME) \
843 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
844#include "clang/AST/DeclNodes.inc"
David Blaikie83d382b2011-09-23 05:06:16 +0000845 llvm_unreachable("a decl that inherits DeclContext isn't handled");
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000846 }
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000847}
848
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000849SourceLocation Decl::getBodyRBrace() const {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +0000850 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
851 // FunctionDecl stores EndRangeLoc for this purpose.
852 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
853 const FunctionDecl *Definition;
854 if (FD->hasBody(Definition))
855 return Definition->getSourceRange().getEnd();
856 return SourceLocation();
857 }
858
Argyrios Kyrtzidis6fbc8fa2010-07-07 11:31:27 +0000859 if (Stmt *Body = getBody())
860 return Body->getSourceRange().getEnd();
861
862 return SourceLocation();
Sebastian Redla7b98a72009-04-26 20:35:05 +0000863}
864
Alp Tokerc1086762013-12-07 13:51:35 +0000865bool Decl::AccessDeclContextSanity() const {
Douglas Gregor4b00d3b2010-12-02 00:22:25 +0000866#ifndef NDEBUG
John McCall401982f2010-01-20 21:53:11 +0000867 // Suppress this check if any of the following hold:
868 // 1. this is the translation unit (and thus has no parent)
869 // 2. this is a template parameter (and thus doesn't belong to its context)
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000870 // 3. this is a non-type template parameter
871 // 4. the context is not a record
872 // 5. it's invalid
873 // 6. it's a C++0x static_assert.
Anders Carlssonadf36b22009-08-29 20:47:47 +0000874 if (isa<TranslationUnitDecl>(this) ||
Argyrios Kyrtzidisa45855f2010-07-02 11:55:44 +0000875 isa<TemplateTypeParmDecl>(this) ||
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000876 isa<NonTypeTemplateParmDecl>(this) ||
Douglas Gregor2b76dd92010-02-22 17:53:38 +0000877 !isa<CXXRecordDecl>(getDeclContext()) ||
Argyrios Kyrtzidis260b4a82010-09-08 21:32:35 +0000878 isInvalidDecl() ||
879 isa<StaticAssertDecl>(this) ||
880 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
881 // as DeclContext (?).
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000882 isa<ParmVarDecl>(this) ||
883 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
884 // AS_none as access specifier.
Francois Pichet09af8c32011-08-17 01:06:54 +0000885 isa<CXXRecordDecl>(this) ||
886 isa<ClassScopeFunctionSpecializationDecl>(this))
Alp Tokerc1086762013-12-07 13:51:35 +0000887 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000888
889 assert(Access != AS_none &&
Anders Carlssona28908d2009-03-25 23:38:06 +0000890 "Access specifier is AS_none inside a record decl");
Douglas Gregor4b00d3b2010-12-02 00:22:25 +0000891#endif
Alp Tokerc1086762013-12-07 13:51:35 +0000892 return true;
Anders Carlssona28908d2009-03-25 23:38:06 +0000893}
894
John McCalldec348f72013-05-03 07:33:41 +0000895static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
896static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
897
Aaron Ballman12b9f652014-01-16 13:55:42 +0000898const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
899 QualType Ty;
900 if (const ValueDecl *D = dyn_cast<ValueDecl>(this))
901 Ty = D->getType();
902 else if (const TypedefNameDecl *D = dyn_cast<TypedefNameDecl>(this))
903 Ty = D->getUnderlyingType();
904 else
Craig Topper36250ad2014-05-12 05:36:57 +0000905 return nullptr;
Aaron Ballman12b9f652014-01-16 13:55:42 +0000906
907 if (Ty->isFunctionPointerType())
908 Ty = Ty->getAs<PointerType>()->getPointeeType();
909 else if (BlocksToo && Ty->isBlockPointerType())
910 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
911
912 return Ty->getAs<FunctionType>();
913}
914
915
John McCalldec348f72013-05-03 07:33:41 +0000916/// Starting at a given context (a Decl or DeclContext), look for a
917/// code context that is not a closure (a lambda, block, etc.).
918template <class T> static Decl *getNonClosureContext(T *D) {
919 if (getKind(D) == Decl::CXXMethod) {
920 CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
John McCall55c0cee2013-05-03 17:11:14 +0000921 if (MD->getOverloadedOperator() == OO_Call &&
922 MD->getParent()->isLambda())
John McCalldec348f72013-05-03 07:33:41 +0000923 return getNonClosureContext(MD->getParent()->getParent());
924 return MD;
925 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
926 return FD;
927 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
928 return MD;
929 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
930 return getNonClosureContext(BD->getParent());
931 } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
932 return getNonClosureContext(CD->getParent());
933 } else {
Craig Topper36250ad2014-05-12 05:36:57 +0000934 return nullptr;
John McCalldec348f72013-05-03 07:33:41 +0000935 }
John McCallfe96e0b2011-11-06 09:01:30 +0000936}
937
John McCalldec348f72013-05-03 07:33:41 +0000938Decl *Decl::getNonClosureContext() {
939 return ::getNonClosureContext(this);
940}
John McCallb67608f2011-02-22 22:25:23 +0000941
John McCalldec348f72013-05-03 07:33:41 +0000942Decl *DeclContext::getNonClosureAncestor() {
943 return ::getNonClosureContext(this);
John McCallb67608f2011-02-22 22:25:23 +0000944}
Anders Carlssona28908d2009-03-25 23:38:06 +0000945
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000946//===----------------------------------------------------------------------===//
947// DeclContext Implementation
948//===----------------------------------------------------------------------===//
949
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000950bool DeclContext::classof(const Decl *D) {
951 switch (D->getKind()) {
Alexis Hunted053252010-05-30 07:21:58 +0000952#define DECL(NAME, BASE)
953#define DECL_CONTEXT(NAME) case Decl::NAME:
954#define DECL_CONTEXT_BASE(NAME)
955#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000956 return true;
957 default:
Alexis Hunted053252010-05-30 07:21:58 +0000958#define DECL(NAME, BASE)
959#define DECL_CONTEXT_BASE(NAME) \
960 if (D->getKind() >= Decl::first##NAME && \
961 D->getKind() <= Decl::last##NAME) \
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000962 return true;
Alexis Hunted053252010-05-30 07:21:58 +0000963#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000964 return false;
965 }
966}
967
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000968DeclContext::~DeclContext() { }
Douglas Gregor91f84212008-12-11 16:49:14 +0000969
Douglas Gregor7f737c02009-09-10 16:57:35 +0000970/// \brief Find the parent context of this context that will be
971/// used for unqualified name lookup.
972///
973/// Generally, the parent lookup context is the semantic context. However, for
974/// a friend function the parent lookup context is the lexical context, which
975/// is the class in which the friend is declared.
976DeclContext *DeclContext::getLookupParent() {
977 // FIXME: Find a better way to identify friends
978 if (isa<FunctionDecl>(this))
Sebastian Redl50c68252010-08-31 00:36:30 +0000979 if (getParent()->getRedeclContext()->isFileContext() &&
980 getLexicalParent()->getRedeclContext()->isRecord())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000981 return getLexicalParent();
982
983 return getParent();
984}
985
Sebastian Redlbd595762010-08-31 20:53:31 +0000986bool DeclContext::isInlineNamespace() const {
987 return isNamespace() &&
988 cast<NamespaceDecl>(this)->isInline();
989}
990
Richard Trieuc771d5d2014-05-28 02:16:01 +0000991bool DeclContext::isStdNamespace() const {
992 if (!isNamespace())
993 return false;
994
995 const NamespaceDecl *ND = cast<NamespaceDecl>(this);
996 if (ND->isInline()) {
997 return ND->getParent()->isStdNamespace();
998 }
999
1000 if (!getParent()->getRedeclContext()->isTranslationUnit())
1001 return false;
1002
1003 const IdentifierInfo *II = ND->getIdentifier();
1004 return II && II->isStr("std");
1005}
1006
Douglas Gregor9e927ab2009-05-28 16:34:51 +00001007bool DeclContext::isDependentContext() const {
1008 if (isFileContext())
1009 return false;
1010
Douglas Gregor2373c592009-05-31 09:31:02 +00001011 if (isa<ClassTemplatePartialSpecializationDecl>(this))
1012 return true;
1013
Douglas Gregor680e9e02012-02-21 19:11:17 +00001014 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
Douglas Gregor9e927ab2009-05-28 16:34:51 +00001015 if (Record->getDescribedClassTemplate())
1016 return true;
Douglas Gregor680e9e02012-02-21 19:11:17 +00001017
1018 if (Record->isDependentLambda())
1019 return true;
1020 }
1021
John McCallc62bb642010-03-24 05:22:00 +00001022 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
Douglas Gregor9e927ab2009-05-28 16:34:51 +00001023 if (Function->getDescribedFunctionTemplate())
1024 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001025
John McCallc62bb642010-03-24 05:22:00 +00001026 // Friend function declarations are dependent if their *lexical*
1027 // context is dependent.
1028 if (cast<Decl>(this)->getFriendObjectKind())
1029 return getLexicalParent()->isDependentContext();
1030 }
1031
Richard Smith2b560572015-02-07 03:11:11 +00001032 // FIXME: A variable template is a dependent context, but is not a
1033 // DeclContext. A context within it (such as a lambda-expression)
1034 // should be considered dependent.
1035
Douglas Gregor9e927ab2009-05-28 16:34:51 +00001036 return getParent() && getParent()->isDependentContext();
1037}
1038
Douglas Gregor07665a62009-01-05 19:45:36 +00001039bool DeclContext::isTransparentContext() const {
1040 if (DeclKind == Decl::Enum)
Douglas Gregor0bf31402010-10-08 23:50:27 +00001041 return !cast<EnumDecl>(this)->isScoped();
Richard Smith8df390f2016-09-08 23:14:54 +00001042 else if (DeclKind == Decl::LinkageSpec || DeclKind == Decl::Export)
Douglas Gregor07665a62009-01-05 19:45:36 +00001043 return true;
Douglas Gregor07665a62009-01-05 19:45:36 +00001044
1045 return false;
1046}
1047
Serge Pavlov3cb80222013-11-14 02:13:03 +00001048static bool isLinkageSpecContext(const DeclContext *DC,
1049 LinkageSpecDecl::LanguageIDs ID) {
1050 while (DC->getDeclKind() != Decl::TranslationUnit) {
1051 if (DC->getDeclKind() == Decl::LinkageSpec)
1052 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
Richard Smithac9c9a02014-04-14 20:23:58 +00001053 DC = DC->getLexicalParent();
Serge Pavlov3cb80222013-11-14 02:13:03 +00001054 }
1055 return false;
1056}
1057
1058bool DeclContext::isExternCContext() const {
1059 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_c);
1060}
1061
Alex Lorenz560ae562016-11-02 15:46:34 +00001062const LinkageSpecDecl *DeclContext::getExternCContext() const {
1063 const DeclContext *DC = this;
1064 while (DC->getDeclKind() != Decl::TranslationUnit) {
1065 if (DC->getDeclKind() == Decl::LinkageSpec &&
1066 cast<LinkageSpecDecl>(DC)->getLanguage() ==
1067 clang::LinkageSpecDecl::lang_c)
1068 return cast<LinkageSpecDecl>(DC);
1069 DC = DC->getLexicalParent();
1070 }
1071 return nullptr;
1072}
1073
Serge Pavlov3cb80222013-11-14 02:13:03 +00001074bool DeclContext::isExternCXXContext() const {
1075 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_cxx);
1076}
1077
Sebastian Redl50c68252010-08-31 00:36:30 +00001078bool DeclContext::Encloses(const DeclContext *DC) const {
Douglas Gregore985a3b2009-08-27 06:03:53 +00001079 if (getPrimaryContext() != this)
1080 return getPrimaryContext()->Encloses(DC);
Mike Stump11289f42009-09-09 15:08:12 +00001081
Douglas Gregore985a3b2009-08-27 06:03:53 +00001082 for (; DC; DC = DC->getParent())
1083 if (DC->getPrimaryContext() == this)
1084 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001085 return false;
Douglas Gregore985a3b2009-08-27 06:03:53 +00001086}
1087
Steve Naroff35c62ae2009-01-08 17:28:14 +00001088DeclContext *DeclContext::getPrimaryContext() {
Douglas Gregor91f84212008-12-11 16:49:14 +00001089 switch (DeclKind) {
Douglas Gregor91f84212008-12-11 16:49:14 +00001090 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00001091 case Decl::ExternCContext:
Douglas Gregor07665a62009-01-05 19:45:36 +00001092 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00001093 case Decl::Export:
Mike Stump11289f42009-09-09 15:08:12 +00001094 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001095 case Decl::Captured:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001096 case Decl::OMPDeclareReduction:
Douglas Gregor91f84212008-12-11 16:49:14 +00001097 // There is only one DeclContext for these entities.
1098 return this;
1099
1100 case Decl::Namespace:
1101 // The original namespace is our primary context.
1102 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
1103
Douglas Gregor91f84212008-12-11 16:49:14 +00001104 case Decl::ObjCMethod:
1105 return this;
1106
1107 case Decl::ObjCInterface:
Douglas Gregor66b310c2011-12-15 18:03:09 +00001108 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
1109 return Def;
1110
1111 return this;
1112
Steve Naroff35c62ae2009-01-08 17:28:14 +00001113 case Decl::ObjCProtocol:
Douglas Gregora715bff2012-01-01 19:51:50 +00001114 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
1115 return Def;
1116
1117 return this;
Douglas Gregor66b310c2011-12-15 18:03:09 +00001118
Steve Naroff35c62ae2009-01-08 17:28:14 +00001119 case Decl::ObjCCategory:
Douglas Gregor91f84212008-12-11 16:49:14 +00001120 return this;
1121
Steve Naroff35c62ae2009-01-08 17:28:14 +00001122 case Decl::ObjCImplementation:
1123 case Decl::ObjCCategoryImpl:
1124 return this;
1125
Douglas Gregor91f84212008-12-11 16:49:14 +00001126 default:
Alexis Hunted053252010-05-30 07:21:58 +00001127 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
Douglas Gregor67a65642009-02-17 23:15:12 +00001128 // If this is a tag type that has a definition or is currently
1129 // being defined, that definition is our primary context.
John McCalle78aac42010-03-10 03:28:59 +00001130 TagDecl *Tag = cast<TagDecl>(this);
John McCalle78aac42010-03-10 03:28:59 +00001131
1132 if (TagDecl *Def = Tag->getDefinition())
1133 return Def;
1134
Richard Smith5b21db82014-04-23 18:20:42 +00001135 if (const TagType *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
1136 // Note, TagType::getDecl returns the (partial) definition one exists.
1137 TagDecl *PossiblePartialDef = TagTy->getDecl();
1138 if (PossiblePartialDef->isBeingDefined())
1139 return PossiblePartialDef;
1140 } else {
1141 assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
John McCalle78aac42010-03-10 03:28:59 +00001142 }
1143
1144 return Tag;
Douglas Gregor67a65642009-02-17 23:15:12 +00001145 }
1146
Alexis Hunted053252010-05-30 07:21:58 +00001147 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
Douglas Gregor91f84212008-12-11 16:49:14 +00001148 "Unknown DeclContext kind");
1149 return this;
1150 }
1151}
1152
Douglas Gregore57e7522012-01-07 09:11:48 +00001153void
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001154DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
Douglas Gregore57e7522012-01-07 09:11:48 +00001155 Contexts.clear();
1156
1157 if (DeclKind != Decl::Namespace) {
1158 Contexts.push_back(this);
1159 return;
Douglas Gregor91f84212008-12-11 16:49:14 +00001160 }
Douglas Gregore57e7522012-01-07 09:11:48 +00001161
1162 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
Douglas Gregorec9fd132012-01-14 16:38:05 +00001163 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
1164 N = N->getPreviousDecl())
Douglas Gregore57e7522012-01-07 09:11:48 +00001165 Contexts.push_back(N);
1166
1167 std::reverse(Contexts.begin(), Contexts.end());
Douglas Gregor91f84212008-12-11 16:49:14 +00001168}
1169
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001170std::pair<Decl *, Decl *>
Bill Wendling8eb771d2012-02-22 09:51:33 +00001171DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00001172 bool FieldsAlreadyLoaded) {
Douglas Gregor781f7132012-01-06 16:59:53 +00001173 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
Craig Topper36250ad2014-05-12 05:36:57 +00001174 Decl *FirstNewDecl = nullptr;
1175 Decl *PrevDecl = nullptr;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001176 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00001177 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
1178 continue;
1179
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001180 Decl *D = Decls[I];
1181 if (PrevDecl)
Douglas Gregor781f7132012-01-06 16:59:53 +00001182 PrevDecl->NextInContextAndBits.setPointer(D);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001183 else
1184 FirstNewDecl = D;
1185
1186 PrevDecl = D;
1187 }
1188
1189 return std::make_pair(FirstNewDecl, PrevDecl);
1190}
1191
Richard Smith645d7552013-02-07 03:37:08 +00001192/// \brief We have just acquired external visible storage, and we already have
1193/// built a lookup map. For every name in the map, pull in the new names from
1194/// the external storage.
Richard Smitha8b74592014-03-25 00:34:21 +00001195void DeclContext::reconcileExternalVisibleStorage() const {
Richard Smith9e2341d2015-03-23 03:25:59 +00001196 assert(NeedToReconcileExternalVisibleStorage && LookupPtr);
Richard Smith645d7552013-02-07 03:37:08 +00001197 NeedToReconcileExternalVisibleStorage = false;
1198
Richard Smith9e2341d2015-03-23 03:25:59 +00001199 for (auto &Lookup : *LookupPtr)
Richard Smitha8b74592014-03-25 00:34:21 +00001200 Lookup.second.setHasExternalDecls();
Richard Smith645d7552013-02-07 03:37:08 +00001201}
1202
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001203/// \brief Load the declarations within this lexical storage from an
1204/// external source.
Richard Smith18b380b2015-03-24 02:44:20 +00001205/// \return \c true if any declarations were added.
1206bool
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001207DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1208 ExternalASTSource *Source = getParentASTContext().getExternalSource();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001209 assert(hasExternalLexicalStorage() && Source && "No external storage?");
1210
Argyrios Kyrtzidis98d045e2010-07-30 10:03:23 +00001211 // Notify that we have a DeclContext that is initializing.
1212 ExternalASTSource::Deserializing ADeclContext(Source);
Richard Smith9e2341d2015-03-23 03:25:59 +00001213
Douglas Gregor3d0adb32011-07-15 21:46:17 +00001214 // Load the external declarations, if any.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001215 SmallVector<Decl*, 64> Decls;
Richard Smith18b380b2015-03-24 02:44:20 +00001216 ExternalLexicalStorage = false;
Richard Smith3cb15722015-08-05 22:41:45 +00001217 Source->FindExternalLexicalDecls(this, Decls);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001218
1219 if (Decls.empty())
Richard Smith18b380b2015-03-24 02:44:20 +00001220 return false;
Richard Smith9e2341d2015-03-23 03:25:59 +00001221
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00001222 // We may have already loaded just the fields of this record, in which case
1223 // we need to ignore them.
1224 bool FieldsAlreadyLoaded = false;
1225 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
1226 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
1227
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001228 // Splice the newly-read declarations into the beginning of the list
1229 // of declarations.
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001230 Decl *ExternalFirst, *ExternalLast;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001231 std::tie(ExternalFirst, ExternalLast) =
1232 BuildDeclChain(Decls, FieldsAlreadyLoaded);
Douglas Gregor781f7132012-01-06 16:59:53 +00001233 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001234 FirstDecl = ExternalFirst;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001235 if (!LastDecl)
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001236 LastDecl = ExternalLast;
Richard Smith18b380b2015-03-24 02:44:20 +00001237 return true;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001238}
1239
John McCall75b960e2010-06-01 09:23:16 +00001240DeclContext::lookup_result
1241ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1242 DeclarationName Name) {
1243 ASTContext &Context = DC->getParentASTContext();
1244 StoredDeclsMap *Map;
Richard Smith9e2341d2015-03-23 03:25:59 +00001245 if (!(Map = DC->LookupPtr))
John McCall75b960e2010-06-01 09:23:16 +00001246 Map = DC->CreateStoredDeclsMap(Context);
Richard Smitha8b74592014-03-25 00:34:21 +00001247 if (DC->NeedToReconcileExternalVisibleStorage)
1248 DC->reconcileExternalVisibleStorage();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001249
Richard Smith4abe0a82013-09-09 07:34:56 +00001250 (*Map)[Name].removeExternalDecls();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001251
John McCall75b960e2010-06-01 09:23:16 +00001252 return DeclContext::lookup_result();
1253}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001254
John McCall75b960e2010-06-01 09:23:16 +00001255DeclContext::lookup_result
1256ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
John McCall75b960e2010-06-01 09:23:16 +00001257 DeclarationName Name,
Argyrios Kyrtzidis94d3f9d2011-09-09 06:44:14 +00001258 ArrayRef<NamedDecl*> Decls) {
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00001259 ASTContext &Context = DC->getParentASTContext();
John McCall75b960e2010-06-01 09:23:16 +00001260 StoredDeclsMap *Map;
Richard Smith9e2341d2015-03-23 03:25:59 +00001261 if (!(Map = DC->LookupPtr))
John McCall75b960e2010-06-01 09:23:16 +00001262 Map = DC->CreateStoredDeclsMap(Context);
Richard Smitha8b74592014-03-25 00:34:21 +00001263 if (DC->NeedToReconcileExternalVisibleStorage)
1264 DC->reconcileExternalVisibleStorage();
John McCall75b960e2010-06-01 09:23:16 +00001265
1266 StoredDeclsList &List = (*Map)[Name];
Richard Smith51445cd2013-06-24 01:46:41 +00001267
1268 // Clear out any old external visible declarations, to avoid quadratic
1269 // performance in the redeclaration checks below.
1270 List.removeExternalDecls();
1271
1272 if (!List.isNull()) {
1273 // We have both existing declarations and new declarations for this name.
1274 // Some of the declarations may simply replace existing ones. Handle those
1275 // first.
1276 llvm::SmallVector<unsigned, 8> Skip;
1277 for (unsigned I = 0, N = Decls.size(); I != N; ++I)
Richard Smithe8292b12015-02-10 03:28:10 +00001278 if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
Richard Smith51445cd2013-06-24 01:46:41 +00001279 Skip.push_back(I);
1280 Skip.push_back(Decls.size());
1281
1282 // Add in any new declarations.
1283 unsigned SkipPos = 0;
1284 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1285 if (I == Skip[SkipPos])
1286 ++SkipPos;
1287 else
1288 List.AddSubsequentDecl(Decls[I]);
1289 }
1290 } else {
1291 // Convert the array to a StoredDeclsList.
1292 for (ArrayRef<NamedDecl*>::iterator
1293 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1294 if (List.isNull())
1295 List.setOnlyValue(*I);
1296 else
1297 List.AddSubsequentDecl(*I);
1298 }
John McCall75b960e2010-06-01 09:23:16 +00001299 }
1300
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001301 return List.getLookupResult();
John McCall75b960e2010-06-01 09:23:16 +00001302}
1303
Aaron Ballmanda634f12014-03-07 22:17:20 +00001304DeclContext::decl_iterator DeclContext::decls_begin() const {
1305 if (hasExternalLexicalStorage())
1306 LoadLexicalDeclsFromExternalStorage();
1307 return decl_iterator(FirstDecl);
1308}
1309
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001310bool DeclContext::decls_empty() const {
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001311 if (hasExternalLexicalStorage())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001312 LoadLexicalDeclsFromExternalStorage();
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001313
1314 return !FirstDecl;
1315}
1316
Sean Callanan0325fb82013-05-04 02:04:27 +00001317bool DeclContext::containsDecl(Decl *D) const {
1318 return (D->getLexicalDeclContext() == this &&
1319 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1320}
1321
John McCall84d87672009-12-10 09:41:52 +00001322void DeclContext::removeDecl(Decl *D) {
1323 assert(D->getLexicalDeclContext() == this &&
1324 "decl being removed from non-lexical context");
Douglas Gregor781f7132012-01-06 16:59:53 +00001325 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
John McCall84d87672009-12-10 09:41:52 +00001326 "decl is not in decls list");
1327
1328 // Remove D from the decl chain. This is O(n) but hopefully rare.
1329 if (D == FirstDecl) {
1330 if (D == LastDecl)
Craig Topper36250ad2014-05-12 05:36:57 +00001331 FirstDecl = LastDecl = nullptr;
John McCall84d87672009-12-10 09:41:52 +00001332 else
Douglas Gregor781f7132012-01-06 16:59:53 +00001333 FirstDecl = D->NextInContextAndBits.getPointer();
John McCall84d87672009-12-10 09:41:52 +00001334 } else {
Douglas Gregor781f7132012-01-06 16:59:53 +00001335 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
John McCall84d87672009-12-10 09:41:52 +00001336 assert(I && "decl not found in linked list");
Douglas Gregor781f7132012-01-06 16:59:53 +00001337 if (I->NextInContextAndBits.getPointer() == D) {
1338 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
John McCall84d87672009-12-10 09:41:52 +00001339 if (D == LastDecl) LastDecl = I;
1340 break;
1341 }
1342 }
1343 }
1344
1345 // Mark that D is no longer in the decl chain.
Craig Topper36250ad2014-05-12 05:36:57 +00001346 D->NextInContextAndBits.setPointer(nullptr);
John McCall84d87672009-12-10 09:41:52 +00001347
1348 // Remove D from the lookup table if necessary.
1349 if (isa<NamedDecl>(D)) {
1350 NamedDecl *ND = cast<NamedDecl>(D);
1351
Axel Naumanncb2c52f2011-08-26 14:06:12 +00001352 // Remove only decls that have a name
1353 if (!ND->getDeclName()) return;
1354
Richard Smith26210db2015-11-13 03:52:13 +00001355 auto *DC = this;
1356 do {
1357 StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1358 if (Map) {
1359 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1360 assert(Pos != Map->end() && "no lookup entry for decl");
1361 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1362 Pos->second.remove(ND);
1363 }
1364 } while (DC->isTransparentContext() && (DC = DC->getParent()));
John McCall84d87672009-12-10 09:41:52 +00001365 }
1366}
1367
John McCalld1e9d832009-08-11 06:59:38 +00001368void DeclContext::addHiddenDecl(Decl *D) {
Chris Lattner33f219d2009-02-20 00:56:18 +00001369 assert(D->getLexicalDeclContext() == this &&
1370 "Decl inserted into wrong lexical context");
Mike Stump11289f42009-09-09 15:08:12 +00001371 assert(!D->getNextDeclInContext() && D != LastDecl &&
Douglas Gregor020713e2009-01-09 19:42:16 +00001372 "Decl already inserted into a DeclContext");
1373
1374 if (FirstDecl) {
Douglas Gregor781f7132012-01-06 16:59:53 +00001375 LastDecl->NextInContextAndBits.setPointer(D);
Douglas Gregor020713e2009-01-09 19:42:16 +00001376 LastDecl = D;
1377 } else {
1378 FirstDecl = LastDecl = D;
1379 }
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001380
1381 // Notify a C++ record declaration that we've added a member, so it can
Nick Lewycky4b81fc872015-10-18 20:32:12 +00001382 // update its class-specific state.
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001383 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1384 Record->addedMember(D);
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001385
1386 // If this is a newly-created (not de-serialized) import declaration, wire
1387 // it in to the list of local import declarations.
1388 if (!D->isFromASTFile()) {
1389 if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1390 D->getASTContext().addedLocalImportDecl(Import);
1391 }
John McCalld1e9d832009-08-11 06:59:38 +00001392}
1393
1394void DeclContext::addDecl(Decl *D) {
1395 addHiddenDecl(D);
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001396
1397 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithf634c902012-03-16 06:12:59 +00001398 ND->getDeclContext()->getPrimaryContext()->
1399 makeDeclVisibleInContextWithFlags(ND, false, true);
Douglas Gregor91f84212008-12-11 16:49:14 +00001400}
1401
Sean Callanan95e74be2011-10-21 02:57:43 +00001402void DeclContext::addDeclInternal(Decl *D) {
1403 addHiddenDecl(D);
1404
1405 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithf634c902012-03-16 06:12:59 +00001406 ND->getDeclContext()->getPrimaryContext()->
1407 makeDeclVisibleInContextWithFlags(ND, true, true);
1408}
1409
1410/// shouldBeHidden - Determine whether a declaration which was declared
1411/// within its semantic context should be invisible to qualified name lookup.
1412static bool shouldBeHidden(NamedDecl *D) {
1413 // Skip unnamed declarations.
1414 if (!D->getDeclName())
1415 return true;
1416
1417 // Skip entities that can't be found by name lookup into a particular
1418 // context.
1419 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1420 D->isTemplateParameter())
1421 return true;
1422
1423 // Skip template specializations.
1424 // FIXME: This feels like a hack. Should DeclarationName support
1425 // template-ids, or is there a better way to keep specializations
1426 // from being visible?
1427 if (isa<ClassTemplateSpecializationDecl>(D))
1428 return true;
1429 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1430 if (FD->isFunctionTemplateSpecialization())
1431 return true;
1432
1433 return false;
1434}
1435
1436/// buildLookup - Build the lookup data structure with all of the
1437/// declarations in this DeclContext (and any other contexts linked
1438/// to it or transparent contexts nested within it) and return it.
Richard Smitha8b74592014-03-25 00:34:21 +00001439///
1440/// Note that the produced map may miss out declarations from an
1441/// external source. If it does, those entries will be marked with
1442/// the 'hasExternalDecls' flag.
Richard Smithf634c902012-03-16 06:12:59 +00001443StoredDeclsMap *DeclContext::buildLookup() {
1444 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1445
Richard Smith9e2341d2015-03-23 03:25:59 +00001446 if (!HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups)
1447 return LookupPtr;
1448
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001449 SmallVector<DeclContext *, 2> Contexts;
Richard Smithf634c902012-03-16 06:12:59 +00001450 collectAllContexts(Contexts);
Richard Smith18b380b2015-03-24 02:44:20 +00001451
1452 if (HasLazyExternalLexicalLookups) {
1453 HasLazyExternalLexicalLookups = false;
1454 for (auto *DC : Contexts) {
1455 if (DC->hasExternalLexicalStorage())
1456 HasLazyLocalLexicalLookups |=
1457 DC->LoadLexicalDeclsFromExternalStorage();
1458 }
1459
1460 if (!HasLazyLocalLexicalLookups)
1461 return LookupPtr;
1462 }
1463
1464 for (auto *DC : Contexts)
1465 buildLookupImpl(DC, hasExternalVisibleStorage());
Richard Smithf634c902012-03-16 06:12:59 +00001466
1467 // We no longer have any lazy decls.
Richard Smith9e2341d2015-03-23 03:25:59 +00001468 HasLazyLocalLexicalLookups = false;
1469 return LookupPtr;
Richard Smithf634c902012-03-16 06:12:59 +00001470}
1471
1472/// buildLookupImpl - Build part of the lookup data structure for the
1473/// declarations contained within DCtx, which will either be this
1474/// DeclContext, a DeclContext linked to it, or a transparent context
1475/// nested within it.
Richard Smitha3271c12015-02-07 00:45:52 +00001476void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
Richard Smith9e2341d2015-03-23 03:25:59 +00001477 for (Decl *D : DCtx->noload_decls()) {
Richard Smithf634c902012-03-16 06:12:59 +00001478 // Insert this declaration into the lookup structure, but only if
1479 // it's semantically within its decl context. Any other decls which
1480 // should be found in this context are added eagerly.
Richard Smithcf4ab522013-06-24 07:20:36 +00001481 //
1482 // If it's from an AST file, don't add it now. It'll get handled by
1483 // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1484 // in C++, we do not track external visible decls for the TU, so in
1485 // that case we need to collect them all here.
Richard Smithf634c902012-03-16 06:12:59 +00001486 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithcf4ab522013-06-24 07:20:36 +00001487 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1488 (!ND->isFromASTFile() ||
1489 (isTranslationUnit() &&
1490 !getParentASTContext().getLangOpts().CPlusPlus)))
Richard Smitha3271c12015-02-07 00:45:52 +00001491 makeDeclVisibleInContextImpl(ND, Internal);
Richard Smithf634c902012-03-16 06:12:59 +00001492
1493 // If this declaration is itself a transparent declaration context
1494 // or inline namespace, add the members of this declaration of that
1495 // context (recursively).
1496 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1497 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Richard Smith9e2341d2015-03-23 03:25:59 +00001498 buildLookupImpl(InnerCtx, Internal);
Richard Smithf634c902012-03-16 06:12:59 +00001499 }
Sean Callanan95e74be2011-10-21 02:57:43 +00001500}
1501
Richard Smith40c78062015-02-21 02:31:57 +00001502NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1503
Mike Stump11289f42009-09-09 15:08:12 +00001504DeclContext::lookup_result
Richard Smith40c78062015-02-21 02:31:57 +00001505DeclContext::lookup(DeclarationName Name) const {
Richard Smith8df390f2016-09-08 23:14:54 +00001506 assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1507 "should not perform lookups into transparent contexts");
Nick Lewycky2bd636f2012-03-13 04:12:34 +00001508
Manman Ren7d2f5c42016-09-09 19:03:07 +00001509 const DeclContext *PrimaryContext = getPrimaryContext();
1510 if (PrimaryContext != this)
1511 return PrimaryContext->lookup(Name);
1512
Richard Smith8cebe372015-02-25 22:20:13 +00001513 // If we have an external source, ensure that any later redeclarations of this
1514 // context have been loaded, since they may add names to the result of this
1515 // lookup (or add external visible storage).
1516 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1517 if (Source)
1518 (void)cast<Decl>(this)->getMostRecentDecl();
Richard Smithbb853c72014-08-13 01:23:33 +00001519
Richard Smith05afe5e2012-03-13 03:12:56 +00001520 if (hasExternalVisibleStorage()) {
Richard Smith8cebe372015-02-25 22:20:13 +00001521 assert(Source && "external visible storage but no external source?");
1522
Richard Smitha8b74592014-03-25 00:34:21 +00001523 if (NeedToReconcileExternalVisibleStorage)
1524 reconcileExternalVisibleStorage();
1525
Richard Smith9e2341d2015-03-23 03:25:59 +00001526 StoredDeclsMap *Map = LookupPtr;
Richard Smitha8b74592014-03-25 00:34:21 +00001527
Richard Smith9e2341d2015-03-23 03:25:59 +00001528 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
Richard Smith40c78062015-02-21 02:31:57 +00001529 // FIXME: Make buildLookup const?
1530 Map = const_cast<DeclContext*>(this)->buildLookup();
Richard Smith645d7552013-02-07 03:37:08 +00001531
Richard Smith75fc3bf2013-02-08 00:37:45 +00001532 if (!Map)
1533 Map = CreateStoredDeclsMap(getParentASTContext());
1534
Richard Smith4abe0a82013-09-09 07:34:56 +00001535 // If we have a lookup result with no external decls, we are done.
Richard Smith75fc3bf2013-02-08 00:37:45 +00001536 std::pair<StoredDeclsMap::iterator, bool> R =
1537 Map->insert(std::make_pair(Name, StoredDeclsList()));
Richard Smith4abe0a82013-09-09 07:34:56 +00001538 if (!R.second && !R.first->second.hasExternalDecls())
Richard Smith75fc3bf2013-02-08 00:37:45 +00001539 return R.first->second.getLookupResult();
Richard Smithf634c902012-03-16 06:12:59 +00001540
Richard Smith309271b2014-03-04 00:21:14 +00001541 if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
Richard Smith9e2341d2015-03-23 03:25:59 +00001542 if (StoredDeclsMap *Map = LookupPtr) {
Richard Smith9ce12e32013-02-07 03:30:24 +00001543 StoredDeclsMap::iterator I = Map->find(Name);
1544 if (I != Map->end())
1545 return I->second.getLookupResult();
1546 }
1547 }
1548
Richard Smith40c78062015-02-21 02:31:57 +00001549 return lookup_result();
John McCall75b960e2010-06-01 09:23:16 +00001550 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001551
Richard Smith9e2341d2015-03-23 03:25:59 +00001552 StoredDeclsMap *Map = LookupPtr;
1553 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
Richard Smith40c78062015-02-21 02:31:57 +00001554 Map = const_cast<DeclContext*>(this)->buildLookup();
Richard Smithf634c902012-03-16 06:12:59 +00001555
1556 if (!Map)
Richard Smith40c78062015-02-21 02:31:57 +00001557 return lookup_result();
Richard Smithf634c902012-03-16 06:12:59 +00001558
1559 StoredDeclsMap::iterator I = Map->find(Name);
1560 if (I == Map->end())
Richard Smith40c78062015-02-21 02:31:57 +00001561 return lookup_result();
Richard Smithf634c902012-03-16 06:12:59 +00001562
1563 return I->second.getLookupResult();
Douglas Gregor91f84212008-12-11 16:49:14 +00001564}
1565
Richard Smith95d99302013-07-13 02:00:19 +00001566DeclContext::lookup_result
1567DeclContext::noload_lookup(DeclarationName Name) {
Richard Smith8df390f2016-09-08 23:14:54 +00001568 assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1569 "should not perform lookups into transparent contexts");
Richard Smith95d99302013-07-13 02:00:19 +00001570
1571 DeclContext *PrimaryContext = getPrimaryContext();
1572 if (PrimaryContext != this)
1573 return PrimaryContext->noload_lookup(Name);
1574
Richard Smith9e2341d2015-03-23 03:25:59 +00001575 // If we have any lazy lexical declarations not in our lookup map, add them
1576 // now. Don't import any external declarations, not even if we know we have
1577 // some missing from the external visible lookups.
1578 if (HasLazyLocalLexicalLookups) {
Vince Harrona3ea9a42015-03-22 05:59:59 +00001579 SmallVector<DeclContext *, 2> Contexts;
1580 collectAllContexts(Contexts);
1581 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
Richard Smith9e2341d2015-03-23 03:25:59 +00001582 buildLookupImpl(Contexts[I], hasExternalVisibleStorage());
1583 HasLazyLocalLexicalLookups = false;
Vince Harrona3ea9a42015-03-22 05:59:59 +00001584 }
1585
Richard Smith9e2341d2015-03-23 03:25:59 +00001586 StoredDeclsMap *Map = LookupPtr;
Richard Smith95d99302013-07-13 02:00:19 +00001587 if (!Map)
Richard Smith40c78062015-02-21 02:31:57 +00001588 return lookup_result();
Richard Smith95d99302013-07-13 02:00:19 +00001589
1590 StoredDeclsMap::iterator I = Map->find(Name);
Craig Topper36250ad2014-05-12 05:36:57 +00001591 return I != Map->end() ? I->second.getLookupResult()
Richard Smith40c78062015-02-21 02:31:57 +00001592 : lookup_result();
Richard Smith95d99302013-07-13 02:00:19 +00001593}
1594
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001595void DeclContext::localUncachedLookup(DeclarationName Name,
1596 SmallVectorImpl<NamedDecl *> &Results) {
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001597 Results.clear();
1598
1599 // If there's no external storage, just perform a normal lookup and copy
1600 // the results.
Douglas Gregordd6006f2012-07-17 21:16:27 +00001601 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001602 lookup_result LookupResults = lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00001603 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001604 return;
1605 }
1606
1607 // If we have a lookup table, check there first. Maybe we'll get lucky.
Richard Smith9e2341d2015-03-23 03:25:59 +00001608 // FIXME: Should we be checking these flags on the primary context?
1609 if (Name && !HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups) {
1610 if (StoredDeclsMap *Map = LookupPtr) {
Douglas Gregordd6006f2012-07-17 21:16:27 +00001611 StoredDeclsMap::iterator Pos = Map->find(Name);
1612 if (Pos != Map->end()) {
1613 Results.insert(Results.end(),
David Blaikieff7d47a2012-12-19 00:45:41 +00001614 Pos->second.getLookupResult().begin(),
1615 Pos->second.getLookupResult().end());
Douglas Gregordd6006f2012-07-17 21:16:27 +00001616 return;
1617 }
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001618 }
1619 }
Douglas Gregordd6006f2012-07-17 21:16:27 +00001620
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001621 // Slow case: grovel through the declarations in our chain looking for
1622 // matches.
Richard Smith9e2341d2015-03-23 03:25:59 +00001623 // FIXME: If we have lazy external declarations, this will not find them!
1624 // FIXME: Should we CollectAllContexts and walk them all here?
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001625 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1626 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1627 if (ND->getDeclName() == Name)
1628 Results.push_back(ND);
1629 }
1630}
1631
Sebastian Redl50c68252010-08-31 00:36:30 +00001632DeclContext *DeclContext::getRedeclContext() {
Chris Lattner17a1bfa2009-03-27 19:19:59 +00001633 DeclContext *Ctx = this;
Sebastian Redlbd595762010-08-31 20:53:31 +00001634 // Skip through transparent contexts.
1635 while (Ctx->isTransparentContext())
Douglas Gregor6ad0ef52009-01-06 23:51:29 +00001636 Ctx = Ctx->getParent();
1637 return Ctx;
1638}
1639
Douglas Gregorf47b9112009-02-25 22:02:03 +00001640DeclContext *DeclContext::getEnclosingNamespaceContext() {
1641 DeclContext *Ctx = this;
1642 // Skip through non-namespace, non-translation-unit contexts.
Sebastian Redl4f08c962010-08-31 00:36:23 +00001643 while (!Ctx->isFileContext())
Douglas Gregorf47b9112009-02-25 22:02:03 +00001644 Ctx = Ctx->getParent();
1645 return Ctx->getPrimaryContext();
1646}
1647
Reid Klecknerd60b82f2014-11-17 23:36:45 +00001648RecordDecl *DeclContext::getOuterLexicalRecordContext() {
1649 // Loop until we find a non-record context.
1650 RecordDecl *OutermostRD = nullptr;
1651 DeclContext *DC = this;
1652 while (DC->isRecord()) {
1653 OutermostRD = cast<RecordDecl>(DC);
1654 DC = DC->getLexicalParent();
1655 }
1656 return OutermostRD;
1657}
1658
Sebastian Redl50c68252010-08-31 00:36:30 +00001659bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1660 // For non-file contexts, this is equivalent to Equals.
1661 if (!isFileContext())
1662 return O->Equals(this);
1663
1664 do {
1665 if (O->Equals(this))
1666 return true;
1667
1668 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1669 if (!NS || !NS->isInline())
1670 break;
1671 O = NS->getParent();
1672 } while (O);
1673
1674 return false;
1675}
1676
Richard Smithf634c902012-03-16 06:12:59 +00001677void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1678 DeclContext *PrimaryDC = this->getPrimaryContext();
1679 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1680 // If the decl is being added outside of its semantic decl context, we
1681 // need to ensure that we eagerly build the lookup information for it.
1682 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
Sean Callanan95e74be2011-10-21 02:57:43 +00001683}
1684
Richard Smithf634c902012-03-16 06:12:59 +00001685void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1686 bool Recoverable) {
1687 assert(this == getPrimaryContext() && "expected a primary DC");
Sean Callanan95e74be2011-10-21 02:57:43 +00001688
Vassil Vassilev71eafde2016-04-06 20:56:03 +00001689 if (!isLookupContext()) {
1690 if (isTransparentContext())
1691 getParent()->getPrimaryContext()
1692 ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
Richard Smith05afe5e2012-03-13 03:12:56 +00001693 return;
Vassil Vassilev71eafde2016-04-06 20:56:03 +00001694 }
Richard Smith05afe5e2012-03-13 03:12:56 +00001695
Richard Smithf634c902012-03-16 06:12:59 +00001696 // Skip declarations which should be invisible to name lookup.
1697 if (shouldBeHidden(D))
1698 return;
1699
1700 // If we already have a lookup data structure, perform the insertion into
1701 // it. If we might have externally-stored decls with this name, look them
1702 // up and perform the insertion. If this decl was declared outside its
1703 // semantic context, buildLookup won't add it, so add it now.
1704 //
1705 // FIXME: As a performance hack, don't add such decls into the translation
1706 // unit unless we're in C++, since qualified lookup into the TU is never
1707 // performed.
Richard Smith9e2341d2015-03-23 03:25:59 +00001708 if (LookupPtr || hasExternalVisibleStorage() ||
Richard Smithf634c902012-03-16 06:12:59 +00001709 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1710 (getParentASTContext().getLangOpts().CPlusPlus ||
1711 !isTranslationUnit()))) {
1712 // If we have lazily omitted any decls, they might have the same name as
1713 // the decl which we are adding, so build a full lookup table before adding
1714 // this decl.
1715 buildLookup();
1716 makeDeclVisibleInContextImpl(D, Internal);
1717 } else {
Richard Smith9e2341d2015-03-23 03:25:59 +00001718 HasLazyLocalLexicalLookups = true;
Richard Smithf634c902012-03-16 06:12:59 +00001719 }
1720
1721 // If we are a transparent context or inline namespace, insert into our
1722 // parent context, too. This operation is recursive.
1723 if (isTransparentContext() || isInlineNamespace())
1724 getParent()->getPrimaryContext()->
1725 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1726
1727 Decl *DCAsDecl = cast<Decl>(this);
1728 // Notify that a decl was made visible unless we are a Tag being defined.
1729 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1730 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1731 L->AddedVisibleDecl(this, D);
1732}
1733
1734void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1735 // Find or create the stored declaration map.
Richard Smith9e2341d2015-03-23 03:25:59 +00001736 StoredDeclsMap *Map = LookupPtr;
Richard Smithf634c902012-03-16 06:12:59 +00001737 if (!Map) {
1738 ASTContext *C = &getParentASTContext();
1739 Map = CreateStoredDeclsMap(*C);
Argyrios Kyrtzidise51e5542010-07-04 21:44:25 +00001740 }
1741
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001742 // If there is an external AST source, load any declarations it knows about
1743 // with this declaration's name.
1744 // If the lookup table contains an entry about this name it means that we
1745 // have already checked the external source.
Sean Callanan95e74be2011-10-21 02:57:43 +00001746 if (!Internal)
1747 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1748 if (hasExternalVisibleStorage() &&
Richard Smithf634c902012-03-16 06:12:59 +00001749 Map->find(D->getDeclName()) == Map->end())
Sean Callanan95e74be2011-10-21 02:57:43 +00001750 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001751
Douglas Gregor91f84212008-12-11 16:49:14 +00001752 // Insert this declaration into the map.
Richard Smithf634c902012-03-16 06:12:59 +00001753 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
Richard Smith4abe0a82013-09-09 07:34:56 +00001754
1755 if (Internal) {
1756 // If this is being added as part of loading an external declaration,
1757 // this may not be the only external declaration with this name.
1758 // In this case, we never try to replace an existing declaration; we'll
1759 // handle that when we finalize the list of declarations for this name.
1760 DeclNameEntries.setHasExternalDecls();
1761 DeclNameEntries.AddSubsequentDecl(D);
1762 return;
1763 }
1764
Richard Smitha3271c12015-02-07 00:45:52 +00001765 if (DeclNameEntries.isNull()) {
Chris Lattnercaae7162009-02-20 01:44:05 +00001766 DeclNameEntries.setOnlyValue(D);
Richard Smithf634c902012-03-16 06:12:59 +00001767 return;
Douglas Gregor91f84212008-12-11 16:49:14 +00001768 }
Chris Lattner24e24d52009-02-20 00:55:03 +00001769
Richard Smithe8292b12015-02-10 03:28:10 +00001770 if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
Richard Smithf634c902012-03-16 06:12:59 +00001771 // This declaration has replaced an existing one for which
1772 // declarationReplaces returns true.
1773 return;
1774 }
Mike Stump11289f42009-09-09 15:08:12 +00001775
Richard Smithf634c902012-03-16 06:12:59 +00001776 // Put this declaration into the appropriate slot.
1777 DeclNameEntries.AddSubsequentDecl(D);
Douglas Gregor91f84212008-12-11 16:49:14 +00001778}
Douglas Gregor889ceb72009-02-03 19:21:40 +00001779
Richard Smith40c78062015-02-21 02:31:57 +00001780UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
1781 return cast<UsingDirectiveDecl>(*I);
1782}
1783
Douglas Gregor889ceb72009-02-03 19:21:40 +00001784/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1785/// this context.
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001786DeclContext::udir_range DeclContext::using_directives() const {
Richard Smith05afe5e2012-03-13 03:12:56 +00001787 // FIXME: Use something more efficient than normal lookup for using
1788 // directives. In C++, using directives are looked up more than anything else.
Richard Smithcf4bdde2015-02-21 02:45:19 +00001789 lookup_result Result = lookup(UsingDirectiveDecl::getName());
Richard Smith40c78062015-02-21 02:31:57 +00001790 return udir_range(Result.begin(), Result.end());
Douglas Gregor889ceb72009-02-03 19:21:40 +00001791}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001792
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001793//===----------------------------------------------------------------------===//
1794// Creation and Destruction of StoredDeclsMaps. //
1795//===----------------------------------------------------------------------===//
1796
John McCallc62bb642010-03-24 05:22:00 +00001797StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
Richard Smith9e2341d2015-03-23 03:25:59 +00001798 assert(!LookupPtr && "context already has a decls map");
John McCallc62bb642010-03-24 05:22:00 +00001799 assert(getPrimaryContext() == this &&
1800 "creating decls map on non-primary context");
1801
1802 StoredDeclsMap *M;
1803 bool Dependent = isDependentContext();
1804 if (Dependent)
1805 M = new DependentStoredDeclsMap();
1806 else
1807 M = new StoredDeclsMap();
1808 M->Previous = C.LastSDM;
1809 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
Richard Smith9e2341d2015-03-23 03:25:59 +00001810 LookupPtr = M;
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001811 return M;
1812}
1813
1814void ASTContext::ReleaseDeclContextMaps() {
John McCallc62bb642010-03-24 05:22:00 +00001815 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1816 // pointer because the subclass doesn't add anything that needs to
1817 // be deleted.
John McCallc62bb642010-03-24 05:22:00 +00001818 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1819}
1820
1821void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1822 while (Map) {
1823 // Advance the iteration before we invalidate memory.
1824 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1825
1826 if (Dependent)
1827 delete static_cast<DependentStoredDeclsMap*>(Map);
1828 else
1829 delete Map;
1830
1831 Map = Next.getPointer();
1832 Dependent = Next.getInt();
1833 }
1834}
1835
John McCallc62bb642010-03-24 05:22:00 +00001836DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1837 DeclContext *Parent,
1838 const PartialDiagnostic &PDiag) {
1839 assert(Parent->isDependentContext()
1840 && "cannot iterate dependent diagnostics of non-dependent context");
1841 Parent = Parent->getPrimaryContext();
Richard Smith9e2341d2015-03-23 03:25:59 +00001842 if (!Parent->LookupPtr)
John McCallc62bb642010-03-24 05:22:00 +00001843 Parent->CreateStoredDeclsMap(C);
1844
Richard Smith9e2341d2015-03-23 03:25:59 +00001845 DependentStoredDeclsMap *Map =
1846 static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
John McCallc62bb642010-03-24 05:22:00 +00001847
Douglas Gregora55530e2010-03-29 23:56:53 +00001848 // Allocate the copy of the PartialDiagnostic via the ASTContext's
Douglas Gregor89336232010-03-29 23:34:08 +00001849 // BumpPtrAllocator, rather than the ASTContext itself.
Craig Topper36250ad2014-05-12 05:36:57 +00001850 PartialDiagnostic::Storage *DiagStorage = nullptr;
Douglas Gregora55530e2010-03-29 23:56:53 +00001851 if (PDiag.hasStorage())
1852 DiagStorage = new (C) PartialDiagnostic::Storage;
1853
1854 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
John McCallc62bb642010-03-24 05:22:00 +00001855
1856 // TODO: Maybe we shouldn't reverse the order during insertion.
1857 DD->NextDiagnostic = Map->FirstDiagnostic;
1858 Map->FirstDiagnostic = DD;
1859
1860 return DD;
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001861}