blob: 5c2c9cbd0180233d6ffc18b1e5ef081adfacb63f [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.
Daniel Jasper89f9ad82017-05-15 07:51:10 +000078 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;
Daniel Jasper89f9ad82017-05-15 07:51:10 +000086 return new (Buffer) Module*(nullptr) + 1;
Richard Smith42413142015-05-15 20:05:43 +000087 }
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 {
Daniel Jasper89f9ad82017-05-15 07:51:10 +000097 return getASTContext().getLangOpts().ModulesLocalVisibility;
Richard Smith87bb5692015-06-09 00:35:49 +000098}
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
Alex Lorenza8a372d2017-04-27 10:43:48 +0000418StringRef getRealizedPlatform(const AvailabilityAttr *A,
419 const ASTContext &Context) {
420 // Check if this is an App Extension "platform", and if so chop off
421 // the suffix for matching with the actual platform.
422 StringRef RealizedPlatform = A->getPlatform()->getName();
423 if (!Context.getLangOpts().AppExt)
424 return RealizedPlatform;
425 size_t suffix = RealizedPlatform.rfind("_app_extension");
426 if (suffix != StringRef::npos)
427 return RealizedPlatform.slice(0, suffix);
428 return RealizedPlatform;
429}
430
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000431/// \brief Determine the availability of the given declaration based on
432/// the target platform.
433///
434/// When it returns an availability result other than \c AR_Available,
435/// if the \p Message parameter is non-NULL, it will be set to a
436/// string describing why the entity is unavailable.
437///
438/// FIXME: Make these strings localizable, since they end up in
439/// diagnostics.
440static AvailabilityResult CheckAvailability(ASTContext &Context,
441 const AvailabilityAttr *A,
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000442 std::string *Message,
443 VersionTuple EnclosingVersion) {
444 if (EnclosingVersion.empty())
445 EnclosingVersion = Context.getTargetInfo().getPlatformMinVersion();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000446
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000447 if (EnclosingVersion.empty())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000448 return AR_Available;
449
Bob Wilsonb111ec92015-03-02 19:01:14 +0000450 StringRef ActualPlatform = A->getPlatform()->getName();
Bob Wilsonb111ec92015-03-02 19:01:14 +0000451 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
452
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000453 // Match the platform name.
Alex Lorenza8a372d2017-04-27 10:43:48 +0000454 if (getRealizedPlatform(A, Context) != TargetPlatform)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000455 return AR_Available;
Bob Wilsonb111ec92015-03-02 19:01:14 +0000456
457 StringRef PrettyPlatformName
458 = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
459
460 if (PrettyPlatformName.empty())
461 PrettyPlatformName = ActualPlatform;
462
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000463 std::string HintMessage;
464 if (!A->getMessage().empty()) {
465 HintMessage = " - ";
466 HintMessage += A->getMessage();
467 }
468
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000469 // Make sure that this declaration has not been marked 'unavailable'.
470 if (A->getUnavailable()) {
471 if (Message) {
472 Message->clear();
473 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000474 Out << "not available on " << PrettyPlatformName
475 << HintMessage;
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000476 }
477
478 return AR_Unavailable;
479 }
480
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000481 // Make sure that this declaration has already been introduced.
482 if (!A->getIntroduced().empty() &&
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000483 EnclosingVersion < A->getIntroduced()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000484 if (Message) {
485 Message->clear();
486 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000487 VersionTuple VTI(A->getIntroduced());
488 VTI.UseDotAsSeparator();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000489 Out << "introduced in " << PrettyPlatformName << ' '
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000490 << VTI << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000491 }
492
Duncan P. N. Exon Smith5d6790c2016-03-08 06:12:54 +0000493 return A->getStrict() ? AR_Unavailable : AR_NotYetIntroduced;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000494 }
495
496 // Make sure that this declaration hasn't been obsoleted.
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000497 if (!A->getObsoleted().empty() && EnclosingVersion >= A->getObsoleted()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000498 if (Message) {
499 Message->clear();
500 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000501 VersionTuple VTO(A->getObsoleted());
502 VTO.UseDotAsSeparator();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000503 Out << "obsoleted in " << PrettyPlatformName << ' '
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000504 << VTO << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000505 }
506
507 return AR_Unavailable;
508 }
509
510 // Make sure that this declaration hasn't been deprecated.
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000511 if (!A->getDeprecated().empty() && EnclosingVersion >= A->getDeprecated()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000512 if (Message) {
513 Message->clear();
514 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000515 VersionTuple VTD(A->getDeprecated());
516 VTD.UseDotAsSeparator();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000517 Out << "first deprecated in " << PrettyPlatformName << ' '
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000518 << VTD << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000519 }
520
521 return AR_Deprecated;
522 }
523
524 return AR_Available;
525}
526
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000527AvailabilityResult Decl::getAvailability(std::string *Message,
528 VersionTuple EnclosingVersion) const {
Duncan P. N. Exon Smithec599a92016-02-26 19:27:00 +0000529 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000530 return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion);
Duncan P. N. Exon Smithec599a92016-02-26 19:27:00 +0000531
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000532 AvailabilityResult Result = AR_Available;
533 std::string ResultMessage;
534
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000535 for (const auto *A : attrs()) {
536 if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000537 if (Result >= AR_Deprecated)
538 continue;
539
540 if (Message)
541 ResultMessage = Deprecated->getMessage();
542
543 Result = AR_Deprecated;
544 continue;
545 }
546
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000547 if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000548 if (Message)
549 *Message = Unavailable->getMessage();
550 return AR_Unavailable;
551 }
552
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000553 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000554 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000555 Message, EnclosingVersion);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000556
557 if (AR == AR_Unavailable)
558 return AR_Unavailable;
559
560 if (AR > Result) {
561 Result = AR;
562 if (Message)
563 ResultMessage.swap(*Message);
564 }
565 continue;
566 }
567 }
568
569 if (Message)
570 Message->swap(ResultMessage);
571 return Result;
572}
573
Alex Lorenza8a372d2017-04-27 10:43:48 +0000574VersionTuple Decl::getVersionIntroduced() const {
575 const ASTContext &Context = getASTContext();
576 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
577 for (const auto *A : attrs()) {
578 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
579 if (getRealizedPlatform(Availability, Context) != TargetPlatform)
580 continue;
581 if (!Availability->getIntroduced().empty())
582 return Availability->getIntroduced();
583 }
584 }
585 return VersionTuple();
586}
587
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000588bool Decl::canBeWeakImported(bool &IsDefinition) const {
589 IsDefinition = false;
John McCall5fb5df92012-06-20 06:18:46 +0000590
591 // Variables, if they aren't definitions.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000592 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000593 if (Var->isThisDeclarationADefinition()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000594 IsDefinition = true;
595 return false;
596 }
John McCall5fb5df92012-06-20 06:18:46 +0000597 return true;
598
599 // Functions, if they aren't definitions.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000600 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
601 if (FD->hasBody()) {
602 IsDefinition = true;
603 return false;
604 }
John McCall5fb5df92012-06-20 06:18:46 +0000605 return true;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000606
John McCall5fb5df92012-06-20 06:18:46 +0000607 // Objective-C classes, if this is the non-fragile runtime.
608 } else if (isa<ObjCInterfaceDecl>(this) &&
John McCall18ac1632012-06-20 21:58:02 +0000609 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
John McCall5fb5df92012-06-20 06:18:46 +0000610 return true;
611
612 // Nothing else.
613 } else {
614 return false;
615 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000616}
617
618bool Decl::isWeakImported() const {
619 bool IsDefinition;
620 if (!canBeWeakImported(IsDefinition))
621 return false;
622
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000623 for (const auto *A : attrs()) {
624 if (isa<WeakImportAttr>(A))
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000625 return true;
626
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000627 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000628 if (CheckAvailability(getASTContext(), Availability, nullptr,
629 VersionTuple()) == AR_NotYetIntroduced)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000630 return true;
631 }
632 }
633
634 return false;
635}
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000636
Chris Lattner8e097192009-03-27 20:18:19 +0000637unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
638 switch (DeclKind) {
John McCall3f746822009-11-17 05:59:44 +0000639 case Function:
Richard Smithbc491202017-02-17 20:05:37 +0000640 case CXXDeductionGuide:
John McCall3f746822009-11-17 05:59:44 +0000641 case CXXMethod:
642 case CXXConstructor:
Richard Smith5179eb72016-06-28 19:03:57 +0000643 case ConstructorUsingShadow:
John McCall3f746822009-11-17 05:59:44 +0000644 case CXXDestructor:
645 case CXXConversion:
Chris Lattner8e097192009-03-27 20:18:19 +0000646 case EnumConstant:
647 case Var:
Richard Smithbdb84f32016-07-22 23:36:59 +0000648 case Binding:
Chris Lattner8e097192009-03-27 20:18:19 +0000649 case ImplicitParam:
650 case ParmVar:
Chris Lattner8e097192009-03-27 20:18:19 +0000651 case ObjCMethod:
Daniel Dunbar45b2d8a2010-04-23 13:07:39 +0000652 case ObjCProperty:
John McCall5e77d762013-04-16 07:28:30 +0000653 case MSProperty:
Daniel Dunbar45b2d8a2010-04-23 13:07:39 +0000654 return IDNS_Ordinary;
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000655 case Label:
656 return IDNS_Label;
Francois Pichet783dd6e2010-11-21 06:08:52 +0000657 case IndirectField:
658 return IDNS_Ordinary | IDNS_Member;
659
Richard Smith9f951822016-01-06 22:49:11 +0000660 case NonTypeTemplateParm:
661 // Non-type template parameters are not found by lookups that ignore
662 // non-types, but they are found by redeclaration lookups for tag types,
663 // so we include them in the tag namespace.
664 return IDNS_Ordinary | IDNS_Tag;
665
John McCalle87beb22010-04-23 18:46:30 +0000666 case ObjCCompatibleAlias:
667 case ObjCInterface:
668 return IDNS_Ordinary | IDNS_Type;
669
670 case Typedef:
Richard Smithdda56e42011-04-15 14:24:37 +0000671 case TypeAlias:
Richard Smith3f1b5d02011-05-05 21:57:07 +0000672 case TypeAliasTemplate:
John McCalle87beb22010-04-23 18:46:30 +0000673 case TemplateTypeParm:
Douglas Gregor85f3f952015-07-07 03:57:15 +0000674 case ObjCTypeParam:
John McCalle87beb22010-04-23 18:46:30 +0000675 return IDNS_Ordinary | IDNS_Type;
676
Richard Smith151c4562016-12-20 21:35:28 +0000677 case UnresolvedUsingTypename:
678 return IDNS_Ordinary | IDNS_Type | IDNS_Using;
679
John McCall3f746822009-11-17 05:59:44 +0000680 case UsingShadow:
681 return 0; // we'll actually overwrite this later
682
John McCalle61f2ba2009-11-18 02:36:19 +0000683 case UnresolvedUsingValue:
John McCalle61f2ba2009-11-18 02:36:19 +0000684 return IDNS_Ordinary | IDNS_Using;
John McCall3f746822009-11-17 05:59:44 +0000685
686 case Using:
Richard Smith151c4562016-12-20 21:35:28 +0000687 case UsingPack:
John McCall3f746822009-11-17 05:59:44 +0000688 return IDNS_Using;
689
Chris Lattner8e097192009-03-27 20:18:19 +0000690 case ObjCProtocol:
Douglas Gregor79947a22009-04-24 00:11:27 +0000691 return IDNS_ObjCProtocol;
Mike Stump11289f42009-09-09 15:08:12 +0000692
Chris Lattner8e097192009-03-27 20:18:19 +0000693 case Field:
694 case ObjCAtDefsField:
695 case ObjCIvar:
696 return IDNS_Member;
Mike Stump11289f42009-09-09 15:08:12 +0000697
Chris Lattner8e097192009-03-27 20:18:19 +0000698 case Record:
699 case CXXRecord:
700 case Enum:
John McCalle87beb22010-04-23 18:46:30 +0000701 return IDNS_Tag | IDNS_Type;
Mike Stump11289f42009-09-09 15:08:12 +0000702
Chris Lattner8e097192009-03-27 20:18:19 +0000703 case Namespace:
John McCalle87beb22010-04-23 18:46:30 +0000704 case NamespaceAlias:
705 return IDNS_Namespace;
706
Chris Lattner8e097192009-03-27 20:18:19 +0000707 case FunctionTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +0000708 case VarTemplate:
John McCalle87beb22010-04-23 18:46:30 +0000709 return IDNS_Ordinary;
710
Chris Lattner8e097192009-03-27 20:18:19 +0000711 case ClassTemplate:
712 case TemplateTemplateParm:
John McCalle87beb22010-04-23 18:46:30 +0000713 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
Mike Stump11289f42009-09-09 15:08:12 +0000714
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000715 case OMPDeclareReduction:
716 return IDNS_OMPReduction;
717
Chris Lattner8e097192009-03-27 20:18:19 +0000718 // Never have names.
John McCallaa74a0c2009-08-28 07:59:38 +0000719 case Friend:
John McCall11083da2009-09-16 22:47:08 +0000720 case FriendTemplate:
Abramo Bagnarad7340582010-06-05 05:09:32 +0000721 case AccessSpec:
Chris Lattner8e097192009-03-27 20:18:19 +0000722 case LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +0000723 case Export:
Chris Lattner8e097192009-03-27 20:18:19 +0000724 case FileScopeAsm:
725 case StaticAssert:
Chris Lattner8e097192009-03-27 20:18:19 +0000726 case ObjCPropertyImpl:
Nico Weber66220292016-03-02 17:28:48 +0000727 case PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +0000728 case PragmaDetectMismatch:
Chris Lattner8e097192009-03-27 20:18:19 +0000729 case Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +0000730 case Captured:
Chris Lattner8e097192009-03-27 20:18:19 +0000731 case TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +0000732 case ExternCContext:
Richard Smithbdb84f32016-07-22 23:36:59 +0000733 case Decomposition:
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000734
Chris Lattner8e097192009-03-27 20:18:19 +0000735 case UsingDirective:
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000736 case BuiltinTemplate:
Chris Lattner8e097192009-03-27 20:18:19 +0000737 case ClassTemplateSpecialization:
Douglas Gregor2373c592009-05-31 09:31:02 +0000738 case ClassTemplatePartialSpecialization:
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000739 case ClassScopeFunctionSpecialization:
Larisse Voufo39a1e502013-08-06 01:03:05 +0000740 case VarTemplateSpecialization:
741 case VarTemplatePartialSpecialization:
Douglas Gregore93525e2010-04-22 23:19:50 +0000742 case ObjCImplementation:
743 case ObjCCategory:
744 case ObjCCategoryImpl:
Douglas Gregorba345522011-12-02 23:23:56 +0000745 case Import:
Alexey Bataeva769e072013-03-22 06:34:35 +0000746 case OMPThreadPrivate:
Alexey Bataev4244be22016-02-11 05:35:55 +0000747 case OMPCapturedExpr:
Michael Han84324352013-02-22 17:15:32 +0000748 case Empty:
Douglas Gregore93525e2010-04-22 23:19:50 +0000749 // Never looked up by name.
Chris Lattner8e097192009-03-27 20:18:19 +0000750 return 0;
751 }
John McCall3f746822009-11-17 05:59:44 +0000752
David Blaikiee4d798f2012-01-20 21:50:17 +0000753 llvm_unreachable("Invalid DeclKind!");
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000754}
755
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000756void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
Argyrios Kyrtzidis91167172010-06-11 23:09:25 +0000757 assert(!HasAttrs && "Decl already contains attrs.");
758
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000759 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000760 assert(AttrBlank.empty() && "HasAttrs was wrong?");
Argyrios Kyrtzidis91167172010-06-11 23:09:25 +0000761
762 AttrBlank = attrs;
763 HasAttrs = true;
764}
765
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000766void Decl::dropAttrs() {
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000767 if (!HasAttrs) return;
Mike Stump11289f42009-09-09 15:08:12 +0000768
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000769 HasAttrs = false;
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000770 getASTContext().eraseDeclAttrs(this);
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000771}
772
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000773const AttrVec &Decl::getAttrs() const {
774 assert(HasAttrs && "No attrs to get!");
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000775 return getASTContext().getDeclAttrs(this);
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000776}
777
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000778Decl *Decl::castFromDeclContext (const DeclContext *D) {
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000779 Decl::Kind DK = D->getDeclKind();
780 switch(DK) {
Alexis Hunted053252010-05-30 07:21:58 +0000781#define DECL(NAME, BASE)
782#define DECL_CONTEXT(NAME) \
783 case Decl::NAME: \
784 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
785#define DECL_CONTEXT_BASE(NAME)
786#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000787 default:
Alexis Hunted053252010-05-30 07:21:58 +0000788#define DECL(NAME, BASE)
789#define DECL_CONTEXT_BASE(NAME) \
790 if (DK >= first##NAME && DK <= last##NAME) \
791 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
792#include "clang/AST/DeclNodes.inc"
David Blaikie83d382b2011-09-23 05:06:16 +0000793 llvm_unreachable("a decl that inherits DeclContext isn't handled");
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000794 }
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000795}
796
797DeclContext *Decl::castToDeclContext(const Decl *D) {
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000798 Decl::Kind DK = D->getKind();
799 switch(DK) {
Alexis Hunted053252010-05-30 07:21:58 +0000800#define DECL(NAME, BASE)
801#define DECL_CONTEXT(NAME) \
802 case Decl::NAME: \
803 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
804#define DECL_CONTEXT_BASE(NAME)
805#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000806 default:
Alexis Hunted053252010-05-30 07:21:58 +0000807#define DECL(NAME, BASE)
808#define DECL_CONTEXT_BASE(NAME) \
809 if (DK >= first##NAME && DK <= last##NAME) \
810 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
811#include "clang/AST/DeclNodes.inc"
David Blaikie83d382b2011-09-23 05:06:16 +0000812 llvm_unreachable("a decl that inherits DeclContext isn't handled");
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000813 }
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000814}
815
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000816SourceLocation Decl::getBodyRBrace() const {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +0000817 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
818 // FunctionDecl stores EndRangeLoc for this purpose.
819 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
820 const FunctionDecl *Definition;
821 if (FD->hasBody(Definition))
822 return Definition->getSourceRange().getEnd();
823 return SourceLocation();
824 }
825
Argyrios Kyrtzidis6fbc8fa2010-07-07 11:31:27 +0000826 if (Stmt *Body = getBody())
827 return Body->getSourceRange().getEnd();
828
829 return SourceLocation();
Sebastian Redla7b98a72009-04-26 20:35:05 +0000830}
831
Alp Tokerc1086762013-12-07 13:51:35 +0000832bool Decl::AccessDeclContextSanity() const {
Douglas Gregor4b00d3b2010-12-02 00:22:25 +0000833#ifndef NDEBUG
John McCall401982f2010-01-20 21:53:11 +0000834 // Suppress this check if any of the following hold:
835 // 1. this is the translation unit (and thus has no parent)
836 // 2. this is a template parameter (and thus doesn't belong to its context)
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000837 // 3. this is a non-type template parameter
838 // 4. the context is not a record
839 // 5. it's invalid
840 // 6. it's a C++0x static_assert.
Anders Carlssonadf36b22009-08-29 20:47:47 +0000841 if (isa<TranslationUnitDecl>(this) ||
Argyrios Kyrtzidisa45855f2010-07-02 11:55:44 +0000842 isa<TemplateTypeParmDecl>(this) ||
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000843 isa<NonTypeTemplateParmDecl>(this) ||
Douglas Gregor2b76dd92010-02-22 17:53:38 +0000844 !isa<CXXRecordDecl>(getDeclContext()) ||
Argyrios Kyrtzidis260b4a82010-09-08 21:32:35 +0000845 isInvalidDecl() ||
846 isa<StaticAssertDecl>(this) ||
847 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
848 // as DeclContext (?).
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000849 isa<ParmVarDecl>(this) ||
850 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
851 // AS_none as access specifier.
Francois Pichet09af8c32011-08-17 01:06:54 +0000852 isa<CXXRecordDecl>(this) ||
853 isa<ClassScopeFunctionSpecializationDecl>(this))
Alp Tokerc1086762013-12-07 13:51:35 +0000854 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000855
856 assert(Access != AS_none &&
Anders Carlssona28908d2009-03-25 23:38:06 +0000857 "Access specifier is AS_none inside a record decl");
Douglas Gregor4b00d3b2010-12-02 00:22:25 +0000858#endif
Alp Tokerc1086762013-12-07 13:51:35 +0000859 return true;
Anders Carlssona28908d2009-03-25 23:38:06 +0000860}
861
John McCalldec348f72013-05-03 07:33:41 +0000862static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
863static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
864
Aaron Ballman12b9f652014-01-16 13:55:42 +0000865const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
866 QualType Ty;
867 if (const ValueDecl *D = dyn_cast<ValueDecl>(this))
868 Ty = D->getType();
869 else if (const TypedefNameDecl *D = dyn_cast<TypedefNameDecl>(this))
870 Ty = D->getUnderlyingType();
871 else
Craig Topper36250ad2014-05-12 05:36:57 +0000872 return nullptr;
Aaron Ballman12b9f652014-01-16 13:55:42 +0000873
874 if (Ty->isFunctionPointerType())
875 Ty = Ty->getAs<PointerType>()->getPointeeType();
876 else if (BlocksToo && Ty->isBlockPointerType())
877 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
878
879 return Ty->getAs<FunctionType>();
880}
881
882
John McCalldec348f72013-05-03 07:33:41 +0000883/// Starting at a given context (a Decl or DeclContext), look for a
884/// code context that is not a closure (a lambda, block, etc.).
885template <class T> static Decl *getNonClosureContext(T *D) {
886 if (getKind(D) == Decl::CXXMethod) {
887 CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
John McCall55c0cee2013-05-03 17:11:14 +0000888 if (MD->getOverloadedOperator() == OO_Call &&
889 MD->getParent()->isLambda())
John McCalldec348f72013-05-03 07:33:41 +0000890 return getNonClosureContext(MD->getParent()->getParent());
891 return MD;
892 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
893 return FD;
894 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
895 return MD;
896 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
897 return getNonClosureContext(BD->getParent());
898 } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
899 return getNonClosureContext(CD->getParent());
900 } else {
Craig Topper36250ad2014-05-12 05:36:57 +0000901 return nullptr;
John McCalldec348f72013-05-03 07:33:41 +0000902 }
John McCallfe96e0b2011-11-06 09:01:30 +0000903}
904
John McCalldec348f72013-05-03 07:33:41 +0000905Decl *Decl::getNonClosureContext() {
906 return ::getNonClosureContext(this);
907}
John McCallb67608f2011-02-22 22:25:23 +0000908
John McCalldec348f72013-05-03 07:33:41 +0000909Decl *DeclContext::getNonClosureAncestor() {
910 return ::getNonClosureContext(this);
John McCallb67608f2011-02-22 22:25:23 +0000911}
Anders Carlssona28908d2009-03-25 23:38:06 +0000912
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000913//===----------------------------------------------------------------------===//
914// DeclContext Implementation
915//===----------------------------------------------------------------------===//
916
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000917bool DeclContext::classof(const Decl *D) {
918 switch (D->getKind()) {
Alexis Hunted053252010-05-30 07:21:58 +0000919#define DECL(NAME, BASE)
920#define DECL_CONTEXT(NAME) case Decl::NAME:
921#define DECL_CONTEXT_BASE(NAME)
922#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000923 return true;
924 default:
Alexis Hunted053252010-05-30 07:21:58 +0000925#define DECL(NAME, BASE)
926#define DECL_CONTEXT_BASE(NAME) \
927 if (D->getKind() >= Decl::first##NAME && \
928 D->getKind() <= Decl::last##NAME) \
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000929 return true;
Alexis Hunted053252010-05-30 07:21:58 +0000930#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000931 return false;
932 }
933}
934
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000935DeclContext::~DeclContext() { }
Douglas Gregor91f84212008-12-11 16:49:14 +0000936
Douglas Gregor7f737c02009-09-10 16:57:35 +0000937/// \brief Find the parent context of this context that will be
938/// used for unqualified name lookup.
939///
940/// Generally, the parent lookup context is the semantic context. However, for
941/// a friend function the parent lookup context is the lexical context, which
942/// is the class in which the friend is declared.
943DeclContext *DeclContext::getLookupParent() {
944 // FIXME: Find a better way to identify friends
945 if (isa<FunctionDecl>(this))
Sebastian Redl50c68252010-08-31 00:36:30 +0000946 if (getParent()->getRedeclContext()->isFileContext() &&
947 getLexicalParent()->getRedeclContext()->isRecord())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000948 return getLexicalParent();
949
950 return getParent();
951}
952
Sebastian Redlbd595762010-08-31 20:53:31 +0000953bool DeclContext::isInlineNamespace() const {
954 return isNamespace() &&
955 cast<NamespaceDecl>(this)->isInline();
956}
957
Richard Trieuc771d5d2014-05-28 02:16:01 +0000958bool DeclContext::isStdNamespace() const {
959 if (!isNamespace())
960 return false;
961
962 const NamespaceDecl *ND = cast<NamespaceDecl>(this);
963 if (ND->isInline()) {
964 return ND->getParent()->isStdNamespace();
965 }
966
967 if (!getParent()->getRedeclContext()->isTranslationUnit())
968 return false;
969
970 const IdentifierInfo *II = ND->getIdentifier();
971 return II && II->isStr("std");
972}
973
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000974bool DeclContext::isDependentContext() const {
975 if (isFileContext())
976 return false;
977
Douglas Gregor2373c592009-05-31 09:31:02 +0000978 if (isa<ClassTemplatePartialSpecializationDecl>(this))
979 return true;
980
Douglas Gregor680e9e02012-02-21 19:11:17 +0000981 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000982 if (Record->getDescribedClassTemplate())
983 return true;
Douglas Gregor680e9e02012-02-21 19:11:17 +0000984
985 if (Record->isDependentLambda())
986 return true;
987 }
988
John McCallc62bb642010-03-24 05:22:00 +0000989 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000990 if (Function->getDescribedFunctionTemplate())
991 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000992
John McCallc62bb642010-03-24 05:22:00 +0000993 // Friend function declarations are dependent if their *lexical*
994 // context is dependent.
995 if (cast<Decl>(this)->getFriendObjectKind())
996 return getLexicalParent()->isDependentContext();
997 }
998
Richard Smith2b560572015-02-07 03:11:11 +0000999 // FIXME: A variable template is a dependent context, but is not a
1000 // DeclContext. A context within it (such as a lambda-expression)
1001 // should be considered dependent.
1002
Douglas Gregor9e927ab2009-05-28 16:34:51 +00001003 return getParent() && getParent()->isDependentContext();
1004}
1005
Douglas Gregor07665a62009-01-05 19:45:36 +00001006bool DeclContext::isTransparentContext() const {
1007 if (DeclKind == Decl::Enum)
Douglas Gregor0bf31402010-10-08 23:50:27 +00001008 return !cast<EnumDecl>(this)->isScoped();
Richard Smith8df390f2016-09-08 23:14:54 +00001009 else if (DeclKind == Decl::LinkageSpec || DeclKind == Decl::Export)
Douglas Gregor07665a62009-01-05 19:45:36 +00001010 return true;
Douglas Gregor07665a62009-01-05 19:45:36 +00001011
1012 return false;
1013}
1014
Serge Pavlov3cb80222013-11-14 02:13:03 +00001015static bool isLinkageSpecContext(const DeclContext *DC,
1016 LinkageSpecDecl::LanguageIDs ID) {
1017 while (DC->getDeclKind() != Decl::TranslationUnit) {
1018 if (DC->getDeclKind() == Decl::LinkageSpec)
1019 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
Richard Smithac9c9a02014-04-14 20:23:58 +00001020 DC = DC->getLexicalParent();
Serge Pavlov3cb80222013-11-14 02:13:03 +00001021 }
1022 return false;
1023}
1024
1025bool DeclContext::isExternCContext() const {
1026 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_c);
1027}
1028
Alex Lorenz560ae562016-11-02 15:46:34 +00001029const LinkageSpecDecl *DeclContext::getExternCContext() const {
1030 const DeclContext *DC = this;
1031 while (DC->getDeclKind() != Decl::TranslationUnit) {
1032 if (DC->getDeclKind() == Decl::LinkageSpec &&
1033 cast<LinkageSpecDecl>(DC)->getLanguage() ==
1034 clang::LinkageSpecDecl::lang_c)
1035 return cast<LinkageSpecDecl>(DC);
1036 DC = DC->getLexicalParent();
1037 }
1038 return nullptr;
1039}
1040
Serge Pavlov3cb80222013-11-14 02:13:03 +00001041bool DeclContext::isExternCXXContext() const {
1042 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_cxx);
1043}
1044
Sebastian Redl50c68252010-08-31 00:36:30 +00001045bool DeclContext::Encloses(const DeclContext *DC) const {
Douglas Gregore985a3b2009-08-27 06:03:53 +00001046 if (getPrimaryContext() != this)
1047 return getPrimaryContext()->Encloses(DC);
Mike Stump11289f42009-09-09 15:08:12 +00001048
Douglas Gregore985a3b2009-08-27 06:03:53 +00001049 for (; DC; DC = DC->getParent())
1050 if (DC->getPrimaryContext() == this)
1051 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001052 return false;
Douglas Gregore985a3b2009-08-27 06:03:53 +00001053}
1054
Steve Naroff35c62ae2009-01-08 17:28:14 +00001055DeclContext *DeclContext::getPrimaryContext() {
Douglas Gregor91f84212008-12-11 16:49:14 +00001056 switch (DeclKind) {
Douglas Gregor91f84212008-12-11 16:49:14 +00001057 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00001058 case Decl::ExternCContext:
Douglas Gregor07665a62009-01-05 19:45:36 +00001059 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00001060 case Decl::Export:
Mike Stump11289f42009-09-09 15:08:12 +00001061 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001062 case Decl::Captured:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001063 case Decl::OMPDeclareReduction:
Douglas Gregor91f84212008-12-11 16:49:14 +00001064 // There is only one DeclContext for these entities.
1065 return this;
1066
1067 case Decl::Namespace:
1068 // The original namespace is our primary context.
1069 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
1070
Douglas Gregor91f84212008-12-11 16:49:14 +00001071 case Decl::ObjCMethod:
1072 return this;
1073
1074 case Decl::ObjCInterface:
Douglas Gregor66b310c2011-12-15 18:03:09 +00001075 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
1076 return Def;
1077
1078 return this;
1079
Steve Naroff35c62ae2009-01-08 17:28:14 +00001080 case Decl::ObjCProtocol:
Douglas Gregora715bff2012-01-01 19:51:50 +00001081 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
1082 return Def;
1083
1084 return this;
Douglas Gregor66b310c2011-12-15 18:03:09 +00001085
Steve Naroff35c62ae2009-01-08 17:28:14 +00001086 case Decl::ObjCCategory:
Douglas Gregor91f84212008-12-11 16:49:14 +00001087 return this;
1088
Steve Naroff35c62ae2009-01-08 17:28:14 +00001089 case Decl::ObjCImplementation:
1090 case Decl::ObjCCategoryImpl:
1091 return this;
1092
Douglas Gregor91f84212008-12-11 16:49:14 +00001093 default:
Alexis Hunted053252010-05-30 07:21:58 +00001094 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
Douglas Gregor67a65642009-02-17 23:15:12 +00001095 // If this is a tag type that has a definition or is currently
1096 // being defined, that definition is our primary context.
John McCalle78aac42010-03-10 03:28:59 +00001097 TagDecl *Tag = cast<TagDecl>(this);
John McCalle78aac42010-03-10 03:28:59 +00001098
1099 if (TagDecl *Def = Tag->getDefinition())
1100 return Def;
1101
Richard Smith5b21db82014-04-23 18:20:42 +00001102 if (const TagType *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
1103 // Note, TagType::getDecl returns the (partial) definition one exists.
1104 TagDecl *PossiblePartialDef = TagTy->getDecl();
1105 if (PossiblePartialDef->isBeingDefined())
1106 return PossiblePartialDef;
1107 } else {
1108 assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
John McCalle78aac42010-03-10 03:28:59 +00001109 }
1110
1111 return Tag;
Douglas Gregor67a65642009-02-17 23:15:12 +00001112 }
1113
Alexis Hunted053252010-05-30 07:21:58 +00001114 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
Douglas Gregor91f84212008-12-11 16:49:14 +00001115 "Unknown DeclContext kind");
1116 return this;
1117 }
1118}
1119
Douglas Gregore57e7522012-01-07 09:11:48 +00001120void
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001121DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
Douglas Gregore57e7522012-01-07 09:11:48 +00001122 Contexts.clear();
1123
1124 if (DeclKind != Decl::Namespace) {
1125 Contexts.push_back(this);
1126 return;
Douglas Gregor91f84212008-12-11 16:49:14 +00001127 }
Douglas Gregore57e7522012-01-07 09:11:48 +00001128
1129 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
Douglas Gregorec9fd132012-01-14 16:38:05 +00001130 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
1131 N = N->getPreviousDecl())
Douglas Gregore57e7522012-01-07 09:11:48 +00001132 Contexts.push_back(N);
1133
1134 std::reverse(Contexts.begin(), Contexts.end());
Douglas Gregor91f84212008-12-11 16:49:14 +00001135}
1136
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001137std::pair<Decl *, Decl *>
Bill Wendling8eb771d2012-02-22 09:51:33 +00001138DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00001139 bool FieldsAlreadyLoaded) {
Douglas Gregor781f7132012-01-06 16:59:53 +00001140 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
Craig Topper36250ad2014-05-12 05:36:57 +00001141 Decl *FirstNewDecl = nullptr;
1142 Decl *PrevDecl = nullptr;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001143 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00001144 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
1145 continue;
1146
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001147 Decl *D = Decls[I];
1148 if (PrevDecl)
Douglas Gregor781f7132012-01-06 16:59:53 +00001149 PrevDecl->NextInContextAndBits.setPointer(D);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001150 else
1151 FirstNewDecl = D;
1152
1153 PrevDecl = D;
1154 }
1155
1156 return std::make_pair(FirstNewDecl, PrevDecl);
1157}
1158
Richard Smith645d7552013-02-07 03:37:08 +00001159/// \brief We have just acquired external visible storage, and we already have
1160/// built a lookup map. For every name in the map, pull in the new names from
1161/// the external storage.
Richard Smitha8b74592014-03-25 00:34:21 +00001162void DeclContext::reconcileExternalVisibleStorage() const {
Richard Smith9e2341d2015-03-23 03:25:59 +00001163 assert(NeedToReconcileExternalVisibleStorage && LookupPtr);
Richard Smith645d7552013-02-07 03:37:08 +00001164 NeedToReconcileExternalVisibleStorage = false;
1165
Richard Smith9e2341d2015-03-23 03:25:59 +00001166 for (auto &Lookup : *LookupPtr)
Richard Smitha8b74592014-03-25 00:34:21 +00001167 Lookup.second.setHasExternalDecls();
Richard Smith645d7552013-02-07 03:37:08 +00001168}
1169
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001170/// \brief Load the declarations within this lexical storage from an
1171/// external source.
Richard Smith18b380b2015-03-24 02:44:20 +00001172/// \return \c true if any declarations were added.
1173bool
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001174DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1175 ExternalASTSource *Source = getParentASTContext().getExternalSource();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001176 assert(hasExternalLexicalStorage() && Source && "No external storage?");
1177
Argyrios Kyrtzidis98d045e2010-07-30 10:03:23 +00001178 // Notify that we have a DeclContext that is initializing.
1179 ExternalASTSource::Deserializing ADeclContext(Source);
Richard Smith9e2341d2015-03-23 03:25:59 +00001180
Douglas Gregor3d0adb32011-07-15 21:46:17 +00001181 // Load the external declarations, if any.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001182 SmallVector<Decl*, 64> Decls;
Richard Smith18b380b2015-03-24 02:44:20 +00001183 ExternalLexicalStorage = false;
Richard Smith3cb15722015-08-05 22:41:45 +00001184 Source->FindExternalLexicalDecls(this, Decls);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001185
1186 if (Decls.empty())
Richard Smith18b380b2015-03-24 02:44:20 +00001187 return false;
Richard Smith9e2341d2015-03-23 03:25:59 +00001188
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00001189 // We may have already loaded just the fields of this record, in which case
1190 // we need to ignore them.
1191 bool FieldsAlreadyLoaded = false;
1192 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
1193 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
1194
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001195 // Splice the newly-read declarations into the beginning of the list
1196 // of declarations.
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001197 Decl *ExternalFirst, *ExternalLast;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001198 std::tie(ExternalFirst, ExternalLast) =
1199 BuildDeclChain(Decls, FieldsAlreadyLoaded);
Douglas Gregor781f7132012-01-06 16:59:53 +00001200 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001201 FirstDecl = ExternalFirst;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001202 if (!LastDecl)
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001203 LastDecl = ExternalLast;
Richard Smith18b380b2015-03-24 02:44:20 +00001204 return true;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001205}
1206
John McCall75b960e2010-06-01 09:23:16 +00001207DeclContext::lookup_result
1208ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1209 DeclarationName Name) {
1210 ASTContext &Context = DC->getParentASTContext();
1211 StoredDeclsMap *Map;
Richard Smith9e2341d2015-03-23 03:25:59 +00001212 if (!(Map = DC->LookupPtr))
John McCall75b960e2010-06-01 09:23:16 +00001213 Map = DC->CreateStoredDeclsMap(Context);
Richard Smitha8b74592014-03-25 00:34:21 +00001214 if (DC->NeedToReconcileExternalVisibleStorage)
1215 DC->reconcileExternalVisibleStorage();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001216
Richard Smith4abe0a82013-09-09 07:34:56 +00001217 (*Map)[Name].removeExternalDecls();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001218
John McCall75b960e2010-06-01 09:23:16 +00001219 return DeclContext::lookup_result();
1220}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001221
John McCall75b960e2010-06-01 09:23:16 +00001222DeclContext::lookup_result
1223ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
John McCall75b960e2010-06-01 09:23:16 +00001224 DeclarationName Name,
Argyrios Kyrtzidis94d3f9d2011-09-09 06:44:14 +00001225 ArrayRef<NamedDecl*> Decls) {
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00001226 ASTContext &Context = DC->getParentASTContext();
John McCall75b960e2010-06-01 09:23:16 +00001227 StoredDeclsMap *Map;
Richard Smith9e2341d2015-03-23 03:25:59 +00001228 if (!(Map = DC->LookupPtr))
John McCall75b960e2010-06-01 09:23:16 +00001229 Map = DC->CreateStoredDeclsMap(Context);
Richard Smitha8b74592014-03-25 00:34:21 +00001230 if (DC->NeedToReconcileExternalVisibleStorage)
1231 DC->reconcileExternalVisibleStorage();
John McCall75b960e2010-06-01 09:23:16 +00001232
1233 StoredDeclsList &List = (*Map)[Name];
Richard Smith51445cd2013-06-24 01:46:41 +00001234
1235 // Clear out any old external visible declarations, to avoid quadratic
1236 // performance in the redeclaration checks below.
1237 List.removeExternalDecls();
1238
1239 if (!List.isNull()) {
1240 // We have both existing declarations and new declarations for this name.
1241 // Some of the declarations may simply replace existing ones. Handle those
1242 // first.
1243 llvm::SmallVector<unsigned, 8> Skip;
1244 for (unsigned I = 0, N = Decls.size(); I != N; ++I)
Richard Smithe8292b12015-02-10 03:28:10 +00001245 if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
Richard Smith51445cd2013-06-24 01:46:41 +00001246 Skip.push_back(I);
1247 Skip.push_back(Decls.size());
1248
1249 // Add in any new declarations.
1250 unsigned SkipPos = 0;
1251 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1252 if (I == Skip[SkipPos])
1253 ++SkipPos;
1254 else
1255 List.AddSubsequentDecl(Decls[I]);
1256 }
1257 } else {
1258 // Convert the array to a StoredDeclsList.
1259 for (ArrayRef<NamedDecl*>::iterator
1260 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1261 if (List.isNull())
1262 List.setOnlyValue(*I);
1263 else
1264 List.AddSubsequentDecl(*I);
1265 }
John McCall75b960e2010-06-01 09:23:16 +00001266 }
1267
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001268 return List.getLookupResult();
John McCall75b960e2010-06-01 09:23:16 +00001269}
1270
Aaron Ballmanda634f12014-03-07 22:17:20 +00001271DeclContext::decl_iterator DeclContext::decls_begin() const {
1272 if (hasExternalLexicalStorage())
1273 LoadLexicalDeclsFromExternalStorage();
1274 return decl_iterator(FirstDecl);
1275}
1276
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001277bool DeclContext::decls_empty() const {
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001278 if (hasExternalLexicalStorage())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001279 LoadLexicalDeclsFromExternalStorage();
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001280
1281 return !FirstDecl;
1282}
1283
Sean Callanan0325fb82013-05-04 02:04:27 +00001284bool DeclContext::containsDecl(Decl *D) const {
1285 return (D->getLexicalDeclContext() == this &&
1286 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1287}
1288
John McCall84d87672009-12-10 09:41:52 +00001289void DeclContext::removeDecl(Decl *D) {
1290 assert(D->getLexicalDeclContext() == this &&
1291 "decl being removed from non-lexical context");
Douglas Gregor781f7132012-01-06 16:59:53 +00001292 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
John McCall84d87672009-12-10 09:41:52 +00001293 "decl is not in decls list");
1294
1295 // Remove D from the decl chain. This is O(n) but hopefully rare.
1296 if (D == FirstDecl) {
1297 if (D == LastDecl)
Craig Topper36250ad2014-05-12 05:36:57 +00001298 FirstDecl = LastDecl = nullptr;
John McCall84d87672009-12-10 09:41:52 +00001299 else
Douglas Gregor781f7132012-01-06 16:59:53 +00001300 FirstDecl = D->NextInContextAndBits.getPointer();
John McCall84d87672009-12-10 09:41:52 +00001301 } else {
Douglas Gregor781f7132012-01-06 16:59:53 +00001302 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
John McCall84d87672009-12-10 09:41:52 +00001303 assert(I && "decl not found in linked list");
Douglas Gregor781f7132012-01-06 16:59:53 +00001304 if (I->NextInContextAndBits.getPointer() == D) {
1305 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
John McCall84d87672009-12-10 09:41:52 +00001306 if (D == LastDecl) LastDecl = I;
1307 break;
1308 }
1309 }
1310 }
1311
1312 // Mark that D is no longer in the decl chain.
Craig Topper36250ad2014-05-12 05:36:57 +00001313 D->NextInContextAndBits.setPointer(nullptr);
John McCall84d87672009-12-10 09:41:52 +00001314
1315 // Remove D from the lookup table if necessary.
1316 if (isa<NamedDecl>(D)) {
1317 NamedDecl *ND = cast<NamedDecl>(D);
1318
Axel Naumanncb2c52f2011-08-26 14:06:12 +00001319 // Remove only decls that have a name
1320 if (!ND->getDeclName()) return;
1321
Richard Smith26210db2015-11-13 03:52:13 +00001322 auto *DC = this;
1323 do {
1324 StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1325 if (Map) {
1326 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1327 assert(Pos != Map->end() && "no lookup entry for decl");
1328 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1329 Pos->second.remove(ND);
1330 }
1331 } while (DC->isTransparentContext() && (DC = DC->getParent()));
John McCall84d87672009-12-10 09:41:52 +00001332 }
1333}
1334
John McCalld1e9d832009-08-11 06:59:38 +00001335void DeclContext::addHiddenDecl(Decl *D) {
Chris Lattner33f219d2009-02-20 00:56:18 +00001336 assert(D->getLexicalDeclContext() == this &&
1337 "Decl inserted into wrong lexical context");
Mike Stump11289f42009-09-09 15:08:12 +00001338 assert(!D->getNextDeclInContext() && D != LastDecl &&
Douglas Gregor020713e2009-01-09 19:42:16 +00001339 "Decl already inserted into a DeclContext");
1340
1341 if (FirstDecl) {
Douglas Gregor781f7132012-01-06 16:59:53 +00001342 LastDecl->NextInContextAndBits.setPointer(D);
Douglas Gregor020713e2009-01-09 19:42:16 +00001343 LastDecl = D;
1344 } else {
1345 FirstDecl = LastDecl = D;
1346 }
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001347
1348 // Notify a C++ record declaration that we've added a member, so it can
Nick Lewycky4b81fc872015-10-18 20:32:12 +00001349 // update its class-specific state.
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001350 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1351 Record->addedMember(D);
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001352
1353 // If this is a newly-created (not de-serialized) import declaration, wire
1354 // it in to the list of local import declarations.
1355 if (!D->isFromASTFile()) {
1356 if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1357 D->getASTContext().addedLocalImportDecl(Import);
1358 }
John McCalld1e9d832009-08-11 06:59:38 +00001359}
1360
1361void DeclContext::addDecl(Decl *D) {
1362 addHiddenDecl(D);
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001363
1364 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithf634c902012-03-16 06:12:59 +00001365 ND->getDeclContext()->getPrimaryContext()->
1366 makeDeclVisibleInContextWithFlags(ND, false, true);
Douglas Gregor91f84212008-12-11 16:49:14 +00001367}
1368
Sean Callanan95e74be2011-10-21 02:57:43 +00001369void DeclContext::addDeclInternal(Decl *D) {
1370 addHiddenDecl(D);
1371
1372 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithf634c902012-03-16 06:12:59 +00001373 ND->getDeclContext()->getPrimaryContext()->
1374 makeDeclVisibleInContextWithFlags(ND, true, true);
1375}
1376
1377/// shouldBeHidden - Determine whether a declaration which was declared
1378/// within its semantic context should be invisible to qualified name lookup.
1379static bool shouldBeHidden(NamedDecl *D) {
1380 // Skip unnamed declarations.
1381 if (!D->getDeclName())
1382 return true;
1383
1384 // Skip entities that can't be found by name lookup into a particular
1385 // context.
1386 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1387 D->isTemplateParameter())
1388 return true;
1389
1390 // Skip template specializations.
1391 // FIXME: This feels like a hack. Should DeclarationName support
1392 // template-ids, or is there a better way to keep specializations
1393 // from being visible?
1394 if (isa<ClassTemplateSpecializationDecl>(D))
1395 return true;
1396 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1397 if (FD->isFunctionTemplateSpecialization())
1398 return true;
1399
1400 return false;
1401}
1402
1403/// buildLookup - Build the lookup data structure with all of the
1404/// declarations in this DeclContext (and any other contexts linked
1405/// to it or transparent contexts nested within it) and return it.
Richard Smitha8b74592014-03-25 00:34:21 +00001406///
1407/// Note that the produced map may miss out declarations from an
1408/// external source. If it does, those entries will be marked with
1409/// the 'hasExternalDecls' flag.
Richard Smithf634c902012-03-16 06:12:59 +00001410StoredDeclsMap *DeclContext::buildLookup() {
1411 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1412
Richard Smith9e2341d2015-03-23 03:25:59 +00001413 if (!HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups)
1414 return LookupPtr;
1415
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001416 SmallVector<DeclContext *, 2> Contexts;
Richard Smithf634c902012-03-16 06:12:59 +00001417 collectAllContexts(Contexts);
Richard Smith18b380b2015-03-24 02:44:20 +00001418
1419 if (HasLazyExternalLexicalLookups) {
1420 HasLazyExternalLexicalLookups = false;
1421 for (auto *DC : Contexts) {
1422 if (DC->hasExternalLexicalStorage())
1423 HasLazyLocalLexicalLookups |=
1424 DC->LoadLexicalDeclsFromExternalStorage();
1425 }
1426
1427 if (!HasLazyLocalLexicalLookups)
1428 return LookupPtr;
1429 }
1430
1431 for (auto *DC : Contexts)
1432 buildLookupImpl(DC, hasExternalVisibleStorage());
Richard Smithf634c902012-03-16 06:12:59 +00001433
1434 // We no longer have any lazy decls.
Richard Smith9e2341d2015-03-23 03:25:59 +00001435 HasLazyLocalLexicalLookups = false;
1436 return LookupPtr;
Richard Smithf634c902012-03-16 06:12:59 +00001437}
1438
1439/// buildLookupImpl - Build part of the lookup data structure for the
1440/// declarations contained within DCtx, which will either be this
1441/// DeclContext, a DeclContext linked to it, or a transparent context
1442/// nested within it.
Richard Smitha3271c12015-02-07 00:45:52 +00001443void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
Richard Smith9e2341d2015-03-23 03:25:59 +00001444 for (Decl *D : DCtx->noload_decls()) {
Richard Smithf634c902012-03-16 06:12:59 +00001445 // Insert this declaration into the lookup structure, but only if
1446 // it's semantically within its decl context. Any other decls which
1447 // should be found in this context are added eagerly.
Richard Smithcf4ab522013-06-24 07:20:36 +00001448 //
1449 // If it's from an AST file, don't add it now. It'll get handled by
1450 // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1451 // in C++, we do not track external visible decls for the TU, so in
1452 // that case we need to collect them all here.
Richard Smithf634c902012-03-16 06:12:59 +00001453 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithcf4ab522013-06-24 07:20:36 +00001454 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1455 (!ND->isFromASTFile() ||
1456 (isTranslationUnit() &&
1457 !getParentASTContext().getLangOpts().CPlusPlus)))
Richard Smitha3271c12015-02-07 00:45:52 +00001458 makeDeclVisibleInContextImpl(ND, Internal);
Richard Smithf634c902012-03-16 06:12:59 +00001459
1460 // If this declaration is itself a transparent declaration context
1461 // or inline namespace, add the members of this declaration of that
1462 // context (recursively).
1463 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1464 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Richard Smith9e2341d2015-03-23 03:25:59 +00001465 buildLookupImpl(InnerCtx, Internal);
Richard Smithf634c902012-03-16 06:12:59 +00001466 }
Sean Callanan95e74be2011-10-21 02:57:43 +00001467}
1468
Richard Smith40c78062015-02-21 02:31:57 +00001469NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1470
Mike Stump11289f42009-09-09 15:08:12 +00001471DeclContext::lookup_result
Richard Smith40c78062015-02-21 02:31:57 +00001472DeclContext::lookup(DeclarationName Name) const {
Richard Smith8df390f2016-09-08 23:14:54 +00001473 assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1474 "should not perform lookups into transparent contexts");
Nick Lewycky2bd636f2012-03-13 04:12:34 +00001475
Manman Ren7d2f5c42016-09-09 19:03:07 +00001476 const DeclContext *PrimaryContext = getPrimaryContext();
1477 if (PrimaryContext != this)
1478 return PrimaryContext->lookup(Name);
1479
Richard Smith8cebe372015-02-25 22:20:13 +00001480 // If we have an external source, ensure that any later redeclarations of this
1481 // context have been loaded, since they may add names to the result of this
1482 // lookup (or add external visible storage).
1483 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1484 if (Source)
1485 (void)cast<Decl>(this)->getMostRecentDecl();
Richard Smithbb853c72014-08-13 01:23:33 +00001486
Richard Smith05afe5e2012-03-13 03:12:56 +00001487 if (hasExternalVisibleStorage()) {
Richard Smith8cebe372015-02-25 22:20:13 +00001488 assert(Source && "external visible storage but no external source?");
1489
Richard Smitha8b74592014-03-25 00:34:21 +00001490 if (NeedToReconcileExternalVisibleStorage)
1491 reconcileExternalVisibleStorage();
1492
Richard Smith9e2341d2015-03-23 03:25:59 +00001493 StoredDeclsMap *Map = LookupPtr;
Richard Smitha8b74592014-03-25 00:34:21 +00001494
Richard Smith9e2341d2015-03-23 03:25:59 +00001495 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
Richard Smith40c78062015-02-21 02:31:57 +00001496 // FIXME: Make buildLookup const?
1497 Map = const_cast<DeclContext*>(this)->buildLookup();
Richard Smith645d7552013-02-07 03:37:08 +00001498
Richard Smith75fc3bf2013-02-08 00:37:45 +00001499 if (!Map)
1500 Map = CreateStoredDeclsMap(getParentASTContext());
1501
Richard Smith4abe0a82013-09-09 07:34:56 +00001502 // If we have a lookup result with no external decls, we are done.
Richard Smith75fc3bf2013-02-08 00:37:45 +00001503 std::pair<StoredDeclsMap::iterator, bool> R =
1504 Map->insert(std::make_pair(Name, StoredDeclsList()));
Richard Smith4abe0a82013-09-09 07:34:56 +00001505 if (!R.second && !R.first->second.hasExternalDecls())
Richard Smith75fc3bf2013-02-08 00:37:45 +00001506 return R.first->second.getLookupResult();
Richard Smithf634c902012-03-16 06:12:59 +00001507
Richard Smith309271b2014-03-04 00:21:14 +00001508 if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
Richard Smith9e2341d2015-03-23 03:25:59 +00001509 if (StoredDeclsMap *Map = LookupPtr) {
Richard Smith9ce12e32013-02-07 03:30:24 +00001510 StoredDeclsMap::iterator I = Map->find(Name);
1511 if (I != Map->end())
1512 return I->second.getLookupResult();
1513 }
1514 }
1515
Richard Smith40c78062015-02-21 02:31:57 +00001516 return lookup_result();
John McCall75b960e2010-06-01 09:23:16 +00001517 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001518
Richard Smith9e2341d2015-03-23 03:25:59 +00001519 StoredDeclsMap *Map = LookupPtr;
1520 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
Richard Smith40c78062015-02-21 02:31:57 +00001521 Map = const_cast<DeclContext*>(this)->buildLookup();
Richard Smithf634c902012-03-16 06:12:59 +00001522
1523 if (!Map)
Richard Smith40c78062015-02-21 02:31:57 +00001524 return lookup_result();
Richard Smithf634c902012-03-16 06:12:59 +00001525
1526 StoredDeclsMap::iterator I = Map->find(Name);
1527 if (I == Map->end())
Richard Smith40c78062015-02-21 02:31:57 +00001528 return lookup_result();
Richard Smithf634c902012-03-16 06:12:59 +00001529
1530 return I->second.getLookupResult();
Douglas Gregor91f84212008-12-11 16:49:14 +00001531}
1532
Richard Smith95d99302013-07-13 02:00:19 +00001533DeclContext::lookup_result
1534DeclContext::noload_lookup(DeclarationName Name) {
Richard Smith8df390f2016-09-08 23:14:54 +00001535 assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1536 "should not perform lookups into transparent contexts");
Richard Smith95d99302013-07-13 02:00:19 +00001537
1538 DeclContext *PrimaryContext = getPrimaryContext();
1539 if (PrimaryContext != this)
1540 return PrimaryContext->noload_lookup(Name);
1541
Richard Smith9e2341d2015-03-23 03:25:59 +00001542 // If we have any lazy lexical declarations not in our lookup map, add them
1543 // now. Don't import any external declarations, not even if we know we have
1544 // some missing from the external visible lookups.
1545 if (HasLazyLocalLexicalLookups) {
Vince Harrona3ea9a42015-03-22 05:59:59 +00001546 SmallVector<DeclContext *, 2> Contexts;
1547 collectAllContexts(Contexts);
1548 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
Richard Smith9e2341d2015-03-23 03:25:59 +00001549 buildLookupImpl(Contexts[I], hasExternalVisibleStorage());
1550 HasLazyLocalLexicalLookups = false;
Vince Harrona3ea9a42015-03-22 05:59:59 +00001551 }
1552
Richard Smith9e2341d2015-03-23 03:25:59 +00001553 StoredDeclsMap *Map = LookupPtr;
Richard Smith95d99302013-07-13 02:00:19 +00001554 if (!Map)
Richard Smith40c78062015-02-21 02:31:57 +00001555 return lookup_result();
Richard Smith95d99302013-07-13 02:00:19 +00001556
1557 StoredDeclsMap::iterator I = Map->find(Name);
Craig Topper36250ad2014-05-12 05:36:57 +00001558 return I != Map->end() ? I->second.getLookupResult()
Richard Smith40c78062015-02-21 02:31:57 +00001559 : lookup_result();
Richard Smith95d99302013-07-13 02:00:19 +00001560}
1561
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001562void DeclContext::localUncachedLookup(DeclarationName Name,
1563 SmallVectorImpl<NamedDecl *> &Results) {
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001564 Results.clear();
1565
1566 // If there's no external storage, just perform a normal lookup and copy
1567 // the results.
Douglas Gregordd6006f2012-07-17 21:16:27 +00001568 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001569 lookup_result LookupResults = lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00001570 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001571 return;
1572 }
1573
1574 // If we have a lookup table, check there first. Maybe we'll get lucky.
Richard Smith9e2341d2015-03-23 03:25:59 +00001575 // FIXME: Should we be checking these flags on the primary context?
1576 if (Name && !HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups) {
1577 if (StoredDeclsMap *Map = LookupPtr) {
Douglas Gregordd6006f2012-07-17 21:16:27 +00001578 StoredDeclsMap::iterator Pos = Map->find(Name);
1579 if (Pos != Map->end()) {
1580 Results.insert(Results.end(),
David Blaikieff7d47a2012-12-19 00:45:41 +00001581 Pos->second.getLookupResult().begin(),
1582 Pos->second.getLookupResult().end());
Douglas Gregordd6006f2012-07-17 21:16:27 +00001583 return;
1584 }
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001585 }
1586 }
Douglas Gregordd6006f2012-07-17 21:16:27 +00001587
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001588 // Slow case: grovel through the declarations in our chain looking for
1589 // matches.
Richard Smith9e2341d2015-03-23 03:25:59 +00001590 // FIXME: If we have lazy external declarations, this will not find them!
1591 // FIXME: Should we CollectAllContexts and walk them all here?
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001592 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1593 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1594 if (ND->getDeclName() == Name)
1595 Results.push_back(ND);
1596 }
1597}
1598
Sebastian Redl50c68252010-08-31 00:36:30 +00001599DeclContext *DeclContext::getRedeclContext() {
Chris Lattner17a1bfa2009-03-27 19:19:59 +00001600 DeclContext *Ctx = this;
Sebastian Redlbd595762010-08-31 20:53:31 +00001601 // Skip through transparent contexts.
1602 while (Ctx->isTransparentContext())
Douglas Gregor6ad0ef52009-01-06 23:51:29 +00001603 Ctx = Ctx->getParent();
1604 return Ctx;
1605}
1606
Douglas Gregorf47b9112009-02-25 22:02:03 +00001607DeclContext *DeclContext::getEnclosingNamespaceContext() {
1608 DeclContext *Ctx = this;
1609 // Skip through non-namespace, non-translation-unit contexts.
Sebastian Redl4f08c962010-08-31 00:36:23 +00001610 while (!Ctx->isFileContext())
Douglas Gregorf47b9112009-02-25 22:02:03 +00001611 Ctx = Ctx->getParent();
1612 return Ctx->getPrimaryContext();
1613}
1614
Reid Klecknerd60b82f2014-11-17 23:36:45 +00001615RecordDecl *DeclContext::getOuterLexicalRecordContext() {
1616 // Loop until we find a non-record context.
1617 RecordDecl *OutermostRD = nullptr;
1618 DeclContext *DC = this;
1619 while (DC->isRecord()) {
1620 OutermostRD = cast<RecordDecl>(DC);
1621 DC = DC->getLexicalParent();
1622 }
1623 return OutermostRD;
1624}
1625
Sebastian Redl50c68252010-08-31 00:36:30 +00001626bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1627 // For non-file contexts, this is equivalent to Equals.
1628 if (!isFileContext())
1629 return O->Equals(this);
1630
1631 do {
1632 if (O->Equals(this))
1633 return true;
1634
1635 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1636 if (!NS || !NS->isInline())
1637 break;
1638 O = NS->getParent();
1639 } while (O);
1640
1641 return false;
1642}
1643
Richard Smithf634c902012-03-16 06:12:59 +00001644void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1645 DeclContext *PrimaryDC = this->getPrimaryContext();
1646 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1647 // If the decl is being added outside of its semantic decl context, we
1648 // need to ensure that we eagerly build the lookup information for it.
1649 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
Sean Callanan95e74be2011-10-21 02:57:43 +00001650}
1651
Richard Smithf634c902012-03-16 06:12:59 +00001652void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1653 bool Recoverable) {
1654 assert(this == getPrimaryContext() && "expected a primary DC");
Sean Callanan95e74be2011-10-21 02:57:43 +00001655
Vassil Vassilev71eafde2016-04-06 20:56:03 +00001656 if (!isLookupContext()) {
1657 if (isTransparentContext())
1658 getParent()->getPrimaryContext()
1659 ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
Richard Smith05afe5e2012-03-13 03:12:56 +00001660 return;
Vassil Vassilev71eafde2016-04-06 20:56:03 +00001661 }
Richard Smith05afe5e2012-03-13 03:12:56 +00001662
Richard Smithf634c902012-03-16 06:12:59 +00001663 // Skip declarations which should be invisible to name lookup.
1664 if (shouldBeHidden(D))
1665 return;
1666
1667 // If we already have a lookup data structure, perform the insertion into
1668 // it. If we might have externally-stored decls with this name, look them
1669 // up and perform the insertion. If this decl was declared outside its
1670 // semantic context, buildLookup won't add it, so add it now.
1671 //
1672 // FIXME: As a performance hack, don't add such decls into the translation
1673 // unit unless we're in C++, since qualified lookup into the TU is never
1674 // performed.
Richard Smith9e2341d2015-03-23 03:25:59 +00001675 if (LookupPtr || hasExternalVisibleStorage() ||
Richard Smithf634c902012-03-16 06:12:59 +00001676 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1677 (getParentASTContext().getLangOpts().CPlusPlus ||
1678 !isTranslationUnit()))) {
1679 // If we have lazily omitted any decls, they might have the same name as
1680 // the decl which we are adding, so build a full lookup table before adding
1681 // this decl.
1682 buildLookup();
1683 makeDeclVisibleInContextImpl(D, Internal);
1684 } else {
Richard Smith9e2341d2015-03-23 03:25:59 +00001685 HasLazyLocalLexicalLookups = true;
Richard Smithf634c902012-03-16 06:12:59 +00001686 }
1687
1688 // If we are a transparent context or inline namespace, insert into our
1689 // parent context, too. This operation is recursive.
1690 if (isTransparentContext() || isInlineNamespace())
1691 getParent()->getPrimaryContext()->
1692 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1693
1694 Decl *DCAsDecl = cast<Decl>(this);
1695 // Notify that a decl was made visible unless we are a Tag being defined.
1696 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1697 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1698 L->AddedVisibleDecl(this, D);
1699}
1700
1701void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1702 // Find or create the stored declaration map.
Richard Smith9e2341d2015-03-23 03:25:59 +00001703 StoredDeclsMap *Map = LookupPtr;
Richard Smithf634c902012-03-16 06:12:59 +00001704 if (!Map) {
1705 ASTContext *C = &getParentASTContext();
1706 Map = CreateStoredDeclsMap(*C);
Argyrios Kyrtzidise51e5542010-07-04 21:44:25 +00001707 }
1708
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001709 // If there is an external AST source, load any declarations it knows about
1710 // with this declaration's name.
1711 // If the lookup table contains an entry about this name it means that we
1712 // have already checked the external source.
Sean Callanan95e74be2011-10-21 02:57:43 +00001713 if (!Internal)
1714 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1715 if (hasExternalVisibleStorage() &&
Richard Smithf634c902012-03-16 06:12:59 +00001716 Map->find(D->getDeclName()) == Map->end())
Sean Callanan95e74be2011-10-21 02:57:43 +00001717 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001718
Douglas Gregor91f84212008-12-11 16:49:14 +00001719 // Insert this declaration into the map.
Richard Smithf634c902012-03-16 06:12:59 +00001720 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
Richard Smith4abe0a82013-09-09 07:34:56 +00001721
1722 if (Internal) {
1723 // If this is being added as part of loading an external declaration,
1724 // this may not be the only external declaration with this name.
1725 // In this case, we never try to replace an existing declaration; we'll
1726 // handle that when we finalize the list of declarations for this name.
1727 DeclNameEntries.setHasExternalDecls();
1728 DeclNameEntries.AddSubsequentDecl(D);
1729 return;
1730 }
1731
Richard Smitha3271c12015-02-07 00:45:52 +00001732 if (DeclNameEntries.isNull()) {
Chris Lattnercaae7162009-02-20 01:44:05 +00001733 DeclNameEntries.setOnlyValue(D);
Richard Smithf634c902012-03-16 06:12:59 +00001734 return;
Douglas Gregor91f84212008-12-11 16:49:14 +00001735 }
Chris Lattner24e24d52009-02-20 00:55:03 +00001736
Richard Smithe8292b12015-02-10 03:28:10 +00001737 if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
Richard Smithf634c902012-03-16 06:12:59 +00001738 // This declaration has replaced an existing one for which
1739 // declarationReplaces returns true.
1740 return;
1741 }
Mike Stump11289f42009-09-09 15:08:12 +00001742
Richard Smithf634c902012-03-16 06:12:59 +00001743 // Put this declaration into the appropriate slot.
1744 DeclNameEntries.AddSubsequentDecl(D);
Douglas Gregor91f84212008-12-11 16:49:14 +00001745}
Douglas Gregor889ceb72009-02-03 19:21:40 +00001746
Richard Smith40c78062015-02-21 02:31:57 +00001747UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
1748 return cast<UsingDirectiveDecl>(*I);
1749}
1750
Douglas Gregor889ceb72009-02-03 19:21:40 +00001751/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1752/// this context.
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001753DeclContext::udir_range DeclContext::using_directives() const {
Richard Smith05afe5e2012-03-13 03:12:56 +00001754 // FIXME: Use something more efficient than normal lookup for using
1755 // directives. In C++, using directives are looked up more than anything else.
Richard Smithcf4bdde2015-02-21 02:45:19 +00001756 lookup_result Result = lookup(UsingDirectiveDecl::getName());
Richard Smith40c78062015-02-21 02:31:57 +00001757 return udir_range(Result.begin(), Result.end());
Douglas Gregor889ceb72009-02-03 19:21:40 +00001758}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001759
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001760//===----------------------------------------------------------------------===//
1761// Creation and Destruction of StoredDeclsMaps. //
1762//===----------------------------------------------------------------------===//
1763
John McCallc62bb642010-03-24 05:22:00 +00001764StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
Richard Smith9e2341d2015-03-23 03:25:59 +00001765 assert(!LookupPtr && "context already has a decls map");
John McCallc62bb642010-03-24 05:22:00 +00001766 assert(getPrimaryContext() == this &&
1767 "creating decls map on non-primary context");
1768
1769 StoredDeclsMap *M;
1770 bool Dependent = isDependentContext();
1771 if (Dependent)
1772 M = new DependentStoredDeclsMap();
1773 else
1774 M = new StoredDeclsMap();
1775 M->Previous = C.LastSDM;
1776 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
Richard Smith9e2341d2015-03-23 03:25:59 +00001777 LookupPtr = M;
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001778 return M;
1779}
1780
1781void ASTContext::ReleaseDeclContextMaps() {
John McCallc62bb642010-03-24 05:22:00 +00001782 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1783 // pointer because the subclass doesn't add anything that needs to
1784 // be deleted.
John McCallc62bb642010-03-24 05:22:00 +00001785 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1786}
1787
1788void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1789 while (Map) {
1790 // Advance the iteration before we invalidate memory.
1791 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1792
1793 if (Dependent)
1794 delete static_cast<DependentStoredDeclsMap*>(Map);
1795 else
1796 delete Map;
1797
1798 Map = Next.getPointer();
1799 Dependent = Next.getInt();
1800 }
1801}
1802
John McCallc62bb642010-03-24 05:22:00 +00001803DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1804 DeclContext *Parent,
1805 const PartialDiagnostic &PDiag) {
1806 assert(Parent->isDependentContext()
1807 && "cannot iterate dependent diagnostics of non-dependent context");
1808 Parent = Parent->getPrimaryContext();
Richard Smith9e2341d2015-03-23 03:25:59 +00001809 if (!Parent->LookupPtr)
John McCallc62bb642010-03-24 05:22:00 +00001810 Parent->CreateStoredDeclsMap(C);
1811
Richard Smith9e2341d2015-03-23 03:25:59 +00001812 DependentStoredDeclsMap *Map =
1813 static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
John McCallc62bb642010-03-24 05:22:00 +00001814
Douglas Gregora55530e2010-03-29 23:56:53 +00001815 // Allocate the copy of the PartialDiagnostic via the ASTContext's
Douglas Gregor89336232010-03-29 23:34:08 +00001816 // BumpPtrAllocator, rather than the ASTContext itself.
Craig Topper36250ad2014-05-12 05:36:57 +00001817 PartialDiagnostic::Storage *DiagStorage = nullptr;
Douglas Gregora55530e2010-03-29 23:56:53 +00001818 if (PDiag.hasStorage())
1819 DiagStorage = new (C) PartialDiagnostic::Storage;
1820
1821 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
John McCallc62bb642010-03-24 05:22:00 +00001822
1823 // TODO: Maybe we shouldn't reverse the order during insertion.
1824 DD->NextDiagnostic = Map->FirstDiagnostic;
1825 Map->FirstDiagnostic = DD;
1826
1827 return DD;
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001828}