blob: 8deef3343dbdb77b5d5f39b47da30c4796cac012 [file] [log] [blame]
Eli Friedman7dbab8a2008-06-07 16:52:53 +00001//===--- DeclBase.cpp - Declaration AST Node Implementation ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Decl and DeclContext classes.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/DeclBase.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +000018#include "clang/AST/Decl.h"
Argyrios Kyrtzidis2951e142008-06-09 21:05:31 +000019#include "clang/AST/DeclCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/DeclContextInternals.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000021#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000022#include "clang/AST/DeclObjC.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000023#include "clang/AST/DeclOpenMP.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000024#include "clang/AST/DeclTemplate.h"
John McCallc62bb642010-03-24 05:22:00 +000025#include "clang/AST/DependentDiagnostic.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000026#include "clang/AST/ExternalASTSource.h"
Sebastian Redla7b98a72009-04-26 20:35:05 +000027#include "clang/AST/Stmt.h"
28#include "clang/AST/StmtCXX.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000029#include "clang/AST/Type.h"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000030#include "clang/Basic/TargetInfo.h"
Chris Lattnereae6cb62009-03-05 08:00:35 +000031#include "llvm/Support/raw_ostream.h"
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000032#include <algorithm>
Eli Friedman7dbab8a2008-06-07 16:52:53 +000033using namespace clang;
34
35//===----------------------------------------------------------------------===//
36// Statistics
37//===----------------------------------------------------------------------===//
38
Alexis Hunted053252010-05-30 07:21:58 +000039#define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
40#define ABSTRACT_DECL(DECL)
41#include "clang/AST/DeclNodes.inc"
Eli Friedman7dbab8a2008-06-07 16:52:53 +000042
Douglas Gregor7dab26b2013-02-09 01:35:03 +000043void Decl::updateOutOfDate(IdentifierInfo &II) const {
44 getASTContext().getExternalSource()->updateOutOfDateIdentifier(II);
45}
46
James Y Knight53c76162015-07-17 18:21:37 +000047#define DECL(DERIVED, BASE) \
Benjamin Kramerc3f89252016-10-20 14:27:22 +000048 static_assert(alignof(Decl) >= alignof(DERIVED##Decl), \
James Y Knight53c76162015-07-17 18:21:37 +000049 "Alignment sufficient after objects prepended to " #DERIVED);
50#define ABSTRACT_DECL(DECL)
51#include "clang/AST/DeclNodes.inc"
52
Richard Smithf7981722013-11-22 09:01:48 +000053void *Decl::operator new(std::size_t Size, const ASTContext &Context,
54 unsigned ID, std::size_t Extra) {
Douglas Gregor52261fd2012-01-05 23:49:36 +000055 // Allocate an extra 8 bytes worth of storage, which ensures that the
James Y Knight53c76162015-07-17 18:21:37 +000056 // resulting pointer will still be 8-byte aligned.
Benjamin Kramerc3f89252016-10-20 14:27:22 +000057 static_assert(sizeof(unsigned) * 2 >= alignof(Decl),
James Y Knight53c76162015-07-17 18:21:37 +000058 "Decl won't be misaligned");
Richard Smithf7981722013-11-22 09:01:48 +000059 void *Start = Context.Allocate(Size + Extra + 8);
Douglas Gregor52261fd2012-01-05 23:49:36 +000060 void *Result = (char*)Start + 8;
Richard Smithf7981722013-11-22 09:01:48 +000061
Douglas Gregorcfe7dc62012-01-09 17:30:44 +000062 unsigned *PrefixPtr = (unsigned *)Result - 2;
Richard Smithf7981722013-11-22 09:01:48 +000063
Douglas Gregorcfe7dc62012-01-09 17:30:44 +000064 // Zero out the first 4 bytes; this is used to store the owning module ID.
65 PrefixPtr[0] = 0;
Richard Smithf7981722013-11-22 09:01:48 +000066
Douglas Gregorcfe7dc62012-01-09 17:30:44 +000067 // Store the global declaration ID in the second 4 bytes.
68 PrefixPtr[1] = ID;
Richard Smithf7981722013-11-22 09:01:48 +000069
Douglas Gregor64af53c2012-01-05 22:27:05 +000070 return Result;
Douglas Gregor72172e92012-01-05 21:55:30 +000071}
72
Richard Smithf7981722013-11-22 09:01:48 +000073void *Decl::operator new(std::size_t Size, const ASTContext &Ctx,
74 DeclContext *Parent, std::size_t Extra) {
75 assert(!Parent || &Parent->getParentASTContext() == &Ctx);
Richard Smith42413142015-05-15 20:05:43 +000076 // With local visibility enabled, we track the owning module even for local
77 // declarations.
78 if (Ctx.getLangOpts().ModulesLocalVisibility) {
James Y Knight53c76162015-07-17 18:21:37 +000079 // Ensure required alignment of the resulting object by adding extra
80 // padding at the start if required.
81 size_t ExtraAlign =
Benjamin Kramerc3f89252016-10-20 14:27:22 +000082 llvm::OffsetToAlignment(sizeof(Module *), alignof(Decl));
James Y Knight53c76162015-07-17 18:21:37 +000083 char *Buffer = reinterpret_cast<char *>(
84 ::operator new(ExtraAlign + sizeof(Module *) + Size + Extra, Ctx));
85 Buffer += ExtraAlign;
Richard Smith42413142015-05-15 20:05:43 +000086 return new (Buffer) Module*(nullptr) + 1;
87 }
Richard Smithf7981722013-11-22 09:01:48 +000088 return ::operator new(Size + Extra, Ctx);
89}
90
Douglas Gregorc147b0b2013-01-12 01:29:50 +000091Module *Decl::getOwningModuleSlow() const {
92 assert(isFromASTFile() && "Not from AST file?");
93 return getASTContext().getExternalSource()->getModule(getOwningModuleID());
94}
95
Richard Smith87bb5692015-06-09 00:35:49 +000096bool Decl::hasLocalOwningModuleStorage() const {
97 return getASTContext().getLangOpts().ModulesLocalVisibility;
98}
99
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000100const char *Decl::getDeclKindName() const {
101 switch (DeclKind) {
David Blaikie83d382b2011-09-23 05:06:16 +0000102 default: llvm_unreachable("Declaration not in DeclNodes.inc!");
Alexis Hunted053252010-05-30 07:21:58 +0000103#define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
104#define ABSTRACT_DECL(DECL)
105#include "clang/AST/DeclNodes.inc"
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000106 }
107}
108
Douglas Gregor90d47172010-03-05 00:26:45 +0000109void Decl::setInvalidDecl(bool Invalid) {
110 InvalidDecl = Invalid;
Alp Tokera5d64592013-12-21 01:10:54 +0000111 assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
Richard Trieucbd54302016-11-11 20:51:04 +0000112 if (!Invalid) {
113 return;
114 }
115
116 if (!isa<ParmVarDecl>(this)) {
Douglas Gregor90d47172010-03-05 00:26:45 +0000117 // Defensive maneuver for ill-formed code: we're likely not to make it to
118 // a point where we set the access specifier, so default it to "public"
119 // to avoid triggering asserts elsewhere in the front end.
120 setAccess(AS_public);
121 }
Richard Trieucbd54302016-11-11 20:51:04 +0000122
123 // Marking a DecompositionDecl as invalid implies all the child BindingDecl's
124 // are invalid too.
125 if (DecompositionDecl *DD = dyn_cast<DecompositionDecl>(this)) {
126 for (BindingDecl *Binding : DD->bindings()) {
127 Binding->setInvalidDecl();
128 }
129 }
Douglas Gregor90d47172010-03-05 00:26:45 +0000130}
131
Steve Naroff5faaef72009-01-20 19:53:53 +0000132const char *DeclContext::getDeclKindName() const {
133 switch (DeclKind) {
David Blaikie83d382b2011-09-23 05:06:16 +0000134 default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
Alexis Hunted053252010-05-30 07:21:58 +0000135#define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
136#define ABSTRACT_DECL(DECL)
137#include "clang/AST/DeclNodes.inc"
Steve Naroff5faaef72009-01-20 19:53:53 +0000138 }
139}
140
Daniel Dunbar62905572012-03-05 21:42:49 +0000141bool Decl::StatisticsEnabled = false;
142void Decl::EnableStatistics() {
143 StatisticsEnabled = true;
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000144}
145
146void Decl::PrintStats() {
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000147 llvm::errs() << "\n*** Decl Stats:\n";
Mike Stump11289f42009-09-09 15:08:12 +0000148
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000149 int totalDecls = 0;
Alexis Hunted053252010-05-30 07:21:58 +0000150#define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
151#define ABSTRACT_DECL(DECL)
152#include "clang/AST/DeclNodes.inc"
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000153 llvm::errs() << " " << totalDecls << " decls total.\n";
Mike Stump11289f42009-09-09 15:08:12 +0000154
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000155 int totalBytes = 0;
Alexis Hunted053252010-05-30 07:21:58 +0000156#define DECL(DERIVED, BASE) \
157 if (n##DERIVED##s > 0) { \
158 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000159 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
160 << sizeof(DERIVED##Decl) << " each (" \
161 << n##DERIVED##s * sizeof(DERIVED##Decl) \
162 << " bytes)\n"; \
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000163 }
Alexis Hunted053252010-05-30 07:21:58 +0000164#define ABSTRACT_DECL(DECL)
165#include "clang/AST/DeclNodes.inc"
Mike Stump11289f42009-09-09 15:08:12 +0000166
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000167 llvm::errs() << "Total bytes = " << totalBytes << "\n";
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000168}
169
Alexis Hunted053252010-05-30 07:21:58 +0000170void Decl::add(Kind k) {
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000171 switch (k) {
Alexis Hunted053252010-05-30 07:21:58 +0000172#define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
173#define ABSTRACT_DECL(DECL)
174#include "clang/AST/DeclNodes.inc"
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000175 }
176}
177
Anders Carlssonaa73b912009-06-13 00:08:58 +0000178bool Decl::isTemplateParameterPack() const {
179 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
180 return TTP->isParameterPack();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000181 if (const NonTypeTemplateParmDecl *NTTP
Douglas Gregorf5500772011-01-05 15:48:55 +0000182 = dyn_cast<NonTypeTemplateParmDecl>(this))
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000183 return NTTP->isParameterPack();
Douglas Gregorf5500772011-01-05 15:48:55 +0000184 if (const TemplateTemplateParmDecl *TTP
185 = dyn_cast<TemplateTemplateParmDecl>(this))
186 return TTP->isParameterPack();
Anders Carlssonaa73b912009-06-13 00:08:58 +0000187 return false;
188}
189
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +0000190bool Decl::isParameterPack() const {
191 if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
192 return Parm->isParameterPack();
193
194 return isTemplateParameterPack();
195}
196
Alp Tokera2794f92014-01-22 07:29:52 +0000197FunctionDecl *Decl::getAsFunction() {
198 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
199 return FD;
200 if (const FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(this))
201 return FTD->getTemplatedDecl();
Craig Topper36250ad2014-05-12 05:36:57 +0000202 return nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000203}
204
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000205bool Decl::isTemplateDecl() const {
206 return isa<TemplateDecl>(this);
207}
208
Serge Pavlov7dcc97e2016-04-19 06:19:52 +0000209TemplateDecl *Decl::getDescribedTemplate() const {
210 if (auto *FD = dyn_cast<FunctionDecl>(this))
211 return FD->getDescribedFunctionTemplate();
212 else if (auto *RD = dyn_cast<CXXRecordDecl>(this))
213 return RD->getDescribedClassTemplate();
214 else if (auto *VD = dyn_cast<VarDecl>(this))
215 return VD->getDescribedVarTemplate();
216
217 return nullptr;
218}
219
Argyrios Kyrtzidis0ce4c9a2011-09-28 02:45:33 +0000220const DeclContext *Decl::getParentFunctionOrMethod() const {
221 for (const DeclContext *DC = getDeclContext();
222 DC && !DC->isTranslationUnit() && !DC->isNamespace();
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000223 DC = DC->getParent())
224 if (DC->isFunctionOrMethod())
Argyrios Kyrtzidis0ce4c9a2011-09-28 02:45:33 +0000225 return DC;
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000226
Craig Topper36250ad2014-05-12 05:36:57 +0000227 return nullptr;
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000228}
229
Douglas Gregor133eddd2011-02-17 08:47:29 +0000230
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000231//===----------------------------------------------------------------------===//
Chris Lattnereae6cb62009-03-05 08:00:35 +0000232// PrettyStackTraceDecl Implementation
233//===----------------------------------------------------------------------===//
Mike Stump11289f42009-09-09 15:08:12 +0000234
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000235void PrettyStackTraceDecl::print(raw_ostream &OS) const {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000236 SourceLocation TheLoc = Loc;
237 if (TheLoc.isInvalid() && TheDecl)
238 TheLoc = TheDecl->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000239
Chris Lattnereae6cb62009-03-05 08:00:35 +0000240 if (TheLoc.isValid()) {
241 TheLoc.print(OS, SM);
242 OS << ": ";
243 }
244
245 OS << Message;
246
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +0000247 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
248 OS << " '";
249 DN->printQualifiedName(OS);
250 OS << '\'';
251 }
Chris Lattnereae6cb62009-03-05 08:00:35 +0000252 OS << '\n';
253}
Mike Stump11289f42009-09-09 15:08:12 +0000254
Chris Lattnereae6cb62009-03-05 08:00:35 +0000255//===----------------------------------------------------------------------===//
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000256// Decl Implementation
257//===----------------------------------------------------------------------===//
258
Douglas Gregorb11aad82011-02-19 18:51:44 +0000259// Out-of-line virtual method providing a home for Decl.
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000260Decl::~Decl() { }
Douglas Gregora43942a2011-02-17 07:02:32 +0000261
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000262void Decl::setDeclContext(DeclContext *DC) {
Chris Lattnerb81eb052009-03-29 06:06:59 +0000263 DeclCtx = DC;
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000264}
265
266void Decl::setLexicalDeclContext(DeclContext *DC) {
267 if (DC == getLexicalDeclContext())
268 return;
269
270 if (isInSemaDC()) {
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000271 setDeclContextsImpl(getDeclContext(), DC, getASTContext());
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000272 } else {
273 getMultipleDC()->LexicalDC = DC;
274 }
Richard Smith5327b892015-07-01 19:32:54 +0000275 Hidden = cast<Decl>(DC)->Hidden;
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000276}
277
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000278void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
279 ASTContext &Ctx) {
280 if (SemaDC == LexicalDC) {
281 DeclCtx = SemaDC;
282 } else {
283 Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
284 MDC->SemanticDC = SemaDC;
285 MDC->LexicalDC = LexicalDC;
286 DeclCtx = MDC;
287 }
288}
289
Serge Pavlov73c6a242015-08-23 10:22:28 +0000290bool Decl::isLexicallyWithinFunctionOrMethod() const {
291 const DeclContext *LDC = getLexicalDeclContext();
Serge Pavlovb24a7112015-08-23 11:09:40 +0000292 while (true) {
Serge Pavlov73c6a242015-08-23 10:22:28 +0000293 if (LDC->isFunctionOrMethod())
294 return true;
295 if (!isa<TagDecl>(LDC))
296 return false;
Serge Pavlovb24a7112015-08-23 11:09:40 +0000297 LDC = LDC->getLexicalParent();
298 }
Serge Pavlov73c6a242015-08-23 10:22:28 +0000299 return false;
300}
301
John McCall4fa53422009-10-01 00:25:31 +0000302bool Decl::isInAnonymousNamespace() const {
303 const DeclContext *DC = getDeclContext();
304 do {
305 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
306 if (ND->isAnonymousNamespace())
307 return true;
308 } while ((DC = DC->getParent()));
309
310 return false;
311}
312
Richard Trieuc771d5d2014-05-28 02:16:01 +0000313bool Decl::isInStdNamespace() const {
314 return getDeclContext()->isStdNamespace();
315}
316
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000317TranslationUnitDecl *Decl::getTranslationUnitDecl() {
Argyrios Kyrtzidis4e1a72b2009-06-30 02:34:53 +0000318 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
319 return TUD;
320
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000321 DeclContext *DC = getDeclContext();
322 assert(DC && "This decl is not contained in a translation unit!");
Mike Stump11289f42009-09-09 15:08:12 +0000323
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000324 while (!DC->isTranslationUnit()) {
325 DC = DC->getParent();
326 assert(DC && "This decl is not contained in a translation unit!");
327 }
Mike Stump11289f42009-09-09 15:08:12 +0000328
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000329 return cast<TranslationUnitDecl>(DC);
330}
331
332ASTContext &Decl::getASTContext() const {
Mike Stump11289f42009-09-09 15:08:12 +0000333 return getTranslationUnitDecl()->getASTContext();
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000334}
335
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +0000336ASTMutationListener *Decl::getASTMutationListener() const {
337 return getASTContext().getASTMutationListener();
338}
339
Benjamin Kramerea70eb32012-12-01 15:09:41 +0000340unsigned Decl::getMaxAlignment() const {
341 if (!hasAttrs())
342 return 0;
343
344 unsigned Align = 0;
345 const AttrVec &V = getAttrs();
346 ASTContext &Ctx = getASTContext();
347 specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
348 for (; I != E; ++I)
349 Align = std::max(Align, I->getAlignment(Ctx));
350 return Align;
351}
352
Vassil Vassilev928c8252016-04-28 14:13:28 +0000353bool Decl::isUsed(bool CheckUsedAttr) const {
354 const Decl *CanonD = getCanonicalDecl();
355 if (CanonD->Used)
Vassil Vassileva4d7d782016-04-27 10:46:06 +0000356 return true;
357
Vassil Vassilev928c8252016-04-28 14:13:28 +0000358 // Check for used attribute.
359 // Ask the most recent decl, since attributes accumulate in the redecl chain.
360 if (CheckUsedAttr && getMostRecentDecl()->hasAttr<UsedAttr>())
361 return true;
362
363 // The information may have not been deserialized yet. Force deserialization
364 // to complete the needed information.
365 return getMostRecentDecl()->getCanonicalDecl()->Used;
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000366}
367
Eli Friedman276dd182013-09-05 00:02:25 +0000368void Decl::markUsed(ASTContext &C) {
Vassil Vassilev928c8252016-04-28 14:13:28 +0000369 if (isUsed(false))
Eli Friedman276dd182013-09-05 00:02:25 +0000370 return;
371
372 if (C.getASTMutationListener())
373 C.getASTMutationListener()->DeclarationMarkedUsed(this);
374
Vassil Vassilev928c8252016-04-28 14:13:28 +0000375 setIsUsed();
Eli Friedman276dd182013-09-05 00:02:25 +0000376}
377
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +0000378bool Decl::isReferenced() const {
379 if (Referenced)
380 return true;
381
382 // Check redeclarations.
Aaron Ballman86c93902014-03-06 23:45:36 +0000383 for (auto I : redecls())
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +0000384 if (I->Referenced)
385 return true;
386
387 return false;
388}
389
Richard Smith3b660562016-09-26 21:27:23 +0000390bool Decl::isExported() const {
391 if (isModulePrivate())
392 return false;
393 // Namespaces are always exported.
394 if (isa<TranslationUnitDecl>(this) || isa<NamespaceDecl>(this))
395 return true;
396 // Otherwise, this is a strictly lexical check.
397 for (auto *DC = getLexicalDeclContext(); DC; DC = DC->getLexicalParent()) {
398 if (cast<Decl>(DC)->isModulePrivate())
399 return false;
400 if (isa<ExportDecl>(DC))
401 return true;
402 }
403 return false;
404}
405
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000406bool Decl::hasDefiningAttr() const {
407 return hasAttr<AliasAttr>() || hasAttr<IFuncAttr>();
408}
409
410const Attr *Decl::getDefiningAttr() const {
411 if (AliasAttr *AA = getAttr<AliasAttr>())
412 return AA;
413 if (IFuncAttr *IFA = getAttr<IFuncAttr>())
414 return IFA;
415 return nullptr;
416}
417
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000418/// \brief Determine the availability of the given declaration based on
419/// the target platform.
420///
421/// When it returns an availability result other than \c AR_Available,
422/// if the \p Message parameter is non-NULL, it will be set to a
423/// string describing why the entity is unavailable.
424///
425/// FIXME: Make these strings localizable, since they end up in
426/// diagnostics.
427static AvailabilityResult CheckAvailability(ASTContext &Context,
428 const AvailabilityAttr *A,
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000429 std::string *Message,
430 VersionTuple EnclosingVersion) {
431 if (EnclosingVersion.empty())
432 EnclosingVersion = Context.getTargetInfo().getPlatformMinVersion();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000433
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000434 if (EnclosingVersion.empty())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000435 return AR_Available;
436
Bob Wilsonb111ec92015-03-02 19:01:14 +0000437 // Check if this is an App Extension "platform", and if so chop off
438 // the suffix for matching with the actual platform.
439 StringRef ActualPlatform = A->getPlatform()->getName();
440 StringRef RealizedPlatform = ActualPlatform;
441 if (Context.getLangOpts().AppExt) {
442 size_t suffix = RealizedPlatform.rfind("_app_extension");
443 if (suffix != StringRef::npos)
444 RealizedPlatform = RealizedPlatform.slice(0, suffix);
445 }
446
447 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
448
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000449 // Match the platform name.
Bob Wilsonb111ec92015-03-02 19:01:14 +0000450 if (RealizedPlatform != TargetPlatform)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000451 return AR_Available;
Bob Wilsonb111ec92015-03-02 19:01:14 +0000452
453 StringRef PrettyPlatformName
454 = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
455
456 if (PrettyPlatformName.empty())
457 PrettyPlatformName = ActualPlatform;
458
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000459 std::string HintMessage;
460 if (!A->getMessage().empty()) {
461 HintMessage = " - ";
462 HintMessage += A->getMessage();
463 }
464
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000465 // Make sure that this declaration has not been marked 'unavailable'.
466 if (A->getUnavailable()) {
467 if (Message) {
468 Message->clear();
469 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000470 Out << "not available on " << PrettyPlatformName
471 << HintMessage;
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000472 }
473
474 return AR_Unavailable;
475 }
476
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000477 // Make sure that this declaration has already been introduced.
478 if (!A->getIntroduced().empty() &&
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000479 EnclosingVersion < A->getIntroduced()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000480 if (Message) {
481 Message->clear();
482 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000483 VersionTuple VTI(A->getIntroduced());
484 VTI.UseDotAsSeparator();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000485 Out << "introduced in " << PrettyPlatformName << ' '
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000486 << VTI << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000487 }
488
Duncan P. N. Exon Smith5d6790c2016-03-08 06:12:54 +0000489 return A->getStrict() ? AR_Unavailable : AR_NotYetIntroduced;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000490 }
491
492 // Make sure that this declaration hasn't been obsoleted.
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000493 if (!A->getObsoleted().empty() && EnclosingVersion >= A->getObsoleted()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000494 if (Message) {
495 Message->clear();
496 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000497 VersionTuple VTO(A->getObsoleted());
498 VTO.UseDotAsSeparator();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000499 Out << "obsoleted in " << PrettyPlatformName << ' '
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000500 << VTO << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000501 }
502
503 return AR_Unavailable;
504 }
505
506 // Make sure that this declaration hasn't been deprecated.
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000507 if (!A->getDeprecated().empty() && EnclosingVersion >= A->getDeprecated()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000508 if (Message) {
509 Message->clear();
510 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000511 VersionTuple VTD(A->getDeprecated());
512 VTD.UseDotAsSeparator();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000513 Out << "first deprecated in " << PrettyPlatformName << ' '
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000514 << VTD << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000515 }
516
517 return AR_Deprecated;
518 }
519
520 return AR_Available;
521}
522
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000523AvailabilityResult Decl::getAvailability(std::string *Message,
524 VersionTuple EnclosingVersion) const {
Duncan P. N. Exon Smithec599a92016-02-26 19:27:00 +0000525 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000526 return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion);
Duncan P. N. Exon Smithec599a92016-02-26 19:27:00 +0000527
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000528 AvailabilityResult Result = AR_Available;
529 std::string ResultMessage;
530
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000531 for (const auto *A : attrs()) {
532 if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000533 if (Result >= AR_Deprecated)
534 continue;
535
536 if (Message)
537 ResultMessage = Deprecated->getMessage();
538
539 Result = AR_Deprecated;
540 continue;
541 }
542
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000543 if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000544 if (Message)
545 *Message = Unavailable->getMessage();
546 return AR_Unavailable;
547 }
548
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000549 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000550 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000551 Message, EnclosingVersion);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000552
553 if (AR == AR_Unavailable)
554 return AR_Unavailable;
555
556 if (AR > Result) {
557 Result = AR;
558 if (Message)
559 ResultMessage.swap(*Message);
560 }
561 continue;
562 }
563 }
564
565 if (Message)
566 Message->swap(ResultMessage);
567 return Result;
568}
569
570bool Decl::canBeWeakImported(bool &IsDefinition) const {
571 IsDefinition = false;
John McCall5fb5df92012-06-20 06:18:46 +0000572
573 // Variables, if they aren't definitions.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000574 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000575 if (Var->isThisDeclarationADefinition()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000576 IsDefinition = true;
577 return false;
578 }
John McCall5fb5df92012-06-20 06:18:46 +0000579 return true;
580
581 // Functions, if they aren't definitions.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000582 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
583 if (FD->hasBody()) {
584 IsDefinition = true;
585 return false;
586 }
John McCall5fb5df92012-06-20 06:18:46 +0000587 return true;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000588
John McCall5fb5df92012-06-20 06:18:46 +0000589 // Objective-C classes, if this is the non-fragile runtime.
590 } else if (isa<ObjCInterfaceDecl>(this) &&
John McCall18ac1632012-06-20 21:58:02 +0000591 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
John McCall5fb5df92012-06-20 06:18:46 +0000592 return true;
593
594 // Nothing else.
595 } else {
596 return false;
597 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000598}
599
600bool Decl::isWeakImported() const {
601 bool IsDefinition;
602 if (!canBeWeakImported(IsDefinition))
603 return false;
604
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000605 for (const auto *A : attrs()) {
606 if (isa<WeakImportAttr>(A))
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000607 return true;
608
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000609 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000610 if (CheckAvailability(getASTContext(), Availability, nullptr,
611 VersionTuple()) == AR_NotYetIntroduced)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000612 return true;
613 }
614 }
615
616 return false;
617}
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000618
Chris Lattner8e097192009-03-27 20:18:19 +0000619unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
620 switch (DeclKind) {
John McCall3f746822009-11-17 05:59:44 +0000621 case Function:
622 case CXXMethod:
623 case CXXConstructor:
Richard Smith5179eb72016-06-28 19:03:57 +0000624 case ConstructorUsingShadow:
John McCall3f746822009-11-17 05:59:44 +0000625 case CXXDestructor:
626 case CXXConversion:
Chris Lattner8e097192009-03-27 20:18:19 +0000627 case EnumConstant:
628 case Var:
Richard Smithbdb84f32016-07-22 23:36:59 +0000629 case Binding:
Chris Lattner8e097192009-03-27 20:18:19 +0000630 case ImplicitParam:
631 case ParmVar:
Chris Lattner8e097192009-03-27 20:18:19 +0000632 case ObjCMethod:
Daniel Dunbar45b2d8a2010-04-23 13:07:39 +0000633 case ObjCProperty:
John McCall5e77d762013-04-16 07:28:30 +0000634 case MSProperty:
Daniel Dunbar45b2d8a2010-04-23 13:07:39 +0000635 return IDNS_Ordinary;
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000636 case Label:
637 return IDNS_Label;
Francois Pichet783dd6e2010-11-21 06:08:52 +0000638 case IndirectField:
639 return IDNS_Ordinary | IDNS_Member;
640
Richard Smith9f951822016-01-06 22:49:11 +0000641 case NonTypeTemplateParm:
642 // Non-type template parameters are not found by lookups that ignore
643 // non-types, but they are found by redeclaration lookups for tag types,
644 // so we include them in the tag namespace.
645 return IDNS_Ordinary | IDNS_Tag;
646
John McCalle87beb22010-04-23 18:46:30 +0000647 case ObjCCompatibleAlias:
648 case ObjCInterface:
649 return IDNS_Ordinary | IDNS_Type;
650
651 case Typedef:
Richard Smithdda56e42011-04-15 14:24:37 +0000652 case TypeAlias:
Richard Smith3f1b5d02011-05-05 21:57:07 +0000653 case TypeAliasTemplate:
John McCalle87beb22010-04-23 18:46:30 +0000654 case UnresolvedUsingTypename:
655 case TemplateTypeParm:
Douglas Gregor85f3f952015-07-07 03:57:15 +0000656 case ObjCTypeParam:
John McCalle87beb22010-04-23 18:46:30 +0000657 return IDNS_Ordinary | IDNS_Type;
658
John McCall3f746822009-11-17 05:59:44 +0000659 case UsingShadow:
660 return 0; // we'll actually overwrite this later
661
John McCalle61f2ba2009-11-18 02:36:19 +0000662 case UnresolvedUsingValue:
John McCalle61f2ba2009-11-18 02:36:19 +0000663 return IDNS_Ordinary | IDNS_Using;
John McCall3f746822009-11-17 05:59:44 +0000664
665 case Using:
666 return IDNS_Using;
667
Chris Lattner8e097192009-03-27 20:18:19 +0000668 case ObjCProtocol:
Douglas Gregor79947a22009-04-24 00:11:27 +0000669 return IDNS_ObjCProtocol;
Mike Stump11289f42009-09-09 15:08:12 +0000670
Chris Lattner8e097192009-03-27 20:18:19 +0000671 case Field:
672 case ObjCAtDefsField:
673 case ObjCIvar:
674 return IDNS_Member;
Mike Stump11289f42009-09-09 15:08:12 +0000675
Chris Lattner8e097192009-03-27 20:18:19 +0000676 case Record:
677 case CXXRecord:
678 case Enum:
John McCalle87beb22010-04-23 18:46:30 +0000679 return IDNS_Tag | IDNS_Type;
Mike Stump11289f42009-09-09 15:08:12 +0000680
Chris Lattner8e097192009-03-27 20:18:19 +0000681 case Namespace:
John McCalle87beb22010-04-23 18:46:30 +0000682 case NamespaceAlias:
683 return IDNS_Namespace;
684
Chris Lattner8e097192009-03-27 20:18:19 +0000685 case FunctionTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +0000686 case VarTemplate:
John McCalle87beb22010-04-23 18:46:30 +0000687 return IDNS_Ordinary;
688
Chris Lattner8e097192009-03-27 20:18:19 +0000689 case ClassTemplate:
690 case TemplateTemplateParm:
John McCalle87beb22010-04-23 18:46:30 +0000691 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
Mike Stump11289f42009-09-09 15:08:12 +0000692
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000693 case OMPDeclareReduction:
694 return IDNS_OMPReduction;
695
Chris Lattner8e097192009-03-27 20:18:19 +0000696 // Never have names.
John McCallaa74a0c2009-08-28 07:59:38 +0000697 case Friend:
John McCall11083da2009-09-16 22:47:08 +0000698 case FriendTemplate:
Abramo Bagnarad7340582010-06-05 05:09:32 +0000699 case AccessSpec:
Chris Lattner8e097192009-03-27 20:18:19 +0000700 case LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +0000701 case Export:
Chris Lattner8e097192009-03-27 20:18:19 +0000702 case FileScopeAsm:
703 case StaticAssert:
Chris Lattner8e097192009-03-27 20:18:19 +0000704 case ObjCPropertyImpl:
Nico Weber66220292016-03-02 17:28:48 +0000705 case PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +0000706 case PragmaDetectMismatch:
Chris Lattner8e097192009-03-27 20:18:19 +0000707 case Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +0000708 case Captured:
Chris Lattner8e097192009-03-27 20:18:19 +0000709 case TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +0000710 case ExternCContext:
Richard Smithbdb84f32016-07-22 23:36:59 +0000711 case Decomposition:
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000712
Chris Lattner8e097192009-03-27 20:18:19 +0000713 case UsingDirective:
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000714 case BuiltinTemplate:
Chris Lattner8e097192009-03-27 20:18:19 +0000715 case ClassTemplateSpecialization:
Douglas Gregor2373c592009-05-31 09:31:02 +0000716 case ClassTemplatePartialSpecialization:
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000717 case ClassScopeFunctionSpecialization:
Larisse Voufo39a1e502013-08-06 01:03:05 +0000718 case VarTemplateSpecialization:
719 case VarTemplatePartialSpecialization:
Douglas Gregore93525e2010-04-22 23:19:50 +0000720 case ObjCImplementation:
721 case ObjCCategory:
722 case ObjCCategoryImpl:
Douglas Gregorba345522011-12-02 23:23:56 +0000723 case Import:
Alexey Bataeva769e072013-03-22 06:34:35 +0000724 case OMPThreadPrivate:
Alexey Bataev4244be22016-02-11 05:35:55 +0000725 case OMPCapturedExpr:
Michael Han84324352013-02-22 17:15:32 +0000726 case Empty:
Douglas Gregore93525e2010-04-22 23:19:50 +0000727 // Never looked up by name.
Chris Lattner8e097192009-03-27 20:18:19 +0000728 return 0;
729 }
John McCall3f746822009-11-17 05:59:44 +0000730
David Blaikiee4d798f2012-01-20 21:50:17 +0000731 llvm_unreachable("Invalid DeclKind!");
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000732}
733
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000734void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
Argyrios Kyrtzidis91167172010-06-11 23:09:25 +0000735 assert(!HasAttrs && "Decl already contains attrs.");
736
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000737 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000738 assert(AttrBlank.empty() && "HasAttrs was wrong?");
Argyrios Kyrtzidis91167172010-06-11 23:09:25 +0000739
740 AttrBlank = attrs;
741 HasAttrs = true;
742}
743
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000744void Decl::dropAttrs() {
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000745 if (!HasAttrs) return;
Mike Stump11289f42009-09-09 15:08:12 +0000746
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000747 HasAttrs = false;
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000748 getASTContext().eraseDeclAttrs(this);
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000749}
750
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000751const AttrVec &Decl::getAttrs() const {
752 assert(HasAttrs && "No attrs to get!");
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000753 return getASTContext().getDeclAttrs(this);
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000754}
755
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000756Decl *Decl::castFromDeclContext (const DeclContext *D) {
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000757 Decl::Kind DK = D->getDeclKind();
758 switch(DK) {
Alexis Hunted053252010-05-30 07:21:58 +0000759#define DECL(NAME, BASE)
760#define DECL_CONTEXT(NAME) \
761 case Decl::NAME: \
762 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
763#define DECL_CONTEXT_BASE(NAME)
764#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000765 default:
Alexis Hunted053252010-05-30 07:21:58 +0000766#define DECL(NAME, BASE)
767#define DECL_CONTEXT_BASE(NAME) \
768 if (DK >= first##NAME && DK <= last##NAME) \
769 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
770#include "clang/AST/DeclNodes.inc"
David Blaikie83d382b2011-09-23 05:06:16 +0000771 llvm_unreachable("a decl that inherits DeclContext isn't handled");
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000772 }
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000773}
774
775DeclContext *Decl::castToDeclContext(const Decl *D) {
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000776 Decl::Kind DK = D->getKind();
777 switch(DK) {
Alexis Hunted053252010-05-30 07:21:58 +0000778#define DECL(NAME, BASE)
779#define DECL_CONTEXT(NAME) \
780 case Decl::NAME: \
781 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
782#define DECL_CONTEXT_BASE(NAME)
783#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000784 default:
Alexis Hunted053252010-05-30 07:21:58 +0000785#define DECL(NAME, BASE)
786#define DECL_CONTEXT_BASE(NAME) \
787 if (DK >= first##NAME && DK <= last##NAME) \
788 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
789#include "clang/AST/DeclNodes.inc"
David Blaikie83d382b2011-09-23 05:06:16 +0000790 llvm_unreachable("a decl that inherits DeclContext isn't handled");
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000791 }
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000792}
793
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000794SourceLocation Decl::getBodyRBrace() const {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +0000795 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
796 // FunctionDecl stores EndRangeLoc for this purpose.
797 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
798 const FunctionDecl *Definition;
799 if (FD->hasBody(Definition))
800 return Definition->getSourceRange().getEnd();
801 return SourceLocation();
802 }
803
Argyrios Kyrtzidis6fbc8fa2010-07-07 11:31:27 +0000804 if (Stmt *Body = getBody())
805 return Body->getSourceRange().getEnd();
806
807 return SourceLocation();
Sebastian Redla7b98a72009-04-26 20:35:05 +0000808}
809
Alp Tokerc1086762013-12-07 13:51:35 +0000810bool Decl::AccessDeclContextSanity() const {
Douglas Gregor4b00d3b2010-12-02 00:22:25 +0000811#ifndef NDEBUG
John McCall401982f2010-01-20 21:53:11 +0000812 // Suppress this check if any of the following hold:
813 // 1. this is the translation unit (and thus has no parent)
814 // 2. this is a template parameter (and thus doesn't belong to its context)
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000815 // 3. this is a non-type template parameter
816 // 4. the context is not a record
817 // 5. it's invalid
818 // 6. it's a C++0x static_assert.
Anders Carlssonadf36b22009-08-29 20:47:47 +0000819 if (isa<TranslationUnitDecl>(this) ||
Argyrios Kyrtzidisa45855f2010-07-02 11:55:44 +0000820 isa<TemplateTypeParmDecl>(this) ||
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000821 isa<NonTypeTemplateParmDecl>(this) ||
Douglas Gregor2b76dd92010-02-22 17:53:38 +0000822 !isa<CXXRecordDecl>(getDeclContext()) ||
Argyrios Kyrtzidis260b4a82010-09-08 21:32:35 +0000823 isInvalidDecl() ||
824 isa<StaticAssertDecl>(this) ||
825 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
826 // as DeclContext (?).
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000827 isa<ParmVarDecl>(this) ||
828 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
829 // AS_none as access specifier.
Francois Pichet09af8c32011-08-17 01:06:54 +0000830 isa<CXXRecordDecl>(this) ||
831 isa<ClassScopeFunctionSpecializationDecl>(this))
Alp Tokerc1086762013-12-07 13:51:35 +0000832 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000833
834 assert(Access != AS_none &&
Anders Carlssona28908d2009-03-25 23:38:06 +0000835 "Access specifier is AS_none inside a record decl");
Douglas Gregor4b00d3b2010-12-02 00:22:25 +0000836#endif
Alp Tokerc1086762013-12-07 13:51:35 +0000837 return true;
Anders Carlssona28908d2009-03-25 23:38:06 +0000838}
839
John McCalldec348f72013-05-03 07:33:41 +0000840static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
841static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
842
Aaron Ballman12b9f652014-01-16 13:55:42 +0000843const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
844 QualType Ty;
845 if (const ValueDecl *D = dyn_cast<ValueDecl>(this))
846 Ty = D->getType();
847 else if (const TypedefNameDecl *D = dyn_cast<TypedefNameDecl>(this))
848 Ty = D->getUnderlyingType();
849 else
Craig Topper36250ad2014-05-12 05:36:57 +0000850 return nullptr;
Aaron Ballman12b9f652014-01-16 13:55:42 +0000851
852 if (Ty->isFunctionPointerType())
853 Ty = Ty->getAs<PointerType>()->getPointeeType();
854 else if (BlocksToo && Ty->isBlockPointerType())
855 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
856
857 return Ty->getAs<FunctionType>();
858}
859
860
John McCalldec348f72013-05-03 07:33:41 +0000861/// Starting at a given context (a Decl or DeclContext), look for a
862/// code context that is not a closure (a lambda, block, etc.).
863template <class T> static Decl *getNonClosureContext(T *D) {
864 if (getKind(D) == Decl::CXXMethod) {
865 CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
John McCall55c0cee2013-05-03 17:11:14 +0000866 if (MD->getOverloadedOperator() == OO_Call &&
867 MD->getParent()->isLambda())
John McCalldec348f72013-05-03 07:33:41 +0000868 return getNonClosureContext(MD->getParent()->getParent());
869 return MD;
870 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
871 return FD;
872 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
873 return MD;
874 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
875 return getNonClosureContext(BD->getParent());
876 } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
877 return getNonClosureContext(CD->getParent());
878 } else {
Craig Topper36250ad2014-05-12 05:36:57 +0000879 return nullptr;
John McCalldec348f72013-05-03 07:33:41 +0000880 }
John McCallfe96e0b2011-11-06 09:01:30 +0000881}
882
John McCalldec348f72013-05-03 07:33:41 +0000883Decl *Decl::getNonClosureContext() {
884 return ::getNonClosureContext(this);
885}
John McCallb67608f2011-02-22 22:25:23 +0000886
John McCalldec348f72013-05-03 07:33:41 +0000887Decl *DeclContext::getNonClosureAncestor() {
888 return ::getNonClosureContext(this);
John McCallb67608f2011-02-22 22:25:23 +0000889}
Anders Carlssona28908d2009-03-25 23:38:06 +0000890
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000891//===----------------------------------------------------------------------===//
892// DeclContext Implementation
893//===----------------------------------------------------------------------===//
894
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000895bool DeclContext::classof(const Decl *D) {
896 switch (D->getKind()) {
Alexis Hunted053252010-05-30 07:21:58 +0000897#define DECL(NAME, BASE)
898#define DECL_CONTEXT(NAME) case Decl::NAME:
899#define DECL_CONTEXT_BASE(NAME)
900#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000901 return true;
902 default:
Alexis Hunted053252010-05-30 07:21:58 +0000903#define DECL(NAME, BASE)
904#define DECL_CONTEXT_BASE(NAME) \
905 if (D->getKind() >= Decl::first##NAME && \
906 D->getKind() <= Decl::last##NAME) \
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000907 return true;
Alexis Hunted053252010-05-30 07:21:58 +0000908#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000909 return false;
910 }
911}
912
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000913DeclContext::~DeclContext() { }
Douglas Gregor91f84212008-12-11 16:49:14 +0000914
Douglas Gregor7f737c02009-09-10 16:57:35 +0000915/// \brief Find the parent context of this context that will be
916/// used for unqualified name lookup.
917///
918/// Generally, the parent lookup context is the semantic context. However, for
919/// a friend function the parent lookup context is the lexical context, which
920/// is the class in which the friend is declared.
921DeclContext *DeclContext::getLookupParent() {
922 // FIXME: Find a better way to identify friends
923 if (isa<FunctionDecl>(this))
Sebastian Redl50c68252010-08-31 00:36:30 +0000924 if (getParent()->getRedeclContext()->isFileContext() &&
925 getLexicalParent()->getRedeclContext()->isRecord())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000926 return getLexicalParent();
927
928 return getParent();
929}
930
Sebastian Redlbd595762010-08-31 20:53:31 +0000931bool DeclContext::isInlineNamespace() const {
932 return isNamespace() &&
933 cast<NamespaceDecl>(this)->isInline();
934}
935
Richard Trieuc771d5d2014-05-28 02:16:01 +0000936bool DeclContext::isStdNamespace() const {
937 if (!isNamespace())
938 return false;
939
940 const NamespaceDecl *ND = cast<NamespaceDecl>(this);
941 if (ND->isInline()) {
942 return ND->getParent()->isStdNamespace();
943 }
944
945 if (!getParent()->getRedeclContext()->isTranslationUnit())
946 return false;
947
948 const IdentifierInfo *II = ND->getIdentifier();
949 return II && II->isStr("std");
950}
951
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000952bool DeclContext::isDependentContext() const {
953 if (isFileContext())
954 return false;
955
Douglas Gregor2373c592009-05-31 09:31:02 +0000956 if (isa<ClassTemplatePartialSpecializationDecl>(this))
957 return true;
958
Douglas Gregor680e9e02012-02-21 19:11:17 +0000959 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000960 if (Record->getDescribedClassTemplate())
961 return true;
Douglas Gregor680e9e02012-02-21 19:11:17 +0000962
963 if (Record->isDependentLambda())
964 return true;
965 }
966
John McCallc62bb642010-03-24 05:22:00 +0000967 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000968 if (Function->getDescribedFunctionTemplate())
969 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000970
John McCallc62bb642010-03-24 05:22:00 +0000971 // Friend function declarations are dependent if their *lexical*
972 // context is dependent.
973 if (cast<Decl>(this)->getFriendObjectKind())
974 return getLexicalParent()->isDependentContext();
975 }
976
Richard Smith2b560572015-02-07 03:11:11 +0000977 // FIXME: A variable template is a dependent context, but is not a
978 // DeclContext. A context within it (such as a lambda-expression)
979 // should be considered dependent.
980
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000981 return getParent() && getParent()->isDependentContext();
982}
983
Douglas Gregor07665a62009-01-05 19:45:36 +0000984bool DeclContext::isTransparentContext() const {
985 if (DeclKind == Decl::Enum)
Douglas Gregor0bf31402010-10-08 23:50:27 +0000986 return !cast<EnumDecl>(this)->isScoped();
Richard Smith8df390f2016-09-08 23:14:54 +0000987 else if (DeclKind == Decl::LinkageSpec || DeclKind == Decl::Export)
Douglas Gregor07665a62009-01-05 19:45:36 +0000988 return true;
Douglas Gregor07665a62009-01-05 19:45:36 +0000989
990 return false;
991}
992
Serge Pavlov3cb80222013-11-14 02:13:03 +0000993static bool isLinkageSpecContext(const DeclContext *DC,
994 LinkageSpecDecl::LanguageIDs ID) {
995 while (DC->getDeclKind() != Decl::TranslationUnit) {
996 if (DC->getDeclKind() == Decl::LinkageSpec)
997 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
Richard Smithac9c9a02014-04-14 20:23:58 +0000998 DC = DC->getLexicalParent();
Serge Pavlov3cb80222013-11-14 02:13:03 +0000999 }
1000 return false;
1001}
1002
1003bool DeclContext::isExternCContext() const {
1004 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_c);
1005}
1006
Alex Lorenz560ae562016-11-02 15:46:34 +00001007const LinkageSpecDecl *DeclContext::getExternCContext() const {
1008 const DeclContext *DC = this;
1009 while (DC->getDeclKind() != Decl::TranslationUnit) {
1010 if (DC->getDeclKind() == Decl::LinkageSpec &&
1011 cast<LinkageSpecDecl>(DC)->getLanguage() ==
1012 clang::LinkageSpecDecl::lang_c)
1013 return cast<LinkageSpecDecl>(DC);
1014 DC = DC->getLexicalParent();
1015 }
1016 return nullptr;
1017}
1018
Serge Pavlov3cb80222013-11-14 02:13:03 +00001019bool DeclContext::isExternCXXContext() const {
1020 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_cxx);
1021}
1022
Sebastian Redl50c68252010-08-31 00:36:30 +00001023bool DeclContext::Encloses(const DeclContext *DC) const {
Douglas Gregore985a3b2009-08-27 06:03:53 +00001024 if (getPrimaryContext() != this)
1025 return getPrimaryContext()->Encloses(DC);
Mike Stump11289f42009-09-09 15:08:12 +00001026
Douglas Gregore985a3b2009-08-27 06:03:53 +00001027 for (; DC; DC = DC->getParent())
1028 if (DC->getPrimaryContext() == this)
1029 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001030 return false;
Douglas Gregore985a3b2009-08-27 06:03:53 +00001031}
1032
Steve Naroff35c62ae2009-01-08 17:28:14 +00001033DeclContext *DeclContext::getPrimaryContext() {
Douglas Gregor91f84212008-12-11 16:49:14 +00001034 switch (DeclKind) {
Douglas Gregor91f84212008-12-11 16:49:14 +00001035 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00001036 case Decl::ExternCContext:
Douglas Gregor07665a62009-01-05 19:45:36 +00001037 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00001038 case Decl::Export:
Mike Stump11289f42009-09-09 15:08:12 +00001039 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001040 case Decl::Captured:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001041 case Decl::OMPDeclareReduction:
Douglas Gregor91f84212008-12-11 16:49:14 +00001042 // There is only one DeclContext for these entities.
1043 return this;
1044
1045 case Decl::Namespace:
1046 // The original namespace is our primary context.
1047 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
1048
Douglas Gregor91f84212008-12-11 16:49:14 +00001049 case Decl::ObjCMethod:
1050 return this;
1051
1052 case Decl::ObjCInterface:
Douglas Gregor66b310c2011-12-15 18:03:09 +00001053 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
1054 return Def;
1055
1056 return this;
1057
Steve Naroff35c62ae2009-01-08 17:28:14 +00001058 case Decl::ObjCProtocol:
Douglas Gregora715bff2012-01-01 19:51:50 +00001059 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
1060 return Def;
1061
1062 return this;
Douglas Gregor66b310c2011-12-15 18:03:09 +00001063
Steve Naroff35c62ae2009-01-08 17:28:14 +00001064 case Decl::ObjCCategory:
Douglas Gregor91f84212008-12-11 16:49:14 +00001065 return this;
1066
Steve Naroff35c62ae2009-01-08 17:28:14 +00001067 case Decl::ObjCImplementation:
1068 case Decl::ObjCCategoryImpl:
1069 return this;
1070
Douglas Gregor91f84212008-12-11 16:49:14 +00001071 default:
Alexis Hunted053252010-05-30 07:21:58 +00001072 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
Douglas Gregor67a65642009-02-17 23:15:12 +00001073 // If this is a tag type that has a definition or is currently
1074 // being defined, that definition is our primary context.
John McCalle78aac42010-03-10 03:28:59 +00001075 TagDecl *Tag = cast<TagDecl>(this);
John McCalle78aac42010-03-10 03:28:59 +00001076
1077 if (TagDecl *Def = Tag->getDefinition())
1078 return Def;
1079
Richard Smith5b21db82014-04-23 18:20:42 +00001080 if (const TagType *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
1081 // Note, TagType::getDecl returns the (partial) definition one exists.
1082 TagDecl *PossiblePartialDef = TagTy->getDecl();
1083 if (PossiblePartialDef->isBeingDefined())
1084 return PossiblePartialDef;
1085 } else {
1086 assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
John McCalle78aac42010-03-10 03:28:59 +00001087 }
1088
1089 return Tag;
Douglas Gregor67a65642009-02-17 23:15:12 +00001090 }
1091
Alexis Hunted053252010-05-30 07:21:58 +00001092 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
Douglas Gregor91f84212008-12-11 16:49:14 +00001093 "Unknown DeclContext kind");
1094 return this;
1095 }
1096}
1097
Douglas Gregore57e7522012-01-07 09:11:48 +00001098void
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001099DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
Douglas Gregore57e7522012-01-07 09:11:48 +00001100 Contexts.clear();
1101
1102 if (DeclKind != Decl::Namespace) {
1103 Contexts.push_back(this);
1104 return;
Douglas Gregor91f84212008-12-11 16:49:14 +00001105 }
Douglas Gregore57e7522012-01-07 09:11:48 +00001106
1107 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
Douglas Gregorec9fd132012-01-14 16:38:05 +00001108 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
1109 N = N->getPreviousDecl())
Douglas Gregore57e7522012-01-07 09:11:48 +00001110 Contexts.push_back(N);
1111
1112 std::reverse(Contexts.begin(), Contexts.end());
Douglas Gregor91f84212008-12-11 16:49:14 +00001113}
1114
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001115std::pair<Decl *, Decl *>
Bill Wendling8eb771d2012-02-22 09:51:33 +00001116DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00001117 bool FieldsAlreadyLoaded) {
Douglas Gregor781f7132012-01-06 16:59:53 +00001118 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
Craig Topper36250ad2014-05-12 05:36:57 +00001119 Decl *FirstNewDecl = nullptr;
1120 Decl *PrevDecl = nullptr;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001121 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00001122 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
1123 continue;
1124
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001125 Decl *D = Decls[I];
1126 if (PrevDecl)
Douglas Gregor781f7132012-01-06 16:59:53 +00001127 PrevDecl->NextInContextAndBits.setPointer(D);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001128 else
1129 FirstNewDecl = D;
1130
1131 PrevDecl = D;
1132 }
1133
1134 return std::make_pair(FirstNewDecl, PrevDecl);
1135}
1136
Richard Smith645d7552013-02-07 03:37:08 +00001137/// \brief We have just acquired external visible storage, and we already have
1138/// built a lookup map. For every name in the map, pull in the new names from
1139/// the external storage.
Richard Smitha8b74592014-03-25 00:34:21 +00001140void DeclContext::reconcileExternalVisibleStorage() const {
Richard Smith9e2341d2015-03-23 03:25:59 +00001141 assert(NeedToReconcileExternalVisibleStorage && LookupPtr);
Richard Smith645d7552013-02-07 03:37:08 +00001142 NeedToReconcileExternalVisibleStorage = false;
1143
Richard Smith9e2341d2015-03-23 03:25:59 +00001144 for (auto &Lookup : *LookupPtr)
Richard Smitha8b74592014-03-25 00:34:21 +00001145 Lookup.second.setHasExternalDecls();
Richard Smith645d7552013-02-07 03:37:08 +00001146}
1147
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001148/// \brief Load the declarations within this lexical storage from an
1149/// external source.
Richard Smith18b380b2015-03-24 02:44:20 +00001150/// \return \c true if any declarations were added.
1151bool
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001152DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1153 ExternalASTSource *Source = getParentASTContext().getExternalSource();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001154 assert(hasExternalLexicalStorage() && Source && "No external storage?");
1155
Argyrios Kyrtzidis98d045e2010-07-30 10:03:23 +00001156 // Notify that we have a DeclContext that is initializing.
1157 ExternalASTSource::Deserializing ADeclContext(Source);
Richard Smith9e2341d2015-03-23 03:25:59 +00001158
Douglas Gregor3d0adb32011-07-15 21:46:17 +00001159 // Load the external declarations, if any.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001160 SmallVector<Decl*, 64> Decls;
Richard Smith18b380b2015-03-24 02:44:20 +00001161 ExternalLexicalStorage = false;
Richard Smith3cb15722015-08-05 22:41:45 +00001162 Source->FindExternalLexicalDecls(this, Decls);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001163
1164 if (Decls.empty())
Richard Smith18b380b2015-03-24 02:44:20 +00001165 return false;
Richard Smith9e2341d2015-03-23 03:25:59 +00001166
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00001167 // We may have already loaded just the fields of this record, in which case
1168 // we need to ignore them.
1169 bool FieldsAlreadyLoaded = false;
1170 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
1171 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
1172
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001173 // Splice the newly-read declarations into the beginning of the list
1174 // of declarations.
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001175 Decl *ExternalFirst, *ExternalLast;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001176 std::tie(ExternalFirst, ExternalLast) =
1177 BuildDeclChain(Decls, FieldsAlreadyLoaded);
Douglas Gregor781f7132012-01-06 16:59:53 +00001178 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001179 FirstDecl = ExternalFirst;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001180 if (!LastDecl)
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001181 LastDecl = ExternalLast;
Richard Smith18b380b2015-03-24 02:44:20 +00001182 return true;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001183}
1184
John McCall75b960e2010-06-01 09:23:16 +00001185DeclContext::lookup_result
1186ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1187 DeclarationName Name) {
1188 ASTContext &Context = DC->getParentASTContext();
1189 StoredDeclsMap *Map;
Richard Smith9e2341d2015-03-23 03:25:59 +00001190 if (!(Map = DC->LookupPtr))
John McCall75b960e2010-06-01 09:23:16 +00001191 Map = DC->CreateStoredDeclsMap(Context);
Richard Smitha8b74592014-03-25 00:34:21 +00001192 if (DC->NeedToReconcileExternalVisibleStorage)
1193 DC->reconcileExternalVisibleStorage();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001194
Richard Smith4abe0a82013-09-09 07:34:56 +00001195 (*Map)[Name].removeExternalDecls();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001196
John McCall75b960e2010-06-01 09:23:16 +00001197 return DeclContext::lookup_result();
1198}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001199
John McCall75b960e2010-06-01 09:23:16 +00001200DeclContext::lookup_result
1201ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
John McCall75b960e2010-06-01 09:23:16 +00001202 DeclarationName Name,
Argyrios Kyrtzidis94d3f9d2011-09-09 06:44:14 +00001203 ArrayRef<NamedDecl*> Decls) {
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00001204 ASTContext &Context = DC->getParentASTContext();
John McCall75b960e2010-06-01 09:23:16 +00001205 StoredDeclsMap *Map;
Richard Smith9e2341d2015-03-23 03:25:59 +00001206 if (!(Map = DC->LookupPtr))
John McCall75b960e2010-06-01 09:23:16 +00001207 Map = DC->CreateStoredDeclsMap(Context);
Richard Smitha8b74592014-03-25 00:34:21 +00001208 if (DC->NeedToReconcileExternalVisibleStorage)
1209 DC->reconcileExternalVisibleStorage();
John McCall75b960e2010-06-01 09:23:16 +00001210
1211 StoredDeclsList &List = (*Map)[Name];
Richard Smith51445cd2013-06-24 01:46:41 +00001212
1213 // Clear out any old external visible declarations, to avoid quadratic
1214 // performance in the redeclaration checks below.
1215 List.removeExternalDecls();
1216
1217 if (!List.isNull()) {
1218 // We have both existing declarations and new declarations for this name.
1219 // Some of the declarations may simply replace existing ones. Handle those
1220 // first.
1221 llvm::SmallVector<unsigned, 8> Skip;
1222 for (unsigned I = 0, N = Decls.size(); I != N; ++I)
Richard Smithe8292b12015-02-10 03:28:10 +00001223 if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
Richard Smith51445cd2013-06-24 01:46:41 +00001224 Skip.push_back(I);
1225 Skip.push_back(Decls.size());
1226
1227 // Add in any new declarations.
1228 unsigned SkipPos = 0;
1229 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1230 if (I == Skip[SkipPos])
1231 ++SkipPos;
1232 else
1233 List.AddSubsequentDecl(Decls[I]);
1234 }
1235 } else {
1236 // Convert the array to a StoredDeclsList.
1237 for (ArrayRef<NamedDecl*>::iterator
1238 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1239 if (List.isNull())
1240 List.setOnlyValue(*I);
1241 else
1242 List.AddSubsequentDecl(*I);
1243 }
John McCall75b960e2010-06-01 09:23:16 +00001244 }
1245
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001246 return List.getLookupResult();
John McCall75b960e2010-06-01 09:23:16 +00001247}
1248
Aaron Ballmanda634f12014-03-07 22:17:20 +00001249DeclContext::decl_iterator DeclContext::decls_begin() const {
1250 if (hasExternalLexicalStorage())
1251 LoadLexicalDeclsFromExternalStorage();
1252 return decl_iterator(FirstDecl);
1253}
1254
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001255bool DeclContext::decls_empty() const {
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001256 if (hasExternalLexicalStorage())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001257 LoadLexicalDeclsFromExternalStorage();
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001258
1259 return !FirstDecl;
1260}
1261
Sean Callanan0325fb82013-05-04 02:04:27 +00001262bool DeclContext::containsDecl(Decl *D) const {
1263 return (D->getLexicalDeclContext() == this &&
1264 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1265}
1266
John McCall84d87672009-12-10 09:41:52 +00001267void DeclContext::removeDecl(Decl *D) {
1268 assert(D->getLexicalDeclContext() == this &&
1269 "decl being removed from non-lexical context");
Douglas Gregor781f7132012-01-06 16:59:53 +00001270 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
John McCall84d87672009-12-10 09:41:52 +00001271 "decl is not in decls list");
1272
1273 // Remove D from the decl chain. This is O(n) but hopefully rare.
1274 if (D == FirstDecl) {
1275 if (D == LastDecl)
Craig Topper36250ad2014-05-12 05:36:57 +00001276 FirstDecl = LastDecl = nullptr;
John McCall84d87672009-12-10 09:41:52 +00001277 else
Douglas Gregor781f7132012-01-06 16:59:53 +00001278 FirstDecl = D->NextInContextAndBits.getPointer();
John McCall84d87672009-12-10 09:41:52 +00001279 } else {
Douglas Gregor781f7132012-01-06 16:59:53 +00001280 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
John McCall84d87672009-12-10 09:41:52 +00001281 assert(I && "decl not found in linked list");
Douglas Gregor781f7132012-01-06 16:59:53 +00001282 if (I->NextInContextAndBits.getPointer() == D) {
1283 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
John McCall84d87672009-12-10 09:41:52 +00001284 if (D == LastDecl) LastDecl = I;
1285 break;
1286 }
1287 }
1288 }
1289
1290 // Mark that D is no longer in the decl chain.
Craig Topper36250ad2014-05-12 05:36:57 +00001291 D->NextInContextAndBits.setPointer(nullptr);
John McCall84d87672009-12-10 09:41:52 +00001292
1293 // Remove D from the lookup table if necessary.
1294 if (isa<NamedDecl>(D)) {
1295 NamedDecl *ND = cast<NamedDecl>(D);
1296
Axel Naumanncb2c52f2011-08-26 14:06:12 +00001297 // Remove only decls that have a name
1298 if (!ND->getDeclName()) return;
1299
Richard Smith26210db2015-11-13 03:52:13 +00001300 auto *DC = this;
1301 do {
1302 StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1303 if (Map) {
1304 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1305 assert(Pos != Map->end() && "no lookup entry for decl");
1306 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1307 Pos->second.remove(ND);
1308 }
1309 } while (DC->isTransparentContext() && (DC = DC->getParent()));
John McCall84d87672009-12-10 09:41:52 +00001310 }
1311}
1312
John McCalld1e9d832009-08-11 06:59:38 +00001313void DeclContext::addHiddenDecl(Decl *D) {
Chris Lattner33f219d2009-02-20 00:56:18 +00001314 assert(D->getLexicalDeclContext() == this &&
1315 "Decl inserted into wrong lexical context");
Mike Stump11289f42009-09-09 15:08:12 +00001316 assert(!D->getNextDeclInContext() && D != LastDecl &&
Douglas Gregor020713e2009-01-09 19:42:16 +00001317 "Decl already inserted into a DeclContext");
1318
1319 if (FirstDecl) {
Douglas Gregor781f7132012-01-06 16:59:53 +00001320 LastDecl->NextInContextAndBits.setPointer(D);
Douglas Gregor020713e2009-01-09 19:42:16 +00001321 LastDecl = D;
1322 } else {
1323 FirstDecl = LastDecl = D;
1324 }
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001325
1326 // Notify a C++ record declaration that we've added a member, so it can
Nick Lewycky4b81fc872015-10-18 20:32:12 +00001327 // update its class-specific state.
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001328 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1329 Record->addedMember(D);
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001330
1331 // If this is a newly-created (not de-serialized) import declaration, wire
1332 // it in to the list of local import declarations.
1333 if (!D->isFromASTFile()) {
1334 if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1335 D->getASTContext().addedLocalImportDecl(Import);
1336 }
John McCalld1e9d832009-08-11 06:59:38 +00001337}
1338
1339void DeclContext::addDecl(Decl *D) {
1340 addHiddenDecl(D);
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001341
1342 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithf634c902012-03-16 06:12:59 +00001343 ND->getDeclContext()->getPrimaryContext()->
1344 makeDeclVisibleInContextWithFlags(ND, false, true);
Douglas Gregor91f84212008-12-11 16:49:14 +00001345}
1346
Sean Callanan95e74be2011-10-21 02:57:43 +00001347void DeclContext::addDeclInternal(Decl *D) {
1348 addHiddenDecl(D);
1349
1350 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithf634c902012-03-16 06:12:59 +00001351 ND->getDeclContext()->getPrimaryContext()->
1352 makeDeclVisibleInContextWithFlags(ND, true, true);
1353}
1354
1355/// shouldBeHidden - Determine whether a declaration which was declared
1356/// within its semantic context should be invisible to qualified name lookup.
1357static bool shouldBeHidden(NamedDecl *D) {
1358 // Skip unnamed declarations.
1359 if (!D->getDeclName())
1360 return true;
1361
1362 // Skip entities that can't be found by name lookup into a particular
1363 // context.
1364 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1365 D->isTemplateParameter())
1366 return true;
1367
1368 // Skip template specializations.
1369 // FIXME: This feels like a hack. Should DeclarationName support
1370 // template-ids, or is there a better way to keep specializations
1371 // from being visible?
1372 if (isa<ClassTemplateSpecializationDecl>(D))
1373 return true;
1374 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1375 if (FD->isFunctionTemplateSpecialization())
1376 return true;
1377
1378 return false;
1379}
1380
1381/// buildLookup - Build the lookup data structure with all of the
1382/// declarations in this DeclContext (and any other contexts linked
1383/// to it or transparent contexts nested within it) and return it.
Richard Smitha8b74592014-03-25 00:34:21 +00001384///
1385/// Note that the produced map may miss out declarations from an
1386/// external source. If it does, those entries will be marked with
1387/// the 'hasExternalDecls' flag.
Richard Smithf634c902012-03-16 06:12:59 +00001388StoredDeclsMap *DeclContext::buildLookup() {
1389 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1390
Richard Smith9e2341d2015-03-23 03:25:59 +00001391 if (!HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups)
1392 return LookupPtr;
1393
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001394 SmallVector<DeclContext *, 2> Contexts;
Richard Smithf634c902012-03-16 06:12:59 +00001395 collectAllContexts(Contexts);
Richard Smith18b380b2015-03-24 02:44:20 +00001396
1397 if (HasLazyExternalLexicalLookups) {
1398 HasLazyExternalLexicalLookups = false;
1399 for (auto *DC : Contexts) {
1400 if (DC->hasExternalLexicalStorage())
1401 HasLazyLocalLexicalLookups |=
1402 DC->LoadLexicalDeclsFromExternalStorage();
1403 }
1404
1405 if (!HasLazyLocalLexicalLookups)
1406 return LookupPtr;
1407 }
1408
1409 for (auto *DC : Contexts)
1410 buildLookupImpl(DC, hasExternalVisibleStorage());
Richard Smithf634c902012-03-16 06:12:59 +00001411
1412 // We no longer have any lazy decls.
Richard Smith9e2341d2015-03-23 03:25:59 +00001413 HasLazyLocalLexicalLookups = false;
1414 return LookupPtr;
Richard Smithf634c902012-03-16 06:12:59 +00001415}
1416
1417/// buildLookupImpl - Build part of the lookup data structure for the
1418/// declarations contained within DCtx, which will either be this
1419/// DeclContext, a DeclContext linked to it, or a transparent context
1420/// nested within it.
Richard Smitha3271c12015-02-07 00:45:52 +00001421void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
Richard Smith9e2341d2015-03-23 03:25:59 +00001422 for (Decl *D : DCtx->noload_decls()) {
Richard Smithf634c902012-03-16 06:12:59 +00001423 // Insert this declaration into the lookup structure, but only if
1424 // it's semantically within its decl context. Any other decls which
1425 // should be found in this context are added eagerly.
Richard Smithcf4ab522013-06-24 07:20:36 +00001426 //
1427 // If it's from an AST file, don't add it now. It'll get handled by
1428 // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1429 // in C++, we do not track external visible decls for the TU, so in
1430 // that case we need to collect them all here.
Richard Smithf634c902012-03-16 06:12:59 +00001431 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithcf4ab522013-06-24 07:20:36 +00001432 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1433 (!ND->isFromASTFile() ||
1434 (isTranslationUnit() &&
1435 !getParentASTContext().getLangOpts().CPlusPlus)))
Richard Smitha3271c12015-02-07 00:45:52 +00001436 makeDeclVisibleInContextImpl(ND, Internal);
Richard Smithf634c902012-03-16 06:12:59 +00001437
1438 // If this declaration is itself a transparent declaration context
1439 // or inline namespace, add the members of this declaration of that
1440 // context (recursively).
1441 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1442 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Richard Smith9e2341d2015-03-23 03:25:59 +00001443 buildLookupImpl(InnerCtx, Internal);
Richard Smithf634c902012-03-16 06:12:59 +00001444 }
Sean Callanan95e74be2011-10-21 02:57:43 +00001445}
1446
Richard Smith40c78062015-02-21 02:31:57 +00001447NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1448
Mike Stump11289f42009-09-09 15:08:12 +00001449DeclContext::lookup_result
Richard Smith40c78062015-02-21 02:31:57 +00001450DeclContext::lookup(DeclarationName Name) const {
Richard Smith8df390f2016-09-08 23:14:54 +00001451 assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1452 "should not perform lookups into transparent contexts");
Nick Lewycky2bd636f2012-03-13 04:12:34 +00001453
Manman Ren7d2f5c42016-09-09 19:03:07 +00001454 const DeclContext *PrimaryContext = getPrimaryContext();
1455 if (PrimaryContext != this)
1456 return PrimaryContext->lookup(Name);
1457
Richard Smith8cebe372015-02-25 22:20:13 +00001458 // If we have an external source, ensure that any later redeclarations of this
1459 // context have been loaded, since they may add names to the result of this
1460 // lookup (or add external visible storage).
1461 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1462 if (Source)
1463 (void)cast<Decl>(this)->getMostRecentDecl();
Richard Smithbb853c72014-08-13 01:23:33 +00001464
Richard Smith05afe5e2012-03-13 03:12:56 +00001465 if (hasExternalVisibleStorage()) {
Richard Smith8cebe372015-02-25 22:20:13 +00001466 assert(Source && "external visible storage but no external source?");
1467
Richard Smitha8b74592014-03-25 00:34:21 +00001468 if (NeedToReconcileExternalVisibleStorage)
1469 reconcileExternalVisibleStorage();
1470
Richard Smith9e2341d2015-03-23 03:25:59 +00001471 StoredDeclsMap *Map = LookupPtr;
Richard Smitha8b74592014-03-25 00:34:21 +00001472
Richard Smith9e2341d2015-03-23 03:25:59 +00001473 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
Richard Smith40c78062015-02-21 02:31:57 +00001474 // FIXME: Make buildLookup const?
1475 Map = const_cast<DeclContext*>(this)->buildLookup();
Richard Smith645d7552013-02-07 03:37:08 +00001476
Richard Smith75fc3bf2013-02-08 00:37:45 +00001477 if (!Map)
1478 Map = CreateStoredDeclsMap(getParentASTContext());
1479
Richard Smith4abe0a82013-09-09 07:34:56 +00001480 // If we have a lookup result with no external decls, we are done.
Richard Smith75fc3bf2013-02-08 00:37:45 +00001481 std::pair<StoredDeclsMap::iterator, bool> R =
1482 Map->insert(std::make_pair(Name, StoredDeclsList()));
Richard Smith4abe0a82013-09-09 07:34:56 +00001483 if (!R.second && !R.first->second.hasExternalDecls())
Richard Smith75fc3bf2013-02-08 00:37:45 +00001484 return R.first->second.getLookupResult();
Richard Smithf634c902012-03-16 06:12:59 +00001485
Richard Smith309271b2014-03-04 00:21:14 +00001486 if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
Richard Smith9e2341d2015-03-23 03:25:59 +00001487 if (StoredDeclsMap *Map = LookupPtr) {
Richard Smith9ce12e32013-02-07 03:30:24 +00001488 StoredDeclsMap::iterator I = Map->find(Name);
1489 if (I != Map->end())
1490 return I->second.getLookupResult();
1491 }
1492 }
1493
Richard Smith40c78062015-02-21 02:31:57 +00001494 return lookup_result();
John McCall75b960e2010-06-01 09:23:16 +00001495 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001496
Richard Smith9e2341d2015-03-23 03:25:59 +00001497 StoredDeclsMap *Map = LookupPtr;
1498 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
Richard Smith40c78062015-02-21 02:31:57 +00001499 Map = const_cast<DeclContext*>(this)->buildLookup();
Richard Smithf634c902012-03-16 06:12:59 +00001500
1501 if (!Map)
Richard Smith40c78062015-02-21 02:31:57 +00001502 return lookup_result();
Richard Smithf634c902012-03-16 06:12:59 +00001503
1504 StoredDeclsMap::iterator I = Map->find(Name);
1505 if (I == Map->end())
Richard Smith40c78062015-02-21 02:31:57 +00001506 return lookup_result();
Richard Smithf634c902012-03-16 06:12:59 +00001507
1508 return I->second.getLookupResult();
Douglas Gregor91f84212008-12-11 16:49:14 +00001509}
1510
Richard Smith95d99302013-07-13 02:00:19 +00001511DeclContext::lookup_result
1512DeclContext::noload_lookup(DeclarationName Name) {
Richard Smith8df390f2016-09-08 23:14:54 +00001513 assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1514 "should not perform lookups into transparent contexts");
Richard Smith95d99302013-07-13 02:00:19 +00001515
1516 DeclContext *PrimaryContext = getPrimaryContext();
1517 if (PrimaryContext != this)
1518 return PrimaryContext->noload_lookup(Name);
1519
Richard Smith9e2341d2015-03-23 03:25:59 +00001520 // If we have any lazy lexical declarations not in our lookup map, add them
1521 // now. Don't import any external declarations, not even if we know we have
1522 // some missing from the external visible lookups.
1523 if (HasLazyLocalLexicalLookups) {
Vince Harrona3ea9a42015-03-22 05:59:59 +00001524 SmallVector<DeclContext *, 2> Contexts;
1525 collectAllContexts(Contexts);
1526 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
Richard Smith9e2341d2015-03-23 03:25:59 +00001527 buildLookupImpl(Contexts[I], hasExternalVisibleStorage());
1528 HasLazyLocalLexicalLookups = false;
Vince Harrona3ea9a42015-03-22 05:59:59 +00001529 }
1530
Richard Smith9e2341d2015-03-23 03:25:59 +00001531 StoredDeclsMap *Map = LookupPtr;
Richard Smith95d99302013-07-13 02:00:19 +00001532 if (!Map)
Richard Smith40c78062015-02-21 02:31:57 +00001533 return lookup_result();
Richard Smith95d99302013-07-13 02:00:19 +00001534
1535 StoredDeclsMap::iterator I = Map->find(Name);
Craig Topper36250ad2014-05-12 05:36:57 +00001536 return I != Map->end() ? I->second.getLookupResult()
Richard Smith40c78062015-02-21 02:31:57 +00001537 : lookup_result();
Richard Smith95d99302013-07-13 02:00:19 +00001538}
1539
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001540void DeclContext::localUncachedLookup(DeclarationName Name,
1541 SmallVectorImpl<NamedDecl *> &Results) {
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001542 Results.clear();
1543
1544 // If there's no external storage, just perform a normal lookup and copy
1545 // the results.
Douglas Gregordd6006f2012-07-17 21:16:27 +00001546 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001547 lookup_result LookupResults = lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00001548 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001549 return;
1550 }
1551
1552 // If we have a lookup table, check there first. Maybe we'll get lucky.
Richard Smith9e2341d2015-03-23 03:25:59 +00001553 // FIXME: Should we be checking these flags on the primary context?
1554 if (Name && !HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups) {
1555 if (StoredDeclsMap *Map = LookupPtr) {
Douglas Gregordd6006f2012-07-17 21:16:27 +00001556 StoredDeclsMap::iterator Pos = Map->find(Name);
1557 if (Pos != Map->end()) {
1558 Results.insert(Results.end(),
David Blaikieff7d47a2012-12-19 00:45:41 +00001559 Pos->second.getLookupResult().begin(),
1560 Pos->second.getLookupResult().end());
Douglas Gregordd6006f2012-07-17 21:16:27 +00001561 return;
1562 }
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001563 }
1564 }
Douglas Gregordd6006f2012-07-17 21:16:27 +00001565
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001566 // Slow case: grovel through the declarations in our chain looking for
1567 // matches.
Richard Smith9e2341d2015-03-23 03:25:59 +00001568 // FIXME: If we have lazy external declarations, this will not find them!
1569 // FIXME: Should we CollectAllContexts and walk them all here?
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001570 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1571 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1572 if (ND->getDeclName() == Name)
1573 Results.push_back(ND);
1574 }
1575}
1576
Sebastian Redl50c68252010-08-31 00:36:30 +00001577DeclContext *DeclContext::getRedeclContext() {
Chris Lattner17a1bfa2009-03-27 19:19:59 +00001578 DeclContext *Ctx = this;
Sebastian Redlbd595762010-08-31 20:53:31 +00001579 // Skip through transparent contexts.
1580 while (Ctx->isTransparentContext())
Douglas Gregor6ad0ef52009-01-06 23:51:29 +00001581 Ctx = Ctx->getParent();
1582 return Ctx;
1583}
1584
Douglas Gregorf47b9112009-02-25 22:02:03 +00001585DeclContext *DeclContext::getEnclosingNamespaceContext() {
1586 DeclContext *Ctx = this;
1587 // Skip through non-namespace, non-translation-unit contexts.
Sebastian Redl4f08c962010-08-31 00:36:23 +00001588 while (!Ctx->isFileContext())
Douglas Gregorf47b9112009-02-25 22:02:03 +00001589 Ctx = Ctx->getParent();
1590 return Ctx->getPrimaryContext();
1591}
1592
Reid Klecknerd60b82f2014-11-17 23:36:45 +00001593RecordDecl *DeclContext::getOuterLexicalRecordContext() {
1594 // Loop until we find a non-record context.
1595 RecordDecl *OutermostRD = nullptr;
1596 DeclContext *DC = this;
1597 while (DC->isRecord()) {
1598 OutermostRD = cast<RecordDecl>(DC);
1599 DC = DC->getLexicalParent();
1600 }
1601 return OutermostRD;
1602}
1603
Sebastian Redl50c68252010-08-31 00:36:30 +00001604bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1605 // For non-file contexts, this is equivalent to Equals.
1606 if (!isFileContext())
1607 return O->Equals(this);
1608
1609 do {
1610 if (O->Equals(this))
1611 return true;
1612
1613 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1614 if (!NS || !NS->isInline())
1615 break;
1616 O = NS->getParent();
1617 } while (O);
1618
1619 return false;
1620}
1621
Richard Smithf634c902012-03-16 06:12:59 +00001622void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1623 DeclContext *PrimaryDC = this->getPrimaryContext();
1624 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1625 // If the decl is being added outside of its semantic decl context, we
1626 // need to ensure that we eagerly build the lookup information for it.
1627 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
Sean Callanan95e74be2011-10-21 02:57:43 +00001628}
1629
Richard Smithf634c902012-03-16 06:12:59 +00001630void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1631 bool Recoverable) {
1632 assert(this == getPrimaryContext() && "expected a primary DC");
Sean Callanan95e74be2011-10-21 02:57:43 +00001633
Vassil Vassilev71eafde2016-04-06 20:56:03 +00001634 if (!isLookupContext()) {
1635 if (isTransparentContext())
1636 getParent()->getPrimaryContext()
1637 ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
Richard Smith05afe5e2012-03-13 03:12:56 +00001638 return;
Vassil Vassilev71eafde2016-04-06 20:56:03 +00001639 }
Richard Smith05afe5e2012-03-13 03:12:56 +00001640
Richard Smithf634c902012-03-16 06:12:59 +00001641 // Skip declarations which should be invisible to name lookup.
1642 if (shouldBeHidden(D))
1643 return;
1644
1645 // If we already have a lookup data structure, perform the insertion into
1646 // it. If we might have externally-stored decls with this name, look them
1647 // up and perform the insertion. If this decl was declared outside its
1648 // semantic context, buildLookup won't add it, so add it now.
1649 //
1650 // FIXME: As a performance hack, don't add such decls into the translation
1651 // unit unless we're in C++, since qualified lookup into the TU is never
1652 // performed.
Richard Smith9e2341d2015-03-23 03:25:59 +00001653 if (LookupPtr || hasExternalVisibleStorage() ||
Richard Smithf634c902012-03-16 06:12:59 +00001654 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1655 (getParentASTContext().getLangOpts().CPlusPlus ||
1656 !isTranslationUnit()))) {
1657 // If we have lazily omitted any decls, they might have the same name as
1658 // the decl which we are adding, so build a full lookup table before adding
1659 // this decl.
1660 buildLookup();
1661 makeDeclVisibleInContextImpl(D, Internal);
1662 } else {
Richard Smith9e2341d2015-03-23 03:25:59 +00001663 HasLazyLocalLexicalLookups = true;
Richard Smithf634c902012-03-16 06:12:59 +00001664 }
1665
1666 // If we are a transparent context or inline namespace, insert into our
1667 // parent context, too. This operation is recursive.
1668 if (isTransparentContext() || isInlineNamespace())
1669 getParent()->getPrimaryContext()->
1670 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1671
1672 Decl *DCAsDecl = cast<Decl>(this);
1673 // Notify that a decl was made visible unless we are a Tag being defined.
1674 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1675 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1676 L->AddedVisibleDecl(this, D);
1677}
1678
1679void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1680 // Find or create the stored declaration map.
Richard Smith9e2341d2015-03-23 03:25:59 +00001681 StoredDeclsMap *Map = LookupPtr;
Richard Smithf634c902012-03-16 06:12:59 +00001682 if (!Map) {
1683 ASTContext *C = &getParentASTContext();
1684 Map = CreateStoredDeclsMap(*C);
Argyrios Kyrtzidise51e5542010-07-04 21:44:25 +00001685 }
1686
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001687 // If there is an external AST source, load any declarations it knows about
1688 // with this declaration's name.
1689 // If the lookup table contains an entry about this name it means that we
1690 // have already checked the external source.
Sean Callanan95e74be2011-10-21 02:57:43 +00001691 if (!Internal)
1692 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1693 if (hasExternalVisibleStorage() &&
Richard Smithf634c902012-03-16 06:12:59 +00001694 Map->find(D->getDeclName()) == Map->end())
Sean Callanan95e74be2011-10-21 02:57:43 +00001695 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001696
Douglas Gregor91f84212008-12-11 16:49:14 +00001697 // Insert this declaration into the map.
Richard Smithf634c902012-03-16 06:12:59 +00001698 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
Richard Smith4abe0a82013-09-09 07:34:56 +00001699
1700 if (Internal) {
1701 // If this is being added as part of loading an external declaration,
1702 // this may not be the only external declaration with this name.
1703 // In this case, we never try to replace an existing declaration; we'll
1704 // handle that when we finalize the list of declarations for this name.
1705 DeclNameEntries.setHasExternalDecls();
1706 DeclNameEntries.AddSubsequentDecl(D);
1707 return;
1708 }
1709
Richard Smitha3271c12015-02-07 00:45:52 +00001710 if (DeclNameEntries.isNull()) {
Chris Lattnercaae7162009-02-20 01:44:05 +00001711 DeclNameEntries.setOnlyValue(D);
Richard Smithf634c902012-03-16 06:12:59 +00001712 return;
Douglas Gregor91f84212008-12-11 16:49:14 +00001713 }
Chris Lattner24e24d52009-02-20 00:55:03 +00001714
Richard Smithe8292b12015-02-10 03:28:10 +00001715 if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
Richard Smithf634c902012-03-16 06:12:59 +00001716 // This declaration has replaced an existing one for which
1717 // declarationReplaces returns true.
1718 return;
1719 }
Mike Stump11289f42009-09-09 15:08:12 +00001720
Richard Smithf634c902012-03-16 06:12:59 +00001721 // Put this declaration into the appropriate slot.
1722 DeclNameEntries.AddSubsequentDecl(D);
Douglas Gregor91f84212008-12-11 16:49:14 +00001723}
Douglas Gregor889ceb72009-02-03 19:21:40 +00001724
Richard Smith40c78062015-02-21 02:31:57 +00001725UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
1726 return cast<UsingDirectiveDecl>(*I);
1727}
1728
Douglas Gregor889ceb72009-02-03 19:21:40 +00001729/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1730/// this context.
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001731DeclContext::udir_range DeclContext::using_directives() const {
Richard Smith05afe5e2012-03-13 03:12:56 +00001732 // FIXME: Use something more efficient than normal lookup for using
1733 // directives. In C++, using directives are looked up more than anything else.
Richard Smithcf4bdde2015-02-21 02:45:19 +00001734 lookup_result Result = lookup(UsingDirectiveDecl::getName());
Richard Smith40c78062015-02-21 02:31:57 +00001735 return udir_range(Result.begin(), Result.end());
Douglas Gregor889ceb72009-02-03 19:21:40 +00001736}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001737
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001738//===----------------------------------------------------------------------===//
1739// Creation and Destruction of StoredDeclsMaps. //
1740//===----------------------------------------------------------------------===//
1741
John McCallc62bb642010-03-24 05:22:00 +00001742StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
Richard Smith9e2341d2015-03-23 03:25:59 +00001743 assert(!LookupPtr && "context already has a decls map");
John McCallc62bb642010-03-24 05:22:00 +00001744 assert(getPrimaryContext() == this &&
1745 "creating decls map on non-primary context");
1746
1747 StoredDeclsMap *M;
1748 bool Dependent = isDependentContext();
1749 if (Dependent)
1750 M = new DependentStoredDeclsMap();
1751 else
1752 M = new StoredDeclsMap();
1753 M->Previous = C.LastSDM;
1754 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
Richard Smith9e2341d2015-03-23 03:25:59 +00001755 LookupPtr = M;
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001756 return M;
1757}
1758
1759void ASTContext::ReleaseDeclContextMaps() {
John McCallc62bb642010-03-24 05:22:00 +00001760 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1761 // pointer because the subclass doesn't add anything that needs to
1762 // be deleted.
John McCallc62bb642010-03-24 05:22:00 +00001763 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1764}
1765
1766void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1767 while (Map) {
1768 // Advance the iteration before we invalidate memory.
1769 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1770
1771 if (Dependent)
1772 delete static_cast<DependentStoredDeclsMap*>(Map);
1773 else
1774 delete Map;
1775
1776 Map = Next.getPointer();
1777 Dependent = Next.getInt();
1778 }
1779}
1780
John McCallc62bb642010-03-24 05:22:00 +00001781DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1782 DeclContext *Parent,
1783 const PartialDiagnostic &PDiag) {
1784 assert(Parent->isDependentContext()
1785 && "cannot iterate dependent diagnostics of non-dependent context");
1786 Parent = Parent->getPrimaryContext();
Richard Smith9e2341d2015-03-23 03:25:59 +00001787 if (!Parent->LookupPtr)
John McCallc62bb642010-03-24 05:22:00 +00001788 Parent->CreateStoredDeclsMap(C);
1789
Richard Smith9e2341d2015-03-23 03:25:59 +00001790 DependentStoredDeclsMap *Map =
1791 static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
John McCallc62bb642010-03-24 05:22:00 +00001792
Douglas Gregora55530e2010-03-29 23:56:53 +00001793 // Allocate the copy of the PartialDiagnostic via the ASTContext's
Douglas Gregor89336232010-03-29 23:34:08 +00001794 // BumpPtrAllocator, rather than the ASTContext itself.
Craig Topper36250ad2014-05-12 05:36:57 +00001795 PartialDiagnostic::Storage *DiagStorage = nullptr;
Douglas Gregora55530e2010-03-29 23:56:53 +00001796 if (PDiag.hasStorage())
1797 DiagStorage = new (C) PartialDiagnostic::Storage;
1798
1799 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
John McCallc62bb642010-03-24 05:22:00 +00001800
1801 // TODO: Maybe we shouldn't reverse the order during insertion.
1802 DD->NextDiagnostic = Map->FirstDiagnostic;
1803 Map->FirstDiagnostic = DD;
1804
1805 return DD;
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001806}