blob: 42f0ba0bd796ad8be4f10a4d08ba47f719b02489 [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
Richard Smithdebbaef2017-09-05 00:50:19 +000077 // declarations. We create the TU decl early and may not yet know what the
78 // LangOpts are, so conservatively allocate the storage.
79 if (Ctx.getLangOpts().trackLocalOwningModule() || !Parent) {
James Y Knight53c76162015-07-17 18:21:37 +000080 // Ensure required alignment of the resulting object by adding extra
81 // padding at the start if required.
82 size_t ExtraAlign =
Benjamin Kramerc3f89252016-10-20 14:27:22 +000083 llvm::OffsetToAlignment(sizeof(Module *), alignof(Decl));
James Y Knight53c76162015-07-17 18:21:37 +000084 char *Buffer = reinterpret_cast<char *>(
85 ::operator new(ExtraAlign + sizeof(Module *) + Size + Extra, Ctx));
86 Buffer += ExtraAlign;
Richard Smith26342f92017-05-17 00:24:14 +000087 auto *ParentModule =
88 Parent ? cast<Decl>(Parent)->getOwningModule() : nullptr;
89 return new (Buffer) Module*(ParentModule) + 1;
Richard Smith42413142015-05-15 20:05:43 +000090 }
Richard Smithf7981722013-11-22 09:01:48 +000091 return ::operator new(Size + Extra, Ctx);
92}
93
Douglas Gregorc147b0b2013-01-12 01:29:50 +000094Module *Decl::getOwningModuleSlow() const {
95 assert(isFromASTFile() && "Not from AST file?");
96 return getASTContext().getExternalSource()->getModule(getOwningModuleID());
97}
98
Richard Smith87bb5692015-06-09 00:35:49 +000099bool Decl::hasLocalOwningModuleStorage() const {
Richard Smith26342f92017-05-17 00:24:14 +0000100 return getASTContext().getLangOpts().trackLocalOwningModule();
Richard Smith87bb5692015-06-09 00:35:49 +0000101}
102
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000103const char *Decl::getDeclKindName() const {
104 switch (DeclKind) {
David Blaikie83d382b2011-09-23 05:06:16 +0000105 default: llvm_unreachable("Declaration not in DeclNodes.inc!");
Alexis Hunted053252010-05-30 07:21:58 +0000106#define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
107#define ABSTRACT_DECL(DECL)
108#include "clang/AST/DeclNodes.inc"
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000109 }
110}
111
Douglas Gregor90d47172010-03-05 00:26:45 +0000112void Decl::setInvalidDecl(bool Invalid) {
113 InvalidDecl = Invalid;
Alp Tokera5d64592013-12-21 01:10:54 +0000114 assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
Richard Trieucbd54302016-11-11 20:51:04 +0000115 if (!Invalid) {
116 return;
117 }
118
119 if (!isa<ParmVarDecl>(this)) {
Douglas Gregor90d47172010-03-05 00:26:45 +0000120 // Defensive maneuver for ill-formed code: we're likely not to make it to
121 // a point where we set the access specifier, so default it to "public"
122 // to avoid triggering asserts elsewhere in the front end.
123 setAccess(AS_public);
124 }
Richard Trieucbd54302016-11-11 20:51:04 +0000125
126 // Marking a DecompositionDecl as invalid implies all the child BindingDecl's
127 // are invalid too.
128 if (DecompositionDecl *DD = dyn_cast<DecompositionDecl>(this)) {
129 for (BindingDecl *Binding : DD->bindings()) {
130 Binding->setInvalidDecl();
131 }
132 }
Douglas Gregor90d47172010-03-05 00:26:45 +0000133}
134
Steve Naroff5faaef72009-01-20 19:53:53 +0000135const char *DeclContext::getDeclKindName() const {
136 switch (DeclKind) {
David Blaikie83d382b2011-09-23 05:06:16 +0000137 default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
Alexis Hunted053252010-05-30 07:21:58 +0000138#define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
139#define ABSTRACT_DECL(DECL)
140#include "clang/AST/DeclNodes.inc"
Steve Naroff5faaef72009-01-20 19:53:53 +0000141 }
142}
143
Daniel Dunbar62905572012-03-05 21:42:49 +0000144bool Decl::StatisticsEnabled = false;
145void Decl::EnableStatistics() {
146 StatisticsEnabled = true;
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000147}
148
149void Decl::PrintStats() {
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000150 llvm::errs() << "\n*** Decl Stats:\n";
Mike Stump11289f42009-09-09 15:08:12 +0000151
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000152 int totalDecls = 0;
Alexis Hunted053252010-05-30 07:21:58 +0000153#define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
154#define ABSTRACT_DECL(DECL)
155#include "clang/AST/DeclNodes.inc"
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000156 llvm::errs() << " " << totalDecls << " decls total.\n";
Mike Stump11289f42009-09-09 15:08:12 +0000157
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000158 int totalBytes = 0;
Alexis Hunted053252010-05-30 07:21:58 +0000159#define DECL(DERIVED, BASE) \
160 if (n##DERIVED##s > 0) { \
161 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000162 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
163 << sizeof(DERIVED##Decl) << " each (" \
164 << n##DERIVED##s * sizeof(DERIVED##Decl) \
165 << " bytes)\n"; \
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000166 }
Alexis Hunted053252010-05-30 07:21:58 +0000167#define ABSTRACT_DECL(DECL)
168#include "clang/AST/DeclNodes.inc"
Mike Stump11289f42009-09-09 15:08:12 +0000169
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000170 llvm::errs() << "Total bytes = " << totalBytes << "\n";
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000171}
172
Alexis Hunted053252010-05-30 07:21:58 +0000173void Decl::add(Kind k) {
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000174 switch (k) {
Alexis Hunted053252010-05-30 07:21:58 +0000175#define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
176#define ABSTRACT_DECL(DECL)
177#include "clang/AST/DeclNodes.inc"
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000178 }
179}
180
Anders Carlssonaa73b912009-06-13 00:08:58 +0000181bool Decl::isTemplateParameterPack() const {
182 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
183 return TTP->isParameterPack();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000184 if (const NonTypeTemplateParmDecl *NTTP
Douglas Gregorf5500772011-01-05 15:48:55 +0000185 = dyn_cast<NonTypeTemplateParmDecl>(this))
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000186 return NTTP->isParameterPack();
Douglas Gregorf5500772011-01-05 15:48:55 +0000187 if (const TemplateTemplateParmDecl *TTP
188 = dyn_cast<TemplateTemplateParmDecl>(this))
189 return TTP->isParameterPack();
Anders Carlssonaa73b912009-06-13 00:08:58 +0000190 return false;
191}
192
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +0000193bool Decl::isParameterPack() const {
194 if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
195 return Parm->isParameterPack();
196
197 return isTemplateParameterPack();
198}
199
Alp Tokera2794f92014-01-22 07:29:52 +0000200FunctionDecl *Decl::getAsFunction() {
201 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
202 return FD;
203 if (const FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(this))
204 return FTD->getTemplatedDecl();
Craig Topper36250ad2014-05-12 05:36:57 +0000205 return nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000206}
207
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000208bool Decl::isTemplateDecl() const {
209 return isa<TemplateDecl>(this);
210}
211
Serge Pavlov7dcc97e2016-04-19 06:19:52 +0000212TemplateDecl *Decl::getDescribedTemplate() const {
213 if (auto *FD = dyn_cast<FunctionDecl>(this))
214 return FD->getDescribedFunctionTemplate();
215 else if (auto *RD = dyn_cast<CXXRecordDecl>(this))
216 return RD->getDescribedClassTemplate();
217 else if (auto *VD = dyn_cast<VarDecl>(this))
218 return VD->getDescribedVarTemplate();
219
220 return nullptr;
221}
222
Argyrios Kyrtzidis0ce4c9a2011-09-28 02:45:33 +0000223const DeclContext *Decl::getParentFunctionOrMethod() const {
224 for (const DeclContext *DC = getDeclContext();
225 DC && !DC->isTranslationUnit() && !DC->isNamespace();
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000226 DC = DC->getParent())
227 if (DC->isFunctionOrMethod())
Argyrios Kyrtzidis0ce4c9a2011-09-28 02:45:33 +0000228 return DC;
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000229
Craig Topper36250ad2014-05-12 05:36:57 +0000230 return nullptr;
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000231}
232
Douglas Gregor133eddd2011-02-17 08:47:29 +0000233
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000234//===----------------------------------------------------------------------===//
Chris Lattnereae6cb62009-03-05 08:00:35 +0000235// PrettyStackTraceDecl Implementation
236//===----------------------------------------------------------------------===//
Mike Stump11289f42009-09-09 15:08:12 +0000237
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000238void PrettyStackTraceDecl::print(raw_ostream &OS) const {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000239 SourceLocation TheLoc = Loc;
240 if (TheLoc.isInvalid() && TheDecl)
241 TheLoc = TheDecl->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000242
Chris Lattnereae6cb62009-03-05 08:00:35 +0000243 if (TheLoc.isValid()) {
244 TheLoc.print(OS, SM);
245 OS << ": ";
246 }
247
248 OS << Message;
249
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +0000250 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
251 OS << " '";
252 DN->printQualifiedName(OS);
253 OS << '\'';
254 }
Chris Lattnereae6cb62009-03-05 08:00:35 +0000255 OS << '\n';
256}
Mike Stump11289f42009-09-09 15:08:12 +0000257
Chris Lattnereae6cb62009-03-05 08:00:35 +0000258//===----------------------------------------------------------------------===//
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000259// Decl Implementation
260//===----------------------------------------------------------------------===//
261
Douglas Gregorb11aad82011-02-19 18:51:44 +0000262// Out-of-line virtual method providing a home for Decl.
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000263Decl::~Decl() { }
Douglas Gregora43942a2011-02-17 07:02:32 +0000264
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000265void Decl::setDeclContext(DeclContext *DC) {
Chris Lattnerb81eb052009-03-29 06:06:59 +0000266 DeclCtx = DC;
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000267}
268
269void Decl::setLexicalDeclContext(DeclContext *DC) {
270 if (DC == getLexicalDeclContext())
271 return;
272
273 if (isInSemaDC()) {
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000274 setDeclContextsImpl(getDeclContext(), DC, getASTContext());
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000275 } else {
276 getMultipleDC()->LexicalDC = DC;
277 }
Richard Smithae50c562017-05-23 22:02:49 +0000278
279 // FIXME: We shouldn't be changing the lexical context of declarations
280 // imported from AST files.
281 if (!isFromASTFile()) {
Richard Smith90dc5252017-06-23 01:04:34 +0000282 setModuleOwnershipKind(getModuleOwnershipKindForChildOf(DC));
283 if (hasOwningModule())
Richard Smithae50c562017-05-23 22:02:49 +0000284 setLocalOwningModule(cast<Decl>(DC)->getOwningModule());
285 }
286
Richard Smithd19389a2017-07-05 07:47:11 +0000287 assert(
288 (getModuleOwnershipKind() != ModuleOwnershipKind::VisibleWhenImported ||
289 getOwningModule()) &&
290 "hidden declaration has no owning module");
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000291}
292
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000293void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
294 ASTContext &Ctx) {
295 if (SemaDC == LexicalDC) {
296 DeclCtx = SemaDC;
297 } else {
298 Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
299 MDC->SemanticDC = SemaDC;
300 MDC->LexicalDC = LexicalDC;
301 DeclCtx = MDC;
302 }
303}
304
Serge Pavlov73c6a242015-08-23 10:22:28 +0000305bool Decl::isLexicallyWithinFunctionOrMethod() const {
306 const DeclContext *LDC = getLexicalDeclContext();
Serge Pavlovb24a7112015-08-23 11:09:40 +0000307 while (true) {
Serge Pavlov73c6a242015-08-23 10:22:28 +0000308 if (LDC->isFunctionOrMethod())
309 return true;
310 if (!isa<TagDecl>(LDC))
311 return false;
Serge Pavlovb24a7112015-08-23 11:09:40 +0000312 LDC = LDC->getLexicalParent();
313 }
Serge Pavlov73c6a242015-08-23 10:22:28 +0000314 return false;
315}
316
John McCall4fa53422009-10-01 00:25:31 +0000317bool Decl::isInAnonymousNamespace() const {
Eric Liuf01516d2017-10-10 13:09:40 +0000318 const DeclContext *DC = getDeclContext();
319 do {
John McCall4fa53422009-10-01 00:25:31 +0000320 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
321 if (ND->isAnonymousNamespace())
322 return true;
Eric Liuf01516d2017-10-10 13:09:40 +0000323 } while ((DC = DC->getParent()));
John McCall4fa53422009-10-01 00:25:31 +0000324
325 return false;
326}
327
Richard Trieuc771d5d2014-05-28 02:16:01 +0000328bool Decl::isInStdNamespace() const {
329 return getDeclContext()->isStdNamespace();
330}
331
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000332TranslationUnitDecl *Decl::getTranslationUnitDecl() {
Argyrios Kyrtzidis4e1a72b2009-06-30 02:34:53 +0000333 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
334 return TUD;
335
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000336 DeclContext *DC = getDeclContext();
337 assert(DC && "This decl is not contained in a translation unit!");
Mike Stump11289f42009-09-09 15:08:12 +0000338
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000339 while (!DC->isTranslationUnit()) {
340 DC = DC->getParent();
341 assert(DC && "This decl is not contained in a translation unit!");
342 }
Mike Stump11289f42009-09-09 15:08:12 +0000343
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000344 return cast<TranslationUnitDecl>(DC);
345}
346
347ASTContext &Decl::getASTContext() const {
Mike Stump11289f42009-09-09 15:08:12 +0000348 return getTranslationUnitDecl()->getASTContext();
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000349}
350
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +0000351ASTMutationListener *Decl::getASTMutationListener() const {
352 return getASTContext().getASTMutationListener();
353}
354
Benjamin Kramerea70eb32012-12-01 15:09:41 +0000355unsigned Decl::getMaxAlignment() const {
356 if (!hasAttrs())
357 return 0;
358
359 unsigned Align = 0;
360 const AttrVec &V = getAttrs();
361 ASTContext &Ctx = getASTContext();
362 specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
363 for (; I != E; ++I)
364 Align = std::max(Align, I->getAlignment(Ctx));
365 return Align;
366}
367
Vassil Vassilev928c8252016-04-28 14:13:28 +0000368bool Decl::isUsed(bool CheckUsedAttr) const {
369 const Decl *CanonD = getCanonicalDecl();
370 if (CanonD->Used)
Vassil Vassileva4d7d782016-04-27 10:46:06 +0000371 return true;
372
Vassil Vassilev928c8252016-04-28 14:13:28 +0000373 // Check for used attribute.
374 // Ask the most recent decl, since attributes accumulate in the redecl chain.
375 if (CheckUsedAttr && getMostRecentDecl()->hasAttr<UsedAttr>())
376 return true;
377
378 // The information may have not been deserialized yet. Force deserialization
379 // to complete the needed information.
380 return getMostRecentDecl()->getCanonicalDecl()->Used;
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000381}
382
Eli Friedman276dd182013-09-05 00:02:25 +0000383void Decl::markUsed(ASTContext &C) {
Vassil Vassilev928c8252016-04-28 14:13:28 +0000384 if (isUsed(false))
Eli Friedman276dd182013-09-05 00:02:25 +0000385 return;
386
387 if (C.getASTMutationListener())
388 C.getASTMutationListener()->DeclarationMarkedUsed(this);
389
Vassil Vassilev928c8252016-04-28 14:13:28 +0000390 setIsUsed();
Eli Friedman276dd182013-09-05 00:02:25 +0000391}
392
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +0000393bool Decl::isReferenced() const {
394 if (Referenced)
395 return true;
396
397 // Check redeclarations.
Aaron Ballman86c93902014-03-06 23:45:36 +0000398 for (auto I : redecls())
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +0000399 if (I->Referenced)
400 return true;
401
402 return false;
403}
404
Richard Smith3b660562016-09-26 21:27:23 +0000405bool Decl::isExported() const {
406 if (isModulePrivate())
407 return false;
408 // Namespaces are always exported.
409 if (isa<TranslationUnitDecl>(this) || isa<NamespaceDecl>(this))
410 return true;
411 // Otherwise, this is a strictly lexical check.
412 for (auto *DC = getLexicalDeclContext(); DC; DC = DC->getLexicalParent()) {
413 if (cast<Decl>(DC)->isModulePrivate())
414 return false;
415 if (isa<ExportDecl>(DC))
416 return true;
417 }
418 return false;
419}
420
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +0000421ExternalSourceSymbolAttr *Decl::getExternalSourceSymbolAttr() const {
422 const Decl *Definition = nullptr;
423 if (auto ID = dyn_cast<ObjCInterfaceDecl>(this)) {
424 Definition = ID->getDefinition();
425 } else if (auto PD = dyn_cast<ObjCProtocolDecl>(this)) {
426 Definition = PD->getDefinition();
427 } else if (auto TD = dyn_cast<TagDecl>(this)) {
428 Definition = TD->getDefinition();
429 }
430 if (!Definition)
431 Definition = this;
432
433 if (auto *attr = Definition->getAttr<ExternalSourceSymbolAttr>())
434 return attr;
435 if (auto *dcd = dyn_cast<Decl>(getDeclContext())) {
436 return dcd->getAttr<ExternalSourceSymbolAttr>();
437 }
438
439 return nullptr;
440}
441
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000442bool Decl::hasDefiningAttr() const {
443 return hasAttr<AliasAttr>() || hasAttr<IFuncAttr>();
444}
445
446const Attr *Decl::getDefiningAttr() const {
447 if (AliasAttr *AA = getAttr<AliasAttr>())
448 return AA;
449 if (IFuncAttr *IFA = getAttr<IFuncAttr>())
450 return IFA;
451 return nullptr;
452}
453
Benjamin Kramer674d5792017-05-26 20:08:24 +0000454static StringRef getRealizedPlatform(const AvailabilityAttr *A,
455 const ASTContext &Context) {
Alex Lorenza8a372d2017-04-27 10:43:48 +0000456 // Check if this is an App Extension "platform", and if so chop off
457 // the suffix for matching with the actual platform.
458 StringRef RealizedPlatform = A->getPlatform()->getName();
459 if (!Context.getLangOpts().AppExt)
460 return RealizedPlatform;
461 size_t suffix = RealizedPlatform.rfind("_app_extension");
462 if (suffix != StringRef::npos)
463 return RealizedPlatform.slice(0, suffix);
464 return RealizedPlatform;
465}
466
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000467/// \brief Determine the availability of the given declaration based on
468/// the target platform.
469///
470/// When it returns an availability result other than \c AR_Available,
471/// if the \p Message parameter is non-NULL, it will be set to a
472/// string describing why the entity is unavailable.
473///
474/// FIXME: Make these strings localizable, since they end up in
475/// diagnostics.
476static AvailabilityResult CheckAvailability(ASTContext &Context,
477 const AvailabilityAttr *A,
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000478 std::string *Message,
479 VersionTuple EnclosingVersion) {
480 if (EnclosingVersion.empty())
481 EnclosingVersion = Context.getTargetInfo().getPlatformMinVersion();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000482
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000483 if (EnclosingVersion.empty())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000484 return AR_Available;
485
Bob Wilsonb111ec92015-03-02 19:01:14 +0000486 StringRef ActualPlatform = A->getPlatform()->getName();
Bob Wilsonb111ec92015-03-02 19:01:14 +0000487 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
488
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000489 // Match the platform name.
Alex Lorenza8a372d2017-04-27 10:43:48 +0000490 if (getRealizedPlatform(A, Context) != TargetPlatform)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000491 return AR_Available;
Bob Wilsonb111ec92015-03-02 19:01:14 +0000492
493 StringRef PrettyPlatformName
494 = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
495
496 if (PrettyPlatformName.empty())
497 PrettyPlatformName = ActualPlatform;
498
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000499 std::string HintMessage;
500 if (!A->getMessage().empty()) {
501 HintMessage = " - ";
502 HintMessage += A->getMessage();
503 }
504
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000505 // Make sure that this declaration has not been marked 'unavailable'.
506 if (A->getUnavailable()) {
507 if (Message) {
508 Message->clear();
509 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000510 Out << "not available on " << PrettyPlatformName
511 << HintMessage;
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000512 }
513
514 return AR_Unavailable;
515 }
516
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000517 // Make sure that this declaration has already been introduced.
518 if (!A->getIntroduced().empty() &&
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000519 EnclosingVersion < A->getIntroduced()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000520 if (Message) {
521 Message->clear();
522 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000523 VersionTuple VTI(A->getIntroduced());
524 VTI.UseDotAsSeparator();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000525 Out << "introduced in " << PrettyPlatformName << ' '
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000526 << VTI << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000527 }
528
Duncan P. N. Exon Smith5d6790c2016-03-08 06:12:54 +0000529 return A->getStrict() ? AR_Unavailable : AR_NotYetIntroduced;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000530 }
531
532 // Make sure that this declaration hasn't been obsoleted.
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000533 if (!A->getObsoleted().empty() && EnclosingVersion >= A->getObsoleted()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000534 if (Message) {
535 Message->clear();
536 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000537 VersionTuple VTO(A->getObsoleted());
538 VTO.UseDotAsSeparator();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000539 Out << "obsoleted in " << PrettyPlatformName << ' '
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000540 << VTO << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000541 }
542
543 return AR_Unavailable;
544 }
545
546 // Make sure that this declaration hasn't been deprecated.
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000547 if (!A->getDeprecated().empty() && EnclosingVersion >= A->getDeprecated()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000548 if (Message) {
549 Message->clear();
550 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000551 VersionTuple VTD(A->getDeprecated());
552 VTD.UseDotAsSeparator();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000553 Out << "first deprecated in " << PrettyPlatformName << ' '
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000554 << VTD << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000555 }
556
557 return AR_Deprecated;
558 }
559
560 return AR_Available;
561}
562
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000563AvailabilityResult Decl::getAvailability(std::string *Message,
564 VersionTuple EnclosingVersion) const {
Duncan P. N. Exon Smithec599a92016-02-26 19:27:00 +0000565 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000566 return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion);
Duncan P. N. Exon Smithec599a92016-02-26 19:27:00 +0000567
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000568 AvailabilityResult Result = AR_Available;
569 std::string ResultMessage;
570
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000571 for (const auto *A : attrs()) {
572 if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000573 if (Result >= AR_Deprecated)
574 continue;
575
576 if (Message)
577 ResultMessage = Deprecated->getMessage();
578
579 Result = AR_Deprecated;
580 continue;
581 }
582
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000583 if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000584 if (Message)
585 *Message = Unavailable->getMessage();
586 return AR_Unavailable;
587 }
588
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000589 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000590 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000591 Message, EnclosingVersion);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000592
593 if (AR == AR_Unavailable)
594 return AR_Unavailable;
595
596 if (AR > Result) {
597 Result = AR;
598 if (Message)
599 ResultMessage.swap(*Message);
600 }
601 continue;
602 }
603 }
604
605 if (Message)
606 Message->swap(ResultMessage);
607 return Result;
608}
609
Alex Lorenza8a372d2017-04-27 10:43:48 +0000610VersionTuple Decl::getVersionIntroduced() const {
611 const ASTContext &Context = getASTContext();
612 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
613 for (const auto *A : attrs()) {
614 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
615 if (getRealizedPlatform(Availability, Context) != TargetPlatform)
616 continue;
617 if (!Availability->getIntroduced().empty())
618 return Availability->getIntroduced();
619 }
620 }
621 return VersionTuple();
622}
623
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000624bool Decl::canBeWeakImported(bool &IsDefinition) const {
625 IsDefinition = false;
John McCall5fb5df92012-06-20 06:18:46 +0000626
627 // Variables, if they aren't definitions.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000628 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000629 if (Var->isThisDeclarationADefinition()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000630 IsDefinition = true;
631 return false;
632 }
John McCall5fb5df92012-06-20 06:18:46 +0000633 return true;
634
635 // Functions, if they aren't definitions.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000636 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
637 if (FD->hasBody()) {
638 IsDefinition = true;
639 return false;
640 }
John McCall5fb5df92012-06-20 06:18:46 +0000641 return true;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000642
John McCall5fb5df92012-06-20 06:18:46 +0000643 // Objective-C classes, if this is the non-fragile runtime.
644 } else if (isa<ObjCInterfaceDecl>(this) &&
John McCall18ac1632012-06-20 21:58:02 +0000645 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
John McCall5fb5df92012-06-20 06:18:46 +0000646 return true;
647
648 // Nothing else.
649 } else {
650 return false;
651 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000652}
653
654bool Decl::isWeakImported() const {
655 bool IsDefinition;
656 if (!canBeWeakImported(IsDefinition))
657 return false;
658
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000659 for (const auto *A : attrs()) {
660 if (isa<WeakImportAttr>(A))
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000661 return true;
662
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000663 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000664 if (CheckAvailability(getASTContext(), Availability, nullptr,
665 VersionTuple()) == AR_NotYetIntroduced)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000666 return true;
667 }
668 }
669
670 return false;
671}
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000672
Chris Lattner8e097192009-03-27 20:18:19 +0000673unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
674 switch (DeclKind) {
John McCall3f746822009-11-17 05:59:44 +0000675 case Function:
Richard Smithbc491202017-02-17 20:05:37 +0000676 case CXXDeductionGuide:
John McCall3f746822009-11-17 05:59:44 +0000677 case CXXMethod:
678 case CXXConstructor:
Richard Smith5179eb72016-06-28 19:03:57 +0000679 case ConstructorUsingShadow:
John McCall3f746822009-11-17 05:59:44 +0000680 case CXXDestructor:
681 case CXXConversion:
Chris Lattner8e097192009-03-27 20:18:19 +0000682 case EnumConstant:
683 case Var:
684 case ImplicitParam:
685 case ParmVar:
Chris Lattner8e097192009-03-27 20:18:19 +0000686 case ObjCMethod:
Daniel Dunbar45b2d8a2010-04-23 13:07:39 +0000687 case ObjCProperty:
John McCall5e77d762013-04-16 07:28:30 +0000688 case MSProperty:
Daniel Dunbar45b2d8a2010-04-23 13:07:39 +0000689 return IDNS_Ordinary;
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000690 case Label:
691 return IDNS_Label;
Francois Pichet783dd6e2010-11-21 06:08:52 +0000692 case IndirectField:
693 return IDNS_Ordinary | IDNS_Member;
694
Richard Smithb8c41902017-09-07 20:22:00 +0000695 case Binding:
Richard Smith9f951822016-01-06 22:49:11 +0000696 case NonTypeTemplateParm:
Richard Smithb8c41902017-09-07 20:22:00 +0000697 case VarTemplate:
698 // These (C++-only) declarations are found by redeclaration lookup for
699 // tag types, so we include them in the tag namespace.
Richard Smith9f951822016-01-06 22:49:11 +0000700 return IDNS_Ordinary | IDNS_Tag;
701
John McCalle87beb22010-04-23 18:46:30 +0000702 case ObjCCompatibleAlias:
703 case ObjCInterface:
704 return IDNS_Ordinary | IDNS_Type;
705
706 case Typedef:
Richard Smithdda56e42011-04-15 14:24:37 +0000707 case TypeAlias:
John McCalle87beb22010-04-23 18:46:30 +0000708 case TemplateTypeParm:
Douglas Gregor85f3f952015-07-07 03:57:15 +0000709 case ObjCTypeParam:
John McCalle87beb22010-04-23 18:46:30 +0000710 return IDNS_Ordinary | IDNS_Type;
711
Richard Smith151c4562016-12-20 21:35:28 +0000712 case UnresolvedUsingTypename:
713 return IDNS_Ordinary | IDNS_Type | IDNS_Using;
714
John McCall3f746822009-11-17 05:59:44 +0000715 case UsingShadow:
716 return 0; // we'll actually overwrite this later
717
John McCalle61f2ba2009-11-18 02:36:19 +0000718 case UnresolvedUsingValue:
John McCalle61f2ba2009-11-18 02:36:19 +0000719 return IDNS_Ordinary | IDNS_Using;
John McCall3f746822009-11-17 05:59:44 +0000720
721 case Using:
Richard Smith151c4562016-12-20 21:35:28 +0000722 case UsingPack:
John McCall3f746822009-11-17 05:59:44 +0000723 return IDNS_Using;
724
Chris Lattner8e097192009-03-27 20:18:19 +0000725 case ObjCProtocol:
Douglas Gregor79947a22009-04-24 00:11:27 +0000726 return IDNS_ObjCProtocol;
Mike Stump11289f42009-09-09 15:08:12 +0000727
Chris Lattner8e097192009-03-27 20:18:19 +0000728 case Field:
729 case ObjCAtDefsField:
730 case ObjCIvar:
731 return IDNS_Member;
Mike Stump11289f42009-09-09 15:08:12 +0000732
Chris Lattner8e097192009-03-27 20:18:19 +0000733 case Record:
734 case CXXRecord:
735 case Enum:
John McCalle87beb22010-04-23 18:46:30 +0000736 return IDNS_Tag | IDNS_Type;
Mike Stump11289f42009-09-09 15:08:12 +0000737
Chris Lattner8e097192009-03-27 20:18:19 +0000738 case Namespace:
John McCalle87beb22010-04-23 18:46:30 +0000739 case NamespaceAlias:
740 return IDNS_Namespace;
741
Chris Lattner8e097192009-03-27 20:18:19 +0000742 case FunctionTemplate:
John McCalle87beb22010-04-23 18:46:30 +0000743 return IDNS_Ordinary;
744
Chris Lattner8e097192009-03-27 20:18:19 +0000745 case ClassTemplate:
746 case TemplateTemplateParm:
Richard Smithb8c41902017-09-07 20:22:00 +0000747 case TypeAliasTemplate:
John McCalle87beb22010-04-23 18:46:30 +0000748 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
Mike Stump11289f42009-09-09 15:08:12 +0000749
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000750 case OMPDeclareReduction:
751 return IDNS_OMPReduction;
752
Chris Lattner8e097192009-03-27 20:18:19 +0000753 // Never have names.
John McCallaa74a0c2009-08-28 07:59:38 +0000754 case Friend:
John McCall11083da2009-09-16 22:47:08 +0000755 case FriendTemplate:
Abramo Bagnarad7340582010-06-05 05:09:32 +0000756 case AccessSpec:
Chris Lattner8e097192009-03-27 20:18:19 +0000757 case LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +0000758 case Export:
Chris Lattner8e097192009-03-27 20:18:19 +0000759 case FileScopeAsm:
760 case StaticAssert:
Chris Lattner8e097192009-03-27 20:18:19 +0000761 case ObjCPropertyImpl:
Nico Weber66220292016-03-02 17:28:48 +0000762 case PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +0000763 case PragmaDetectMismatch:
Chris Lattner8e097192009-03-27 20:18:19 +0000764 case Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +0000765 case Captured:
Chris Lattner8e097192009-03-27 20:18:19 +0000766 case TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +0000767 case ExternCContext:
Richard Smithbdb84f32016-07-22 23:36:59 +0000768 case Decomposition:
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000769
Chris Lattner8e097192009-03-27 20:18:19 +0000770 case UsingDirective:
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000771 case BuiltinTemplate:
Chris Lattner8e097192009-03-27 20:18:19 +0000772 case ClassTemplateSpecialization:
Douglas Gregor2373c592009-05-31 09:31:02 +0000773 case ClassTemplatePartialSpecialization:
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000774 case ClassScopeFunctionSpecialization:
Larisse Voufo39a1e502013-08-06 01:03:05 +0000775 case VarTemplateSpecialization:
776 case VarTemplatePartialSpecialization:
Douglas Gregore93525e2010-04-22 23:19:50 +0000777 case ObjCImplementation:
778 case ObjCCategory:
779 case ObjCCategoryImpl:
Douglas Gregorba345522011-12-02 23:23:56 +0000780 case Import:
Alexey Bataeva769e072013-03-22 06:34:35 +0000781 case OMPThreadPrivate:
Alexey Bataev4244be22016-02-11 05:35:55 +0000782 case OMPCapturedExpr:
Michael Han84324352013-02-22 17:15:32 +0000783 case Empty:
Douglas Gregore93525e2010-04-22 23:19:50 +0000784 // Never looked up by name.
Chris Lattner8e097192009-03-27 20:18:19 +0000785 return 0;
786 }
John McCall3f746822009-11-17 05:59:44 +0000787
David Blaikiee4d798f2012-01-20 21:50:17 +0000788 llvm_unreachable("Invalid DeclKind!");
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000789}
790
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000791void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
Argyrios Kyrtzidis91167172010-06-11 23:09:25 +0000792 assert(!HasAttrs && "Decl already contains attrs.");
793
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000794 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000795 assert(AttrBlank.empty() && "HasAttrs was wrong?");
Argyrios Kyrtzidis91167172010-06-11 23:09:25 +0000796
797 AttrBlank = attrs;
798 HasAttrs = true;
799}
800
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000801void Decl::dropAttrs() {
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000802 if (!HasAttrs) return;
Mike Stump11289f42009-09-09 15:08:12 +0000803
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000804 HasAttrs = false;
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000805 getASTContext().eraseDeclAttrs(this);
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000806}
807
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000808const AttrVec &Decl::getAttrs() const {
809 assert(HasAttrs && "No attrs to get!");
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000810 return getASTContext().getDeclAttrs(this);
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000811}
812
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000813Decl *Decl::castFromDeclContext (const DeclContext *D) {
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000814 Decl::Kind DK = D->getDeclKind();
815 switch(DK) {
Alexis Hunted053252010-05-30 07:21:58 +0000816#define DECL(NAME, BASE)
817#define DECL_CONTEXT(NAME) \
818 case Decl::NAME: \
819 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
820#define DECL_CONTEXT_BASE(NAME)
821#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000822 default:
Alexis Hunted053252010-05-30 07:21:58 +0000823#define DECL(NAME, BASE)
824#define DECL_CONTEXT_BASE(NAME) \
825 if (DK >= first##NAME && DK <= last##NAME) \
826 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
827#include "clang/AST/DeclNodes.inc"
David Blaikie83d382b2011-09-23 05:06:16 +0000828 llvm_unreachable("a decl that inherits DeclContext isn't handled");
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000829 }
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000830}
831
832DeclContext *Decl::castToDeclContext(const Decl *D) {
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000833 Decl::Kind DK = D->getKind();
834 switch(DK) {
Alexis Hunted053252010-05-30 07:21:58 +0000835#define DECL(NAME, BASE)
836#define DECL_CONTEXT(NAME) \
837 case Decl::NAME: \
838 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
839#define DECL_CONTEXT_BASE(NAME)
840#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000841 default:
Alexis Hunted053252010-05-30 07:21:58 +0000842#define DECL(NAME, BASE)
843#define DECL_CONTEXT_BASE(NAME) \
844 if (DK >= first##NAME && DK <= last##NAME) \
845 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
846#include "clang/AST/DeclNodes.inc"
David Blaikie83d382b2011-09-23 05:06:16 +0000847 llvm_unreachable("a decl that inherits DeclContext isn't handled");
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000848 }
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000849}
850
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000851SourceLocation Decl::getBodyRBrace() const {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +0000852 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
853 // FunctionDecl stores EndRangeLoc for this purpose.
854 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
855 const FunctionDecl *Definition;
856 if (FD->hasBody(Definition))
857 return Definition->getSourceRange().getEnd();
858 return SourceLocation();
859 }
860
Argyrios Kyrtzidis6fbc8fa2010-07-07 11:31:27 +0000861 if (Stmt *Body = getBody())
862 return Body->getSourceRange().getEnd();
863
864 return SourceLocation();
Sebastian Redla7b98a72009-04-26 20:35:05 +0000865}
866
Alp Tokerc1086762013-12-07 13:51:35 +0000867bool Decl::AccessDeclContextSanity() const {
Douglas Gregor4b00d3b2010-12-02 00:22:25 +0000868#ifndef NDEBUG
John McCall401982f2010-01-20 21:53:11 +0000869 // Suppress this check if any of the following hold:
870 // 1. this is the translation unit (and thus has no parent)
871 // 2. this is a template parameter (and thus doesn't belong to its context)
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000872 // 3. this is a non-type template parameter
873 // 4. the context is not a record
874 // 5. it's invalid
875 // 6. it's a C++0x static_assert.
Anders Carlssonadf36b22009-08-29 20:47:47 +0000876 if (isa<TranslationUnitDecl>(this) ||
Argyrios Kyrtzidisa45855f2010-07-02 11:55:44 +0000877 isa<TemplateTypeParmDecl>(this) ||
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000878 isa<NonTypeTemplateParmDecl>(this) ||
Douglas Gregor2b76dd92010-02-22 17:53:38 +0000879 !isa<CXXRecordDecl>(getDeclContext()) ||
Argyrios Kyrtzidis260b4a82010-09-08 21:32:35 +0000880 isInvalidDecl() ||
881 isa<StaticAssertDecl>(this) ||
882 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
883 // as DeclContext (?).
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000884 isa<ParmVarDecl>(this) ||
885 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
886 // AS_none as access specifier.
Francois Pichet09af8c32011-08-17 01:06:54 +0000887 isa<CXXRecordDecl>(this) ||
888 isa<ClassScopeFunctionSpecializationDecl>(this))
Alp Tokerc1086762013-12-07 13:51:35 +0000889 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000890
891 assert(Access != AS_none &&
Anders Carlssona28908d2009-03-25 23:38:06 +0000892 "Access specifier is AS_none inside a record decl");
Douglas Gregor4b00d3b2010-12-02 00:22:25 +0000893#endif
Alp Tokerc1086762013-12-07 13:51:35 +0000894 return true;
Anders Carlssona28908d2009-03-25 23:38:06 +0000895}
896
John McCalldec348f72013-05-03 07:33:41 +0000897static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
898static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
899
Aaron Ballman12b9f652014-01-16 13:55:42 +0000900const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
901 QualType Ty;
902 if (const ValueDecl *D = dyn_cast<ValueDecl>(this))
903 Ty = D->getType();
904 else if (const TypedefNameDecl *D = dyn_cast<TypedefNameDecl>(this))
905 Ty = D->getUnderlyingType();
906 else
Craig Topper36250ad2014-05-12 05:36:57 +0000907 return nullptr;
Aaron Ballman12b9f652014-01-16 13:55:42 +0000908
909 if (Ty->isFunctionPointerType())
910 Ty = Ty->getAs<PointerType>()->getPointeeType();
911 else if (BlocksToo && Ty->isBlockPointerType())
912 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
913
914 return Ty->getAs<FunctionType>();
915}
916
917
John McCalldec348f72013-05-03 07:33:41 +0000918/// Starting at a given context (a Decl or DeclContext), look for a
919/// code context that is not a closure (a lambda, block, etc.).
920template <class T> static Decl *getNonClosureContext(T *D) {
921 if (getKind(D) == Decl::CXXMethod) {
922 CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
John McCall55c0cee2013-05-03 17:11:14 +0000923 if (MD->getOverloadedOperator() == OO_Call &&
924 MD->getParent()->isLambda())
John McCalldec348f72013-05-03 07:33:41 +0000925 return getNonClosureContext(MD->getParent()->getParent());
926 return MD;
927 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
928 return FD;
929 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
930 return MD;
931 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
932 return getNonClosureContext(BD->getParent());
933 } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
934 return getNonClosureContext(CD->getParent());
935 } else {
Craig Topper36250ad2014-05-12 05:36:57 +0000936 return nullptr;
John McCalldec348f72013-05-03 07:33:41 +0000937 }
John McCallfe96e0b2011-11-06 09:01:30 +0000938}
939
John McCalldec348f72013-05-03 07:33:41 +0000940Decl *Decl::getNonClosureContext() {
941 return ::getNonClosureContext(this);
942}
John McCallb67608f2011-02-22 22:25:23 +0000943
John McCalldec348f72013-05-03 07:33:41 +0000944Decl *DeclContext::getNonClosureAncestor() {
945 return ::getNonClosureContext(this);
John McCallb67608f2011-02-22 22:25:23 +0000946}
Anders Carlssona28908d2009-03-25 23:38:06 +0000947
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000948//===----------------------------------------------------------------------===//
949// DeclContext Implementation
950//===----------------------------------------------------------------------===//
951
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000952bool DeclContext::classof(const Decl *D) {
953 switch (D->getKind()) {
Alexis Hunted053252010-05-30 07:21:58 +0000954#define DECL(NAME, BASE)
955#define DECL_CONTEXT(NAME) case Decl::NAME:
956#define DECL_CONTEXT_BASE(NAME)
957#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000958 return true;
959 default:
Alexis Hunted053252010-05-30 07:21:58 +0000960#define DECL(NAME, BASE)
961#define DECL_CONTEXT_BASE(NAME) \
962 if (D->getKind() >= Decl::first##NAME && \
963 D->getKind() <= Decl::last##NAME) \
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000964 return true;
Alexis Hunted053252010-05-30 07:21:58 +0000965#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000966 return false;
967 }
968}
969
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000970DeclContext::~DeclContext() { }
Douglas Gregor91f84212008-12-11 16:49:14 +0000971
Douglas Gregor7f737c02009-09-10 16:57:35 +0000972/// \brief Find the parent context of this context that will be
973/// used for unqualified name lookup.
974///
975/// Generally, the parent lookup context is the semantic context. However, for
976/// a friend function the parent lookup context is the lexical context, which
977/// is the class in which the friend is declared.
978DeclContext *DeclContext::getLookupParent() {
979 // FIXME: Find a better way to identify friends
980 if (isa<FunctionDecl>(this))
Sebastian Redl50c68252010-08-31 00:36:30 +0000981 if (getParent()->getRedeclContext()->isFileContext() &&
982 getLexicalParent()->getRedeclContext()->isRecord())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000983 return getLexicalParent();
984
985 return getParent();
986}
987
Sebastian Redlbd595762010-08-31 20:53:31 +0000988bool DeclContext::isInlineNamespace() const {
989 return isNamespace() &&
990 cast<NamespaceDecl>(this)->isInline();
991}
992
Richard Trieuc771d5d2014-05-28 02:16:01 +0000993bool DeclContext::isStdNamespace() const {
994 if (!isNamespace())
995 return false;
996
997 const NamespaceDecl *ND = cast<NamespaceDecl>(this);
998 if (ND->isInline()) {
999 return ND->getParent()->isStdNamespace();
1000 }
1001
1002 if (!getParent()->getRedeclContext()->isTranslationUnit())
1003 return false;
1004
1005 const IdentifierInfo *II = ND->getIdentifier();
1006 return II && II->isStr("std");
1007}
1008
Douglas Gregor9e927ab2009-05-28 16:34:51 +00001009bool DeclContext::isDependentContext() const {
1010 if (isFileContext())
1011 return false;
1012
Douglas Gregor2373c592009-05-31 09:31:02 +00001013 if (isa<ClassTemplatePartialSpecializationDecl>(this))
1014 return true;
1015
Douglas Gregor680e9e02012-02-21 19:11:17 +00001016 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
Douglas Gregor9e927ab2009-05-28 16:34:51 +00001017 if (Record->getDescribedClassTemplate())
1018 return true;
Douglas Gregor680e9e02012-02-21 19:11:17 +00001019
1020 if (Record->isDependentLambda())
1021 return true;
1022 }
1023
John McCallc62bb642010-03-24 05:22:00 +00001024 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
Douglas Gregor9e927ab2009-05-28 16:34:51 +00001025 if (Function->getDescribedFunctionTemplate())
1026 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001027
John McCallc62bb642010-03-24 05:22:00 +00001028 // Friend function declarations are dependent if their *lexical*
1029 // context is dependent.
1030 if (cast<Decl>(this)->getFriendObjectKind())
1031 return getLexicalParent()->isDependentContext();
1032 }
1033
Richard Smith2b560572015-02-07 03:11:11 +00001034 // FIXME: A variable template is a dependent context, but is not a
1035 // DeclContext. A context within it (such as a lambda-expression)
1036 // should be considered dependent.
1037
Douglas Gregor9e927ab2009-05-28 16:34:51 +00001038 return getParent() && getParent()->isDependentContext();
1039}
1040
Douglas Gregor07665a62009-01-05 19:45:36 +00001041bool DeclContext::isTransparentContext() const {
1042 if (DeclKind == Decl::Enum)
Douglas Gregor0bf31402010-10-08 23:50:27 +00001043 return !cast<EnumDecl>(this)->isScoped();
Richard Smith8df390f2016-09-08 23:14:54 +00001044 else if (DeclKind == Decl::LinkageSpec || DeclKind == Decl::Export)
Douglas Gregor07665a62009-01-05 19:45:36 +00001045 return true;
Douglas Gregor07665a62009-01-05 19:45:36 +00001046
1047 return false;
1048}
1049
Serge Pavlov3cb80222013-11-14 02:13:03 +00001050static bool isLinkageSpecContext(const DeclContext *DC,
1051 LinkageSpecDecl::LanguageIDs ID) {
1052 while (DC->getDeclKind() != Decl::TranslationUnit) {
1053 if (DC->getDeclKind() == Decl::LinkageSpec)
1054 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
Richard Smithac9c9a02014-04-14 20:23:58 +00001055 DC = DC->getLexicalParent();
Serge Pavlov3cb80222013-11-14 02:13:03 +00001056 }
1057 return false;
1058}
1059
1060bool DeclContext::isExternCContext() const {
1061 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_c);
1062}
1063
Alex Lorenz560ae562016-11-02 15:46:34 +00001064const LinkageSpecDecl *DeclContext::getExternCContext() const {
1065 const DeclContext *DC = this;
1066 while (DC->getDeclKind() != Decl::TranslationUnit) {
1067 if (DC->getDeclKind() == Decl::LinkageSpec &&
1068 cast<LinkageSpecDecl>(DC)->getLanguage() ==
1069 clang::LinkageSpecDecl::lang_c)
1070 return cast<LinkageSpecDecl>(DC);
1071 DC = DC->getLexicalParent();
1072 }
1073 return nullptr;
1074}
1075
Serge Pavlov3cb80222013-11-14 02:13:03 +00001076bool DeclContext::isExternCXXContext() const {
1077 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_cxx);
1078}
1079
Sebastian Redl50c68252010-08-31 00:36:30 +00001080bool DeclContext::Encloses(const DeclContext *DC) const {
Douglas Gregore985a3b2009-08-27 06:03:53 +00001081 if (getPrimaryContext() != this)
1082 return getPrimaryContext()->Encloses(DC);
Mike Stump11289f42009-09-09 15:08:12 +00001083
Douglas Gregore985a3b2009-08-27 06:03:53 +00001084 for (; DC; DC = DC->getParent())
1085 if (DC->getPrimaryContext() == this)
1086 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001087 return false;
Douglas Gregore985a3b2009-08-27 06:03:53 +00001088}
1089
Steve Naroff35c62ae2009-01-08 17:28:14 +00001090DeclContext *DeclContext::getPrimaryContext() {
Douglas Gregor91f84212008-12-11 16:49:14 +00001091 switch (DeclKind) {
Douglas Gregor91f84212008-12-11 16:49:14 +00001092 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00001093 case Decl::ExternCContext:
Douglas Gregor07665a62009-01-05 19:45:36 +00001094 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00001095 case Decl::Export:
Mike Stump11289f42009-09-09 15:08:12 +00001096 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001097 case Decl::Captured:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001098 case Decl::OMPDeclareReduction:
Douglas Gregor91f84212008-12-11 16:49:14 +00001099 // There is only one DeclContext for these entities.
1100 return this;
1101
1102 case Decl::Namespace:
1103 // The original namespace is our primary context.
1104 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
1105
Douglas Gregor91f84212008-12-11 16:49:14 +00001106 case Decl::ObjCMethod:
1107 return this;
1108
1109 case Decl::ObjCInterface:
Douglas Gregor66b310c2011-12-15 18:03:09 +00001110 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
1111 return Def;
1112
1113 return this;
1114
Steve Naroff35c62ae2009-01-08 17:28:14 +00001115 case Decl::ObjCProtocol:
Douglas Gregora715bff2012-01-01 19:51:50 +00001116 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
1117 return Def;
1118
1119 return this;
Douglas Gregor66b310c2011-12-15 18:03:09 +00001120
Steve Naroff35c62ae2009-01-08 17:28:14 +00001121 case Decl::ObjCCategory:
Douglas Gregor91f84212008-12-11 16:49:14 +00001122 return this;
1123
Steve Naroff35c62ae2009-01-08 17:28:14 +00001124 case Decl::ObjCImplementation:
1125 case Decl::ObjCCategoryImpl:
1126 return this;
1127
Douglas Gregor91f84212008-12-11 16:49:14 +00001128 default:
Alexis Hunted053252010-05-30 07:21:58 +00001129 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
Douglas Gregor67a65642009-02-17 23:15:12 +00001130 // If this is a tag type that has a definition or is currently
1131 // being defined, that definition is our primary context.
John McCalle78aac42010-03-10 03:28:59 +00001132 TagDecl *Tag = cast<TagDecl>(this);
John McCalle78aac42010-03-10 03:28:59 +00001133
1134 if (TagDecl *Def = Tag->getDefinition())
1135 return Def;
1136
Richard Smith5b21db82014-04-23 18:20:42 +00001137 if (const TagType *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
1138 // Note, TagType::getDecl returns the (partial) definition one exists.
1139 TagDecl *PossiblePartialDef = TagTy->getDecl();
1140 if (PossiblePartialDef->isBeingDefined())
1141 return PossiblePartialDef;
1142 } else {
1143 assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
John McCalle78aac42010-03-10 03:28:59 +00001144 }
1145
1146 return Tag;
Douglas Gregor67a65642009-02-17 23:15:12 +00001147 }
1148
Alexis Hunted053252010-05-30 07:21:58 +00001149 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
Douglas Gregor91f84212008-12-11 16:49:14 +00001150 "Unknown DeclContext kind");
1151 return this;
1152 }
1153}
1154
Douglas Gregore57e7522012-01-07 09:11:48 +00001155void
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001156DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
Douglas Gregore57e7522012-01-07 09:11:48 +00001157 Contexts.clear();
1158
1159 if (DeclKind != Decl::Namespace) {
1160 Contexts.push_back(this);
1161 return;
Douglas Gregor91f84212008-12-11 16:49:14 +00001162 }
Douglas Gregore57e7522012-01-07 09:11:48 +00001163
1164 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
Douglas Gregorec9fd132012-01-14 16:38:05 +00001165 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
1166 N = N->getPreviousDecl())
Douglas Gregore57e7522012-01-07 09:11:48 +00001167 Contexts.push_back(N);
1168
1169 std::reverse(Contexts.begin(), Contexts.end());
Douglas Gregor91f84212008-12-11 16:49:14 +00001170}
1171
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001172std::pair<Decl *, Decl *>
Bill Wendling8eb771d2012-02-22 09:51:33 +00001173DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00001174 bool FieldsAlreadyLoaded) {
Douglas Gregor781f7132012-01-06 16:59:53 +00001175 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
Craig Topper36250ad2014-05-12 05:36:57 +00001176 Decl *FirstNewDecl = nullptr;
1177 Decl *PrevDecl = nullptr;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001178 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00001179 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
1180 continue;
1181
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001182 Decl *D = Decls[I];
1183 if (PrevDecl)
Douglas Gregor781f7132012-01-06 16:59:53 +00001184 PrevDecl->NextInContextAndBits.setPointer(D);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001185 else
1186 FirstNewDecl = D;
1187
1188 PrevDecl = D;
1189 }
1190
1191 return std::make_pair(FirstNewDecl, PrevDecl);
1192}
1193
Richard Smith645d7552013-02-07 03:37:08 +00001194/// \brief We have just acquired external visible storage, and we already have
1195/// built a lookup map. For every name in the map, pull in the new names from
1196/// the external storage.
Richard Smitha8b74592014-03-25 00:34:21 +00001197void DeclContext::reconcileExternalVisibleStorage() const {
Richard Smith9e2341d2015-03-23 03:25:59 +00001198 assert(NeedToReconcileExternalVisibleStorage && LookupPtr);
Richard Smith645d7552013-02-07 03:37:08 +00001199 NeedToReconcileExternalVisibleStorage = false;
1200
Richard Smith9e2341d2015-03-23 03:25:59 +00001201 for (auto &Lookup : *LookupPtr)
Richard Smitha8b74592014-03-25 00:34:21 +00001202 Lookup.second.setHasExternalDecls();
Richard Smith645d7552013-02-07 03:37:08 +00001203}
1204
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001205/// \brief Load the declarations within this lexical storage from an
1206/// external source.
Richard Smith18b380b2015-03-24 02:44:20 +00001207/// \return \c true if any declarations were added.
1208bool
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001209DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1210 ExternalASTSource *Source = getParentASTContext().getExternalSource();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001211 assert(hasExternalLexicalStorage() && Source && "No external storage?");
1212
Argyrios Kyrtzidis98d045e2010-07-30 10:03:23 +00001213 // Notify that we have a DeclContext that is initializing.
1214 ExternalASTSource::Deserializing ADeclContext(Source);
Richard Smith9e2341d2015-03-23 03:25:59 +00001215
Douglas Gregor3d0adb32011-07-15 21:46:17 +00001216 // Load the external declarations, if any.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001217 SmallVector<Decl*, 64> Decls;
Richard Smith18b380b2015-03-24 02:44:20 +00001218 ExternalLexicalStorage = false;
Richard Smith3cb15722015-08-05 22:41:45 +00001219 Source->FindExternalLexicalDecls(this, Decls);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001220
1221 if (Decls.empty())
Richard Smith18b380b2015-03-24 02:44:20 +00001222 return false;
Richard Smith9e2341d2015-03-23 03:25:59 +00001223
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00001224 // We may have already loaded just the fields of this record, in which case
1225 // we need to ignore them.
1226 bool FieldsAlreadyLoaded = false;
1227 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
1228 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
1229
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001230 // Splice the newly-read declarations into the beginning of the list
1231 // of declarations.
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001232 Decl *ExternalFirst, *ExternalLast;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001233 std::tie(ExternalFirst, ExternalLast) =
1234 BuildDeclChain(Decls, FieldsAlreadyLoaded);
Douglas Gregor781f7132012-01-06 16:59:53 +00001235 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001236 FirstDecl = ExternalFirst;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001237 if (!LastDecl)
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001238 LastDecl = ExternalLast;
Richard Smith18b380b2015-03-24 02:44:20 +00001239 return true;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001240}
1241
John McCall75b960e2010-06-01 09:23:16 +00001242DeclContext::lookup_result
1243ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1244 DeclarationName Name) {
1245 ASTContext &Context = DC->getParentASTContext();
1246 StoredDeclsMap *Map;
Richard Smith9e2341d2015-03-23 03:25:59 +00001247 if (!(Map = DC->LookupPtr))
John McCall75b960e2010-06-01 09:23:16 +00001248 Map = DC->CreateStoredDeclsMap(Context);
Richard Smitha8b74592014-03-25 00:34:21 +00001249 if (DC->NeedToReconcileExternalVisibleStorage)
1250 DC->reconcileExternalVisibleStorage();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001251
Richard Smith4abe0a82013-09-09 07:34:56 +00001252 (*Map)[Name].removeExternalDecls();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001253
John McCall75b960e2010-06-01 09:23:16 +00001254 return DeclContext::lookup_result();
1255}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001256
John McCall75b960e2010-06-01 09:23:16 +00001257DeclContext::lookup_result
1258ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
John McCall75b960e2010-06-01 09:23:16 +00001259 DeclarationName Name,
Argyrios Kyrtzidis94d3f9d2011-09-09 06:44:14 +00001260 ArrayRef<NamedDecl*> Decls) {
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00001261 ASTContext &Context = DC->getParentASTContext();
John McCall75b960e2010-06-01 09:23:16 +00001262 StoredDeclsMap *Map;
Richard Smith9e2341d2015-03-23 03:25:59 +00001263 if (!(Map = DC->LookupPtr))
John McCall75b960e2010-06-01 09:23:16 +00001264 Map = DC->CreateStoredDeclsMap(Context);
Richard Smitha8b74592014-03-25 00:34:21 +00001265 if (DC->NeedToReconcileExternalVisibleStorage)
1266 DC->reconcileExternalVisibleStorage();
John McCall75b960e2010-06-01 09:23:16 +00001267
1268 StoredDeclsList &List = (*Map)[Name];
Richard Smith51445cd2013-06-24 01:46:41 +00001269
1270 // Clear out any old external visible declarations, to avoid quadratic
1271 // performance in the redeclaration checks below.
1272 List.removeExternalDecls();
1273
1274 if (!List.isNull()) {
1275 // We have both existing declarations and new declarations for this name.
1276 // Some of the declarations may simply replace existing ones. Handle those
1277 // first.
1278 llvm::SmallVector<unsigned, 8> Skip;
1279 for (unsigned I = 0, N = Decls.size(); I != N; ++I)
Richard Smithe8292b12015-02-10 03:28:10 +00001280 if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
Richard Smith51445cd2013-06-24 01:46:41 +00001281 Skip.push_back(I);
1282 Skip.push_back(Decls.size());
1283
1284 // Add in any new declarations.
1285 unsigned SkipPos = 0;
1286 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1287 if (I == Skip[SkipPos])
1288 ++SkipPos;
1289 else
1290 List.AddSubsequentDecl(Decls[I]);
1291 }
1292 } else {
1293 // Convert the array to a StoredDeclsList.
1294 for (ArrayRef<NamedDecl*>::iterator
1295 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1296 if (List.isNull())
1297 List.setOnlyValue(*I);
1298 else
1299 List.AddSubsequentDecl(*I);
1300 }
John McCall75b960e2010-06-01 09:23:16 +00001301 }
1302
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001303 return List.getLookupResult();
John McCall75b960e2010-06-01 09:23:16 +00001304}
1305
Aaron Ballmanda634f12014-03-07 22:17:20 +00001306DeclContext::decl_iterator DeclContext::decls_begin() const {
1307 if (hasExternalLexicalStorage())
1308 LoadLexicalDeclsFromExternalStorage();
1309 return decl_iterator(FirstDecl);
1310}
1311
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001312bool DeclContext::decls_empty() const {
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001313 if (hasExternalLexicalStorage())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001314 LoadLexicalDeclsFromExternalStorage();
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001315
1316 return !FirstDecl;
1317}
1318
Sean Callanan0325fb82013-05-04 02:04:27 +00001319bool DeclContext::containsDecl(Decl *D) const {
1320 return (D->getLexicalDeclContext() == this &&
1321 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1322}
1323
John McCall84d87672009-12-10 09:41:52 +00001324void DeclContext::removeDecl(Decl *D) {
1325 assert(D->getLexicalDeclContext() == this &&
1326 "decl being removed from non-lexical context");
Douglas Gregor781f7132012-01-06 16:59:53 +00001327 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
John McCall84d87672009-12-10 09:41:52 +00001328 "decl is not in decls list");
1329
1330 // Remove D from the decl chain. This is O(n) but hopefully rare.
1331 if (D == FirstDecl) {
1332 if (D == LastDecl)
Craig Topper36250ad2014-05-12 05:36:57 +00001333 FirstDecl = LastDecl = nullptr;
John McCall84d87672009-12-10 09:41:52 +00001334 else
Douglas Gregor781f7132012-01-06 16:59:53 +00001335 FirstDecl = D->NextInContextAndBits.getPointer();
John McCall84d87672009-12-10 09:41:52 +00001336 } else {
Douglas Gregor781f7132012-01-06 16:59:53 +00001337 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
John McCall84d87672009-12-10 09:41:52 +00001338 assert(I && "decl not found in linked list");
Douglas Gregor781f7132012-01-06 16:59:53 +00001339 if (I->NextInContextAndBits.getPointer() == D) {
1340 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
John McCall84d87672009-12-10 09:41:52 +00001341 if (D == LastDecl) LastDecl = I;
1342 break;
1343 }
1344 }
1345 }
1346
1347 // Mark that D is no longer in the decl chain.
Craig Topper36250ad2014-05-12 05:36:57 +00001348 D->NextInContextAndBits.setPointer(nullptr);
John McCall84d87672009-12-10 09:41:52 +00001349
1350 // Remove D from the lookup table if necessary.
1351 if (isa<NamedDecl>(D)) {
1352 NamedDecl *ND = cast<NamedDecl>(D);
1353
Axel Naumanncb2c52f2011-08-26 14:06:12 +00001354 // Remove only decls that have a name
1355 if (!ND->getDeclName()) return;
1356
Vassil Vassilev2e415982017-06-20 14:59:57 +00001357 auto *DC = D->getDeclContext();
Richard Smith26210db2015-11-13 03:52:13 +00001358 do {
1359 StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1360 if (Map) {
1361 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1362 assert(Pos != Map->end() && "no lookup entry for decl");
1363 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1364 Pos->second.remove(ND);
1365 }
1366 } while (DC->isTransparentContext() && (DC = DC->getParent()));
John McCall84d87672009-12-10 09:41:52 +00001367 }
1368}
1369
John McCalld1e9d832009-08-11 06:59:38 +00001370void DeclContext::addHiddenDecl(Decl *D) {
Chris Lattner33f219d2009-02-20 00:56:18 +00001371 assert(D->getLexicalDeclContext() == this &&
1372 "Decl inserted into wrong lexical context");
Mike Stump11289f42009-09-09 15:08:12 +00001373 assert(!D->getNextDeclInContext() && D != LastDecl &&
Douglas Gregor020713e2009-01-09 19:42:16 +00001374 "Decl already inserted into a DeclContext");
1375
1376 if (FirstDecl) {
Douglas Gregor781f7132012-01-06 16:59:53 +00001377 LastDecl->NextInContextAndBits.setPointer(D);
Douglas Gregor020713e2009-01-09 19:42:16 +00001378 LastDecl = D;
1379 } else {
1380 FirstDecl = LastDecl = D;
1381 }
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001382
1383 // Notify a C++ record declaration that we've added a member, so it can
Nick Lewycky4b81fc872015-10-18 20:32:12 +00001384 // update its class-specific state.
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001385 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1386 Record->addedMember(D);
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001387
1388 // If this is a newly-created (not de-serialized) import declaration, wire
1389 // it in to the list of local import declarations.
1390 if (!D->isFromASTFile()) {
1391 if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1392 D->getASTContext().addedLocalImportDecl(Import);
1393 }
John McCalld1e9d832009-08-11 06:59:38 +00001394}
1395
1396void DeclContext::addDecl(Decl *D) {
1397 addHiddenDecl(D);
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001398
1399 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithf634c902012-03-16 06:12:59 +00001400 ND->getDeclContext()->getPrimaryContext()->
1401 makeDeclVisibleInContextWithFlags(ND, false, true);
Douglas Gregor91f84212008-12-11 16:49:14 +00001402}
1403
Sean Callanan95e74be2011-10-21 02:57:43 +00001404void DeclContext::addDeclInternal(Decl *D) {
1405 addHiddenDecl(D);
1406
1407 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithf634c902012-03-16 06:12:59 +00001408 ND->getDeclContext()->getPrimaryContext()->
1409 makeDeclVisibleInContextWithFlags(ND, true, true);
1410}
1411
1412/// shouldBeHidden - Determine whether a declaration which was declared
1413/// within its semantic context should be invisible to qualified name lookup.
1414static bool shouldBeHidden(NamedDecl *D) {
1415 // Skip unnamed declarations.
1416 if (!D->getDeclName())
1417 return true;
1418
1419 // Skip entities that can't be found by name lookup into a particular
1420 // context.
1421 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1422 D->isTemplateParameter())
1423 return true;
1424
1425 // Skip template specializations.
1426 // FIXME: This feels like a hack. Should DeclarationName support
1427 // template-ids, or is there a better way to keep specializations
1428 // from being visible?
1429 if (isa<ClassTemplateSpecializationDecl>(D))
1430 return true;
1431 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1432 if (FD->isFunctionTemplateSpecialization())
1433 return true;
1434
1435 return false;
1436}
1437
1438/// buildLookup - Build the lookup data structure with all of the
1439/// declarations in this DeclContext (and any other contexts linked
1440/// to it or transparent contexts nested within it) and return it.
Richard Smitha8b74592014-03-25 00:34:21 +00001441///
1442/// Note that the produced map may miss out declarations from an
1443/// external source. If it does, those entries will be marked with
1444/// the 'hasExternalDecls' flag.
Richard Smithf634c902012-03-16 06:12:59 +00001445StoredDeclsMap *DeclContext::buildLookup() {
1446 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1447
Richard Smith9e2341d2015-03-23 03:25:59 +00001448 if (!HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups)
1449 return LookupPtr;
1450
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001451 SmallVector<DeclContext *, 2> Contexts;
Richard Smithf634c902012-03-16 06:12:59 +00001452 collectAllContexts(Contexts);
Richard Smith18b380b2015-03-24 02:44:20 +00001453
1454 if (HasLazyExternalLexicalLookups) {
1455 HasLazyExternalLexicalLookups = false;
1456 for (auto *DC : Contexts) {
1457 if (DC->hasExternalLexicalStorage())
1458 HasLazyLocalLexicalLookups |=
1459 DC->LoadLexicalDeclsFromExternalStorage();
1460 }
1461
1462 if (!HasLazyLocalLexicalLookups)
1463 return LookupPtr;
1464 }
1465
1466 for (auto *DC : Contexts)
1467 buildLookupImpl(DC, hasExternalVisibleStorage());
Richard Smithf634c902012-03-16 06:12:59 +00001468
1469 // We no longer have any lazy decls.
Richard Smith9e2341d2015-03-23 03:25:59 +00001470 HasLazyLocalLexicalLookups = false;
1471 return LookupPtr;
Richard Smithf634c902012-03-16 06:12:59 +00001472}
1473
1474/// buildLookupImpl - Build part of the lookup data structure for the
1475/// declarations contained within DCtx, which will either be this
1476/// DeclContext, a DeclContext linked to it, or a transparent context
1477/// nested within it.
Richard Smitha3271c12015-02-07 00:45:52 +00001478void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
Richard Smith9e2341d2015-03-23 03:25:59 +00001479 for (Decl *D : DCtx->noload_decls()) {
Richard Smithf634c902012-03-16 06:12:59 +00001480 // Insert this declaration into the lookup structure, but only if
1481 // it's semantically within its decl context. Any other decls which
1482 // should be found in this context are added eagerly.
Richard Smithcf4ab522013-06-24 07:20:36 +00001483 //
1484 // If it's from an AST file, don't add it now. It'll get handled by
1485 // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1486 // in C++, we do not track external visible decls for the TU, so in
1487 // that case we need to collect them all here.
Richard Smithf634c902012-03-16 06:12:59 +00001488 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithcf4ab522013-06-24 07:20:36 +00001489 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1490 (!ND->isFromASTFile() ||
1491 (isTranslationUnit() &&
1492 !getParentASTContext().getLangOpts().CPlusPlus)))
Richard Smitha3271c12015-02-07 00:45:52 +00001493 makeDeclVisibleInContextImpl(ND, Internal);
Richard Smithf634c902012-03-16 06:12:59 +00001494
1495 // If this declaration is itself a transparent declaration context
1496 // or inline namespace, add the members of this declaration of that
1497 // context (recursively).
1498 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1499 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Richard Smith9e2341d2015-03-23 03:25:59 +00001500 buildLookupImpl(InnerCtx, Internal);
Richard Smithf634c902012-03-16 06:12:59 +00001501 }
Sean Callanan95e74be2011-10-21 02:57:43 +00001502}
1503
Richard Smith40c78062015-02-21 02:31:57 +00001504NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1505
Mike Stump11289f42009-09-09 15:08:12 +00001506DeclContext::lookup_result
Richard Smith40c78062015-02-21 02:31:57 +00001507DeclContext::lookup(DeclarationName Name) const {
Richard Smith8df390f2016-09-08 23:14:54 +00001508 assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1509 "should not perform lookups into transparent contexts");
Nick Lewycky2bd636f2012-03-13 04:12:34 +00001510
Manman Ren7d2f5c42016-09-09 19:03:07 +00001511 const DeclContext *PrimaryContext = getPrimaryContext();
1512 if (PrimaryContext != this)
1513 return PrimaryContext->lookup(Name);
1514
Richard Smith8cebe372015-02-25 22:20:13 +00001515 // If we have an external source, ensure that any later redeclarations of this
1516 // context have been loaded, since they may add names to the result of this
1517 // lookup (or add external visible storage).
1518 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1519 if (Source)
1520 (void)cast<Decl>(this)->getMostRecentDecl();
Richard Smithbb853c72014-08-13 01:23:33 +00001521
Richard Smith05afe5e2012-03-13 03:12:56 +00001522 if (hasExternalVisibleStorage()) {
Richard Smith8cebe372015-02-25 22:20:13 +00001523 assert(Source && "external visible storage but no external source?");
1524
Richard Smitha8b74592014-03-25 00:34:21 +00001525 if (NeedToReconcileExternalVisibleStorage)
1526 reconcileExternalVisibleStorage();
1527
Richard Smith9e2341d2015-03-23 03:25:59 +00001528 StoredDeclsMap *Map = LookupPtr;
Richard Smitha8b74592014-03-25 00:34:21 +00001529
Richard Smith9e2341d2015-03-23 03:25:59 +00001530 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
Richard Smith40c78062015-02-21 02:31:57 +00001531 // FIXME: Make buildLookup const?
1532 Map = const_cast<DeclContext*>(this)->buildLookup();
Richard Smith645d7552013-02-07 03:37:08 +00001533
Richard Smith75fc3bf2013-02-08 00:37:45 +00001534 if (!Map)
1535 Map = CreateStoredDeclsMap(getParentASTContext());
1536
Richard Smith4abe0a82013-09-09 07:34:56 +00001537 // If we have a lookup result with no external decls, we are done.
Richard Smith75fc3bf2013-02-08 00:37:45 +00001538 std::pair<StoredDeclsMap::iterator, bool> R =
1539 Map->insert(std::make_pair(Name, StoredDeclsList()));
Richard Smith4abe0a82013-09-09 07:34:56 +00001540 if (!R.second && !R.first->second.hasExternalDecls())
Richard Smith75fc3bf2013-02-08 00:37:45 +00001541 return R.first->second.getLookupResult();
Richard Smithf634c902012-03-16 06:12:59 +00001542
Richard Smith309271b2014-03-04 00:21:14 +00001543 if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
Richard Smith9e2341d2015-03-23 03:25:59 +00001544 if (StoredDeclsMap *Map = LookupPtr) {
Richard Smith9ce12e32013-02-07 03:30:24 +00001545 StoredDeclsMap::iterator I = Map->find(Name);
1546 if (I != Map->end())
1547 return I->second.getLookupResult();
1548 }
1549 }
1550
Richard Smith40c78062015-02-21 02:31:57 +00001551 return lookup_result();
John McCall75b960e2010-06-01 09:23:16 +00001552 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001553
Richard Smith9e2341d2015-03-23 03:25:59 +00001554 StoredDeclsMap *Map = LookupPtr;
1555 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
Richard Smith40c78062015-02-21 02:31:57 +00001556 Map = const_cast<DeclContext*>(this)->buildLookup();
Richard Smithf634c902012-03-16 06:12:59 +00001557
1558 if (!Map)
Richard Smith40c78062015-02-21 02:31:57 +00001559 return lookup_result();
Richard Smithf634c902012-03-16 06:12:59 +00001560
1561 StoredDeclsMap::iterator I = Map->find(Name);
1562 if (I == Map->end())
Richard Smith40c78062015-02-21 02:31:57 +00001563 return lookup_result();
Richard Smithf634c902012-03-16 06:12:59 +00001564
1565 return I->second.getLookupResult();
Douglas Gregor91f84212008-12-11 16:49:14 +00001566}
1567
Richard Smith95d99302013-07-13 02:00:19 +00001568DeclContext::lookup_result
1569DeclContext::noload_lookup(DeclarationName Name) {
Richard Smith8df390f2016-09-08 23:14:54 +00001570 assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1571 "should not perform lookups into transparent contexts");
Richard Smith95d99302013-07-13 02:00:19 +00001572
1573 DeclContext *PrimaryContext = getPrimaryContext();
1574 if (PrimaryContext != this)
1575 return PrimaryContext->noload_lookup(Name);
1576
Richard Smith9e2341d2015-03-23 03:25:59 +00001577 // If we have any lazy lexical declarations not in our lookup map, add them
1578 // now. Don't import any external declarations, not even if we know we have
1579 // some missing from the external visible lookups.
1580 if (HasLazyLocalLexicalLookups) {
Vince Harrona3ea9a42015-03-22 05:59:59 +00001581 SmallVector<DeclContext *, 2> Contexts;
1582 collectAllContexts(Contexts);
1583 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
Richard Smith9e2341d2015-03-23 03:25:59 +00001584 buildLookupImpl(Contexts[I], hasExternalVisibleStorage());
1585 HasLazyLocalLexicalLookups = false;
Vince Harrona3ea9a42015-03-22 05:59:59 +00001586 }
1587
Richard Smith9e2341d2015-03-23 03:25:59 +00001588 StoredDeclsMap *Map = LookupPtr;
Richard Smith95d99302013-07-13 02:00:19 +00001589 if (!Map)
Richard Smith40c78062015-02-21 02:31:57 +00001590 return lookup_result();
Richard Smith95d99302013-07-13 02:00:19 +00001591
1592 StoredDeclsMap::iterator I = Map->find(Name);
Craig Topper36250ad2014-05-12 05:36:57 +00001593 return I != Map->end() ? I->second.getLookupResult()
Richard Smith40c78062015-02-21 02:31:57 +00001594 : lookup_result();
Richard Smith95d99302013-07-13 02:00:19 +00001595}
1596
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001597void DeclContext::localUncachedLookup(DeclarationName Name,
1598 SmallVectorImpl<NamedDecl *> &Results) {
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001599 Results.clear();
1600
1601 // If there's no external storage, just perform a normal lookup and copy
1602 // the results.
Douglas Gregordd6006f2012-07-17 21:16:27 +00001603 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001604 lookup_result LookupResults = lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00001605 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001606 return;
1607 }
1608
1609 // If we have a lookup table, check there first. Maybe we'll get lucky.
Richard Smith9e2341d2015-03-23 03:25:59 +00001610 // FIXME: Should we be checking these flags on the primary context?
1611 if (Name && !HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups) {
1612 if (StoredDeclsMap *Map = LookupPtr) {
Douglas Gregordd6006f2012-07-17 21:16:27 +00001613 StoredDeclsMap::iterator Pos = Map->find(Name);
1614 if (Pos != Map->end()) {
1615 Results.insert(Results.end(),
David Blaikieff7d47a2012-12-19 00:45:41 +00001616 Pos->second.getLookupResult().begin(),
1617 Pos->second.getLookupResult().end());
Douglas Gregordd6006f2012-07-17 21:16:27 +00001618 return;
1619 }
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001620 }
1621 }
Douglas Gregordd6006f2012-07-17 21:16:27 +00001622
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001623 // Slow case: grovel through the declarations in our chain looking for
1624 // matches.
Richard Smith9e2341d2015-03-23 03:25:59 +00001625 // FIXME: If we have lazy external declarations, this will not find them!
1626 // FIXME: Should we CollectAllContexts and walk them all here?
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001627 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1628 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1629 if (ND->getDeclName() == Name)
1630 Results.push_back(ND);
1631 }
1632}
1633
Sebastian Redl50c68252010-08-31 00:36:30 +00001634DeclContext *DeclContext::getRedeclContext() {
Chris Lattner17a1bfa2009-03-27 19:19:59 +00001635 DeclContext *Ctx = this;
Sebastian Redlbd595762010-08-31 20:53:31 +00001636 // Skip through transparent contexts.
1637 while (Ctx->isTransparentContext())
Douglas Gregor6ad0ef52009-01-06 23:51:29 +00001638 Ctx = Ctx->getParent();
1639 return Ctx;
1640}
1641
Douglas Gregorf47b9112009-02-25 22:02:03 +00001642DeclContext *DeclContext::getEnclosingNamespaceContext() {
1643 DeclContext *Ctx = this;
1644 // Skip through non-namespace, non-translation-unit contexts.
Sebastian Redl4f08c962010-08-31 00:36:23 +00001645 while (!Ctx->isFileContext())
Douglas Gregorf47b9112009-02-25 22:02:03 +00001646 Ctx = Ctx->getParent();
1647 return Ctx->getPrimaryContext();
1648}
1649
Reid Klecknerd60b82f2014-11-17 23:36:45 +00001650RecordDecl *DeclContext::getOuterLexicalRecordContext() {
1651 // Loop until we find a non-record context.
1652 RecordDecl *OutermostRD = nullptr;
1653 DeclContext *DC = this;
1654 while (DC->isRecord()) {
1655 OutermostRD = cast<RecordDecl>(DC);
1656 DC = DC->getLexicalParent();
1657 }
1658 return OutermostRD;
1659}
1660
Sebastian Redl50c68252010-08-31 00:36:30 +00001661bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1662 // For non-file contexts, this is equivalent to Equals.
1663 if (!isFileContext())
1664 return O->Equals(this);
1665
1666 do {
1667 if (O->Equals(this))
1668 return true;
1669
1670 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1671 if (!NS || !NS->isInline())
1672 break;
1673 O = NS->getParent();
1674 } while (O);
1675
1676 return false;
1677}
1678
Richard Smithf634c902012-03-16 06:12:59 +00001679void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1680 DeclContext *PrimaryDC = this->getPrimaryContext();
1681 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1682 // If the decl is being added outside of its semantic decl context, we
1683 // need to ensure that we eagerly build the lookup information for it.
1684 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
Sean Callanan95e74be2011-10-21 02:57:43 +00001685}
1686
Richard Smithf634c902012-03-16 06:12:59 +00001687void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1688 bool Recoverable) {
1689 assert(this == getPrimaryContext() && "expected a primary DC");
Sean Callanan95e74be2011-10-21 02:57:43 +00001690
Vassil Vassilev71eafde2016-04-06 20:56:03 +00001691 if (!isLookupContext()) {
1692 if (isTransparentContext())
1693 getParent()->getPrimaryContext()
1694 ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
Richard Smith05afe5e2012-03-13 03:12:56 +00001695 return;
Vassil Vassilev71eafde2016-04-06 20:56:03 +00001696 }
Richard Smith05afe5e2012-03-13 03:12:56 +00001697
Richard Smithf634c902012-03-16 06:12:59 +00001698 // Skip declarations which should be invisible to name lookup.
1699 if (shouldBeHidden(D))
1700 return;
1701
1702 // If we already have a lookup data structure, perform the insertion into
1703 // it. If we might have externally-stored decls with this name, look them
1704 // up and perform the insertion. If this decl was declared outside its
1705 // semantic context, buildLookup won't add it, so add it now.
1706 //
1707 // FIXME: As a performance hack, don't add such decls into the translation
1708 // unit unless we're in C++, since qualified lookup into the TU is never
1709 // performed.
Richard Smith9e2341d2015-03-23 03:25:59 +00001710 if (LookupPtr || hasExternalVisibleStorage() ||
Richard Smithf634c902012-03-16 06:12:59 +00001711 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1712 (getParentASTContext().getLangOpts().CPlusPlus ||
1713 !isTranslationUnit()))) {
1714 // If we have lazily omitted any decls, they might have the same name as
1715 // the decl which we are adding, so build a full lookup table before adding
1716 // this decl.
1717 buildLookup();
1718 makeDeclVisibleInContextImpl(D, Internal);
1719 } else {
Richard Smith9e2341d2015-03-23 03:25:59 +00001720 HasLazyLocalLexicalLookups = true;
Richard Smithf634c902012-03-16 06:12:59 +00001721 }
1722
1723 // If we are a transparent context or inline namespace, insert into our
1724 // parent context, too. This operation is recursive.
1725 if (isTransparentContext() || isInlineNamespace())
1726 getParent()->getPrimaryContext()->
1727 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1728
1729 Decl *DCAsDecl = cast<Decl>(this);
1730 // Notify that a decl was made visible unless we are a Tag being defined.
1731 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1732 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1733 L->AddedVisibleDecl(this, D);
1734}
1735
1736void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1737 // Find or create the stored declaration map.
Richard Smith9e2341d2015-03-23 03:25:59 +00001738 StoredDeclsMap *Map = LookupPtr;
Richard Smithf634c902012-03-16 06:12:59 +00001739 if (!Map) {
1740 ASTContext *C = &getParentASTContext();
1741 Map = CreateStoredDeclsMap(*C);
Argyrios Kyrtzidise51e5542010-07-04 21:44:25 +00001742 }
1743
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001744 // If there is an external AST source, load any declarations it knows about
1745 // with this declaration's name.
1746 // If the lookup table contains an entry about this name it means that we
1747 // have already checked the external source.
Sean Callanan95e74be2011-10-21 02:57:43 +00001748 if (!Internal)
1749 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1750 if (hasExternalVisibleStorage() &&
Richard Smithf634c902012-03-16 06:12:59 +00001751 Map->find(D->getDeclName()) == Map->end())
Sean Callanan95e74be2011-10-21 02:57:43 +00001752 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001753
Douglas Gregor91f84212008-12-11 16:49:14 +00001754 // Insert this declaration into the map.
Richard Smithf634c902012-03-16 06:12:59 +00001755 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
Richard Smith4abe0a82013-09-09 07:34:56 +00001756
1757 if (Internal) {
1758 // If this is being added as part of loading an external declaration,
1759 // this may not be the only external declaration with this name.
1760 // In this case, we never try to replace an existing declaration; we'll
1761 // handle that when we finalize the list of declarations for this name.
1762 DeclNameEntries.setHasExternalDecls();
1763 DeclNameEntries.AddSubsequentDecl(D);
1764 return;
1765 }
1766
Richard Smitha3271c12015-02-07 00:45:52 +00001767 if (DeclNameEntries.isNull()) {
Chris Lattnercaae7162009-02-20 01:44:05 +00001768 DeclNameEntries.setOnlyValue(D);
Richard Smithf634c902012-03-16 06:12:59 +00001769 return;
Douglas Gregor91f84212008-12-11 16:49:14 +00001770 }
Chris Lattner24e24d52009-02-20 00:55:03 +00001771
Richard Smithe8292b12015-02-10 03:28:10 +00001772 if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
Richard Smithf634c902012-03-16 06:12:59 +00001773 // This declaration has replaced an existing one for which
1774 // declarationReplaces returns true.
1775 return;
1776 }
Mike Stump11289f42009-09-09 15:08:12 +00001777
Richard Smithf634c902012-03-16 06:12:59 +00001778 // Put this declaration into the appropriate slot.
1779 DeclNameEntries.AddSubsequentDecl(D);
Douglas Gregor91f84212008-12-11 16:49:14 +00001780}
Douglas Gregor889ceb72009-02-03 19:21:40 +00001781
Richard Smith40c78062015-02-21 02:31:57 +00001782UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
1783 return cast<UsingDirectiveDecl>(*I);
1784}
1785
Douglas Gregor889ceb72009-02-03 19:21:40 +00001786/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1787/// this context.
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001788DeclContext::udir_range DeclContext::using_directives() const {
Richard Smith05afe5e2012-03-13 03:12:56 +00001789 // FIXME: Use something more efficient than normal lookup for using
1790 // directives. In C++, using directives are looked up more than anything else.
Richard Smithcf4bdde2015-02-21 02:45:19 +00001791 lookup_result Result = lookup(UsingDirectiveDecl::getName());
Richard Smith40c78062015-02-21 02:31:57 +00001792 return udir_range(Result.begin(), Result.end());
Douglas Gregor889ceb72009-02-03 19:21:40 +00001793}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001794
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001795//===----------------------------------------------------------------------===//
1796// Creation and Destruction of StoredDeclsMaps. //
1797//===----------------------------------------------------------------------===//
1798
John McCallc62bb642010-03-24 05:22:00 +00001799StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
Richard Smith9e2341d2015-03-23 03:25:59 +00001800 assert(!LookupPtr && "context already has a decls map");
John McCallc62bb642010-03-24 05:22:00 +00001801 assert(getPrimaryContext() == this &&
1802 "creating decls map on non-primary context");
1803
1804 StoredDeclsMap *M;
1805 bool Dependent = isDependentContext();
1806 if (Dependent)
1807 M = new DependentStoredDeclsMap();
1808 else
1809 M = new StoredDeclsMap();
1810 M->Previous = C.LastSDM;
1811 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
Richard Smith9e2341d2015-03-23 03:25:59 +00001812 LookupPtr = M;
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001813 return M;
1814}
1815
1816void ASTContext::ReleaseDeclContextMaps() {
John McCallc62bb642010-03-24 05:22:00 +00001817 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1818 // pointer because the subclass doesn't add anything that needs to
1819 // be deleted.
John McCallc62bb642010-03-24 05:22:00 +00001820 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1821}
1822
1823void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1824 while (Map) {
1825 // Advance the iteration before we invalidate memory.
1826 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1827
1828 if (Dependent)
1829 delete static_cast<DependentStoredDeclsMap*>(Map);
1830 else
1831 delete Map;
1832
1833 Map = Next.getPointer();
1834 Dependent = Next.getInt();
1835 }
1836}
1837
John McCallc62bb642010-03-24 05:22:00 +00001838DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1839 DeclContext *Parent,
1840 const PartialDiagnostic &PDiag) {
1841 assert(Parent->isDependentContext()
1842 && "cannot iterate dependent diagnostics of non-dependent context");
1843 Parent = Parent->getPrimaryContext();
Richard Smith9e2341d2015-03-23 03:25:59 +00001844 if (!Parent->LookupPtr)
John McCallc62bb642010-03-24 05:22:00 +00001845 Parent->CreateStoredDeclsMap(C);
1846
Richard Smith9e2341d2015-03-23 03:25:59 +00001847 DependentStoredDeclsMap *Map =
1848 static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
John McCallc62bb642010-03-24 05:22:00 +00001849
Douglas Gregora55530e2010-03-29 23:56:53 +00001850 // Allocate the copy of the PartialDiagnostic via the ASTContext's
Douglas Gregor89336232010-03-29 23:34:08 +00001851 // BumpPtrAllocator, rather than the ASTContext itself.
Craig Topper36250ad2014-05-12 05:36:57 +00001852 PartialDiagnostic::Storage *DiagStorage = nullptr;
Douglas Gregora55530e2010-03-29 23:56:53 +00001853 if (PDiag.hasStorage())
1854 DiagStorage = new (C) PartialDiagnostic::Storage;
1855
1856 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
John McCallc62bb642010-03-24 05:22:00 +00001857
1858 // TODO: Maybe we shouldn't reverse the order during insertion.
1859 DD->NextDiagnostic = Map->FirstDiagnostic;
1860 Map->FirstDiagnostic = DD;
1861
1862 return DD;
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001863}