Bug Summary

File:clang/lib/AST/DeclObjC.cpp
Warning:line 1652, column 11
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name DeclObjC.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-12-05-225554-32688-1 -x c++ /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/DeclObjC.cpp

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/DeclObjC.cpp

1//===- DeclObjC.cpp - ObjC Declaration AST Node Implementation ------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Objective-C related Decl classes.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/DeclObjC.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/ASTMutationListener.h"
16#include "clang/AST/Attr.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclBase.h"
19#include "clang/AST/Stmt.h"
20#include "clang/AST/Type.h"
21#include "clang/AST/TypeLoc.h"
22#include "clang/Basic/IdentifierTable.h"
23#include "clang/Basic/LLVM.h"
24#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/SourceLocation.h"
26#include "llvm/ADT/None.h"
27#include "llvm/ADT/SmallString.h"
28#include "llvm/ADT/SmallVector.h"
29#include "llvm/Support/Casting.h"
30#include "llvm/Support/ErrorHandling.h"
31#include "llvm/Support/raw_ostream.h"
32#include <algorithm>
33#include <cassert>
34#include <cstdint>
35#include <cstring>
36#include <utility>
37
38using namespace clang;
39
40//===----------------------------------------------------------------------===//
41// ObjCListBase
42//===----------------------------------------------------------------------===//
43
44void ObjCListBase::set(void *const* InList, unsigned Elts, ASTContext &Ctx) {
45 List = nullptr;
46 if (Elts == 0) return; // Setting to an empty list is a noop.
47
48 List = new (Ctx) void*[Elts];
49 NumElts = Elts;
50 memcpy(List, InList, sizeof(void*)*Elts);
51}
52
53void ObjCProtocolList::set(ObjCProtocolDecl* const* InList, unsigned Elts,
54 const SourceLocation *Locs, ASTContext &Ctx) {
55 if (Elts == 0)
56 return;
57
58 Locations = new (Ctx) SourceLocation[Elts];
59 memcpy(Locations, Locs, sizeof(SourceLocation) * Elts);
60 set(InList, Elts, Ctx);
61}
62
63//===----------------------------------------------------------------------===//
64// ObjCInterfaceDecl
65//===----------------------------------------------------------------------===//
66
67ObjCContainerDecl::ObjCContainerDecl(Kind DK, DeclContext *DC,
68 IdentifierInfo *Id, SourceLocation nameLoc,
69 SourceLocation atStartLoc)
70 : NamedDecl(DK, DC, nameLoc, Id), DeclContext(DK) {
71 setAtStartLoc(atStartLoc);
72}
73
74void ObjCContainerDecl::anchor() {}
75
76/// getIvarDecl - This method looks up an ivar in this ContextDecl.
77///
78ObjCIvarDecl *
79ObjCContainerDecl::getIvarDecl(IdentifierInfo *Id) const {
80 lookup_result R = lookup(Id);
81 for (lookup_iterator Ivar = R.begin(), IvarEnd = R.end();
82 Ivar != IvarEnd; ++Ivar) {
83 if (auto *ivar = dyn_cast<ObjCIvarDecl>(*Ivar))
84 return ivar;
85 }
86 return nullptr;
87}
88
89// Get the local instance/class method declared in this interface.
90ObjCMethodDecl *
91ObjCContainerDecl::getMethod(Selector Sel, bool isInstance,
92 bool AllowHidden) const {
93 // If this context is a hidden protocol definition, don't find any
94 // methods there.
95 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(this)) {
96 if (const ObjCProtocolDecl *Def = Proto->getDefinition())
97 if (Def->isHidden() && !AllowHidden)
98 return nullptr;
99 }
100
101 // Since instance & class methods can have the same name, the loop below
102 // ensures we get the correct method.
103 //
104 // @interface Whatever
105 // - (int) class_method;
106 // + (float) class_method;
107 // @end
108 lookup_result R = lookup(Sel);
109 for (lookup_iterator Meth = R.begin(), MethEnd = R.end();
110 Meth != MethEnd; ++Meth) {
111 auto *MD = dyn_cast<ObjCMethodDecl>(*Meth);
112 if (MD && MD->isInstanceMethod() == isInstance)
113 return MD;
114 }
115 return nullptr;
116}
117
118/// This routine returns 'true' if a user declared setter method was
119/// found in the class, its protocols, its super classes or categories.
120/// It also returns 'true' if one of its categories has declared a 'readwrite'
121/// property. This is because, user must provide a setter method for the
122/// category's 'readwrite' property.
123bool ObjCContainerDecl::HasUserDeclaredSetterMethod(
124 const ObjCPropertyDecl *Property) const {
125 Selector Sel = Property->getSetterName();
126 lookup_result R = lookup(Sel);
127 for (lookup_iterator Meth = R.begin(), MethEnd = R.end();
128 Meth != MethEnd; ++Meth) {
129 auto *MD = dyn_cast<ObjCMethodDecl>(*Meth);
130 if (MD && MD->isInstanceMethod() && !MD->isImplicit())
131 return true;
132 }
133
134 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(this)) {
135 // Also look into categories, including class extensions, looking
136 // for a user declared instance method.
137 for (const auto *Cat : ID->visible_categories()) {
138 if (ObjCMethodDecl *MD = Cat->getInstanceMethod(Sel))
139 if (!MD->isImplicit())
140 return true;
141 if (Cat->IsClassExtension())
142 continue;
143 // Also search through the categories looking for a 'readwrite'
144 // declaration of this property. If one found, presumably a setter will
145 // be provided (properties declared in categories will not get
146 // auto-synthesized).
147 for (const auto *P : Cat->properties())
148 if (P->getIdentifier() == Property->getIdentifier()) {
149 if (P->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_readwrite)
150 return true;
151 break;
152 }
153 }
154
155 // Also look into protocols, for a user declared instance method.
156 for (const auto *Proto : ID->all_referenced_protocols())
157 if (Proto->HasUserDeclaredSetterMethod(Property))
158 return true;
159
160 // And in its super class.
161 ObjCInterfaceDecl *OSC = ID->getSuperClass();
162 while (OSC) {
163 if (OSC->HasUserDeclaredSetterMethod(Property))
164 return true;
165 OSC = OSC->getSuperClass();
166 }
167 }
168 if (const auto *PD = dyn_cast<ObjCProtocolDecl>(this))
169 for (const auto *PI : PD->protocols())
170 if (PI->HasUserDeclaredSetterMethod(Property))
171 return true;
172 return false;
173}
174
175ObjCPropertyDecl *
176ObjCPropertyDecl::findPropertyDecl(const DeclContext *DC,
177 const IdentifierInfo *propertyID,
178 ObjCPropertyQueryKind queryKind) {
179 // If this context is a hidden protocol definition, don't find any
180 // property.
181 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(DC)) {
182 if (const ObjCProtocolDecl *Def = Proto->getDefinition())
183 if (Def->isHidden())
184 return nullptr;
185 }
186
187 // If context is class, then lookup property in its visible extensions.
188 // This comes before property is looked up in primary class.
189 if (auto *IDecl = dyn_cast<ObjCInterfaceDecl>(DC)) {
190 for (const auto *Ext : IDecl->visible_extensions())
191 if (ObjCPropertyDecl *PD = ObjCPropertyDecl::findPropertyDecl(Ext,
192 propertyID,
193 queryKind))
194 return PD;
195 }
196
197 DeclContext::lookup_result R = DC->lookup(propertyID);
198 ObjCPropertyDecl *classProp = nullptr;
199 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
200 ++I)
201 if (auto *PD = dyn_cast<ObjCPropertyDecl>(*I)) {
202 // If queryKind is unknown, we return the instance property if one
203 // exists; otherwise we return the class property.
204 if ((queryKind == ObjCPropertyQueryKind::OBJC_PR_query_unknown &&
205 !PD->isClassProperty()) ||
206 (queryKind == ObjCPropertyQueryKind::OBJC_PR_query_class &&
207 PD->isClassProperty()) ||
208 (queryKind == ObjCPropertyQueryKind::OBJC_PR_query_instance &&
209 !PD->isClassProperty()))
210 return PD;
211
212 if (PD->isClassProperty())
213 classProp = PD;
214 }
215
216 if (queryKind == ObjCPropertyQueryKind::OBJC_PR_query_unknown)
217 // We can't find the instance property, return the class property.
218 return classProp;
219
220 return nullptr;
221}
222
223IdentifierInfo *
224ObjCPropertyDecl::getDefaultSynthIvarName(ASTContext &Ctx) const {
225 SmallString<128> ivarName;
226 {
227 llvm::raw_svector_ostream os(ivarName);
228 os << '_' << getIdentifier()->getName();
229 }
230 return &Ctx.Idents.get(ivarName.str());
231}
232
233/// FindPropertyDeclaration - Finds declaration of the property given its name
234/// in 'PropertyId' and returns it. It returns 0, if not found.
235ObjCPropertyDecl *ObjCContainerDecl::FindPropertyDeclaration(
236 const IdentifierInfo *PropertyId,
237 ObjCPropertyQueryKind QueryKind) const {
238 // Don't find properties within hidden protocol definitions.
239 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(this)) {
240 if (const ObjCProtocolDecl *Def = Proto->getDefinition())
241 if (Def->isHidden())
242 return nullptr;
243 }
244
245 // Search the extensions of a class first; they override what's in
246 // the class itself.
247 if (const auto *ClassDecl = dyn_cast<ObjCInterfaceDecl>(this)) {
248 for (const auto *Ext : ClassDecl->visible_extensions()) {
249 if (auto *P = Ext->FindPropertyDeclaration(PropertyId, QueryKind))
250 return P;
251 }
252 }
253
254 if (ObjCPropertyDecl *PD =
255 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(this), PropertyId,
256 QueryKind))
257 return PD;
258
259 switch (getKind()) {
260 default:
261 break;
262 case Decl::ObjCProtocol: {
263 const auto *PID = cast<ObjCProtocolDecl>(this);
264 for (const auto *I : PID->protocols())
265 if (ObjCPropertyDecl *P = I->FindPropertyDeclaration(PropertyId,
266 QueryKind))
267 return P;
268 break;
269 }
270 case Decl::ObjCInterface: {
271 const auto *OID = cast<ObjCInterfaceDecl>(this);
272 // Look through categories (but not extensions; they were handled above).
273 for (const auto *Cat : OID->visible_categories()) {
274 if (!Cat->IsClassExtension())
275 if (ObjCPropertyDecl *P = Cat->FindPropertyDeclaration(
276 PropertyId, QueryKind))
277 return P;
278 }
279
280 // Look through protocols.
281 for (const auto *I : OID->all_referenced_protocols())
282 if (ObjCPropertyDecl *P = I->FindPropertyDeclaration(PropertyId,
283 QueryKind))
284 return P;
285
286 // Finally, check the super class.
287 if (const ObjCInterfaceDecl *superClass = OID->getSuperClass())
288 return superClass->FindPropertyDeclaration(PropertyId, QueryKind);
289 break;
290 }
291 case Decl::ObjCCategory: {
292 const auto *OCD = cast<ObjCCategoryDecl>(this);
293 // Look through protocols.
294 if (!OCD->IsClassExtension())
295 for (const auto *I : OCD->protocols())
296 if (ObjCPropertyDecl *P = I->FindPropertyDeclaration(PropertyId,
297 QueryKind))
298 return P;
299 break;
300 }
301 }
302 return nullptr;
303}
304
305void ObjCInterfaceDecl::anchor() {}
306
307ObjCTypeParamList *ObjCInterfaceDecl::getTypeParamList() const {
308 // If this particular declaration has a type parameter list, return it.
309 if (ObjCTypeParamList *written = getTypeParamListAsWritten())
310 return written;
311
312 // If there is a definition, return its type parameter list.
313 if (const ObjCInterfaceDecl *def = getDefinition())
314 return def->getTypeParamListAsWritten();
315
316 // Otherwise, look at previous declarations to determine whether any
317 // of them has a type parameter list, skipping over those
318 // declarations that do not.
319 for (const ObjCInterfaceDecl *decl = getMostRecentDecl(); decl;
320 decl = decl->getPreviousDecl()) {
321 if (ObjCTypeParamList *written = decl->getTypeParamListAsWritten())
322 return written;
323 }
324
325 return nullptr;
326}
327
328void ObjCInterfaceDecl::setTypeParamList(ObjCTypeParamList *TPL) {
329 TypeParamList = TPL;
330 if (!TPL)
331 return;
332 // Set the declaration context of each of the type parameters.
333 for (auto *typeParam : *TypeParamList)
334 typeParam->setDeclContext(this);
335}
336
337ObjCInterfaceDecl *ObjCInterfaceDecl::getSuperClass() const {
338 // FIXME: Should make sure no callers ever do this.
339 if (!hasDefinition())
340 return nullptr;
341
342 if (data().ExternallyCompleted)
343 LoadExternalDefinition();
344
345 if (const ObjCObjectType *superType = getSuperClassType()) {
346 if (ObjCInterfaceDecl *superDecl = superType->getInterface()) {
347 if (ObjCInterfaceDecl *superDef = superDecl->getDefinition())
348 return superDef;
349
350 return superDecl;
351 }
352 }
353
354 return nullptr;
355}
356
357SourceLocation ObjCInterfaceDecl::getSuperClassLoc() const {
358 if (TypeSourceInfo *superTInfo = getSuperClassTInfo())
359 return superTInfo->getTypeLoc().getBeginLoc();
360
361 return SourceLocation();
362}
363
364/// FindPropertyVisibleInPrimaryClass - Finds declaration of the property
365/// with name 'PropertyId' in the primary class; including those in protocols
366/// (direct or indirect) used by the primary class.
367ObjCPropertyDecl *
368ObjCInterfaceDecl::FindPropertyVisibleInPrimaryClass(
369 IdentifierInfo *PropertyId,
370 ObjCPropertyQueryKind QueryKind) const {
371 // FIXME: Should make sure no callers ever do this.
372 if (!hasDefinition())
373 return nullptr;
374
375 if (data().ExternallyCompleted)
376 LoadExternalDefinition();
377
378 if (ObjCPropertyDecl *PD =
379 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(this), PropertyId,
380 QueryKind))
381 return PD;
382
383 // Look through protocols.
384 for (const auto *I : all_referenced_protocols())
385 if (ObjCPropertyDecl *P = I->FindPropertyDeclaration(PropertyId,
386 QueryKind))
387 return P;
388
389 return nullptr;
390}
391
392void ObjCInterfaceDecl::collectPropertiesToImplement(PropertyMap &PM,
393 PropertyDeclOrder &PO) const {
394 for (auto *Prop : properties()) {
395 PM[std::make_pair(Prop->getIdentifier(), Prop->isClassProperty())] = Prop;
396 PO.push_back(Prop);
397 }
398 for (const auto *Ext : known_extensions()) {
399 const ObjCCategoryDecl *ClassExt = Ext;
400 for (auto *Prop : ClassExt->properties()) {
401 PM[std::make_pair(Prop->getIdentifier(), Prop->isClassProperty())] = Prop;
402 PO.push_back(Prop);
403 }
404 }
405 for (const auto *PI : all_referenced_protocols())
406 PI->collectPropertiesToImplement(PM, PO);
407 // Note, the properties declared only in class extensions are still copied
408 // into the main @interface's property list, and therefore we don't
409 // explicitly, have to search class extension properties.
410}
411
412bool ObjCInterfaceDecl::isArcWeakrefUnavailable() const {
413 const ObjCInterfaceDecl *Class = this;
414 while (Class) {
415 if (Class->hasAttr<ArcWeakrefUnavailableAttr>())
416 return true;
417 Class = Class->getSuperClass();
418 }
419 return false;
420}
421
422const ObjCInterfaceDecl *ObjCInterfaceDecl::isObjCRequiresPropertyDefs() const {
423 const ObjCInterfaceDecl *Class = this;
424 while (Class) {
425 if (Class->hasAttr<ObjCRequiresPropertyDefsAttr>())
426 return Class;
427 Class = Class->getSuperClass();
428 }
429 return nullptr;
430}
431
432void ObjCInterfaceDecl::mergeClassExtensionProtocolList(
433 ObjCProtocolDecl *const* ExtList, unsigned ExtNum,
434 ASTContext &C) {
435 if (data().ExternallyCompleted)
436 LoadExternalDefinition();
437
438 if (data().AllReferencedProtocols.empty() &&
439 data().ReferencedProtocols.empty()) {
440 data().AllReferencedProtocols.set(ExtList, ExtNum, C);
441 return;
442 }
443
444 // Check for duplicate protocol in class's protocol list.
445 // This is O(n*m). But it is extremely rare and number of protocols in
446 // class or its extension are very few.
447 SmallVector<ObjCProtocolDecl *, 8> ProtocolRefs;
448 for (unsigned i = 0; i < ExtNum; i++) {
449 bool protocolExists = false;
450 ObjCProtocolDecl *ProtoInExtension = ExtList[i];
451 for (auto *Proto : all_referenced_protocols()) {
452 if (C.ProtocolCompatibleWithProtocol(ProtoInExtension, Proto)) {
453 protocolExists = true;
454 break;
455 }
456 }
457 // Do we want to warn on a protocol in extension class which
458 // already exist in the class? Probably not.
459 if (!protocolExists)
460 ProtocolRefs.push_back(ProtoInExtension);
461 }
462
463 if (ProtocolRefs.empty())
464 return;
465
466 // Merge ProtocolRefs into class's protocol list;
467 ProtocolRefs.append(all_referenced_protocol_begin(),
468 all_referenced_protocol_end());
469
470 data().AllReferencedProtocols.set(ProtocolRefs.data(), ProtocolRefs.size(),C);
471}
472
473const ObjCInterfaceDecl *
474ObjCInterfaceDecl::findInterfaceWithDesignatedInitializers() const {
475 const ObjCInterfaceDecl *IFace = this;
476 while (IFace) {
477 if (IFace->hasDesignatedInitializers())
478 return IFace;
479 if (!IFace->inheritsDesignatedInitializers())
480 break;
481 IFace = IFace->getSuperClass();
482 }
483 return nullptr;
484}
485
486static bool isIntroducingInitializers(const ObjCInterfaceDecl *D) {
487 for (const auto *MD : D->instance_methods()) {
488 if (MD->getMethodFamily() == OMF_init && !MD->isOverriding())
489 return true;
490 }
491 for (const auto *Ext : D->visible_extensions()) {
492 for (const auto *MD : Ext->instance_methods()) {
493 if (MD->getMethodFamily() == OMF_init && !MD->isOverriding())
494 return true;
495 }
496 }
497 if (const auto *ImplD = D->getImplementation()) {
498 for (const auto *MD : ImplD->instance_methods()) {
499 if (MD->getMethodFamily() == OMF_init && !MD->isOverriding())
500 return true;
501 }
502 }
503 return false;
504}
505
506bool ObjCInterfaceDecl::inheritsDesignatedInitializers() const {
507 switch (data().InheritedDesignatedInitializers) {
508 case DefinitionData::IDI_Inherited:
509 return true;
510 case DefinitionData::IDI_NotInherited:
511 return false;
512 case DefinitionData::IDI_Unknown:
513 // If the class introduced initializers we conservatively assume that we
514 // don't know if any of them is a designated initializer to avoid possible
515 // misleading warnings.
516 if (isIntroducingInitializers(this)) {
517 data().InheritedDesignatedInitializers = DefinitionData::IDI_NotInherited;
518 } else {
519 if (auto SuperD = getSuperClass()) {
520 data().InheritedDesignatedInitializers =
521 SuperD->declaresOrInheritsDesignatedInitializers() ?
522 DefinitionData::IDI_Inherited :
523 DefinitionData::IDI_NotInherited;
524 } else {
525 data().InheritedDesignatedInitializers =
526 DefinitionData::IDI_NotInherited;
527 }
528 }
529 assert(data().InheritedDesignatedInitializers((data().InheritedDesignatedInitializers != DefinitionData::IDI_Unknown
) ? static_cast<void> (0) : __assert_fail ("data().InheritedDesignatedInitializers != DefinitionData::IDI_Unknown"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/DeclObjC.cpp"
, 530, __PRETTY_FUNCTION__))
530 != DefinitionData::IDI_Unknown)((data().InheritedDesignatedInitializers != DefinitionData::IDI_Unknown
) ? static_cast<void> (0) : __assert_fail ("data().InheritedDesignatedInitializers != DefinitionData::IDI_Unknown"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/DeclObjC.cpp"
, 530, __PRETTY_FUNCTION__))
;
531 return data().InheritedDesignatedInitializers ==
532 DefinitionData::IDI_Inherited;
533 }
534
535 llvm_unreachable("unexpected InheritedDesignatedInitializers value")::llvm::llvm_unreachable_internal("unexpected InheritedDesignatedInitializers value"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/DeclObjC.cpp"
, 535)
;
536}
537
538void ObjCInterfaceDecl::getDesignatedInitializers(
539 llvm::SmallVectorImpl<const ObjCMethodDecl *> &Methods) const {
540 // Check for a complete definition and recover if not so.
541 if (!isThisDeclarationADefinition())
542 return;
543 if (data().ExternallyCompleted)
544 LoadExternalDefinition();
545
546 const ObjCInterfaceDecl *IFace= findInterfaceWithDesignatedInitializers();
547 if (!IFace)
548 return;
549
550 for (const auto *MD : IFace->instance_methods())
551 if (MD->isThisDeclarationADesignatedInitializer())
552 Methods.push_back(MD);
553 for (const auto *Ext : IFace->visible_extensions()) {
554 for (const auto *MD : Ext->instance_methods())
555 if (MD->isThisDeclarationADesignatedInitializer())
556 Methods.push_back(MD);
557 }
558}
559
560bool ObjCInterfaceDecl::isDesignatedInitializer(Selector Sel,
561 const ObjCMethodDecl **InitMethod) const {
562 bool HasCompleteDef = isThisDeclarationADefinition();
563 // During deserialization the data record for the ObjCInterfaceDecl could
564 // be made invariant by reusing the canonical decl. Take this into account
565 // when checking for the complete definition.
566 if (!HasCompleteDef && getCanonicalDecl()->hasDefinition() &&
567 getCanonicalDecl()->getDefinition() == getDefinition())
568 HasCompleteDef = true;
569
570 // Check for a complete definition and recover if not so.
571 if (!HasCompleteDef)
572 return false;
573
574 if (data().ExternallyCompleted)
575 LoadExternalDefinition();
576
577 const ObjCInterfaceDecl *IFace= findInterfaceWithDesignatedInitializers();
578 if (!IFace)
579 return false;
580
581 if (const ObjCMethodDecl *MD = IFace->getInstanceMethod(Sel)) {
582 if (MD->isThisDeclarationADesignatedInitializer()) {
583 if (InitMethod)
584 *InitMethod = MD;
585 return true;
586 }
587 }
588 for (const auto *Ext : IFace->visible_extensions()) {
589 if (const ObjCMethodDecl *MD = Ext->getInstanceMethod(Sel)) {
590 if (MD->isThisDeclarationADesignatedInitializer()) {
591 if (InitMethod)
592 *InitMethod = MD;
593 return true;
594 }
595 }
596 }
597 return false;
598}
599
600void ObjCInterfaceDecl::allocateDefinitionData() {
601 assert(!hasDefinition() && "ObjC class already has a definition")((!hasDefinition() && "ObjC class already has a definition"
) ? static_cast<void> (0) : __assert_fail ("!hasDefinition() && \"ObjC class already has a definition\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/DeclObjC.cpp"
, 601, __PRETTY_FUNCTION__))
;
602 Data.setPointer(new (getASTContext()) DefinitionData());
603 Data.getPointer()->Definition = this;
604
605 // Make the type point at the definition, now that we have one.
606 if (TypeForDecl)
607 cast<ObjCInterfaceType>(TypeForDecl)->Decl = this;
608}
609
610void ObjCInterfaceDecl::startDefinition() {
611 allocateDefinitionData();
612
613 // Update all of the declarations with a pointer to the definition.
614 for (auto *RD : redecls()) {
615 if (RD != this)
616 RD->Data = Data;
617 }
618}
619
620ObjCIvarDecl *ObjCInterfaceDecl::lookupInstanceVariable(IdentifierInfo *ID,
621 ObjCInterfaceDecl *&clsDeclared) {
622 // FIXME: Should make sure no callers ever do this.
623 if (!hasDefinition())
624 return nullptr;
625
626 if (data().ExternallyCompleted)
627 LoadExternalDefinition();
628
629 ObjCInterfaceDecl* ClassDecl = this;
630 while (ClassDecl != nullptr) {
631 if (ObjCIvarDecl *I = ClassDecl->getIvarDecl(ID)) {
632 clsDeclared = ClassDecl;
633 return I;
634 }
635
636 for (const auto *Ext : ClassDecl->visible_extensions()) {
637 if (ObjCIvarDecl *I = Ext->getIvarDecl(ID)) {
638 clsDeclared = ClassDecl;
639 return I;
640 }
641 }
642
643 ClassDecl = ClassDecl->getSuperClass();
644 }
645 return nullptr;
646}
647
648/// lookupInheritedClass - This method returns ObjCInterfaceDecl * of the super
649/// class whose name is passed as argument. If it is not one of the super classes
650/// the it returns NULL.
651ObjCInterfaceDecl *ObjCInterfaceDecl::lookupInheritedClass(
652 const IdentifierInfo*ICName) {
653 // FIXME: Should make sure no callers ever do this.
654 if (!hasDefinition())
655 return nullptr;
656
657 if (data().ExternallyCompleted)
658 LoadExternalDefinition();
659
660 ObjCInterfaceDecl* ClassDecl = this;
661 while (ClassDecl != nullptr) {
662 if (ClassDecl->getIdentifier() == ICName)
663 return ClassDecl;
664 ClassDecl = ClassDecl->getSuperClass();
665 }
666 return nullptr;
667}
668
669ObjCProtocolDecl *
670ObjCInterfaceDecl::lookupNestedProtocol(IdentifierInfo *Name) {
671 for (auto *P : all_referenced_protocols())
672 if (P->lookupProtocolNamed(Name))
673 return P;
674 ObjCInterfaceDecl *SuperClass = getSuperClass();
675 return SuperClass ? SuperClass->lookupNestedProtocol(Name) : nullptr;
676}
677
678/// lookupMethod - This method returns an instance/class method by looking in
679/// the class, its categories, and its super classes (using a linear search).
680/// When argument category "C" is specified, any implicit method found
681/// in this category is ignored.
682ObjCMethodDecl *ObjCInterfaceDecl::lookupMethod(Selector Sel,
683 bool isInstance,
684 bool shallowCategoryLookup,
685 bool followSuper,
686 const ObjCCategoryDecl *C) const
687{
688 // FIXME: Should make sure no callers ever do this.
689 if (!hasDefinition())
690 return nullptr;
691
692 const ObjCInterfaceDecl* ClassDecl = this;
693 ObjCMethodDecl *MethodDecl = nullptr;
694
695 if (data().ExternallyCompleted)
696 LoadExternalDefinition();
697
698 while (ClassDecl) {
699 // 1. Look through primary class.
700 if ((MethodDecl = ClassDecl->getMethod(Sel, isInstance)))
701 return MethodDecl;
702
703 // 2. Didn't find one yet - now look through categories.
704 for (const auto *Cat : ClassDecl->visible_categories())
705 if ((MethodDecl = Cat->getMethod(Sel, isInstance)))
706 if (C != Cat || !MethodDecl->isImplicit())
707 return MethodDecl;
708
709 // 3. Didn't find one yet - look through primary class's protocols.
710 for (const auto *I : ClassDecl->protocols())
711 if ((MethodDecl = I->lookupMethod(Sel, isInstance)))
712 return MethodDecl;
713
714 // 4. Didn't find one yet - now look through categories' protocols
715 if (!shallowCategoryLookup)
716 for (const auto *Cat : ClassDecl->visible_categories()) {
717 // Didn't find one yet - look through protocols.
718 const ObjCList<ObjCProtocolDecl> &Protocols =
719 Cat->getReferencedProtocols();
720 for (auto *Protocol : Protocols)
721 if ((MethodDecl = Protocol->lookupMethod(Sel, isInstance)))
722 if (C != Cat || !MethodDecl->isImplicit())
723 return MethodDecl;
724 }
725
726
727 if (!followSuper)
728 return nullptr;
729
730 // 5. Get to the super class (if any).
731 ClassDecl = ClassDecl->getSuperClass();
732 }
733 return nullptr;
734}
735
736// Will search "local" class/category implementations for a method decl.
737// If failed, then we search in class's root for an instance method.
738// Returns 0 if no method is found.
739ObjCMethodDecl *ObjCInterfaceDecl::lookupPrivateMethod(
740 const Selector &Sel,
741 bool Instance) const {
742 // FIXME: Should make sure no callers ever do this.
743 if (!hasDefinition())
744 return nullptr;
745
746 if (data().ExternallyCompleted)
747 LoadExternalDefinition();
748
749 ObjCMethodDecl *Method = nullptr;
750 if (ObjCImplementationDecl *ImpDecl = getImplementation())
751 Method = Instance ? ImpDecl->getInstanceMethod(Sel)
752 : ImpDecl->getClassMethod(Sel);
753
754 // Look through local category implementations associated with the class.
755 if (!Method)
756 Method = getCategoryMethod(Sel, Instance);
757
758 // Before we give up, check if the selector is an instance method.
759 // But only in the root. This matches gcc's behavior and what the
760 // runtime expects.
761 if (!Instance && !Method && !getSuperClass()) {
762 Method = lookupInstanceMethod(Sel);
763 // Look through local category implementations associated
764 // with the root class.
765 if (!Method)
766 Method = lookupPrivateMethod(Sel, true);
767 }
768
769 if (!Method && getSuperClass())
770 return getSuperClass()->lookupPrivateMethod(Sel, Instance);
771 return Method;
772}
773
774//===----------------------------------------------------------------------===//
775// ObjCMethodDecl
776//===----------------------------------------------------------------------===//
777
778ObjCMethodDecl::ObjCMethodDecl(
779 SourceLocation beginLoc, SourceLocation endLoc, Selector SelInfo,
780 QualType T, TypeSourceInfo *ReturnTInfo, DeclContext *contextDecl,
781 bool isInstance, bool isVariadic, bool isPropertyAccessor,
782 bool isSynthesizedAccessorStub, bool isImplicitlyDeclared, bool isDefined,
783 ImplementationControl impControl, bool HasRelatedResultType)
784 : NamedDecl(ObjCMethod, contextDecl, beginLoc, SelInfo),
785 DeclContext(ObjCMethod), MethodDeclType(T), ReturnTInfo(ReturnTInfo),
786 DeclEndLoc(endLoc) {
787
788 // Initialized the bits stored in DeclContext.
789 ObjCMethodDeclBits.Family =
790 static_cast<ObjCMethodFamily>(InvalidObjCMethodFamily);
791 setInstanceMethod(isInstance);
792 setVariadic(isVariadic);
793 setPropertyAccessor(isPropertyAccessor);
794 setSynthesizedAccessorStub(isSynthesizedAccessorStub);
795 setDefined(isDefined);
796 setIsRedeclaration(false);
797 setHasRedeclaration(false);
798 setDeclImplementation(impControl);
799 setObjCDeclQualifier(OBJC_TQ_None);
800 setRelatedResultType(HasRelatedResultType);
801 setSelLocsKind(SelLoc_StandardNoSpace);
802 setOverriding(false);
803 setHasSkippedBody(false);
804
805 setImplicit(isImplicitlyDeclared);
806}
807
808ObjCMethodDecl *ObjCMethodDecl::Create(
809 ASTContext &C, SourceLocation beginLoc, SourceLocation endLoc,
810 Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo,
811 DeclContext *contextDecl, bool isInstance, bool isVariadic,
812 bool isPropertyAccessor, bool isSynthesizedAccessorStub,
813 bool isImplicitlyDeclared, bool isDefined, ImplementationControl impControl,
814 bool HasRelatedResultType) {
815 return new (C, contextDecl) ObjCMethodDecl(
816 beginLoc, endLoc, SelInfo, T, ReturnTInfo, contextDecl, isInstance,
817 isVariadic, isPropertyAccessor, isSynthesizedAccessorStub,
818 isImplicitlyDeclared, isDefined, impControl, HasRelatedResultType);
819}
820
821ObjCMethodDecl *ObjCMethodDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
822 return new (C, ID) ObjCMethodDecl(SourceLocation(), SourceLocation(),
823 Selector(), QualType(), nullptr, nullptr);
824}
825
826bool ObjCMethodDecl::isThisDeclarationADesignatedInitializer() const {
827 return getMethodFamily() == OMF_init &&
828 hasAttr<ObjCDesignatedInitializerAttr>();
829}
830
831bool ObjCMethodDecl::definedInNSObject(const ASTContext &Ctx) const {
832 if (const auto *PD = dyn_cast<const ObjCProtocolDecl>(getDeclContext()))
833 return PD->getIdentifier() == Ctx.getNSObjectName();
834 if (const auto *ID = dyn_cast<const ObjCInterfaceDecl>(getDeclContext()))
835 return ID->getIdentifier() == Ctx.getNSObjectName();
836 return false;
837}
838
839bool ObjCMethodDecl::isDesignatedInitializerForTheInterface(
840 const ObjCMethodDecl **InitMethod) const {
841 if (getMethodFamily() != OMF_init)
842 return false;
843 const DeclContext *DC = getDeclContext();
844 if (isa<ObjCProtocolDecl>(DC))
845 return false;
846 if (const ObjCInterfaceDecl *ID = getClassInterface())
847 return ID->isDesignatedInitializer(getSelector(), InitMethod);
848 return false;
849}
850
851Stmt *ObjCMethodDecl::getBody() const {
852 return Body.get(getASTContext().getExternalSource());
853}
854
855void ObjCMethodDecl::setAsRedeclaration(const ObjCMethodDecl *PrevMethod) {
856 assert(PrevMethod)((PrevMethod) ? static_cast<void> (0) : __assert_fail (
"PrevMethod", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/DeclObjC.cpp"
, 856, __PRETTY_FUNCTION__))
;
857 getASTContext().setObjCMethodRedeclaration(PrevMethod, this);
858 setIsRedeclaration(true);
859 PrevMethod->setHasRedeclaration(true);
860}
861
862void ObjCMethodDecl::setParamsAndSelLocs(ASTContext &C,
863 ArrayRef<ParmVarDecl*> Params,
864 ArrayRef<SourceLocation> SelLocs) {
865 ParamsAndSelLocs = nullptr;
866 NumParams = Params.size();
867 if (Params.empty() && SelLocs.empty())
868 return;
869
870 static_assert(alignof(ParmVarDecl *) >= alignof(SourceLocation),
871 "Alignment not sufficient for SourceLocation");
872
873 unsigned Size = sizeof(ParmVarDecl *) * NumParams +
874 sizeof(SourceLocation) * SelLocs.size();
875 ParamsAndSelLocs = C.Allocate(Size);
876 std::copy(Params.begin(), Params.end(), getParams());
877 std::copy(SelLocs.begin(), SelLocs.end(), getStoredSelLocs());
878}
879
880void ObjCMethodDecl::getSelectorLocs(
881 SmallVectorImpl<SourceLocation> &SelLocs) const {
882 for (unsigned i = 0, e = getNumSelectorLocs(); i != e; ++i)
883 SelLocs.push_back(getSelectorLoc(i));
884}
885
886void ObjCMethodDecl::setMethodParams(ASTContext &C,
887 ArrayRef<ParmVarDecl*> Params,
888 ArrayRef<SourceLocation> SelLocs) {
889 assert((!SelLocs.empty() || isImplicit()) &&(((!SelLocs.empty() || isImplicit()) && "No selector locs for non-implicit method"
) ? static_cast<void> (0) : __assert_fail ("(!SelLocs.empty() || isImplicit()) && \"No selector locs for non-implicit method\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/DeclObjC.cpp"
, 890, __PRETTY_FUNCTION__))
890 "No selector locs for non-implicit method")(((!SelLocs.empty() || isImplicit()) && "No selector locs for non-implicit method"
) ? static_cast<void> (0) : __assert_fail ("(!SelLocs.empty() || isImplicit()) && \"No selector locs for non-implicit method\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/DeclObjC.cpp"
, 890, __PRETTY_FUNCTION__))
;
891 if (isImplicit())
892 return setParamsAndSelLocs(C, Params, llvm::None);
893
894 setSelLocsKind(hasStandardSelectorLocs(getSelector(), SelLocs, Params,
895 DeclEndLoc));
896 if (getSelLocsKind() != SelLoc_NonStandard)
897 return setParamsAndSelLocs(C, Params, llvm::None);
898
899 setParamsAndSelLocs(C, Params, SelLocs);
900}
901
902/// A definition will return its interface declaration.
903/// An interface declaration will return its definition.
904/// Otherwise it will return itself.
905ObjCMethodDecl *ObjCMethodDecl::getNextRedeclarationImpl() {
906 ASTContext &Ctx = getASTContext();
907 ObjCMethodDecl *Redecl = nullptr;
908 if (hasRedeclaration())
909 Redecl = const_cast<ObjCMethodDecl*>(Ctx.getObjCMethodRedeclaration(this));
910 if (Redecl)
911 return Redecl;
912
913 auto *CtxD = cast<Decl>(getDeclContext());
914
915 if (!CtxD->isInvalidDecl()) {
916 if (auto *IFD = dyn_cast<ObjCInterfaceDecl>(CtxD)) {
917 if (ObjCImplementationDecl *ImplD = Ctx.getObjCImplementation(IFD))
918 if (!ImplD->isInvalidDecl())
919 Redecl = ImplD->getMethod(getSelector(), isInstanceMethod());
920
921 } else if (auto *CD = dyn_cast<ObjCCategoryDecl>(CtxD)) {
922 if (ObjCCategoryImplDecl *ImplD = Ctx.getObjCImplementation(CD))
923 if (!ImplD->isInvalidDecl())
924 Redecl = ImplD->getMethod(getSelector(), isInstanceMethod());
925
926 } else if (auto *ImplD = dyn_cast<ObjCImplementationDecl>(CtxD)) {
927 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
928 if (!IFD->isInvalidDecl())
929 Redecl = IFD->getMethod(getSelector(), isInstanceMethod());
930
931 } else if (auto *CImplD = dyn_cast<ObjCCategoryImplDecl>(CtxD)) {
932 if (ObjCCategoryDecl *CatD = CImplD->getCategoryDecl())
933 if (!CatD->isInvalidDecl())
934 Redecl = CatD->getMethod(getSelector(), isInstanceMethod());
935 }
936 }
937
938 // Ensure that the discovered method redeclaration has a valid declaration
939 // context. Used to prevent infinite loops when iterating redeclarations in
940 // a partially invalid AST.
941 if (Redecl && cast<Decl>(Redecl->getDeclContext())->isInvalidDecl())
942 Redecl = nullptr;
943
944 if (!Redecl && isRedeclaration()) {
945 // This is the last redeclaration, go back to the first method.
946 return cast<ObjCContainerDecl>(CtxD)->getMethod(getSelector(),
947 isInstanceMethod());
948 }
949
950 return Redecl ? Redecl : this;
951}
952
953ObjCMethodDecl *ObjCMethodDecl::getCanonicalDecl() {
954 auto *CtxD = cast<Decl>(getDeclContext());
955
956 if (auto *ImplD = dyn_cast<ObjCImplementationDecl>(CtxD)) {
957 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
958 if (ObjCMethodDecl *MD = IFD->getMethod(getSelector(),
959 isInstanceMethod()))
960 return MD;
961 } else if (auto *CImplD = dyn_cast<ObjCCategoryImplDecl>(CtxD)) {
962 if (ObjCCategoryDecl *CatD = CImplD->getCategoryDecl())
963 if (ObjCMethodDecl *MD = CatD->getMethod(getSelector(),
964 isInstanceMethod()))
965 return MD;
966 }
967
968 if (isRedeclaration()) {
969 // It is possible that we have not done deserializing the ObjCMethod yet.
970 ObjCMethodDecl *MD =
971 cast<ObjCContainerDecl>(CtxD)->getMethod(getSelector(),
972 isInstanceMethod());
973 return MD ? MD : this;
974 }
975
976 return this;
977}
978
979SourceLocation ObjCMethodDecl::getEndLoc() const {
980 if (Stmt *Body = getBody())
981 return Body->getEndLoc();
982 return DeclEndLoc;
983}
984
985ObjCMethodFamily ObjCMethodDecl::getMethodFamily() const {
986 auto family = static_cast<ObjCMethodFamily>(ObjCMethodDeclBits.Family);
987 if (family != static_cast<unsigned>(InvalidObjCMethodFamily))
988 return family;
989
990 // Check for an explicit attribute.
991 if (const ObjCMethodFamilyAttr *attr = getAttr<ObjCMethodFamilyAttr>()) {
992 // The unfortunate necessity of mapping between enums here is due
993 // to the attributes framework.
994 switch (attr->getFamily()) {
995 case ObjCMethodFamilyAttr::OMF_None: family = OMF_None; break;
996 case ObjCMethodFamilyAttr::OMF_alloc: family = OMF_alloc; break;
997 case ObjCMethodFamilyAttr::OMF_copy: family = OMF_copy; break;
998 case ObjCMethodFamilyAttr::OMF_init: family = OMF_init; break;
999 case ObjCMethodFamilyAttr::OMF_mutableCopy: family = OMF_mutableCopy; break;
1000 case ObjCMethodFamilyAttr::OMF_new: family = OMF_new; break;
1001 }
1002 ObjCMethodDeclBits.Family = family;
1003 return family;
1004 }
1005
1006 family = getSelector().getMethodFamily();
1007 switch (family) {
1008 case OMF_None: break;
1009
1010 // init only has a conventional meaning for an instance method, and
1011 // it has to return an object.
1012 case OMF_init:
1013 if (!isInstanceMethod() || !getReturnType()->isObjCObjectPointerType())
1014 family = OMF_None;
1015 break;
1016
1017 // alloc/copy/new have a conventional meaning for both class and
1018 // instance methods, but they require an object return.
1019 case OMF_alloc:
1020 case OMF_copy:
1021 case OMF_mutableCopy:
1022 case OMF_new:
1023 if (!getReturnType()->isObjCObjectPointerType())
1024 family = OMF_None;
1025 break;
1026
1027 // These selectors have a conventional meaning only for instance methods.
1028 case OMF_dealloc:
1029 case OMF_finalize:
1030 case OMF_retain:
1031 case OMF_release:
1032 case OMF_autorelease:
1033 case OMF_retainCount:
1034 case OMF_self:
1035 if (!isInstanceMethod())
1036 family = OMF_None;
1037 break;
1038
1039 case OMF_initialize:
1040 if (isInstanceMethod() || !getReturnType()->isVoidType())
1041 family = OMF_None;
1042 break;
1043
1044 case OMF_performSelector:
1045 if (!isInstanceMethod() || !getReturnType()->isObjCIdType())
1046 family = OMF_None;
1047 else {
1048 unsigned noParams = param_size();
1049 if (noParams < 1 || noParams > 3)
1050 family = OMF_None;
1051 else {
1052 ObjCMethodDecl::param_type_iterator it = param_type_begin();
1053 QualType ArgT = (*it);
1054 if (!ArgT->isObjCSelType()) {
1055 family = OMF_None;
1056 break;
1057 }
1058 while (--noParams) {
1059 it++;
1060 ArgT = (*it);
1061 if (!ArgT->isObjCIdType()) {
1062 family = OMF_None;
1063 break;
1064 }
1065 }
1066 }
1067 }
1068 break;
1069
1070 }
1071
1072 // Cache the result.
1073 ObjCMethodDeclBits.Family = family;
1074 return family;
1075}
1076
1077QualType ObjCMethodDecl::getSelfType(ASTContext &Context,
1078 const ObjCInterfaceDecl *OID,
1079 bool &selfIsPseudoStrong,
1080 bool &selfIsConsumed) {
1081 QualType selfTy;
1082 selfIsPseudoStrong = false;
1083 selfIsConsumed = false;
1084 if (isInstanceMethod()) {
1085 // There may be no interface context due to error in declaration
1086 // of the interface (which has been reported). Recover gracefully.
1087 if (OID) {
1088 selfTy = Context.getObjCInterfaceType(OID);
1089 selfTy = Context.getObjCObjectPointerType(selfTy);
1090 } else {
1091 selfTy = Context.getObjCIdType();
1092 }
1093 } else // we have a factory method.
1094 selfTy = Context.getObjCClassType();
1095
1096 if (Context.getLangOpts().ObjCAutoRefCount) {
1097 if (isInstanceMethod()) {
1098 selfIsConsumed = hasAttr<NSConsumesSelfAttr>();
1099
1100 // 'self' is always __strong. It's actually pseudo-strong except
1101 // in init methods (or methods labeled ns_consumes_self), though.
1102 Qualifiers qs;
1103 qs.setObjCLifetime(Qualifiers::OCL_Strong);
1104 selfTy = Context.getQualifiedType(selfTy, qs);
1105
1106 // In addition, 'self' is const unless this is an init method.
1107 if (getMethodFamily() != OMF_init && !selfIsConsumed) {
1108 selfTy = selfTy.withConst();
1109 selfIsPseudoStrong = true;
1110 }
1111 }
1112 else {
1113 assert(isClassMethod())((isClassMethod()) ? static_cast<void> (0) : __assert_fail
("isClassMethod()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/DeclObjC.cpp"
, 1113, __PRETTY_FUNCTION__))
;
1114 // 'self' is always const in class methods.
1115 selfTy = selfTy.withConst();
1116 selfIsPseudoStrong = true;
1117 }
1118 }
1119 return selfTy;
1120}
1121
1122void ObjCMethodDecl::createImplicitParams(ASTContext &Context,
1123 const ObjCInterfaceDecl *OID) {
1124 bool selfIsPseudoStrong, selfIsConsumed;
1125 QualType selfTy =
1126 getSelfType(Context, OID, selfIsPseudoStrong, selfIsConsumed);
1127 auto *Self = ImplicitParamDecl::Create(Context, this, SourceLocation(),
1128 &Context.Idents.get("self"), selfTy,
1129 ImplicitParamDecl::ObjCSelf);
1130 setSelfDecl(Self);
1131
1132 if (selfIsConsumed)
1133 Self->addAttr(NSConsumedAttr::CreateImplicit(Context));
1134
1135 if (selfIsPseudoStrong)
1136 Self->setARCPseudoStrong(true);
1137
1138 setCmdDecl(ImplicitParamDecl::Create(
1139 Context, this, SourceLocation(), &Context.Idents.get("_cmd"),
1140 Context.getObjCSelType(), ImplicitParamDecl::ObjCCmd));
1141}
1142
1143ObjCInterfaceDecl *ObjCMethodDecl::getClassInterface() {
1144 if (auto *ID = dyn_cast<ObjCInterfaceDecl>(getDeclContext()))
1145 return ID;
1146 if (auto *CD = dyn_cast<ObjCCategoryDecl>(getDeclContext()))
1147 return CD->getClassInterface();
1148 if (auto *IMD = dyn_cast<ObjCImplDecl>(getDeclContext()))
1149 return IMD->getClassInterface();
1150 if (isa<ObjCProtocolDecl>(getDeclContext()))
1151 return nullptr;
1152 llvm_unreachable("unknown method context")::llvm::llvm_unreachable_internal("unknown method context", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/DeclObjC.cpp"
, 1152)
;
1153}
1154
1155SourceRange ObjCMethodDecl::getReturnTypeSourceRange() const {
1156 const auto *TSI = getReturnTypeSourceInfo();
1157 if (TSI)
1158 return TSI->getTypeLoc().getSourceRange();
1159 return SourceRange();
1160}
1161
1162QualType ObjCMethodDecl::getSendResultType() const {
1163 ASTContext &Ctx = getASTContext();
1164 return getReturnType().getNonLValueExprType(Ctx)
1165 .substObjCTypeArgs(Ctx, {}, ObjCSubstitutionContext::Result);
1166}
1167
1168QualType ObjCMethodDecl::getSendResultType(QualType receiverType) const {
1169 // FIXME: Handle related result types here.
1170
1171 return getReturnType().getNonLValueExprType(getASTContext())
1172 .substObjCMemberType(receiverType, getDeclContext(),
1173 ObjCSubstitutionContext::Result);
1174}
1175
1176static void CollectOverriddenMethodsRecurse(const ObjCContainerDecl *Container,
1177 const ObjCMethodDecl *Method,
1178 SmallVectorImpl<const ObjCMethodDecl *> &Methods,
1179 bool MovedToSuper) {
1180 if (!Container)
1181 return;
1182
1183 // In categories look for overridden methods from protocols. A method from
1184 // category is not "overridden" since it is considered as the "same" method
1185 // (same USR) as the one from the interface.
1186 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
1187 // Check whether we have a matching method at this category but only if we
1188 // are at the super class level.
1189 if (MovedToSuper)
1190 if (ObjCMethodDecl *
1191 Overridden = Container->getMethod(Method->getSelector(),
1192 Method->isInstanceMethod(),
1193 /*AllowHidden=*/true))
1194 if (Method != Overridden) {
1195 // We found an override at this category; there is no need to look
1196 // into its protocols.
1197 Methods.push_back(Overridden);
1198 return;
1199 }
1200
1201 for (const auto *P : Category->protocols())
1202 CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper);
1203 return;
1204 }
1205
1206 // Check whether we have a matching method at this level.
1207 if (const ObjCMethodDecl *
1208 Overridden = Container->getMethod(Method->getSelector(),
1209 Method->isInstanceMethod(),
1210 /*AllowHidden=*/true))
1211 if (Method != Overridden) {
1212 // We found an override at this level; there is no need to look
1213 // into other protocols or categories.
1214 Methods.push_back(Overridden);
1215 return;
1216 }
1217
1218 if (const auto *Protocol = dyn_cast<ObjCProtocolDecl>(Container)){
1219 for (const auto *P : Protocol->protocols())
1220 CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper);
1221 }
1222
1223 if (const auto *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
1224 for (const auto *P : Interface->protocols())
1225 CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper);
1226
1227 for (const auto *Cat : Interface->known_categories())
1228 CollectOverriddenMethodsRecurse(Cat, Method, Methods, MovedToSuper);
1229
1230 if (const ObjCInterfaceDecl *Super = Interface->getSuperClass())
1231 return CollectOverriddenMethodsRecurse(Super, Method, Methods,
1232 /*MovedToSuper=*/true);
1233 }
1234}
1235
1236static inline void CollectOverriddenMethods(const ObjCContainerDecl *Container,
1237 const ObjCMethodDecl *Method,
1238 SmallVectorImpl<const ObjCMethodDecl *> &Methods) {
1239 CollectOverriddenMethodsRecurse(Container, Method, Methods,
1240 /*MovedToSuper=*/false);
1241}
1242
1243static void collectOverriddenMethodsSlow(const ObjCMethodDecl *Method,
1244 SmallVectorImpl<const ObjCMethodDecl *> &overridden) {
1245 assert(Method->isOverriding())((Method->isOverriding()) ? static_cast<void> (0) : __assert_fail
("Method->isOverriding()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/DeclObjC.cpp"
, 1245, __PRETTY_FUNCTION__))
;
1246
1247 if (const auto *ProtD =
1248 dyn_cast<ObjCProtocolDecl>(Method->getDeclContext())) {
1249 CollectOverriddenMethods(ProtD, Method, overridden);
1250
1251 } else if (const auto *IMD =
1252 dyn_cast<ObjCImplDecl>(Method->getDeclContext())) {
1253 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
1254 if (!ID)
1255 return;
1256 // Start searching for overridden methods using the method from the
1257 // interface as starting point.
1258 if (const ObjCMethodDecl *IFaceMeth = ID->getMethod(Method->getSelector(),
1259 Method->isInstanceMethod(),
1260 /*AllowHidden=*/true))
1261 Method = IFaceMeth;
1262 CollectOverriddenMethods(ID, Method, overridden);
1263
1264 } else if (const auto *CatD =
1265 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext())) {
1266 const ObjCInterfaceDecl *ID = CatD->getClassInterface();
1267 if (!ID)
1268 return;
1269 // Start searching for overridden methods using the method from the
1270 // interface as starting point.
1271 if (const ObjCMethodDecl *IFaceMeth = ID->getMethod(Method->getSelector(),
1272 Method->isInstanceMethod(),
1273 /*AllowHidden=*/true))
1274 Method = IFaceMeth;
1275 CollectOverriddenMethods(ID, Method, overridden);
1276
1277 } else {
1278 CollectOverriddenMethods(
1279 dyn_cast_or_null<ObjCContainerDecl>(Method->getDeclContext()),
1280 Method, overridden);
1281 }
1282}
1283
1284void ObjCMethodDecl::getOverriddenMethods(
1285 SmallVectorImpl<const ObjCMethodDecl *> &Overridden) const {
1286 const ObjCMethodDecl *Method = this;
1287
1288 if (Method->isRedeclaration()) {
1289 Method = cast<ObjCContainerDecl>(Method->getDeclContext())->
1290 getMethod(Method->getSelector(), Method->isInstanceMethod());
1291 }
1292
1293 if (Method->isOverriding()) {
1294 collectOverriddenMethodsSlow(Method, Overridden);
1295 assert(!Overridden.empty() &&((!Overridden.empty() && "ObjCMethodDecl's overriding bit is not as expected"
) ? static_cast<void> (0) : __assert_fail ("!Overridden.empty() && \"ObjCMethodDecl's overriding bit is not as expected\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/DeclObjC.cpp"
, 1296, __PRETTY_FUNCTION__))
1296 "ObjCMethodDecl's overriding bit is not as expected")((!Overridden.empty() && "ObjCMethodDecl's overriding bit is not as expected"
) ? static_cast<void> (0) : __assert_fail ("!Overridden.empty() && \"ObjCMethodDecl's overriding bit is not as expected\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/DeclObjC.cpp"
, 1296, __PRETTY_FUNCTION__))
;
1297 }
1298}
1299
1300const ObjCPropertyDecl *
1301ObjCMethodDecl::findPropertyDecl(bool CheckOverrides) const {
1302 Selector Sel = getSelector();
1303 unsigned NumArgs = Sel.getNumArgs();
1304 if (NumArgs > 1)
1305 return nullptr;
1306
1307 if (isPropertyAccessor()) {
1308 const auto *Container = cast<ObjCContainerDecl>(getParent());
1309 // For accessor stubs, go back to the interface.
1310 if (auto *ImplDecl = dyn_cast<ObjCImplDecl>(Container))
1311 if (isSynthesizedAccessorStub())
1312 Container = ImplDecl->getClassInterface();
1313
1314 bool IsGetter = (NumArgs == 0);
1315 bool IsInstance = isInstanceMethod();
1316
1317 /// Local function that attempts to find a matching property within the
1318 /// given Objective-C container.
1319 auto findMatchingProperty =
1320 [&](const ObjCContainerDecl *Container) -> const ObjCPropertyDecl * {
1321 if (IsInstance) {
1322 for (const auto *I : Container->instance_properties()) {
1323 Selector NextSel = IsGetter ? I->getGetterName()
1324 : I->getSetterName();
1325 if (NextSel == Sel)
1326 return I;
1327 }
1328 } else {
1329 for (const auto *I : Container->class_properties()) {
1330 Selector NextSel = IsGetter ? I->getGetterName()
1331 : I->getSetterName();
1332 if (NextSel == Sel)
1333 return I;
1334 }
1335 }
1336
1337 return nullptr;
1338 };
1339
1340 // Look in the container we were given.
1341 if (const auto *Found = findMatchingProperty(Container))
1342 return Found;
1343
1344 // If we're in a category or extension, look in the main class.
1345 const ObjCInterfaceDecl *ClassDecl = nullptr;
1346 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
1347 ClassDecl = Category->getClassInterface();
1348 if (const auto *Found = findMatchingProperty(ClassDecl))
1349 return Found;
1350 } else {
1351 // Determine whether the container is a class.
1352 ClassDecl = dyn_cast<ObjCInterfaceDecl>(Container);
1353 }
1354
1355 // If we have a class, check its visible extensions.
1356 if (ClassDecl) {
1357 for (const auto *Ext : ClassDecl->visible_extensions()) {
1358 if (Ext == Container)
1359 continue;
1360
1361 if (const auto *Found = findMatchingProperty(Ext))
1362 return Found;
1363 }
1364 }
1365
1366 assert(isSynthesizedAccessorStub() && "expected an accessor stub")((isSynthesizedAccessorStub() && "expected an accessor stub"
) ? static_cast<void> (0) : __assert_fail ("isSynthesizedAccessorStub() && \"expected an accessor stub\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/DeclObjC.cpp"
, 1366, __PRETTY_FUNCTION__))
;
1367 for (const auto *Cat : ClassDecl->known_categories()) {
1368 if (Cat == Container)
1369 continue;
1370
1371 if (const auto *Found = findMatchingProperty(Cat))
1372 return Found;
1373 }
1374
1375 llvm_unreachable("Marked as a property accessor but no property found!")::llvm::llvm_unreachable_internal("Marked as a property accessor but no property found!"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/DeclObjC.cpp"
, 1375)
;
1376 }
1377
1378 if (!CheckOverrides)
1379 return nullptr;
1380
1381 using OverridesTy = SmallVector<const ObjCMethodDecl *, 8>;
1382
1383 OverridesTy Overrides;
1384 getOverriddenMethods(Overrides);
1385 for (const auto *Override : Overrides)
1386 if (const ObjCPropertyDecl *Prop = Override->findPropertyDecl(false))
1387 return Prop;
1388
1389 return nullptr;
1390}
1391
1392//===----------------------------------------------------------------------===//
1393// ObjCTypeParamDecl
1394//===----------------------------------------------------------------------===//
1395
1396void ObjCTypeParamDecl::anchor() {}
1397
1398ObjCTypeParamDecl *ObjCTypeParamDecl::Create(ASTContext &ctx, DeclContext *dc,
1399 ObjCTypeParamVariance variance,
1400 SourceLocation varianceLoc,
1401 unsigned index,
1402 SourceLocation nameLoc,
1403 IdentifierInfo *name,
1404 SourceLocation colonLoc,
1405 TypeSourceInfo *boundInfo) {
1406 auto *TPDecl =
1407 new (ctx, dc) ObjCTypeParamDecl(ctx, dc, variance, varianceLoc, index,
1408 nameLoc, name, colonLoc, boundInfo);
1409 QualType TPType = ctx.getObjCTypeParamType(TPDecl, {});
1410 TPDecl->setTypeForDecl(TPType.getTypePtr());
1411 return TPDecl;
1412}
1413
1414ObjCTypeParamDecl *ObjCTypeParamDecl::CreateDeserialized(ASTContext &ctx,
1415 unsigned ID) {
1416 return new (ctx, ID) ObjCTypeParamDecl(ctx, nullptr,
1417 ObjCTypeParamVariance::Invariant,
1418 SourceLocation(), 0, SourceLocation(),
1419 nullptr, SourceLocation(), nullptr);
1420}
1421
1422SourceRange ObjCTypeParamDecl::getSourceRange() const {
1423 SourceLocation startLoc = VarianceLoc;
1424 if (startLoc.isInvalid())
1425 startLoc = getLocation();
1426
1427 if (hasExplicitBound()) {
1428 return SourceRange(startLoc,
1429 getTypeSourceInfo()->getTypeLoc().getEndLoc());
1430 }
1431
1432 return SourceRange(startLoc);
1433}
1434
1435//===----------------------------------------------------------------------===//
1436// ObjCTypeParamList
1437//===----------------------------------------------------------------------===//
1438ObjCTypeParamList::ObjCTypeParamList(SourceLocation lAngleLoc,
1439 ArrayRef<ObjCTypeParamDecl *> typeParams,
1440 SourceLocation rAngleLoc)
1441 : NumParams(typeParams.size()) {
1442 Brackets.Begin = lAngleLoc.getRawEncoding();
1443 Brackets.End = rAngleLoc.getRawEncoding();
1444 std::copy(typeParams.begin(), typeParams.end(), begin());
1445}
1446
1447ObjCTypeParamList *ObjCTypeParamList::create(
1448 ASTContext &ctx,
1449 SourceLocation lAngleLoc,
1450 ArrayRef<ObjCTypeParamDecl *> typeParams,
1451 SourceLocation rAngleLoc) {
1452 void *mem =
1453 ctx.Allocate(totalSizeToAlloc<ObjCTypeParamDecl *>(typeParams.size()),
1454 alignof(ObjCTypeParamList));
1455 return new (mem) ObjCTypeParamList(lAngleLoc, typeParams, rAngleLoc);
1456}
1457
1458void ObjCTypeParamList::gatherDefaultTypeArgs(
1459 SmallVectorImpl<QualType> &typeArgs) const {
1460 typeArgs.reserve(size());
1461 for (auto typeParam : *this)
1462 typeArgs.push_back(typeParam->getUnderlyingType());
1463}
1464
1465//===----------------------------------------------------------------------===//
1466// ObjCInterfaceDecl
1467//===----------------------------------------------------------------------===//
1468
1469ObjCInterfaceDecl *ObjCInterfaceDecl::Create(const ASTContext &C,
1470 DeclContext *DC,
1471 SourceLocation atLoc,
1472 IdentifierInfo *Id,
1473 ObjCTypeParamList *typeParamList,
1474 ObjCInterfaceDecl *PrevDecl,
1475 SourceLocation ClassLoc,
1476 bool isInternal){
1477 auto *Result = new (C, DC)
1478 ObjCInterfaceDecl(C, DC, atLoc, Id, typeParamList, ClassLoc, PrevDecl,
1479 isInternal);
1480 Result->Data.setInt(!C.getLangOpts().Modules);
1481 C.getObjCInterfaceType(Result, PrevDecl);
1482 return Result;
1483}
1484
1485ObjCInterfaceDecl *ObjCInterfaceDecl::CreateDeserialized(const ASTContext &C,
1486 unsigned ID) {
1487 auto *Result = new (C, ID)
1488 ObjCInterfaceDecl(C, nullptr, SourceLocation(), nullptr, nullptr,
1489 SourceLocation(), nullptr, false);
1490 Result->Data.setInt(!C.getLangOpts().Modules);
1491 return Result;
1492}
1493
1494ObjCInterfaceDecl::ObjCInterfaceDecl(const ASTContext &C, DeclContext *DC,
1495 SourceLocation AtLoc, IdentifierInfo *Id,
1496 ObjCTypeParamList *typeParamList,
1497 SourceLocation CLoc,
1498 ObjCInterfaceDecl *PrevDecl,
1499 bool IsInternal)
1500 : ObjCContainerDecl(ObjCInterface, DC, Id, CLoc, AtLoc),
1501 redeclarable_base(C) {
1502 setPreviousDecl(PrevDecl);
1503
1504 // Copy the 'data' pointer over.
1505 if (PrevDecl)
1506 Data = PrevDecl->Data;
1507
1508 setImplicit(IsInternal);
1509
1510 setTypeParamList(typeParamList);
1511}
1512
1513void ObjCInterfaceDecl::LoadExternalDefinition() const {
1514 assert(data().ExternallyCompleted && "Class is not externally completed")((data().ExternallyCompleted && "Class is not externally completed"
) ? static_cast<void> (0) : __assert_fail ("data().ExternallyCompleted && \"Class is not externally completed\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/DeclObjC.cpp"
, 1514, __PRETTY_FUNCTION__))
;
1515 data().ExternallyCompleted = false;
1516 getASTContext().getExternalSource()->CompleteType(
1517 const_cast<ObjCInterfaceDecl *>(this));
1518}
1519
1520void ObjCInterfaceDecl::setExternallyCompleted() {
1521 assert(getASTContext().getExternalSource() &&((getASTContext().getExternalSource() && "Class can't be externally completed without an external source"
) ? static_cast<void> (0) : __assert_fail ("getASTContext().getExternalSource() && \"Class can't be externally completed without an external source\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/DeclObjC.cpp"
, 1522, __PRETTY_FUNCTION__))
1522 "Class can't be externally completed without an external source")((getASTContext().getExternalSource() && "Class can't be externally completed without an external source"
) ? static_cast<void> (0) : __assert_fail ("getASTContext().getExternalSource() && \"Class can't be externally completed without an external source\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/DeclObjC.cpp"
, 1522, __PRETTY_FUNCTION__))
;
1523 assert(hasDefinition() &&((hasDefinition() && "Forward declarations can't be externally completed"
) ? static_cast<void> (0) : __assert_fail ("hasDefinition() && \"Forward declarations can't be externally completed\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/DeclObjC.cpp"
, 1524, __PRETTY_FUNCTION__))
1524 "Forward declarations can't be externally completed")((hasDefinition() && "Forward declarations can't be externally completed"
) ? static_cast<void> (0) : __assert_fail ("hasDefinition() && \"Forward declarations can't be externally completed\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/DeclObjC.cpp"
, 1524, __PRETTY_FUNCTION__))
;
1525 data().ExternallyCompleted = true;
1526}
1527
1528void ObjCInterfaceDecl::setHasDesignatedInitializers() {
1529 // Check for a complete definition and recover if not so.
1530 if (!isThisDeclarationADefinition())
1531 return;
1532 data().HasDesignatedInitializers = true;
1533}
1534
1535bool ObjCInterfaceDecl::hasDesignatedInitializers() const {
1536 // Check for a complete definition and recover if not so.
1537 if (!isThisDeclarationADefinition())
1538 return false;
1539 if (data().ExternallyCompleted)
1540 LoadExternalDefinition();
1541
1542 return data().HasDesignatedInitializers;
1543}
1544
1545StringRef
1546ObjCInterfaceDecl::getObjCRuntimeNameAsString() const {
1547 if (const auto *ObjCRTName = getAttr<ObjCRuntimeNameAttr>())
1548 return ObjCRTName->getMetadataName();
1549
1550 return getName();
1551}
1552
1553StringRef
1554ObjCImplementationDecl::getObjCRuntimeNameAsString() const {
1555 if (ObjCInterfaceDecl *ID =
1556 const_cast<ObjCImplementationDecl*>(this)->getClassInterface())
1557 return ID->getObjCRuntimeNameAsString();
1558
1559 return getName();
1560}
1561
1562ObjCImplementationDecl *ObjCInterfaceDecl::getImplementation() const {
1563 if (const ObjCInterfaceDecl *Def = getDefinition()) {
14
Calling 'ObjCInterfaceDecl::getDefinition'
18
Returning from 'ObjCInterfaceDecl::getDefinition'
19
Assuming 'Def' is non-null
20
Taking true branch
1564 if (data().ExternallyCompleted)
21
Assuming field 'ExternallyCompleted' is 0
22
Taking false branch
1565 LoadExternalDefinition();
1566
1567 return getASTContext().getObjCImplementation(
23
Returning pointer, which participates in a condition later
1568 const_cast<ObjCInterfaceDecl*>(Def));
1569 }
1570
1571 // FIXME: Should make sure no callers ever do this.
1572 return nullptr;
1573}
1574
1575void ObjCInterfaceDecl::setImplementation(ObjCImplementationDecl *ImplD) {
1576 getASTContext().setObjCImplementation(getDefinition(), ImplD);
1577}
1578
1579namespace {
1580
1581struct SynthesizeIvarChunk {
1582 uint64_t Size;
1583 ObjCIvarDecl *Ivar;
1584
1585 SynthesizeIvarChunk(uint64_t size, ObjCIvarDecl *ivar)
1586 : Size(size), Ivar(ivar) {}
1587};
1588
1589bool operator<(const SynthesizeIvarChunk & LHS,
1590 const SynthesizeIvarChunk &RHS) {
1591 return LHS.Size < RHS.Size;
1592}
1593
1594} // namespace
1595
1596/// all_declared_ivar_begin - return first ivar declared in this class,
1597/// its extensions and its implementation. Lazily build the list on first
1598/// access.
1599///
1600/// Caveat: The list returned by this method reflects the current
1601/// state of the parser. The cache will be updated for every ivar
1602/// added by an extension or the implementation when they are
1603/// encountered.
1604/// See also ObjCIvarDecl::Create().
1605ObjCIvarDecl *ObjCInterfaceDecl::all_declared_ivar_begin() {
1606 // FIXME: Should make sure no callers ever do this.
1607 if (!hasDefinition())
1
Calling 'ObjCInterfaceDecl::hasDefinition'
5
Returning from 'ObjCInterfaceDecl::hasDefinition'
6
Assuming the condition is false
7
Taking false branch
1608 return nullptr;
1609
1610 ObjCIvarDecl *curIvar = nullptr;
8
'curIvar' initialized to a null pointer value
1611 if (!data().IvarList) {
9
Assuming field 'IvarList' is non-null
10
Taking false branch
1612 if (!ivar_empty()) {
1613 ObjCInterfaceDecl::ivar_iterator I = ivar_begin(), E = ivar_end();
1614 data().IvarList = *I; ++I;
1615 for (curIvar = data().IvarList; I != E; curIvar = *I, ++I)
1616 curIvar->setNextIvar(*I);
1617 }
1618
1619 for (const auto *Ext : known_extensions()) {
1620 if (!Ext->ivar_empty()) {
1621 ObjCCategoryDecl::ivar_iterator
1622 I = Ext->ivar_begin(),
1623 E = Ext->ivar_end();
1624 if (!data().IvarList) {
1625 data().IvarList = *I; ++I;
1626 curIvar = data().IvarList;
1627 }
1628 for ( ;I != E; curIvar = *I, ++I)
1629 curIvar->setNextIvar(*I);
1630 }
1631 }
1632 data().IvarListMissingImplementation = true;
1633 }
1634
1635 // cached and complete!
1636 if (!data().IvarListMissingImplementation)
11
Assuming field 'IvarListMissingImplementation' is not equal to 0
12
Taking false branch
1637 return data().IvarList;
1638
1639 if (ObjCImplementationDecl *ImplDecl = getImplementation()) {
13
Calling 'ObjCInterfaceDecl::getImplementation'
24
Returning from 'ObjCInterfaceDecl::getImplementation'
25
Assuming 'ImplDecl' is non-null
26
Taking true branch
1640 data().IvarListMissingImplementation = false;
1641 if (!ImplDecl->ivar_empty()) {
27
Calling 'ObjCImplementationDecl::ivar_empty'
36
Returning from 'ObjCImplementationDecl::ivar_empty'
37
Taking true branch
1642 SmallVector<SynthesizeIvarChunk, 16> layout;
1643 for (auto *IV : ImplDecl->ivars()) {
1644 if (IV->getSynthesize() && !IV->isInvalidDecl()) {
38
Assuming the condition is false
1645 layout.push_back(SynthesizeIvarChunk(
1646 IV->getASTContext().getTypeSize(IV->getType()), IV));
1647 continue;
1648 }
1649 if (!data().IvarList)
39
Assuming field 'IvarList' is non-null
40
Taking false branch
1650 data().IvarList = IV;
1651 else
1652 curIvar->setNextIvar(IV);
41
Called C++ object pointer is null
1653 curIvar = IV;
1654 }
1655
1656 if (!layout.empty()) {
1657 // Order synthesized ivars by their size.
1658 llvm::stable_sort(layout);
1659 unsigned Ix = 0, EIx = layout.size();
1660 if (!data().IvarList) {
1661 data().IvarList = layout[0].Ivar; Ix++;
1662 curIvar = data().IvarList;
1663 }
1664 for ( ; Ix != EIx; curIvar = layout[Ix].Ivar, Ix++)
1665 curIvar->setNextIvar(layout[Ix].Ivar);
1666 }
1667 }
1668 }
1669 return data().IvarList;
1670}
1671
1672/// FindCategoryDeclaration - Finds category declaration in the list of
1673/// categories for this class and returns it. Name of the category is passed
1674/// in 'CategoryId'. If category not found, return 0;
1675///
1676ObjCCategoryDecl *
1677ObjCInterfaceDecl::FindCategoryDeclaration(IdentifierInfo *CategoryId) const {
1678 // FIXME: Should make sure no callers ever do this.
1679 if (!hasDefinition())
1680 return nullptr;
1681
1682 if (data().ExternallyCompleted)
1683 LoadExternalDefinition();
1684
1685 for (auto *Cat : visible_categories())
1686 if (Cat->getIdentifier() == CategoryId)
1687 return Cat;
1688
1689 return nullptr;
1690}
1691
1692ObjCMethodDecl *
1693ObjCInterfaceDecl::getCategoryInstanceMethod(Selector Sel) const {
1694 for (const auto *Cat : visible_categories()) {
1695 if (ObjCCategoryImplDecl *Impl = Cat->getImplementation())
1696 if (ObjCMethodDecl *MD = Impl->getInstanceMethod(Sel))
1697 return MD;
1698 }
1699
1700 return nullptr;
1701}
1702
1703ObjCMethodDecl *ObjCInterfaceDecl::getCategoryClassMethod(Selector Sel) const {
1704 for (const auto *Cat : visible_categories()) {
1705 if (ObjCCategoryImplDecl *Impl = Cat->getImplementation())
1706 if (ObjCMethodDecl *MD = Impl->getClassMethod(Sel))
1707 return MD;
1708 }
1709
1710 return nullptr;
1711}
1712
1713/// ClassImplementsProtocol - Checks that 'lProto' protocol
1714/// has been implemented in IDecl class, its super class or categories (if
1715/// lookupCategory is true).
1716bool ObjCInterfaceDecl::ClassImplementsProtocol(ObjCProtocolDecl *lProto,
1717 bool lookupCategory,
1718 bool RHSIsQualifiedID) {
1719 if (!hasDefinition())
1720 return false;
1721
1722 ObjCInterfaceDecl *IDecl = this;
1723 // 1st, look up the class.
1724 for (auto *PI : IDecl->protocols()){
1725 if (getASTContext().ProtocolCompatibleWithProtocol(lProto, PI))
1726 return true;
1727 // This is dubious and is added to be compatible with gcc. In gcc, it is
1728 // also allowed assigning a protocol-qualified 'id' type to a LHS object
1729 // when protocol in qualified LHS is in list of protocols in the rhs 'id'
1730 // object. This IMO, should be a bug.
1731 // FIXME: Treat this as an extension, and flag this as an error when GCC
1732 // extensions are not enabled.
1733 if (RHSIsQualifiedID &&
1734 getASTContext().ProtocolCompatibleWithProtocol(PI, lProto))
1735 return true;
1736 }
1737
1738 // 2nd, look up the category.
1739 if (lookupCategory)
1740 for (const auto *Cat : visible_categories()) {
1741 for (auto *PI : Cat->protocols())
1742 if (getASTContext().ProtocolCompatibleWithProtocol(lProto, PI))
1743 return true;
1744 }
1745
1746 // 3rd, look up the super class(s)
1747 if (IDecl->getSuperClass())
1748 return
1749 IDecl->getSuperClass()->ClassImplementsProtocol(lProto, lookupCategory,
1750 RHSIsQualifiedID);
1751
1752 return false;
1753}
1754
1755//===----------------------------------------------------------------------===//
1756// ObjCIvarDecl
1757//===----------------------------------------------------------------------===//
1758
1759void ObjCIvarDecl::anchor() {}
1760
1761ObjCIvarDecl *ObjCIvarDecl::Create(ASTContext &C, ObjCContainerDecl *DC,
1762 SourceLocation StartLoc,
1763 SourceLocation IdLoc, IdentifierInfo *Id,
1764 QualType T, TypeSourceInfo *TInfo,
1765 AccessControl ac, Expr *BW,
1766 bool synthesized) {
1767 if (DC) {
1768 // Ivar's can only appear in interfaces, implementations (via synthesized
1769 // properties), and class extensions (via direct declaration, or synthesized
1770 // properties).
1771 //
1772 // FIXME: This should really be asserting this:
1773 // (isa<ObjCCategoryDecl>(DC) &&
1774 // cast<ObjCCategoryDecl>(DC)->IsClassExtension()))
1775 // but unfortunately we sometimes place ivars into non-class extension
1776 // categories on error. This breaks an AST invariant, and should not be
1777 // fixed.
1778 assert((isa<ObjCInterfaceDecl>(DC) || isa<ObjCImplementationDecl>(DC) ||(((isa<ObjCInterfaceDecl>(DC) || isa<ObjCImplementationDecl
>(DC) || isa<ObjCCategoryDecl>(DC)) && "Invalid ivar decl context!"
) ? static_cast<void> (0) : __assert_fail ("(isa<ObjCInterfaceDecl>(DC) || isa<ObjCImplementationDecl>(DC) || isa<ObjCCategoryDecl>(DC)) && \"Invalid ivar decl context!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/DeclObjC.cpp"
, 1780, __PRETTY_FUNCTION__))
1779 isa<ObjCCategoryDecl>(DC)) &&(((isa<ObjCInterfaceDecl>(DC) || isa<ObjCImplementationDecl
>(DC) || isa<ObjCCategoryDecl>(DC)) && "Invalid ivar decl context!"
) ? static_cast<void> (0) : __assert_fail ("(isa<ObjCInterfaceDecl>(DC) || isa<ObjCImplementationDecl>(DC) || isa<ObjCCategoryDecl>(DC)) && \"Invalid ivar decl context!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/DeclObjC.cpp"
, 1780, __PRETTY_FUNCTION__))
1780 "Invalid ivar decl context!")(((isa<ObjCInterfaceDecl>(DC) || isa<ObjCImplementationDecl
>(DC) || isa<ObjCCategoryDecl>(DC)) && "Invalid ivar decl context!"
) ? static_cast<void> (0) : __assert_fail ("(isa<ObjCInterfaceDecl>(DC) || isa<ObjCImplementationDecl>(DC) || isa<ObjCCategoryDecl>(DC)) && \"Invalid ivar decl context!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/DeclObjC.cpp"
, 1780, __PRETTY_FUNCTION__))
;
1781 // Once a new ivar is created in any of class/class-extension/implementation
1782 // decl contexts, the previously built IvarList must be rebuilt.
1783 auto *ID = dyn_cast<ObjCInterfaceDecl>(DC);
1784 if (!ID) {
1785 if (auto *IM = dyn_cast<ObjCImplementationDecl>(DC))
1786 ID = IM->getClassInterface();
1787 else
1788 ID = cast<ObjCCategoryDecl>(DC)->getClassInterface();
1789 }
1790 ID->setIvarList(nullptr);
1791 }
1792
1793 return new (C, DC) ObjCIvarDecl(DC, StartLoc, IdLoc, Id, T, TInfo, ac, BW,
1794 synthesized);
1795}
1796
1797ObjCIvarDecl *ObjCIvarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1798 return new (C, ID) ObjCIvarDecl(nullptr, SourceLocation(), SourceLocation(),
1799 nullptr, QualType(), nullptr,
1800 ObjCIvarDecl::None, nullptr, false);
1801}
1802
1803const ObjCInterfaceDecl *ObjCIvarDecl::getContainingInterface() const {
1804 const auto *DC = cast<ObjCContainerDecl>(getDeclContext());
1805
1806 switch (DC->getKind()) {
1807 default:
1808 case ObjCCategoryImpl:
1809 case ObjCProtocol:
1810 llvm_unreachable("invalid ivar container!")::llvm::llvm_unreachable_internal("invalid ivar container!", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/DeclObjC.cpp"
, 1810)
;
1811
1812 // Ivars can only appear in class extension categories.
1813 case ObjCCategory: {
1814 const auto *CD = cast<ObjCCategoryDecl>(DC);
1815 assert(CD->IsClassExtension() && "invalid container for ivar!")((CD->IsClassExtension() && "invalid container for ivar!"
) ? static_cast<void> (0) : __assert_fail ("CD->IsClassExtension() && \"invalid container for ivar!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/DeclObjC.cpp"
, 1815, __PRETTY_FUNCTION__))
;
1816 return CD->getClassInterface();
1817 }
1818
1819 case ObjCImplementation:
1820 return cast<ObjCImplementationDecl>(DC)->getClassInterface();
1821
1822 case ObjCInterface:
1823 return cast<ObjCInterfaceDecl>(DC);
1824 }
1825}
1826
1827QualType ObjCIvarDecl::getUsageType(QualType objectType) const {
1828 return getType().substObjCMemberType(objectType, getDeclContext(),
1829 ObjCSubstitutionContext::Property);
1830}
1831
1832//===----------------------------------------------------------------------===//
1833// ObjCAtDefsFieldDecl
1834//===----------------------------------------------------------------------===//
1835
1836void ObjCAtDefsFieldDecl::anchor() {}
1837
1838ObjCAtDefsFieldDecl
1839*ObjCAtDefsFieldDecl::Create(ASTContext &C, DeclContext *DC,
1840 SourceLocation StartLoc, SourceLocation IdLoc,
1841 IdentifierInfo *Id, QualType T, Expr *BW) {
1842 return new (C, DC) ObjCAtDefsFieldDecl(DC, StartLoc, IdLoc, Id, T, BW);
1843}
1844
1845ObjCAtDefsFieldDecl *ObjCAtDefsFieldDecl::CreateDeserialized(ASTContext &C,
1846 unsigned ID) {
1847 return new (C, ID) ObjCAtDefsFieldDecl(nullptr, SourceLocation(),
1848 SourceLocation(), nullptr, QualType(),
1849 nullptr);
1850}
1851
1852//===----------------------------------------------------------------------===//
1853// ObjCProtocolDecl
1854//===----------------------------------------------------------------------===//
1855
1856void ObjCProtocolDecl::anchor() {}
1857
1858ObjCProtocolDecl::ObjCProtocolDecl(ASTContext &C, DeclContext *DC,
1859 IdentifierInfo *Id, SourceLocation nameLoc,
1860 SourceLocation atStartLoc,
1861 ObjCProtocolDecl *PrevDecl)
1862 : ObjCContainerDecl(ObjCProtocol, DC, Id, nameLoc, atStartLoc),
1863 redeclarable_base(C) {
1864 setPreviousDecl(PrevDecl);
1865 if (PrevDecl)
1866 Data = PrevDecl->Data;
1867}
1868
1869ObjCProtocolDecl *ObjCProtocolDecl::Create(ASTContext &C, DeclContext *DC,
1870 IdentifierInfo *Id,
1871 SourceLocation nameLoc,
1872 SourceLocation atStartLoc,
1873 ObjCProtocolDecl *PrevDecl) {
1874 auto *Result =
1875 new (C, DC) ObjCProtocolDecl(C, DC, Id, nameLoc, atStartLoc, PrevDecl);
1876 Result->Data.setInt(!C.getLangOpts().Modules);
1877 return Result;
1878}
1879
1880ObjCProtocolDecl *ObjCProtocolDecl::CreateDeserialized(ASTContext &C,
1881 unsigned ID) {
1882 ObjCProtocolDecl *Result =
1883 new (C, ID) ObjCProtocolDecl(C, nullptr, nullptr, SourceLocation(),
1884 SourceLocation(), nullptr);
1885 Result->Data.setInt(!C.getLangOpts().Modules);
1886 return Result;
1887}
1888
1889ObjCProtocolDecl *ObjCProtocolDecl::lookupProtocolNamed(IdentifierInfo *Name) {
1890 ObjCProtocolDecl *PDecl = this;
1891
1892 if (Name == getIdentifier())
1893 return PDecl;
1894
1895 for (auto *I : protocols())
1896 if ((PDecl = I->lookupProtocolNamed(Name)))
1897 return PDecl;
1898
1899 return nullptr;
1900}
1901
1902// lookupMethod - Lookup a instance/class method in the protocol and protocols
1903// it inherited.
1904ObjCMethodDecl *ObjCProtocolDecl::lookupMethod(Selector Sel,
1905 bool isInstance) const {
1906 ObjCMethodDecl *MethodDecl = nullptr;
1907
1908 // If there is no definition or the definition is hidden, we don't find
1909 // anything.
1910 const ObjCProtocolDecl *Def = getDefinition();
1911 if (!Def || Def->isHidden())
1912 return nullptr;
1913
1914 if ((MethodDecl = getMethod(Sel, isInstance)))
1915 return MethodDecl;
1916
1917 for (const auto *I : protocols())
1918 if ((MethodDecl = I->lookupMethod(Sel, isInstance)))
1919 return MethodDecl;
1920 return nullptr;
1921}
1922
1923void ObjCProtocolDecl::allocateDefinitionData() {
1924 assert(!Data.getPointer() && "Protocol already has a definition!")((!Data.getPointer() && "Protocol already has a definition!"
) ? static_cast<void> (0) : __assert_fail ("!Data.getPointer() && \"Protocol already has a definition!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/DeclObjC.cpp"
, 1924, __PRETTY_FUNCTION__))
;
1925 Data.setPointer(new (getASTContext()) DefinitionData);
1926 Data.getPointer()->Definition = this;
1927}
1928
1929void ObjCProtocolDecl::startDefinition() {
1930 allocateDefinitionData();
1931
1932 // Update all of the declarations with a pointer to the definition.
1933 for (auto *RD : redecls())
1934 RD->Data = this->Data;
1935}
1936
1937void ObjCProtocolDecl::collectPropertiesToImplement(PropertyMap &PM,
1938 PropertyDeclOrder &PO) const {
1939 if (const ObjCProtocolDecl *PDecl = getDefinition()) {
1940 for (auto *Prop : PDecl->properties()) {
1941 // Insert into PM if not there already.
1942 PM.insert(std::make_pair(
1943 std::make_pair(Prop->getIdentifier(), Prop->isClassProperty()),
1944 Prop));
1945 PO.push_back(Prop);
1946 }
1947 // Scan through protocol's protocols.
1948 for (const auto *PI : PDecl->protocols())
1949 PI->collectPropertiesToImplement(PM, PO);
1950 }
1951}
1952
1953void ObjCProtocolDecl::collectInheritedProtocolProperties(
1954 const ObjCPropertyDecl *Property, ProtocolPropertySet &PS,
1955 PropertyDeclOrder &PO) const {
1956 if (const ObjCProtocolDecl *PDecl = getDefinition()) {
1957 if (!PS.insert(PDecl).second)
1958 return;
1959 for (auto *Prop : PDecl->properties()) {
1960 if (Prop == Property)
1961 continue;
1962 if (Prop->getIdentifier() == Property->getIdentifier()) {
1963 PO.push_back(Prop);
1964 return;
1965 }
1966 }
1967 // Scan through protocol's protocols which did not have a matching property.
1968 for (const auto *PI : PDecl->protocols())
1969 PI->collectInheritedProtocolProperties(Property, PS, PO);
1970 }
1971}
1972
1973StringRef
1974ObjCProtocolDecl::getObjCRuntimeNameAsString() const {
1975 if (const auto *ObjCRTName = getAttr<ObjCRuntimeNameAttr>())
1976 return ObjCRTName->getMetadataName();
1977
1978 return getName();
1979}
1980
1981//===----------------------------------------------------------------------===//
1982// ObjCCategoryDecl
1983//===----------------------------------------------------------------------===//
1984
1985void ObjCCategoryDecl::anchor() {}
1986
1987ObjCCategoryDecl::ObjCCategoryDecl(DeclContext *DC, SourceLocation AtLoc,
1988 SourceLocation ClassNameLoc,
1989 SourceLocation CategoryNameLoc,
1990 IdentifierInfo *Id, ObjCInterfaceDecl *IDecl,
1991 ObjCTypeParamList *typeParamList,
1992 SourceLocation IvarLBraceLoc,
1993 SourceLocation IvarRBraceLoc)
1994 : ObjCContainerDecl(ObjCCategory, DC, Id, ClassNameLoc, AtLoc),
1995 ClassInterface(IDecl), CategoryNameLoc(CategoryNameLoc),
1996 IvarLBraceLoc(IvarLBraceLoc), IvarRBraceLoc(IvarRBraceLoc) {
1997 setTypeParamList(typeParamList);
1998}
1999
2000ObjCCategoryDecl *ObjCCategoryDecl::Create(ASTContext &C, DeclContext *DC,
2001 SourceLocation AtLoc,
2002 SourceLocation ClassNameLoc,
2003 SourceLocation CategoryNameLoc,
2004 IdentifierInfo *Id,
2005 ObjCInterfaceDecl *IDecl,
2006 ObjCTypeParamList *typeParamList,
2007 SourceLocation IvarLBraceLoc,
2008 SourceLocation IvarRBraceLoc) {
2009 auto *CatDecl =
2010 new (C, DC) ObjCCategoryDecl(DC, AtLoc, ClassNameLoc, CategoryNameLoc, Id,
2011 IDecl, typeParamList, IvarLBraceLoc,
2012 IvarRBraceLoc);
2013 if (IDecl) {
2014 // Link this category into its class's category list.
2015 CatDecl->NextClassCategory = IDecl->getCategoryListRaw();
2016 if (IDecl->hasDefinition()) {
2017 IDecl->setCategoryListRaw(CatDecl);
2018 if (ASTMutationListener *L = C.getASTMutationListener())
2019 L->AddedObjCCategoryToInterface(CatDecl, IDecl);
2020 }
2021 }
2022
2023 return CatDecl;
2024}
2025
2026ObjCCategoryDecl *ObjCCategoryDecl::CreateDeserialized(ASTContext &C,
2027 unsigned ID) {
2028 return new (C, ID) ObjCCategoryDecl(nullptr, SourceLocation(),
2029 SourceLocation(), SourceLocation(),
2030 nullptr, nullptr, nullptr);
2031}
2032
2033ObjCCategoryImplDecl *ObjCCategoryDecl::getImplementation() const {
2034 return getASTContext().getObjCImplementation(
2035 const_cast<ObjCCategoryDecl*>(this));
2036}
2037
2038void ObjCCategoryDecl::setImplementation(ObjCCategoryImplDecl *ImplD) {
2039 getASTContext().setObjCImplementation(this, ImplD);
2040}
2041
2042void ObjCCategoryDecl::setTypeParamList(ObjCTypeParamList *TPL) {
2043 TypeParamList = TPL;
2044 if (!TPL)
2045 return;
2046 // Set the declaration context of each of the type parameters.
2047 for (auto *typeParam : *TypeParamList)
2048 typeParam->setDeclContext(this);
2049}
2050
2051//===----------------------------------------------------------------------===//
2052// ObjCCategoryImplDecl
2053//===----------------------------------------------------------------------===//
2054
2055void ObjCCategoryImplDecl::anchor() {}
2056
2057ObjCCategoryImplDecl *
2058ObjCCategoryImplDecl::Create(ASTContext &C, DeclContext *DC,
2059 IdentifierInfo *Id,
2060 ObjCInterfaceDecl *ClassInterface,
2061 SourceLocation nameLoc,
2062 SourceLocation atStartLoc,
2063 SourceLocation CategoryNameLoc) {
2064 if (ClassInterface && ClassInterface->hasDefinition())
2065 ClassInterface = ClassInterface->getDefinition();
2066 return new (C, DC) ObjCCategoryImplDecl(DC, Id, ClassInterface, nameLoc,
2067 atStartLoc, CategoryNameLoc);
2068}
2069
2070ObjCCategoryImplDecl *ObjCCategoryImplDecl::CreateDeserialized(ASTContext &C,
2071 unsigned ID) {
2072 return new (C, ID) ObjCCategoryImplDecl(nullptr, nullptr, nullptr,
2073 SourceLocation(), SourceLocation(),
2074 SourceLocation());
2075}
2076
2077ObjCCategoryDecl *ObjCCategoryImplDecl::getCategoryDecl() const {
2078 // The class interface might be NULL if we are working with invalid code.
2079 if (const ObjCInterfaceDecl *ID = getClassInterface())
2080 return ID->FindCategoryDeclaration(getIdentifier());
2081 return nullptr;
2082}
2083
2084void ObjCImplDecl::anchor() {}
2085
2086void ObjCImplDecl::addPropertyImplementation(ObjCPropertyImplDecl *property) {
2087 // FIXME: The context should be correct before we get here.
2088 property->setLexicalDeclContext(this);
2089 addDecl(property);
2090}
2091
2092void ObjCImplDecl::setClassInterface(ObjCInterfaceDecl *IFace) {
2093 ASTContext &Ctx = getASTContext();
2094
2095 if (auto *ImplD = dyn_cast_or_null<ObjCImplementationDecl>(this)) {
2096 if (IFace)
2097 Ctx.setObjCImplementation(IFace, ImplD);
2098
2099 } else if (auto *ImplD = dyn_cast_or_null<ObjCCategoryImplDecl>(this)) {
2100 if (ObjCCategoryDecl *CD = IFace->FindCategoryDeclaration(getIdentifier()))
2101 Ctx.setObjCImplementation(CD, ImplD);
2102 }
2103
2104 ClassInterface = IFace;
2105}
2106
2107/// FindPropertyImplIvarDecl - This method lookup the ivar in the list of
2108/// properties implemented in this \@implementation block and returns
2109/// the implemented property that uses it.
2110ObjCPropertyImplDecl *ObjCImplDecl::
2111FindPropertyImplIvarDecl(IdentifierInfo *ivarId) const {
2112 for (auto *PID : property_impls())
2113 if (PID->getPropertyIvarDecl() &&
2114 PID->getPropertyIvarDecl()->getIdentifier() == ivarId)
2115 return PID;
2116 return nullptr;
2117}
2118
2119/// FindPropertyImplDecl - This method looks up a previous ObjCPropertyImplDecl
2120/// added to the list of those properties \@synthesized/\@dynamic in this
2121/// category \@implementation block.
2122ObjCPropertyImplDecl *ObjCImplDecl::
2123FindPropertyImplDecl(IdentifierInfo *Id,
2124 ObjCPropertyQueryKind QueryKind) const {
2125 ObjCPropertyImplDecl *ClassPropImpl = nullptr;
2126 for (auto *PID : property_impls())
2127 // If queryKind is unknown, we return the instance property if one
2128 // exists; otherwise we return the class property.
2129 if (PID->getPropertyDecl()->getIdentifier() == Id) {
2130 if ((QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_unknown &&
2131 !PID->getPropertyDecl()->isClassProperty()) ||
2132 (QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_class &&
2133 PID->getPropertyDecl()->isClassProperty()) ||
2134 (QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_instance &&
2135 !PID->getPropertyDecl()->isClassProperty()))
2136 return PID;
2137
2138 if (PID->getPropertyDecl()->isClassProperty())
2139 ClassPropImpl = PID;
2140 }
2141
2142 if (QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_unknown)
2143 // We can't find the instance property, return the class property.
2144 return ClassPropImpl;
2145
2146 return nullptr;
2147}
2148
2149raw_ostream &clang::operator<<(raw_ostream &OS,
2150 const ObjCCategoryImplDecl &CID) {
2151 OS << CID.getName();
2152 return OS;
2153}
2154
2155//===----------------------------------------------------------------------===//
2156// ObjCImplementationDecl
2157//===----------------------------------------------------------------------===//
2158
2159void ObjCImplementationDecl::anchor() {}
2160
2161ObjCImplementationDecl *
2162ObjCImplementationDecl::Create(ASTContext &C, DeclContext *DC,
2163 ObjCInterfaceDecl *ClassInterface,
2164 ObjCInterfaceDecl *SuperDecl,
2165 SourceLocation nameLoc,
2166 SourceLocation atStartLoc,
2167 SourceLocation superLoc,
2168 SourceLocation IvarLBraceLoc,
2169 SourceLocation IvarRBraceLoc) {
2170 if (ClassInterface && ClassInterface->hasDefinition())
2171 ClassInterface = ClassInterface->getDefinition();
2172 return new (C, DC) ObjCImplementationDecl(DC, ClassInterface, SuperDecl,
2173 nameLoc, atStartLoc, superLoc,
2174 IvarLBraceLoc, IvarRBraceLoc);
2175}
2176
2177ObjCImplementationDecl *
2178ObjCImplementationDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2179 return new (C, ID) ObjCImplementationDecl(nullptr, nullptr, nullptr,
2180 SourceLocation(), SourceLocation());
2181}
2182
2183void ObjCImplementationDecl::setIvarInitializers(ASTContext &C,
2184 CXXCtorInitializer ** initializers,
2185 unsigned numInitializers) {
2186 if (numInitializers > 0) {
2187 NumIvarInitializers = numInitializers;
2188 auto **ivarInitializers = new (C) CXXCtorInitializer*[NumIvarInitializers];
2189 memcpy(ivarInitializers, initializers,
2190 numInitializers * sizeof(CXXCtorInitializer*));
2191 IvarInitializers = ivarInitializers;
2192 }
2193}
2194
2195ObjCImplementationDecl::init_const_iterator
2196ObjCImplementationDecl::init_begin() const {
2197 return IvarInitializers.get(getASTContext().getExternalSource());
2198}
2199
2200raw_ostream &clang::operator<<(raw_ostream &OS,
2201 const ObjCImplementationDecl &ID) {
2202 OS << ID.getName();
2203 return OS;
2204}
2205
2206//===----------------------------------------------------------------------===//
2207// ObjCCompatibleAliasDecl
2208//===----------------------------------------------------------------------===//
2209
2210void ObjCCompatibleAliasDecl::anchor() {}
2211
2212ObjCCompatibleAliasDecl *
2213ObjCCompatibleAliasDecl::Create(ASTContext &C, DeclContext *DC,
2214 SourceLocation L,
2215 IdentifierInfo *Id,
2216 ObjCInterfaceDecl* AliasedClass) {
2217 return new (C, DC) ObjCCompatibleAliasDecl(DC, L, Id, AliasedClass);
2218}
2219
2220ObjCCompatibleAliasDecl *
2221ObjCCompatibleAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2222 return new (C, ID) ObjCCompatibleAliasDecl(nullptr, SourceLocation(),
2223 nullptr, nullptr);
2224}
2225
2226//===----------------------------------------------------------------------===//
2227// ObjCPropertyDecl
2228//===----------------------------------------------------------------------===//
2229
2230void ObjCPropertyDecl::anchor() {}
2231
2232ObjCPropertyDecl *ObjCPropertyDecl::Create(ASTContext &C, DeclContext *DC,
2233 SourceLocation L,
2234 IdentifierInfo *Id,
2235 SourceLocation AtLoc,
2236 SourceLocation LParenLoc,
2237 QualType T,
2238 TypeSourceInfo *TSI,
2239 PropertyControl propControl) {
2240 return new (C, DC) ObjCPropertyDecl(DC, L, Id, AtLoc, LParenLoc, T, TSI,
2241 propControl);
2242}
2243
2244ObjCPropertyDecl *ObjCPropertyDecl::CreateDeserialized(ASTContext &C,
2245 unsigned ID) {
2246 return new (C, ID) ObjCPropertyDecl(nullptr, SourceLocation(), nullptr,
2247 SourceLocation(), SourceLocation(),
2248 QualType(), nullptr, None);
2249}
2250
2251QualType ObjCPropertyDecl::getUsageType(QualType objectType) const {
2252 return DeclType.substObjCMemberType(objectType, getDeclContext(),
2253 ObjCSubstitutionContext::Property);
2254}
2255
2256//===----------------------------------------------------------------------===//
2257// ObjCPropertyImplDecl
2258//===----------------------------------------------------------------------===//
2259
2260ObjCPropertyImplDecl *ObjCPropertyImplDecl::Create(ASTContext &C,
2261 DeclContext *DC,
2262 SourceLocation atLoc,
2263 SourceLocation L,
2264 ObjCPropertyDecl *property,
2265 Kind PK,
2266 ObjCIvarDecl *ivar,
2267 SourceLocation ivarLoc) {
2268 return new (C, DC) ObjCPropertyImplDecl(DC, atLoc, L, property, PK, ivar,
2269 ivarLoc);
2270}
2271
2272ObjCPropertyImplDecl *ObjCPropertyImplDecl::CreateDeserialized(ASTContext &C,
2273 unsigned ID) {
2274 return new (C, ID) ObjCPropertyImplDecl(nullptr, SourceLocation(),
2275 SourceLocation(), nullptr, Dynamic,
2276 nullptr, SourceLocation());
2277}
2278
2279SourceRange ObjCPropertyImplDecl::getSourceRange() const {
2280 SourceLocation EndLoc = getLocation();
2281 if (IvarLoc.isValid())
2282 EndLoc = IvarLoc;
2283
2284 return SourceRange(AtLoc, EndLoc);
2285}

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclObjC.h

1//===- DeclObjC.h - Classes for representing declarations -------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the DeclObjC interface and subclasses.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_DECLOBJC_H
14#define LLVM_CLANG_AST_DECLOBJC_H
15
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclBase.h"
18#include "clang/AST/ExternalASTSource.h"
19#include "clang/AST/Redeclarable.h"
20#include "clang/AST/SelectorLocationsKind.h"
21#include "clang/AST/Type.h"
22#include "clang/Basic/IdentifierTable.h"
23#include "clang/Basic/LLVM.h"
24#include "clang/Basic/SourceLocation.h"
25#include "clang/Basic/Specifiers.h"
26#include "llvm/ADT/ArrayRef.h"
27#include "llvm/ADT/DenseMap.h"
28#include "llvm/ADT/DenseSet.h"
29#include "llvm/ADT/None.h"
30#include "llvm/ADT/PointerIntPair.h"
31#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/StringRef.h"
33#include "llvm/ADT/iterator_range.h"
34#include "llvm/Support/Compiler.h"
35#include "llvm/Support/TrailingObjects.h"
36#include <cassert>
37#include <cstddef>
38#include <cstdint>
39#include <iterator>
40#include <string>
41#include <utility>
42
43namespace clang {
44
45class ASTContext;
46class CompoundStmt;
47class CXXCtorInitializer;
48class Expr;
49class ObjCCategoryDecl;
50class ObjCCategoryImplDecl;
51class ObjCImplementationDecl;
52class ObjCInterfaceDecl;
53class ObjCIvarDecl;
54class ObjCPropertyDecl;
55class ObjCPropertyImplDecl;
56class ObjCProtocolDecl;
57class Stmt;
58
59class ObjCListBase {
60protected:
61 /// List is an array of pointers to objects that are not owned by this object.
62 void **List = nullptr;
63 unsigned NumElts = 0;
64
65public:
66 ObjCListBase() = default;
67 ObjCListBase(const ObjCListBase &) = delete;
68 ObjCListBase &operator=(const ObjCListBase &) = delete;
69
70 unsigned size() const { return NumElts; }
71 bool empty() const { return NumElts == 0; }
72
73protected:
74 void set(void *const* InList, unsigned Elts, ASTContext &Ctx);
75};
76
77/// ObjCList - This is a simple template class used to hold various lists of
78/// decls etc, which is heavily used by the ObjC front-end. This only use case
79/// this supports is setting the list all at once and then reading elements out
80/// of it.
81template <typename T>
82class ObjCList : public ObjCListBase {
83public:
84 void set(T* const* InList, unsigned Elts, ASTContext &Ctx) {
85 ObjCListBase::set(reinterpret_cast<void*const*>(InList), Elts, Ctx);
86 }
87
88 using iterator = T* const *;
89
90 iterator begin() const { return (iterator)List; }
91 iterator end() const { return (iterator)List+NumElts; }
92
93 T* operator[](unsigned Idx) const {
94 assert(Idx < NumElts && "Invalid access")((Idx < NumElts && "Invalid access") ? static_cast
<void> (0) : __assert_fail ("Idx < NumElts && \"Invalid access\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclObjC.h"
, 94, __PRETTY_FUNCTION__))
;
95 return (T*)List[Idx];
96 }
97};
98
99/// A list of Objective-C protocols, along with the source
100/// locations at which they were referenced.
101class ObjCProtocolList : public ObjCList<ObjCProtocolDecl> {
102 SourceLocation *Locations = nullptr;
103
104 using ObjCList<ObjCProtocolDecl>::set;
105
106public:
107 ObjCProtocolList() = default;
108
109 using loc_iterator = const SourceLocation *;
110
111 loc_iterator loc_begin() const { return Locations; }
112 loc_iterator loc_end() const { return Locations + size(); }
113
114 void set(ObjCProtocolDecl* const* InList, unsigned Elts,
115 const SourceLocation *Locs, ASTContext &Ctx);
116};
117
118/// ObjCMethodDecl - Represents an instance or class method declaration.
119/// ObjC methods can be declared within 4 contexts: class interfaces,
120/// categories, protocols, and class implementations. While C++ member
121/// functions leverage C syntax, Objective-C method syntax is modeled after
122/// Smalltalk (using colons to specify argument types/expressions).
123/// Here are some brief examples:
124///
125/// Setter/getter instance methods:
126/// - (void)setMenu:(NSMenu *)menu;
127/// - (NSMenu *)menu;
128///
129/// Instance method that takes 2 NSView arguments:
130/// - (void)replaceSubview:(NSView *)oldView with:(NSView *)newView;
131///
132/// Getter class method:
133/// + (NSMenu *)defaultMenu;
134///
135/// A selector represents a unique name for a method. The selector names for
136/// the above methods are setMenu:, menu, replaceSubview:with:, and defaultMenu.
137///
138class ObjCMethodDecl : public NamedDecl, public DeclContext {
139 // This class stores some data in DeclContext::ObjCMethodDeclBits
140 // to save some space. Use the provided accessors to access it.
141
142public:
143 enum ImplementationControl { None, Required, Optional };
144
145private:
146 /// Return type of this method.
147 QualType MethodDeclType;
148
149 /// Type source information for the return type.
150 TypeSourceInfo *ReturnTInfo;
151
152 /// Array of ParmVarDecls for the formal parameters of this method
153 /// and optionally followed by selector locations.
154 void *ParamsAndSelLocs = nullptr;
155 unsigned NumParams = 0;
156
157 /// List of attributes for this method declaration.
158 SourceLocation DeclEndLoc; // the location of the ';' or '{'.
159
160 /// The following are only used for method definitions, null otherwise.
161 LazyDeclStmtPtr Body;
162
163 /// SelfDecl - Decl for the implicit self parameter. This is lazily
164 /// constructed by createImplicitParams.
165 ImplicitParamDecl *SelfDecl = nullptr;
166
167 /// CmdDecl - Decl for the implicit _cmd parameter. This is lazily
168 /// constructed by createImplicitParams.
169 ImplicitParamDecl *CmdDecl = nullptr;
170
171 ObjCMethodDecl(SourceLocation beginLoc, SourceLocation endLoc,
172 Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo,
173 DeclContext *contextDecl, bool isInstance = true,
174 bool isVariadic = false, bool isPropertyAccessor = false,
175 bool isSynthesizedAccessorStub = false,
176 bool isImplicitlyDeclared = false, bool isDefined = false,
177 ImplementationControl impControl = None,
178 bool HasRelatedResultType = false);
179
180 SelectorLocationsKind getSelLocsKind() const {
181 return static_cast<SelectorLocationsKind>(ObjCMethodDeclBits.SelLocsKind);
182 }
183
184 void setSelLocsKind(SelectorLocationsKind Kind) {
185 ObjCMethodDeclBits.SelLocsKind = Kind;
186 }
187
188 bool hasStandardSelLocs() const {
189 return getSelLocsKind() != SelLoc_NonStandard;
190 }
191
192 /// Get a pointer to the stored selector identifiers locations array.
193 /// No locations will be stored if HasStandardSelLocs is true.
194 SourceLocation *getStoredSelLocs() {
195 return reinterpret_cast<SourceLocation *>(getParams() + NumParams);
196 }
197 const SourceLocation *getStoredSelLocs() const {
198 return reinterpret_cast<const SourceLocation *>(getParams() + NumParams);
199 }
200
201 /// Get a pointer to the stored selector identifiers locations array.
202 /// No locations will be stored if HasStandardSelLocs is true.
203 ParmVarDecl **getParams() {
204 return reinterpret_cast<ParmVarDecl **>(ParamsAndSelLocs);
205 }
206 const ParmVarDecl *const *getParams() const {
207 return reinterpret_cast<const ParmVarDecl *const *>(ParamsAndSelLocs);
208 }
209
210 /// Get the number of stored selector identifiers locations.
211 /// No locations will be stored if HasStandardSelLocs is true.
212 unsigned getNumStoredSelLocs() const {
213 if (hasStandardSelLocs())
214 return 0;
215 return getNumSelectorLocs();
216 }
217
218 void setParamsAndSelLocs(ASTContext &C,
219 ArrayRef<ParmVarDecl*> Params,
220 ArrayRef<SourceLocation> SelLocs);
221
222 /// A definition will return its interface declaration.
223 /// An interface declaration will return its definition.
224 /// Otherwise it will return itself.
225 ObjCMethodDecl *getNextRedeclarationImpl() override;
226
227public:
228 friend class ASTDeclReader;
229 friend class ASTDeclWriter;
230
231 static ObjCMethodDecl *
232 Create(ASTContext &C, SourceLocation beginLoc, SourceLocation endLoc,
233 Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo,
234 DeclContext *contextDecl, bool isInstance = true,
235 bool isVariadic = false, bool isPropertyAccessor = false,
236 bool isSynthesizedAccessorStub = false,
237 bool isImplicitlyDeclared = false, bool isDefined = false,
238 ImplementationControl impControl = None,
239 bool HasRelatedResultType = false);
240
241 static ObjCMethodDecl *CreateDeserialized(ASTContext &C, unsigned ID);
242
243 ObjCMethodDecl *getCanonicalDecl() override;
244 const ObjCMethodDecl *getCanonicalDecl() const {
245 return const_cast<ObjCMethodDecl*>(this)->getCanonicalDecl();
246 }
247
248 ObjCDeclQualifier getObjCDeclQualifier() const {
249 return static_cast<ObjCDeclQualifier>(ObjCMethodDeclBits.objcDeclQualifier);
250 }
251
252 void setObjCDeclQualifier(ObjCDeclQualifier QV) {
253 ObjCMethodDeclBits.objcDeclQualifier = QV;
254 }
255
256 /// Determine whether this method has a result type that is related
257 /// to the message receiver's type.
258 bool hasRelatedResultType() const {
259 return ObjCMethodDeclBits.RelatedResultType;
260 }
261
262 /// Note whether this method has a related result type.
263 void setRelatedResultType(bool RRT = true) {
264 ObjCMethodDeclBits.RelatedResultType = RRT;
265 }
266
267 /// True if this is a method redeclaration in the same interface.
268 bool isRedeclaration() const { return ObjCMethodDeclBits.IsRedeclaration; }
269 void setIsRedeclaration(bool RD) { ObjCMethodDeclBits.IsRedeclaration = RD; }
270 void setAsRedeclaration(const ObjCMethodDecl *PrevMethod);
271
272 /// True if redeclared in the same interface.
273 bool hasRedeclaration() const { return ObjCMethodDeclBits.HasRedeclaration; }
274 void setHasRedeclaration(bool HRD) const {
275 ObjCMethodDeclBits.HasRedeclaration = HRD;
276 }
277
278 /// Returns the location where the declarator ends. It will be
279 /// the location of ';' for a method declaration and the location of '{'
280 /// for a method definition.
281 SourceLocation getDeclaratorEndLoc() const { return DeclEndLoc; }
282
283 // Location information, modeled after the Stmt API.
284 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return getLocation(); }
285 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__));
286 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
287 return SourceRange(getLocation(), getEndLoc());
288 }
289
290 SourceLocation getSelectorStartLoc() const {
291 if (isImplicit())
292 return getBeginLoc();
293 return getSelectorLoc(0);
294 }
295
296 SourceLocation getSelectorLoc(unsigned Index) const {
297 assert(Index < getNumSelectorLocs() && "Index out of range!")((Index < getNumSelectorLocs() && "Index out of range!"
) ? static_cast<void> (0) : __assert_fail ("Index < getNumSelectorLocs() && \"Index out of range!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclObjC.h"
, 297, __PRETTY_FUNCTION__))
;
298 if (hasStandardSelLocs())
299 return getStandardSelectorLoc(Index, getSelector(),
300 getSelLocsKind() == SelLoc_StandardWithSpace,
301 parameters(),
302 DeclEndLoc);
303 return getStoredSelLocs()[Index];
304 }
305
306 void getSelectorLocs(SmallVectorImpl<SourceLocation> &SelLocs) const;
307
308 unsigned getNumSelectorLocs() const {
309 if (isImplicit())
310 return 0;
311 Selector Sel = getSelector();
312 if (Sel.isUnarySelector())
313 return 1;
314 return Sel.getNumArgs();
315 }
316
317 ObjCInterfaceDecl *getClassInterface();
318 const ObjCInterfaceDecl *getClassInterface() const {
319 return const_cast<ObjCMethodDecl*>(this)->getClassInterface();
320 }
321
322 Selector getSelector() const { return getDeclName().getObjCSelector(); }
323
324 QualType getReturnType() const { return MethodDeclType; }
325 void setReturnType(QualType T) { MethodDeclType = T; }
326 SourceRange getReturnTypeSourceRange() const;
327
328 /// Determine the type of an expression that sends a message to this
329 /// function. This replaces the type parameters with the types they would
330 /// get if the receiver was parameterless (e.g. it may replace the type
331 /// parameter with 'id').
332 QualType getSendResultType() const;
333
334 /// Determine the type of an expression that sends a message to this
335 /// function with the given receiver type.
336 QualType getSendResultType(QualType receiverType) const;
337
338 TypeSourceInfo *getReturnTypeSourceInfo() const { return ReturnTInfo; }
339 void setReturnTypeSourceInfo(TypeSourceInfo *TInfo) { ReturnTInfo = TInfo; }
340
341 // Iterator access to formal parameters.
342 unsigned param_size() const { return NumParams; }
343
344 using param_const_iterator = const ParmVarDecl *const *;
345 using param_iterator = ParmVarDecl *const *;
346 using param_range = llvm::iterator_range<param_iterator>;
347 using param_const_range = llvm::iterator_range<param_const_iterator>;
348
349 param_const_iterator param_begin() const {
350 return param_const_iterator(getParams());
351 }
352
353 param_const_iterator param_end() const {
354 return param_const_iterator(getParams() + NumParams);
355 }
356
357 param_iterator param_begin() { return param_iterator(getParams()); }
358 param_iterator param_end() { return param_iterator(getParams() + NumParams); }
359
360 // This method returns and of the parameters which are part of the selector
361 // name mangling requirements.
362 param_const_iterator sel_param_end() const {
363 return param_begin() + getSelector().getNumArgs();
364 }
365
366 // ArrayRef access to formal parameters. This should eventually
367 // replace the iterator interface above.
368 ArrayRef<ParmVarDecl*> parameters() const {
369 return llvm::makeArrayRef(const_cast<ParmVarDecl**>(getParams()),
370 NumParams);
371 }
372
373 ParmVarDecl *getParamDecl(unsigned Idx) {
374 assert(Idx < NumParams && "Index out of bounds!")((Idx < NumParams && "Index out of bounds!") ? static_cast
<void> (0) : __assert_fail ("Idx < NumParams && \"Index out of bounds!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclObjC.h"
, 374, __PRETTY_FUNCTION__))
;
375 return getParams()[Idx];
376 }
377 const ParmVarDecl *getParamDecl(unsigned Idx) const {
378 return const_cast<ObjCMethodDecl *>(this)->getParamDecl(Idx);
379 }
380
381 /// Sets the method's parameters and selector source locations.
382 /// If the method is implicit (not coming from source) \p SelLocs is
383 /// ignored.
384 void setMethodParams(ASTContext &C,
385 ArrayRef<ParmVarDecl*> Params,
386 ArrayRef<SourceLocation> SelLocs = llvm::None);
387
388 // Iterator access to parameter types.
389 struct GetTypeFn {
390 QualType operator()(const ParmVarDecl *PD) const { return PD->getType(); }
391 };
392
393 using param_type_iterator =
394 llvm::mapped_iterator<param_const_iterator, GetTypeFn>;
395
396 param_type_iterator param_type_begin() const {
397 return llvm::map_iterator(param_begin(), GetTypeFn());
398 }
399
400 param_type_iterator param_type_end() const {
401 return llvm::map_iterator(param_end(), GetTypeFn());
402 }
403
404 /// createImplicitParams - Used to lazily create the self and cmd
405 /// implict parameters. This must be called prior to using getSelfDecl()
406 /// or getCmdDecl(). The call is ignored if the implicit parameters
407 /// have already been created.
408 void createImplicitParams(ASTContext &Context, const ObjCInterfaceDecl *ID);
409
410 /// \return the type for \c self and set \arg selfIsPseudoStrong and
411 /// \arg selfIsConsumed accordingly.
412 QualType getSelfType(ASTContext &Context, const ObjCInterfaceDecl *OID,
413 bool &selfIsPseudoStrong, bool &selfIsConsumed);
414
415 ImplicitParamDecl * getSelfDecl() const { return SelfDecl; }
416 void setSelfDecl(ImplicitParamDecl *SD) { SelfDecl = SD; }
417 ImplicitParamDecl * getCmdDecl() const { return CmdDecl; }
418 void setCmdDecl(ImplicitParamDecl *CD) { CmdDecl = CD; }
419
420 /// Determines the family of this method.
421 ObjCMethodFamily getMethodFamily() const;
422
423 bool isInstanceMethod() const { return ObjCMethodDeclBits.IsInstance; }
424 void setInstanceMethod(bool isInst) {
425 ObjCMethodDeclBits.IsInstance = isInst;
426 }
427
428 bool isVariadic() const { return ObjCMethodDeclBits.IsVariadic; }
429 void setVariadic(bool isVar) { ObjCMethodDeclBits.IsVariadic = isVar; }
430
431 bool isClassMethod() const { return !isInstanceMethod(); }
432
433 bool isPropertyAccessor() const {
434 return ObjCMethodDeclBits.IsPropertyAccessor;
435 }
436
437 void setPropertyAccessor(bool isAccessor) {
438 ObjCMethodDeclBits.IsPropertyAccessor = isAccessor;
439 }
440
441 bool isSynthesizedAccessorStub() const {
442 return ObjCMethodDeclBits.IsSynthesizedAccessorStub;
443 }
444
445 void setSynthesizedAccessorStub(bool isSynthesizedAccessorStub) {
446 ObjCMethodDeclBits.IsSynthesizedAccessorStub = isSynthesizedAccessorStub;
447 }
448
449 bool isDefined() const { return ObjCMethodDeclBits.IsDefined; }
450 void setDefined(bool isDefined) { ObjCMethodDeclBits.IsDefined = isDefined; }
451
452 /// Whether this method overrides any other in the class hierarchy.
453 ///
454 /// A method is said to override any method in the class's
455 /// base classes, its protocols, or its categories' protocols, that has
456 /// the same selector and is of the same kind (class or instance).
457 /// A method in an implementation is not considered as overriding the same
458 /// method in the interface or its categories.
459 bool isOverriding() const { return ObjCMethodDeclBits.IsOverriding; }
460 void setOverriding(bool IsOver) { ObjCMethodDeclBits.IsOverriding = IsOver; }
461
462 /// Return overridden methods for the given \p Method.
463 ///
464 /// An ObjC method is considered to override any method in the class's
465 /// base classes (and base's categories), its protocols, or its categories'
466 /// protocols, that has
467 /// the same selector and is of the same kind (class or instance).
468 /// A method in an implementation is not considered as overriding the same
469 /// method in the interface or its categories.
470 void getOverriddenMethods(
471 SmallVectorImpl<const ObjCMethodDecl *> &Overridden) const;
472
473 /// True if the method was a definition but its body was skipped.
474 bool hasSkippedBody() const { return ObjCMethodDeclBits.HasSkippedBody; }
475 void setHasSkippedBody(bool Skipped = true) {
476 ObjCMethodDeclBits.HasSkippedBody = Skipped;
477 }
478
479 /// Returns the property associated with this method's selector.
480 ///
481 /// Note that even if this particular method is not marked as a property
482 /// accessor, it is still possible for it to match a property declared in a
483 /// superclass. Pass \c false if you only want to check the current class.
484 const ObjCPropertyDecl *findPropertyDecl(bool CheckOverrides = true) const;
485
486 // Related to protocols declared in \@protocol
487 void setDeclImplementation(ImplementationControl ic) {
488 ObjCMethodDeclBits.DeclImplementation = ic;
489 }
490
491 ImplementationControl getImplementationControl() const {
492 return ImplementationControl(ObjCMethodDeclBits.DeclImplementation);
493 }
494
495 bool isOptional() const {
496 return getImplementationControl() == Optional;
497 }
498
499 /// Returns true if this specific method declaration is marked with the
500 /// designated initializer attribute.
501 bool isThisDeclarationADesignatedInitializer() const;
502
503 /// Returns true if the method selector resolves to a designated initializer
504 /// in the class's interface.
505 ///
506 /// \param InitMethod if non-null and the function returns true, it receives
507 /// the method declaration that was marked with the designated initializer
508 /// attribute.
509 bool isDesignatedInitializerForTheInterface(
510 const ObjCMethodDecl **InitMethod = nullptr) const;
511
512 /// Determine whether this method has a body.
513 bool hasBody() const override { return Body.isValid(); }
514
515 /// Retrieve the body of this method, if it has one.
516 Stmt *getBody() const override;
517
518 void setLazyBody(uint64_t Offset) { Body = Offset; }
519
520 CompoundStmt *getCompoundBody() { return (CompoundStmt*)getBody(); }
521 void setBody(Stmt *B) { Body = B; }
522
523 /// Returns whether this specific method is a definition.
524 bool isThisDeclarationADefinition() const { return hasBody(); }
525
526 /// Is this method defined in the NSObject base class?
527 bool definedInNSObject(const ASTContext &) const;
528
529 // Implement isa/cast/dyncast/etc.
530 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
531 static bool classofKind(Kind K) { return K == ObjCMethod; }
532
533 static DeclContext *castToDeclContext(const ObjCMethodDecl *D) {
534 return static_cast<DeclContext *>(const_cast<ObjCMethodDecl*>(D));
535 }
536
537 static ObjCMethodDecl *castFromDeclContext(const DeclContext *DC) {
538 return static_cast<ObjCMethodDecl *>(const_cast<DeclContext*>(DC));
539 }
540};
541
542/// Describes the variance of a given generic parameter.
543enum class ObjCTypeParamVariance : uint8_t {
544 /// The parameter is invariant: must match exactly.
545 Invariant,
546
547 /// The parameter is covariant, e.g., X<T> is a subtype of X<U> when
548 /// the type parameter is covariant and T is a subtype of U.
549 Covariant,
550
551 /// The parameter is contravariant, e.g., X<T> is a subtype of X<U>
552 /// when the type parameter is covariant and U is a subtype of T.
553 Contravariant,
554};
555
556/// Represents the declaration of an Objective-C type parameter.
557///
558/// \code
559/// @interface NSDictionary<Key : id<NSCopying>, Value>
560/// @end
561/// \endcode
562///
563/// In the example above, both \c Key and \c Value are represented by
564/// \c ObjCTypeParamDecl. \c Key has an explicit bound of \c id<NSCopying>,
565/// while \c Value gets an implicit bound of \c id.
566///
567/// Objective-C type parameters are typedef-names in the grammar,
568class ObjCTypeParamDecl : public TypedefNameDecl {
569 /// Index of this type parameter in the type parameter list.
570 unsigned Index : 14;
571
572 /// The variance of the type parameter.
573 unsigned Variance : 2;
574
575 /// The location of the variance, if any.
576 SourceLocation VarianceLoc;
577
578 /// The location of the ':', which will be valid when the bound was
579 /// explicitly specified.
580 SourceLocation ColonLoc;
581
582 ObjCTypeParamDecl(ASTContext &ctx, DeclContext *dc,
583 ObjCTypeParamVariance variance, SourceLocation varianceLoc,
584 unsigned index,
585 SourceLocation nameLoc, IdentifierInfo *name,
586 SourceLocation colonLoc, TypeSourceInfo *boundInfo)
587 : TypedefNameDecl(ObjCTypeParam, ctx, dc, nameLoc, nameLoc, name,
588 boundInfo),
589 Index(index), Variance(static_cast<unsigned>(variance)),
590 VarianceLoc(varianceLoc), ColonLoc(colonLoc) {}
591
592 void anchor() override;
593
594public:
595 friend class ASTDeclReader;
596 friend class ASTDeclWriter;
597
598 static ObjCTypeParamDecl *Create(ASTContext &ctx, DeclContext *dc,
599 ObjCTypeParamVariance variance,
600 SourceLocation varianceLoc,
601 unsigned index,
602 SourceLocation nameLoc,
603 IdentifierInfo *name,
604 SourceLocation colonLoc,
605 TypeSourceInfo *boundInfo);
606 static ObjCTypeParamDecl *CreateDeserialized(ASTContext &ctx, unsigned ID);
607
608 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
609
610 /// Determine the variance of this type parameter.
611 ObjCTypeParamVariance getVariance() const {
612 return static_cast<ObjCTypeParamVariance>(Variance);
613 }
614
615 /// Set the variance of this type parameter.
616 void setVariance(ObjCTypeParamVariance variance) {
617 Variance = static_cast<unsigned>(variance);
618 }
619
620 /// Retrieve the location of the variance keyword.
621 SourceLocation getVarianceLoc() const { return VarianceLoc; }
622
623 /// Retrieve the index into its type parameter list.
624 unsigned getIndex() const { return Index; }
625
626 /// Whether this type parameter has an explicitly-written type bound, e.g.,
627 /// "T : NSView".
628 bool hasExplicitBound() const { return ColonLoc.isValid(); }
629
630 /// Retrieve the location of the ':' separating the type parameter name
631 /// from the explicitly-specified bound.
632 SourceLocation getColonLoc() const { return ColonLoc; }
633
634 // Implement isa/cast/dyncast/etc.
635 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
636 static bool classofKind(Kind K) { return K == ObjCTypeParam; }
637};
638
639/// Stores a list of Objective-C type parameters for a parameterized class
640/// or a category/extension thereof.
641///
642/// \code
643/// @interface NSArray<T> // stores the <T>
644/// @end
645/// \endcode
646class ObjCTypeParamList final
647 : private llvm::TrailingObjects<ObjCTypeParamList, ObjCTypeParamDecl *> {
648 /// Stores the components of a SourceRange as a POD.
649 struct PODSourceRange {
650 unsigned Begin;
651 unsigned End;
652 };
653
654 union {
655 /// Location of the left and right angle brackets.
656 PODSourceRange Brackets;
657
658 // Used only for alignment.
659 ObjCTypeParamDecl *AlignmentHack;
660 };
661
662 /// The number of parameters in the list, which are tail-allocated.
663 unsigned NumParams;
664
665 ObjCTypeParamList(SourceLocation lAngleLoc,
666 ArrayRef<ObjCTypeParamDecl *> typeParams,
667 SourceLocation rAngleLoc);
668
669public:
670 friend TrailingObjects;
671
672 /// Create a new Objective-C type parameter list.
673 static ObjCTypeParamList *create(ASTContext &ctx,
674 SourceLocation lAngleLoc,
675 ArrayRef<ObjCTypeParamDecl *> typeParams,
676 SourceLocation rAngleLoc);
677
678 /// Iterate through the type parameters in the list.
679 using iterator = ObjCTypeParamDecl **;
680
681 iterator begin() { return getTrailingObjects<ObjCTypeParamDecl *>(); }
682
683 iterator end() { return begin() + size(); }
684
685 /// Determine the number of type parameters in this list.
686 unsigned size() const { return NumParams; }
687
688 // Iterate through the type parameters in the list.
689 using const_iterator = ObjCTypeParamDecl * const *;
690
691 const_iterator begin() const {
692 return getTrailingObjects<ObjCTypeParamDecl *>();
693 }
694
695 const_iterator end() const {
696 return begin() + size();
697 }
698
699 ObjCTypeParamDecl *front() const {
700 assert(size() > 0 && "empty Objective-C type parameter list")((size() > 0 && "empty Objective-C type parameter list"
) ? static_cast<void> (0) : __assert_fail ("size() > 0 && \"empty Objective-C type parameter list\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclObjC.h"
, 700, __PRETTY_FUNCTION__))
;
701 return *begin();
702 }
703
704 ObjCTypeParamDecl *back() const {
705 assert(size() > 0 && "empty Objective-C type parameter list")((size() > 0 && "empty Objective-C type parameter list"
) ? static_cast<void> (0) : __assert_fail ("size() > 0 && \"empty Objective-C type parameter list\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclObjC.h"
, 705, __PRETTY_FUNCTION__))
;
706 return *(end() - 1);
707 }
708
709 SourceLocation getLAngleLoc() const {
710 return SourceLocation::getFromRawEncoding(Brackets.Begin);
711 }
712
713 SourceLocation getRAngleLoc() const {
714 return SourceLocation::getFromRawEncoding(Brackets.End);
715 }
716
717 SourceRange getSourceRange() const {
718 return SourceRange(getLAngleLoc(), getRAngleLoc());
719 }
720
721 /// Gather the default set of type arguments to be substituted for
722 /// these type parameters when dealing with an unspecialized type.
723 void gatherDefaultTypeArgs(SmallVectorImpl<QualType> &typeArgs) const;
724};
725
726enum class ObjCPropertyQueryKind : uint8_t {
727 OBJC_PR_query_unknown = 0x00,
728 OBJC_PR_query_instance,
729 OBJC_PR_query_class
730};
731
732/// Represents one property declaration in an Objective-C interface.
733///
734/// For example:
735/// \code{.mm}
736/// \@property (assign, readwrite) int MyProperty;
737/// \endcode
738class ObjCPropertyDecl : public NamedDecl {
739 void anchor() override;
740
741public:
742 enum PropertyAttributeKind {
743 OBJC_PR_noattr = 0x00,
744 OBJC_PR_readonly = 0x01,
745 OBJC_PR_getter = 0x02,
746 OBJC_PR_assign = 0x04,
747 OBJC_PR_readwrite = 0x08,
748 OBJC_PR_retain = 0x10,
749 OBJC_PR_copy = 0x20,
750 OBJC_PR_nonatomic = 0x40,
751 OBJC_PR_setter = 0x80,
752 OBJC_PR_atomic = 0x100,
753 OBJC_PR_weak = 0x200,
754 OBJC_PR_strong = 0x400,
755 OBJC_PR_unsafe_unretained = 0x800,
756 /// Indicates that the nullability of the type was spelled with a
757 /// property attribute rather than a type qualifier.
758 OBJC_PR_nullability = 0x1000,
759 OBJC_PR_null_resettable = 0x2000,
760 OBJC_PR_class = 0x4000
761 // Adding a property should change NumPropertyAttrsBits
762 };
763
764 enum {
765 /// Number of bits fitting all the property attributes.
766 NumPropertyAttrsBits = 15
767 };
768
769 enum SetterKind { Assign, Retain, Copy, Weak };
770 enum PropertyControl { None, Required, Optional };
771
772private:
773 // location of \@property
774 SourceLocation AtLoc;
775
776 // location of '(' starting attribute list or null.
777 SourceLocation LParenLoc;
778
779 QualType DeclType;
780 TypeSourceInfo *DeclTypeSourceInfo;
781 unsigned PropertyAttributes : NumPropertyAttrsBits;
782 unsigned PropertyAttributesAsWritten : NumPropertyAttrsBits;
783
784 // \@required/\@optional
785 unsigned PropertyImplementation : 2;
786
787 // getter name of NULL if no getter
788 Selector GetterName;
789
790 // setter name of NULL if no setter
791 Selector SetterName;
792
793 // location of the getter attribute's value
794 SourceLocation GetterNameLoc;
795
796 // location of the setter attribute's value
797 SourceLocation SetterNameLoc;
798
799 // Declaration of getter instance method
800 ObjCMethodDecl *GetterMethodDecl = nullptr;
801
802 // Declaration of setter instance method
803 ObjCMethodDecl *SetterMethodDecl = nullptr;
804
805 // Synthesize ivar for this property
806 ObjCIvarDecl *PropertyIvarDecl = nullptr;
807
808 ObjCPropertyDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
809 SourceLocation AtLocation, SourceLocation LParenLocation,
810 QualType T, TypeSourceInfo *TSI,
811 PropertyControl propControl)
812 : NamedDecl(ObjCProperty, DC, L, Id), AtLoc(AtLocation),
813 LParenLoc(LParenLocation), DeclType(T), DeclTypeSourceInfo(TSI),
814 PropertyAttributes(OBJC_PR_noattr),
815 PropertyAttributesAsWritten(OBJC_PR_noattr),
816 PropertyImplementation(propControl), GetterName(Selector()),
817 SetterName(Selector()) {}
818
819public:
820 static ObjCPropertyDecl *Create(ASTContext &C, DeclContext *DC,
821 SourceLocation L,
822 IdentifierInfo *Id, SourceLocation AtLocation,
823 SourceLocation LParenLocation,
824 QualType T,
825 TypeSourceInfo *TSI,
826 PropertyControl propControl = None);
827
828 static ObjCPropertyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
829
830 SourceLocation getAtLoc() const { return AtLoc; }
831 void setAtLoc(SourceLocation L) { AtLoc = L; }
832
833 SourceLocation getLParenLoc() const { return LParenLoc; }
834 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
835
836 TypeSourceInfo *getTypeSourceInfo() const { return DeclTypeSourceInfo; }
837
838 QualType getType() const { return DeclType; }
839
840 void setType(QualType T, TypeSourceInfo *TSI) {
841 DeclType = T;
842 DeclTypeSourceInfo = TSI;
843 }
844
845 /// Retrieve the type when this property is used with a specific base object
846 /// type.
847 QualType getUsageType(QualType objectType) const;
848
849 PropertyAttributeKind getPropertyAttributes() const {
850 return PropertyAttributeKind(PropertyAttributes);
851 }
852
853 void setPropertyAttributes(PropertyAttributeKind PRVal) {
854 PropertyAttributes |= PRVal;
855 }
856
857 void overwritePropertyAttributes(unsigned PRVal) {
858 PropertyAttributes = PRVal;
859 }
860
861 PropertyAttributeKind getPropertyAttributesAsWritten() const {
862 return PropertyAttributeKind(PropertyAttributesAsWritten);
863 }
864
865 void setPropertyAttributesAsWritten(PropertyAttributeKind PRVal) {
866 PropertyAttributesAsWritten = PRVal;
867 }
868
869 // Helper methods for accessing attributes.
870
871 /// isReadOnly - Return true iff the property has a setter.
872 bool isReadOnly() const {
873 return (PropertyAttributes & OBJC_PR_readonly);
874 }
875
876 /// isAtomic - Return true if the property is atomic.
877 bool isAtomic() const {
878 return (PropertyAttributes & OBJC_PR_atomic);
879 }
880
881 /// isRetaining - Return true if the property retains its value.
882 bool isRetaining() const {
883 return (PropertyAttributes &
884 (OBJC_PR_retain | OBJC_PR_strong | OBJC_PR_copy));
885 }
886
887 bool isInstanceProperty() const { return !isClassProperty(); }
888 bool isClassProperty() const { return PropertyAttributes & OBJC_PR_class; }
889
890 ObjCPropertyQueryKind getQueryKind() const {
891 return isClassProperty() ? ObjCPropertyQueryKind::OBJC_PR_query_class :
892 ObjCPropertyQueryKind::OBJC_PR_query_instance;
893 }
894
895 static ObjCPropertyQueryKind getQueryKind(bool isClassProperty) {
896 return isClassProperty ? ObjCPropertyQueryKind::OBJC_PR_query_class :
897 ObjCPropertyQueryKind::OBJC_PR_query_instance;
898 }
899
900 /// getSetterKind - Return the method used for doing assignment in
901 /// the property setter. This is only valid if the property has been
902 /// defined to have a setter.
903 SetterKind getSetterKind() const {
904 if (PropertyAttributes & OBJC_PR_strong)
905 return getType()->isBlockPointerType() ? Copy : Retain;
906 if (PropertyAttributes & OBJC_PR_retain)
907 return Retain;
908 if (PropertyAttributes & OBJC_PR_copy)
909 return Copy;
910 if (PropertyAttributes & OBJC_PR_weak)
911 return Weak;
912 return Assign;
913 }
914
915 Selector getGetterName() const { return GetterName; }
916 SourceLocation getGetterNameLoc() const { return GetterNameLoc; }
917
918 void setGetterName(Selector Sel, SourceLocation Loc = SourceLocation()) {
919 GetterName = Sel;
920 GetterNameLoc = Loc;
921 }
922
923 Selector getSetterName() const { return SetterName; }
924 SourceLocation getSetterNameLoc() const { return SetterNameLoc; }
925
926 void setSetterName(Selector Sel, SourceLocation Loc = SourceLocation()) {
927 SetterName = Sel;
928 SetterNameLoc = Loc;
929 }
930
931 ObjCMethodDecl *getGetterMethodDecl() const { return GetterMethodDecl; }
932 void setGetterMethodDecl(ObjCMethodDecl *gDecl) { GetterMethodDecl = gDecl; }
933
934 ObjCMethodDecl *getSetterMethodDecl() const { return SetterMethodDecl; }
935 void setSetterMethodDecl(ObjCMethodDecl *gDecl) { SetterMethodDecl = gDecl; }
936
937 // Related to \@optional/\@required declared in \@protocol
938 void setPropertyImplementation(PropertyControl pc) {
939 PropertyImplementation = pc;
940 }
941
942 PropertyControl getPropertyImplementation() const {
943 return PropertyControl(PropertyImplementation);
944 }
945
946 bool isOptional() const {
947 return getPropertyImplementation() == PropertyControl::Optional;
948 }
949
950 void setPropertyIvarDecl(ObjCIvarDecl *Ivar) {
951 PropertyIvarDecl = Ivar;
952 }
953
954 ObjCIvarDecl *getPropertyIvarDecl() const {
955 return PropertyIvarDecl;
956 }
957
958 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
959 return SourceRange(AtLoc, getLocation());
960 }
961
962 /// Get the default name of the synthesized ivar.
963 IdentifierInfo *getDefaultSynthIvarName(ASTContext &Ctx) const;
964
965 /// Lookup a property by name in the specified DeclContext.
966 static ObjCPropertyDecl *findPropertyDecl(const DeclContext *DC,
967 const IdentifierInfo *propertyID,
968 ObjCPropertyQueryKind queryKind);
969
970 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
971 static bool classofKind(Kind K) { return K == ObjCProperty; }
972};
973
974/// ObjCContainerDecl - Represents a container for method declarations.
975/// Current sub-classes are ObjCInterfaceDecl, ObjCCategoryDecl,
976/// ObjCProtocolDecl, and ObjCImplDecl.
977///
978class ObjCContainerDecl : public NamedDecl, public DeclContext {
979 // This class stores some data in DeclContext::ObjCContainerDeclBits
980 // to save some space. Use the provided accessors to access it.
981
982 // These two locations in the range mark the end of the method container.
983 // The first points to the '@' token, and the second to the 'end' token.
984 SourceRange AtEnd;
985
986 void anchor() override;
987
988public:
989 ObjCContainerDecl(Kind DK, DeclContext *DC, IdentifierInfo *Id,
990 SourceLocation nameLoc, SourceLocation atStartLoc);
991
992 // Iterator access to instance/class properties.
993 using prop_iterator = specific_decl_iterator<ObjCPropertyDecl>;
994 using prop_range =
995 llvm::iterator_range<specific_decl_iterator<ObjCPropertyDecl>>;
996
997 prop_range properties() const { return prop_range(prop_begin(), prop_end()); }
998
999 prop_iterator prop_begin() const {
1000 return prop_iterator(decls_begin());
1001 }
1002
1003 prop_iterator prop_end() const {
1004 return prop_iterator(decls_end());
1005 }
1006
1007 using instprop_iterator =
1008 filtered_decl_iterator<ObjCPropertyDecl,
1009 &ObjCPropertyDecl::isInstanceProperty>;
1010 using instprop_range = llvm::iterator_range<instprop_iterator>;
1011
1012 instprop_range instance_properties() const {
1013 return instprop_range(instprop_begin(), instprop_end());
1014 }
1015
1016 instprop_iterator instprop_begin() const {
1017 return instprop_iterator(decls_begin());
1018 }
1019
1020 instprop_iterator instprop_end() const {
1021 return instprop_iterator(decls_end());
1022 }
1023
1024 using classprop_iterator =
1025 filtered_decl_iterator<ObjCPropertyDecl,
1026 &ObjCPropertyDecl::isClassProperty>;
1027 using classprop_range = llvm::iterator_range<classprop_iterator>;
1028
1029 classprop_range class_properties() const {
1030 return classprop_range(classprop_begin(), classprop_end());
1031 }
1032
1033 classprop_iterator classprop_begin() const {
1034 return classprop_iterator(decls_begin());
1035 }
1036
1037 classprop_iterator classprop_end() const {
1038 return classprop_iterator(decls_end());
1039 }
1040
1041 // Iterator access to instance/class methods.
1042 using method_iterator = specific_decl_iterator<ObjCMethodDecl>;
1043 using method_range =
1044 llvm::iterator_range<specific_decl_iterator<ObjCMethodDecl>>;
1045
1046 method_range methods() const {
1047 return method_range(meth_begin(), meth_end());
1048 }
1049
1050 method_iterator meth_begin() const {
1051 return method_iterator(decls_begin());
1052 }
1053
1054 method_iterator meth_end() const {
1055 return method_iterator(decls_end());
1056 }
1057
1058 using instmeth_iterator =
1059 filtered_decl_iterator<ObjCMethodDecl,
1060 &ObjCMethodDecl::isInstanceMethod>;
1061 using instmeth_range = llvm::iterator_range<instmeth_iterator>;
1062
1063 instmeth_range instance_methods() const {
1064 return instmeth_range(instmeth_begin(), instmeth_end());
1065 }
1066
1067 instmeth_iterator instmeth_begin() const {
1068 return instmeth_iterator(decls_begin());
1069 }
1070
1071 instmeth_iterator instmeth_end() const {
1072 return instmeth_iterator(decls_end());
1073 }
1074
1075 using classmeth_iterator =
1076 filtered_decl_iterator<ObjCMethodDecl,
1077 &ObjCMethodDecl::isClassMethod>;
1078 using classmeth_range = llvm::iterator_range<classmeth_iterator>;
1079
1080 classmeth_range class_methods() const {
1081 return classmeth_range(classmeth_begin(), classmeth_end());
1082 }
1083
1084 classmeth_iterator classmeth_begin() const {
1085 return classmeth_iterator(decls_begin());
1086 }
1087
1088 classmeth_iterator classmeth_end() const {
1089 return classmeth_iterator(decls_end());
1090 }
1091
1092 // Get the local instance/class method declared in this interface.
1093 ObjCMethodDecl *getMethod(Selector Sel, bool isInstance,
1094 bool AllowHidden = false) const;
1095
1096 ObjCMethodDecl *getInstanceMethod(Selector Sel,
1097 bool AllowHidden = false) const {
1098 return getMethod(Sel, true/*isInstance*/, AllowHidden);
1099 }
1100
1101 ObjCMethodDecl *getClassMethod(Selector Sel, bool AllowHidden = false) const {
1102 return getMethod(Sel, false/*isInstance*/, AllowHidden);
1103 }
1104
1105 bool HasUserDeclaredSetterMethod(const ObjCPropertyDecl *P) const;
1106 ObjCIvarDecl *getIvarDecl(IdentifierInfo *Id) const;
1107
1108 ObjCPropertyDecl *
1109 FindPropertyDeclaration(const IdentifierInfo *PropertyId,
1110 ObjCPropertyQueryKind QueryKind) const;
1111
1112 using PropertyMap =
1113 llvm::DenseMap<std::pair<IdentifierInfo *, unsigned/*isClassProperty*/>,
1114 ObjCPropertyDecl *>;
1115 using ProtocolPropertySet = llvm::SmallDenseSet<const ObjCProtocolDecl *, 8>;
1116 using PropertyDeclOrder = llvm::SmallVector<ObjCPropertyDecl *, 8>;
1117
1118 /// This routine collects list of properties to be implemented in the class.
1119 /// This includes, class's and its conforming protocols' properties.
1120 /// Note, the superclass's properties are not included in the list.
1121 virtual void collectPropertiesToImplement(PropertyMap &PM,
1122 PropertyDeclOrder &PO) const {}
1123
1124 SourceLocation getAtStartLoc() const { return ObjCContainerDeclBits.AtStart; }
1125
1126 void setAtStartLoc(SourceLocation Loc) {
1127 ObjCContainerDeclBits.AtStart = Loc;
1128 }
1129
1130 // Marks the end of the container.
1131 SourceRange getAtEndRange() const { return AtEnd; }
1132
1133 void setAtEndRange(SourceRange atEnd) { AtEnd = atEnd; }
1134
1135 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
1136 return SourceRange(getAtStartLoc(), getAtEndRange().getEnd());
1137 }
1138
1139 // Implement isa/cast/dyncast/etc.
1140 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1141
1142 static bool classofKind(Kind K) {
1143 return K >= firstObjCContainer &&
1144 K <= lastObjCContainer;
1145 }
1146
1147 static DeclContext *castToDeclContext(const ObjCContainerDecl *D) {
1148 return static_cast<DeclContext *>(const_cast<ObjCContainerDecl*>(D));
1149 }
1150
1151 static ObjCContainerDecl *castFromDeclContext(const DeclContext *DC) {
1152 return static_cast<ObjCContainerDecl *>(const_cast<DeclContext*>(DC));
1153 }
1154};
1155
1156/// Represents an ObjC class declaration.
1157///
1158/// For example:
1159///
1160/// \code
1161/// // MostPrimitive declares no super class (not particularly useful).
1162/// \@interface MostPrimitive
1163/// // no instance variables or methods.
1164/// \@end
1165///
1166/// // NSResponder inherits from NSObject & implements NSCoding (a protocol).
1167/// \@interface NSResponder : NSObject \<NSCoding>
1168/// { // instance variables are represented by ObjCIvarDecl.
1169/// id nextResponder; // nextResponder instance variable.
1170/// }
1171/// - (NSResponder *)nextResponder; // return a pointer to NSResponder.
1172/// - (void)mouseMoved:(NSEvent *)theEvent; // return void, takes a pointer
1173/// \@end // to an NSEvent.
1174/// \endcode
1175///
1176/// Unlike C/C++, forward class declarations are accomplished with \@class.
1177/// Unlike C/C++, \@class allows for a list of classes to be forward declared.
1178/// Unlike C++, ObjC is a single-rooted class model. In Cocoa, classes
1179/// typically inherit from NSObject (an exception is NSProxy).
1180///
1181class ObjCInterfaceDecl : public ObjCContainerDecl
1182 , public Redeclarable<ObjCInterfaceDecl> {
1183 friend class ASTContext;
1184
1185 /// TypeForDecl - This indicates the Type object that represents this
1186 /// TypeDecl. It is a cache maintained by ASTContext::getObjCInterfaceType
1187 mutable const Type *TypeForDecl = nullptr;
1188
1189 struct DefinitionData {
1190 /// The definition of this class, for quick access from any
1191 /// declaration.
1192 ObjCInterfaceDecl *Definition = nullptr;
1193
1194 /// When non-null, this is always an ObjCObjectType.
1195 TypeSourceInfo *SuperClassTInfo = nullptr;
1196
1197 /// Protocols referenced in the \@interface declaration
1198 ObjCProtocolList ReferencedProtocols;
1199
1200 /// Protocols reference in both the \@interface and class extensions.
1201 ObjCList<ObjCProtocolDecl> AllReferencedProtocols;
1202
1203 /// List of categories and class extensions defined for this class.
1204 ///
1205 /// Categories are stored as a linked list in the AST, since the categories
1206 /// and class extensions come long after the initial interface declaration,
1207 /// and we avoid dynamically-resized arrays in the AST wherever possible.
1208 ObjCCategoryDecl *CategoryList = nullptr;
1209
1210 /// IvarList - List of all ivars defined by this class; including class
1211 /// extensions and implementation. This list is built lazily.
1212 ObjCIvarDecl *IvarList = nullptr;
1213
1214 /// Indicates that the contents of this Objective-C class will be
1215 /// completed by the external AST source when required.
1216 mutable unsigned ExternallyCompleted : 1;
1217
1218 /// Indicates that the ivar cache does not yet include ivars
1219 /// declared in the implementation.
1220 mutable unsigned IvarListMissingImplementation : 1;
1221
1222 /// Indicates that this interface decl contains at least one initializer
1223 /// marked with the 'objc_designated_initializer' attribute.
1224 unsigned HasDesignatedInitializers : 1;
1225
1226 enum InheritedDesignatedInitializersState {
1227 /// We didn't calculate whether the designated initializers should be
1228 /// inherited or not.
1229 IDI_Unknown = 0,
1230
1231 /// Designated initializers are inherited for the super class.
1232 IDI_Inherited = 1,
1233
1234 /// The class does not inherit designated initializers.
1235 IDI_NotInherited = 2
1236 };
1237
1238 /// One of the \c InheritedDesignatedInitializersState enumeratos.
1239 mutable unsigned InheritedDesignatedInitializers : 2;
1240
1241 /// The location of the last location in this declaration, before
1242 /// the properties/methods. For example, this will be the '>', '}', or
1243 /// identifier,
1244 SourceLocation EndLoc;
1245
1246 DefinitionData()
1247 : ExternallyCompleted(false), IvarListMissingImplementation(true),
1248 HasDesignatedInitializers(false),
1249 InheritedDesignatedInitializers(IDI_Unknown) {}
1250 };
1251
1252 /// The type parameters associated with this class, if any.
1253 ObjCTypeParamList *TypeParamList = nullptr;
1254
1255 /// Contains a pointer to the data associated with this class,
1256 /// which will be NULL if this class has not yet been defined.
1257 ///
1258 /// The bit indicates when we don't need to check for out-of-date
1259 /// declarations. It will be set unless modules are enabled.
1260 llvm::PointerIntPair<DefinitionData *, 1, bool> Data;
1261
1262 ObjCInterfaceDecl(const ASTContext &C, DeclContext *DC, SourceLocation AtLoc,
1263 IdentifierInfo *Id, ObjCTypeParamList *typeParamList,
1264 SourceLocation CLoc, ObjCInterfaceDecl *PrevDecl,
1265 bool IsInternal);
1266
1267 void anchor() override;
1268
1269 void LoadExternalDefinition() const;
1270
1271 DefinitionData &data() const {
1272 assert(Data.getPointer() && "Declaration has no definition!")((Data.getPointer() && "Declaration has no definition!"
) ? static_cast<void> (0) : __assert_fail ("Data.getPointer() && \"Declaration has no definition!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclObjC.h"
, 1272, __PRETTY_FUNCTION__))
;
1273 return *Data.getPointer();
1274 }
1275
1276 /// Allocate the definition data for this class.
1277 void allocateDefinitionData();
1278
1279 using redeclarable_base = Redeclarable<ObjCInterfaceDecl>;
1280
1281 ObjCInterfaceDecl *getNextRedeclarationImpl() override {
1282 return getNextRedeclaration();
1283 }
1284
1285 ObjCInterfaceDecl *getPreviousDeclImpl() override {
1286 return getPreviousDecl();
1287 }
1288
1289 ObjCInterfaceDecl *getMostRecentDeclImpl() override {
1290 return getMostRecentDecl();
1291 }
1292
1293public:
1294 static ObjCInterfaceDecl *Create(const ASTContext &C, DeclContext *DC,
1295 SourceLocation atLoc,
1296 IdentifierInfo *Id,
1297 ObjCTypeParamList *typeParamList,
1298 ObjCInterfaceDecl *PrevDecl,
1299 SourceLocation ClassLoc = SourceLocation(),
1300 bool isInternal = false);
1301
1302 static ObjCInterfaceDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
1303
1304 /// Retrieve the type parameters of this class.
1305 ///
1306 /// This function looks for a type parameter list for the given
1307 /// class; if the class has been declared (with \c \@class) but not
1308 /// defined (with \c \@interface), it will search for a declaration that
1309 /// has type parameters, skipping any declarations that do not.
1310 ObjCTypeParamList *getTypeParamList() const;
1311
1312 /// Set the type parameters of this class.
1313 ///
1314 /// This function is used by the AST importer, which must import the type
1315 /// parameters after creating their DeclContext to avoid loops.
1316 void setTypeParamList(ObjCTypeParamList *TPL);
1317
1318 /// Retrieve the type parameters written on this particular declaration of
1319 /// the class.
1320 ObjCTypeParamList *getTypeParamListAsWritten() const {
1321 return TypeParamList;
1322 }
1323
1324 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
1325 if (isThisDeclarationADefinition())
1326 return ObjCContainerDecl::getSourceRange();
1327
1328 return SourceRange(getAtStartLoc(), getLocation());
1329 }
1330
1331 /// Indicate that this Objective-C class is complete, but that
1332 /// the external AST source will be responsible for filling in its contents
1333 /// when a complete class is required.
1334 void setExternallyCompleted();
1335
1336 /// Indicate that this interface decl contains at least one initializer
1337 /// marked with the 'objc_designated_initializer' attribute.
1338 void setHasDesignatedInitializers();
1339
1340 /// Returns true if this interface decl contains at least one initializer
1341 /// marked with the 'objc_designated_initializer' attribute.
1342 bool hasDesignatedInitializers() const;
1343
1344 /// Returns true if this interface decl declares a designated initializer
1345 /// or it inherites one from its super class.
1346 bool declaresOrInheritsDesignatedInitializers() const {
1347 return hasDesignatedInitializers() || inheritsDesignatedInitializers();
1348 }
1349
1350 const ObjCProtocolList &getReferencedProtocols() const {
1351 assert(hasDefinition() && "Caller did not check for forward reference!")((hasDefinition() && "Caller did not check for forward reference!"
) ? static_cast<void> (0) : __assert_fail ("hasDefinition() && \"Caller did not check for forward reference!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclObjC.h"
, 1351, __PRETTY_FUNCTION__))
;
1352 if (data().ExternallyCompleted)
1353 LoadExternalDefinition();
1354
1355 return data().ReferencedProtocols;
1356 }
1357
1358 ObjCImplementationDecl *getImplementation() const;
1359 void setImplementation(ObjCImplementationDecl *ImplD);
1360
1361 ObjCCategoryDecl *FindCategoryDeclaration(IdentifierInfo *CategoryId) const;
1362
1363 // Get the local instance/class method declared in a category.
1364 ObjCMethodDecl *getCategoryInstanceMethod(Selector Sel) const;
1365 ObjCMethodDecl *getCategoryClassMethod(Selector Sel) const;
1366
1367 ObjCMethodDecl *getCategoryMethod(Selector Sel, bool isInstance) const {
1368 return isInstance ? getCategoryInstanceMethod(Sel)
1369 : getCategoryClassMethod(Sel);
1370 }
1371
1372 using protocol_iterator = ObjCProtocolList::iterator;
1373 using protocol_range = llvm::iterator_range<protocol_iterator>;
1374
1375 protocol_range protocols() const {
1376 return protocol_range(protocol_begin(), protocol_end());
1377 }
1378
1379 protocol_iterator protocol_begin() const {
1380 // FIXME: Should make sure no callers ever do this.
1381 if (!hasDefinition())
1382 return protocol_iterator();
1383
1384 if (data().ExternallyCompleted)
1385 LoadExternalDefinition();
1386
1387 return data().ReferencedProtocols.begin();
1388 }
1389
1390 protocol_iterator protocol_end() const {
1391 // FIXME: Should make sure no callers ever do this.
1392 if (!hasDefinition())
1393 return protocol_iterator();
1394
1395 if (data().ExternallyCompleted)
1396 LoadExternalDefinition();
1397
1398 return data().ReferencedProtocols.end();
1399 }
1400
1401 using protocol_loc_iterator = ObjCProtocolList::loc_iterator;
1402 using protocol_loc_range = llvm::iterator_range<protocol_loc_iterator>;
1403
1404 protocol_loc_range protocol_locs() const {
1405 return protocol_loc_range(protocol_loc_begin(), protocol_loc_end());
1406 }
1407
1408 protocol_loc_iterator protocol_loc_begin() const {
1409 // FIXME: Should make sure no callers ever do this.
1410 if (!hasDefinition())
1411 return protocol_loc_iterator();
1412
1413 if (data().ExternallyCompleted)
1414 LoadExternalDefinition();
1415
1416 return data().ReferencedProtocols.loc_begin();
1417 }
1418
1419 protocol_loc_iterator protocol_loc_end() const {
1420 // FIXME: Should make sure no callers ever do this.
1421 if (!hasDefinition())
1422 return protocol_loc_iterator();
1423
1424 if (data().ExternallyCompleted)
1425 LoadExternalDefinition();
1426
1427 return data().ReferencedProtocols.loc_end();
1428 }
1429
1430 using all_protocol_iterator = ObjCList<ObjCProtocolDecl>::iterator;
1431 using all_protocol_range = llvm::iterator_range<all_protocol_iterator>;
1432
1433 all_protocol_range all_referenced_protocols() const {
1434 return all_protocol_range(all_referenced_protocol_begin(),
1435 all_referenced_protocol_end());
1436 }
1437
1438 all_protocol_iterator all_referenced_protocol_begin() const {
1439 // FIXME: Should make sure no callers ever do this.
1440 if (!hasDefinition())
1441 return all_protocol_iterator();
1442
1443 if (data().ExternallyCompleted)
1444 LoadExternalDefinition();
1445
1446 return data().AllReferencedProtocols.empty()
1447 ? protocol_begin()
1448 : data().AllReferencedProtocols.begin();
1449 }
1450
1451 all_protocol_iterator all_referenced_protocol_end() const {
1452 // FIXME: Should make sure no callers ever do this.
1453 if (!hasDefinition())
1454 return all_protocol_iterator();
1455
1456 if (data().ExternallyCompleted)
1457 LoadExternalDefinition();
1458
1459 return data().AllReferencedProtocols.empty()
1460 ? protocol_end()
1461 : data().AllReferencedProtocols.end();
1462 }
1463
1464 using ivar_iterator = specific_decl_iterator<ObjCIvarDecl>;
1465 using ivar_range = llvm::iterator_range<specific_decl_iterator<ObjCIvarDecl>>;
1466
1467 ivar_range ivars() const { return ivar_range(ivar_begin(), ivar_end()); }
1468
1469 ivar_iterator ivar_begin() const {
1470 if (const ObjCInterfaceDecl *Def = getDefinition())
1471 return ivar_iterator(Def->decls_begin());
1472
1473 // FIXME: Should make sure no callers ever do this.
1474 return ivar_iterator();
1475 }
1476
1477 ivar_iterator ivar_end() const {
1478 if (const ObjCInterfaceDecl *Def = getDefinition())
1479 return ivar_iterator(Def->decls_end());
1480
1481 // FIXME: Should make sure no callers ever do this.
1482 return ivar_iterator();
1483 }
1484
1485 unsigned ivar_size() const {
1486 return std::distance(ivar_begin(), ivar_end());
1487 }
1488
1489 bool ivar_empty() const { return ivar_begin() == ivar_end(); }
1490
1491 ObjCIvarDecl *all_declared_ivar_begin();
1492 const ObjCIvarDecl *all_declared_ivar_begin() const {
1493 // Even though this modifies IvarList, it's conceptually const:
1494 // the ivar chain is essentially a cached property of ObjCInterfaceDecl.
1495 return const_cast<ObjCInterfaceDecl *>(this)->all_declared_ivar_begin();
1496 }
1497 void setIvarList(ObjCIvarDecl *ivar) { data().IvarList = ivar; }
1498
1499 /// setProtocolList - Set the list of protocols that this interface
1500 /// implements.
1501 void setProtocolList(ObjCProtocolDecl *const* List, unsigned Num,
1502 const SourceLocation *Locs, ASTContext &C) {
1503 data().ReferencedProtocols.set(List, Num, Locs, C);
1504 }
1505
1506 /// mergeClassExtensionProtocolList - Merge class extension's protocol list
1507 /// into the protocol list for this class.
1508 void mergeClassExtensionProtocolList(ObjCProtocolDecl *const* List,
1509 unsigned Num,
1510 ASTContext &C);
1511
1512 /// Produce a name to be used for class's metadata. It comes either via
1513 /// objc_runtime_name attribute or class name.
1514 StringRef getObjCRuntimeNameAsString() const;
1515
1516 /// Returns the designated initializers for the interface.
1517 ///
1518 /// If this declaration does not have methods marked as designated
1519 /// initializers then the interface inherits the designated initializers of
1520 /// its super class.
1521 void getDesignatedInitializers(
1522 llvm::SmallVectorImpl<const ObjCMethodDecl *> &Methods) const;
1523
1524 /// Returns true if the given selector is a designated initializer for the
1525 /// interface.
1526 ///
1527 /// If this declaration does not have methods marked as designated
1528 /// initializers then the interface inherits the designated initializers of
1529 /// its super class.
1530 ///
1531 /// \param InitMethod if non-null and the function returns true, it receives
1532 /// the method that was marked as a designated initializer.
1533 bool
1534 isDesignatedInitializer(Selector Sel,
1535 const ObjCMethodDecl **InitMethod = nullptr) const;
1536
1537 /// Determine whether this particular declaration of this class is
1538 /// actually also a definition.
1539 bool isThisDeclarationADefinition() const {
1540 return getDefinition() == this;
1541 }
1542
1543 /// Determine whether this class has been defined.
1544 bool hasDefinition() const {
1545 // If the name of this class is out-of-date, bring it up-to-date, which
1546 // might bring in a definition.
1547 // Note: a null value indicates that we don't have a definition and that
1548 // modules are enabled.
1549 if (!Data.getOpaqueValue())
2
Assuming the condition is false
3
Taking false branch
1550 getMostRecentDecl();
1551
1552 return Data.getPointer();
4
Returning value, which participates in a condition later
1553 }
1554
1555 /// Retrieve the definition of this class, or NULL if this class
1556 /// has been forward-declared (with \@class) but not yet defined (with
1557 /// \@interface).
1558 ObjCInterfaceDecl *getDefinition() {
1559 return hasDefinition()? Data.getPointer()->Definition : nullptr;
1560 }
1561
1562 /// Retrieve the definition of this class, or NULL if this class
1563 /// has been forward-declared (with \@class) but not yet defined (with
1564 /// \@interface).
1565 const ObjCInterfaceDecl *getDefinition() const {
1566 return hasDefinition()? Data.getPointer()->Definition : nullptr;
15
Assuming the condition is true
16
'?' condition is true
17
Returning pointer, which participates in a condition later
1567 }
1568
1569 /// Starts the definition of this Objective-C class, taking it from
1570 /// a forward declaration (\@class) to a definition (\@interface).
1571 void startDefinition();
1572
1573 /// Retrieve the superclass type.
1574 const ObjCObjectType *getSuperClassType() const {
1575 if (TypeSourceInfo *TInfo = getSuperClassTInfo())
1576 return TInfo->getType()->castAs<ObjCObjectType>();
1577
1578 return nullptr;
1579 }
1580
1581 // Retrieve the type source information for the superclass.
1582 TypeSourceInfo *getSuperClassTInfo() const {
1583 // FIXME: Should make sure no callers ever do this.
1584 if (!hasDefinition())
1585 return nullptr;
1586
1587 if (data().ExternallyCompleted)
1588 LoadExternalDefinition();
1589
1590 return data().SuperClassTInfo;
1591 }
1592
1593 // Retrieve the declaration for the superclass of this class, which
1594 // does not include any type arguments that apply to the superclass.
1595 ObjCInterfaceDecl *getSuperClass() const;
1596
1597 void setSuperClass(TypeSourceInfo *superClass) {
1598 data().SuperClassTInfo = superClass;
1599 }
1600
1601 /// Iterator that walks over the list of categories, filtering out
1602 /// those that do not meet specific criteria.
1603 ///
1604 /// This class template is used for the various permutations of category
1605 /// and extension iterators.
1606 template<bool (*Filter)(ObjCCategoryDecl *)>
1607 class filtered_category_iterator {
1608 ObjCCategoryDecl *Current = nullptr;
1609
1610 void findAcceptableCategory();
1611
1612 public:
1613 using value_type = ObjCCategoryDecl *;
1614 using reference = value_type;
1615 using pointer = value_type;
1616 using difference_type = std::ptrdiff_t;
1617 using iterator_category = std::input_iterator_tag;
1618
1619 filtered_category_iterator() = default;
1620 explicit filtered_category_iterator(ObjCCategoryDecl *Current)
1621 : Current(Current) {
1622 findAcceptableCategory();
1623 }
1624
1625 reference operator*() const { return Current; }
1626 pointer operator->() const { return Current; }
1627
1628 filtered_category_iterator &operator++();
1629
1630 filtered_category_iterator operator++(int) {
1631 filtered_category_iterator Tmp = *this;
1632 ++(*this);
1633 return Tmp;
1634 }
1635
1636 friend bool operator==(filtered_category_iterator X,
1637 filtered_category_iterator Y) {
1638 return X.Current == Y.Current;
1639 }
1640
1641 friend bool operator!=(filtered_category_iterator X,
1642 filtered_category_iterator Y) {
1643 return X.Current != Y.Current;
1644 }
1645 };
1646
1647private:
1648 /// Test whether the given category is visible.
1649 ///
1650 /// Used in the \c visible_categories_iterator.
1651 static bool isVisibleCategory(ObjCCategoryDecl *Cat);
1652
1653public:
1654 /// Iterator that walks over the list of categories and extensions
1655 /// that are visible, i.e., not hidden in a non-imported submodule.
1656 using visible_categories_iterator =
1657 filtered_category_iterator<isVisibleCategory>;
1658
1659 using visible_categories_range =
1660 llvm::iterator_range<visible_categories_iterator>;
1661
1662 visible_categories_range visible_categories() const {
1663 return visible_categories_range(visible_categories_begin(),
1664 visible_categories_end());
1665 }
1666
1667 /// Retrieve an iterator to the beginning of the visible-categories
1668 /// list.
1669 visible_categories_iterator visible_categories_begin() const {
1670 return visible_categories_iterator(getCategoryListRaw());
1671 }
1672
1673 /// Retrieve an iterator to the end of the visible-categories list.
1674 visible_categories_iterator visible_categories_end() const {
1675 return visible_categories_iterator();
1676 }
1677
1678 /// Determine whether the visible-categories list is empty.
1679 bool visible_categories_empty() const {
1680 return visible_categories_begin() == visible_categories_end();
1681 }
1682
1683private:
1684 /// Test whether the given category... is a category.
1685 ///
1686 /// Used in the \c known_categories_iterator.
1687 static bool isKnownCategory(ObjCCategoryDecl *) { return true; }
1688
1689public:
1690 /// Iterator that walks over all of the known categories and
1691 /// extensions, including those that are hidden.
1692 using known_categories_iterator = filtered_category_iterator<isKnownCategory>;
1693 using known_categories_range =
1694 llvm::iterator_range<known_categories_iterator>;
1695
1696 known_categories_range known_categories() const {
1697 return known_categories_range(known_categories_begin(),
1698 known_categories_end());
1699 }
1700
1701 /// Retrieve an iterator to the beginning of the known-categories
1702 /// list.
1703 known_categories_iterator known_categories_begin() const {
1704 return known_categories_iterator(getCategoryListRaw());
1705 }
1706
1707 /// Retrieve an iterator to the end of the known-categories list.
1708 known_categories_iterator known_categories_end() const {
1709 return known_categories_iterator();
1710 }
1711
1712 /// Determine whether the known-categories list is empty.
1713 bool known_categories_empty() const {
1714 return known_categories_begin() == known_categories_end();
1715 }
1716
1717private:
1718 /// Test whether the given category is a visible extension.
1719 ///
1720 /// Used in the \c visible_extensions_iterator.
1721 static bool isVisibleExtension(ObjCCategoryDecl *Cat);
1722
1723public:
1724 /// Iterator that walks over all of the visible extensions, skipping
1725 /// any that are known but hidden.
1726 using visible_extensions_iterator =
1727 filtered_category_iterator<isVisibleExtension>;
1728
1729 using visible_extensions_range =
1730 llvm::iterator_range<visible_extensions_iterator>;
1731
1732 visible_extensions_range visible_extensions() const {
1733 return visible_extensions_range(visible_extensions_begin(),
1734 visible_extensions_end());
1735 }
1736
1737 /// Retrieve an iterator to the beginning of the visible-extensions
1738 /// list.
1739 visible_extensions_iterator visible_extensions_begin() const {
1740 return visible_extensions_iterator(getCategoryListRaw());
1741 }
1742
1743 /// Retrieve an iterator to the end of the visible-extensions list.
1744 visible_extensions_iterator visible_extensions_end() const {
1745 return visible_extensions_iterator();
1746 }
1747
1748 /// Determine whether the visible-extensions list is empty.
1749 bool visible_extensions_empty() const {
1750 return visible_extensions_begin() == visible_extensions_end();
1751 }
1752
1753private:
1754 /// Test whether the given category is an extension.
1755 ///
1756 /// Used in the \c known_extensions_iterator.
1757 static bool isKnownExtension(ObjCCategoryDecl *Cat);
1758
1759public:
1760 friend class ASTDeclReader;
1761 friend class ASTDeclWriter;
1762 friend class ASTReader;
1763
1764 /// Iterator that walks over all of the known extensions.
1765 using known_extensions_iterator =
1766 filtered_category_iterator<isKnownExtension>;
1767 using known_extensions_range =
1768 llvm::iterator_range<known_extensions_iterator>;
1769
1770 known_extensions_range known_extensions() const {
1771 return known_extensions_range(known_extensions_begin(),
1772 known_extensions_end());
1773 }
1774
1775 /// Retrieve an iterator to the beginning of the known-extensions
1776 /// list.
1777 known_extensions_iterator known_extensions_begin() const {
1778 return known_extensions_iterator(getCategoryListRaw());
1779 }
1780
1781 /// Retrieve an iterator to the end of the known-extensions list.
1782 known_extensions_iterator known_extensions_end() const {
1783 return known_extensions_iterator();
1784 }
1785
1786 /// Determine whether the known-extensions list is empty.
1787 bool known_extensions_empty() const {
1788 return known_extensions_begin() == known_extensions_end();
1789 }
1790
1791 /// Retrieve the raw pointer to the start of the category/extension
1792 /// list.
1793 ObjCCategoryDecl* getCategoryListRaw() const {
1794 // FIXME: Should make sure no callers ever do this.
1795 if (!hasDefinition())
1796 return nullptr;
1797
1798 if (data().ExternallyCompleted)
1799 LoadExternalDefinition();
1800
1801 return data().CategoryList;
1802 }
1803
1804 /// Set the raw pointer to the start of the category/extension
1805 /// list.
1806 void setCategoryListRaw(ObjCCategoryDecl *category) {
1807 data().CategoryList = category;
1808 }
1809
1810 ObjCPropertyDecl
1811 *FindPropertyVisibleInPrimaryClass(IdentifierInfo *PropertyId,
1812 ObjCPropertyQueryKind QueryKind) const;
1813
1814 void collectPropertiesToImplement(PropertyMap &PM,
1815 PropertyDeclOrder &PO) const override;
1816
1817 /// isSuperClassOf - Return true if this class is the specified class or is a
1818 /// super class of the specified interface class.
1819 bool isSuperClassOf(const ObjCInterfaceDecl *I) const {
1820 // If RHS is derived from LHS it is OK; else it is not OK.
1821 while (I != nullptr) {
1822 if (declaresSameEntity(this, I))
1823 return true;
1824
1825 I = I->getSuperClass();
1826 }
1827 return false;
1828 }
1829
1830 /// isArcWeakrefUnavailable - Checks for a class or one of its super classes
1831 /// to be incompatible with __weak references. Returns true if it is.
1832 bool isArcWeakrefUnavailable() const;
1833
1834 /// isObjCRequiresPropertyDefs - Checks that a class or one of its super
1835 /// classes must not be auto-synthesized. Returns class decl. if it must not
1836 /// be; 0, otherwise.
1837 const ObjCInterfaceDecl *isObjCRequiresPropertyDefs() const;
1838
1839 ObjCIvarDecl *lookupInstanceVariable(IdentifierInfo *IVarName,
1840 ObjCInterfaceDecl *&ClassDeclared);
1841 ObjCIvarDecl *lookupInstanceVariable(IdentifierInfo *IVarName) {
1842 ObjCInterfaceDecl *ClassDeclared;
1843 return lookupInstanceVariable(IVarName, ClassDeclared);
1844 }
1845
1846 ObjCProtocolDecl *lookupNestedProtocol(IdentifierInfo *Name);
1847
1848 // Lookup a method. First, we search locally. If a method isn't
1849 // found, we search referenced protocols and class categories.
1850 ObjCMethodDecl *lookupMethod(Selector Sel, bool isInstance,
1851 bool shallowCategoryLookup = false,
1852 bool followSuper = true,
1853 const ObjCCategoryDecl *C = nullptr) const;
1854
1855 /// Lookup an instance method for a given selector.
1856 ObjCMethodDecl *lookupInstanceMethod(Selector Sel) const {
1857 return lookupMethod(Sel, true/*isInstance*/);
1858 }
1859
1860 /// Lookup a class method for a given selector.
1861 ObjCMethodDecl *lookupClassMethod(Selector Sel) const {
1862 return lookupMethod(Sel, false/*isInstance*/);
1863 }
1864
1865 ObjCInterfaceDecl *lookupInheritedClass(const IdentifierInfo *ICName);
1866
1867 /// Lookup a method in the classes implementation hierarchy.
1868 ObjCMethodDecl *lookupPrivateMethod(const Selector &Sel,
1869 bool Instance=true) const;
1870
1871 ObjCMethodDecl *lookupPrivateClassMethod(const Selector &Sel) {
1872 return lookupPrivateMethod(Sel, false);
1873 }
1874
1875 /// Lookup a setter or getter in the class hierarchy,
1876 /// including in all categories except for category passed
1877 /// as argument.
1878 ObjCMethodDecl *lookupPropertyAccessor(const Selector Sel,
1879 const ObjCCategoryDecl *Cat,
1880 bool IsClassProperty) const {
1881 return lookupMethod(Sel, !IsClassProperty/*isInstance*/,
1882 false/*shallowCategoryLookup*/,
1883 true /* followsSuper */,
1884 Cat);
1885 }
1886
1887 SourceLocation getEndOfDefinitionLoc() const {
1888 if (!hasDefinition())
1889 return getLocation();
1890
1891 return data().EndLoc;
1892 }
1893
1894 void setEndOfDefinitionLoc(SourceLocation LE) { data().EndLoc = LE; }
1895
1896 /// Retrieve the starting location of the superclass.
1897 SourceLocation getSuperClassLoc() const;
1898
1899 /// isImplicitInterfaceDecl - check that this is an implicitly declared
1900 /// ObjCInterfaceDecl node. This is for legacy objective-c \@implementation
1901 /// declaration without an \@interface declaration.
1902 bool isImplicitInterfaceDecl() const {
1903 return hasDefinition() ? data().Definition->isImplicit() : isImplicit();
1904 }
1905
1906 /// ClassImplementsProtocol - Checks that 'lProto' protocol
1907 /// has been implemented in IDecl class, its super class or categories (if
1908 /// lookupCategory is true).
1909 bool ClassImplementsProtocol(ObjCProtocolDecl *lProto,
1910 bool lookupCategory,
1911 bool RHSIsQualifiedID = false);
1912
1913 using redecl_range = redeclarable_base::redecl_range;
1914 using redecl_iterator = redeclarable_base::redecl_iterator;
1915
1916 using redeclarable_base::redecls_begin;
1917 using redeclarable_base::redecls_end;
1918 using redeclarable_base::redecls;
1919 using redeclarable_base::getPreviousDecl;
1920 using redeclarable_base::getMostRecentDecl;
1921 using redeclarable_base::isFirstDecl;
1922
1923 /// Retrieves the canonical declaration of this Objective-C class.
1924 ObjCInterfaceDecl *getCanonicalDecl() override { return getFirstDecl(); }
1925 const ObjCInterfaceDecl *getCanonicalDecl() const { return getFirstDecl(); }
1926
1927 // Low-level accessor
1928 const Type *getTypeForDecl() const { return TypeForDecl; }
1929 void setTypeForDecl(const Type *TD) const { TypeForDecl = TD; }
1930
1931 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1932 static bool classofKind(Kind K) { return K == ObjCInterface; }
1933
1934private:
1935 const ObjCInterfaceDecl *findInterfaceWithDesignatedInitializers() const;
1936 bool inheritsDesignatedInitializers() const;
1937};
1938
1939/// ObjCIvarDecl - Represents an ObjC instance variable. In general, ObjC
1940/// instance variables are identical to C. The only exception is Objective-C
1941/// supports C++ style access control. For example:
1942///
1943/// \@interface IvarExample : NSObject
1944/// {
1945/// id defaultToProtected;
1946/// \@public:
1947/// id canBePublic; // same as C++.
1948/// \@protected:
1949/// id canBeProtected; // same as C++.
1950/// \@package:
1951/// id canBePackage; // framework visibility (not available in C++).
1952/// }
1953///
1954class ObjCIvarDecl : public FieldDecl {
1955 void anchor() override;
1956
1957public:
1958 enum AccessControl {
1959 None, Private, Protected, Public, Package
1960 };
1961
1962private:
1963 ObjCIvarDecl(ObjCContainerDecl *DC, SourceLocation StartLoc,
1964 SourceLocation IdLoc, IdentifierInfo *Id,
1965 QualType T, TypeSourceInfo *TInfo, AccessControl ac, Expr *BW,
1966 bool synthesized)
1967 : FieldDecl(ObjCIvar, DC, StartLoc, IdLoc, Id, T, TInfo, BW,
1968 /*Mutable=*/false, /*HasInit=*/ICIS_NoInit),
1969 DeclAccess(ac), Synthesized(synthesized) {}
1970
1971public:
1972 static ObjCIvarDecl *Create(ASTContext &C, ObjCContainerDecl *DC,
1973 SourceLocation StartLoc, SourceLocation IdLoc,
1974 IdentifierInfo *Id, QualType T,
1975 TypeSourceInfo *TInfo,
1976 AccessControl ac, Expr *BW = nullptr,
1977 bool synthesized=false);
1978
1979 static ObjCIvarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1980
1981 /// Return the class interface that this ivar is logically contained
1982 /// in; this is either the interface where the ivar was declared, or the
1983 /// interface the ivar is conceptually a part of in the case of synthesized
1984 /// ivars.
1985 const ObjCInterfaceDecl *getContainingInterface() const;
1986
1987 ObjCIvarDecl *getNextIvar() { return NextIvar; }
1988 const ObjCIvarDecl *getNextIvar() const { return NextIvar; }
1989 void setNextIvar(ObjCIvarDecl *ivar) { NextIvar = ivar; }
1990
1991 void setAccessControl(AccessControl ac) { DeclAccess = ac; }
1992
1993 AccessControl getAccessControl() const { return AccessControl(DeclAccess); }
1994
1995 AccessControl getCanonicalAccessControl() const {
1996 return DeclAccess == None ? Protected : AccessControl(DeclAccess);
1997 }
1998
1999 void setSynthesize(bool synth) { Synthesized = synth; }
2000 bool getSynthesize() const { return Synthesized; }
2001
2002 /// Retrieve the type of this instance variable when viewed as a member of a
2003 /// specific object type.
2004 QualType getUsageType(QualType objectType) const;
2005
2006 // Implement isa/cast/dyncast/etc.
2007 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2008 static bool classofKind(Kind K) { return K == ObjCIvar; }
2009
2010private:
2011 /// NextIvar - Next Ivar in the list of ivars declared in class; class's
2012 /// extensions and class's implementation
2013 ObjCIvarDecl *NextIvar = nullptr;
2014
2015 // NOTE: VC++ treats enums as signed, avoid using the AccessControl enum
2016 unsigned DeclAccess : 3;
2017 unsigned Synthesized : 1;
2018};
2019
2020/// Represents a field declaration created by an \@defs(...).
2021class ObjCAtDefsFieldDecl : public FieldDecl {
2022 ObjCAtDefsFieldDecl(DeclContext *DC, SourceLocation StartLoc,
2023 SourceLocation IdLoc, IdentifierInfo *Id,
2024 QualType T, Expr *BW)
2025 : FieldDecl(ObjCAtDefsField, DC, StartLoc, IdLoc, Id, T,
2026 /*TInfo=*/nullptr, // FIXME: Do ObjCAtDefs have declarators ?
2027 BW, /*Mutable=*/false, /*HasInit=*/ICIS_NoInit) {}
2028
2029 void anchor() override;
2030
2031public:
2032 static ObjCAtDefsFieldDecl *Create(ASTContext &C, DeclContext *DC,
2033 SourceLocation StartLoc,
2034 SourceLocation IdLoc, IdentifierInfo *Id,
2035 QualType T, Expr *BW);
2036
2037 static ObjCAtDefsFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2038
2039 // Implement isa/cast/dyncast/etc.
2040 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2041 static bool classofKind(Kind K) { return K == ObjCAtDefsField; }
2042};
2043
2044/// Represents an Objective-C protocol declaration.
2045///
2046/// Objective-C protocols declare a pure abstract type (i.e., no instance
2047/// variables are permitted). Protocols originally drew inspiration from
2048/// C++ pure virtual functions (a C++ feature with nice semantics and lousy
2049/// syntax:-). Here is an example:
2050///
2051/// \code
2052/// \@protocol NSDraggingInfo <refproto1, refproto2>
2053/// - (NSWindow *)draggingDestinationWindow;
2054/// - (NSImage *)draggedImage;
2055/// \@end
2056/// \endcode
2057///
2058/// This says that NSDraggingInfo requires two methods and requires everything
2059/// that the two "referenced protocols" 'refproto1' and 'refproto2' require as
2060/// well.
2061///
2062/// \code
2063/// \@interface ImplementsNSDraggingInfo : NSObject \<NSDraggingInfo>
2064/// \@end
2065/// \endcode
2066///
2067/// ObjC protocols inspired Java interfaces. Unlike Java, ObjC classes and
2068/// protocols are in distinct namespaces. For example, Cocoa defines both
2069/// an NSObject protocol and class (which isn't allowed in Java). As a result,
2070/// protocols are referenced using angle brackets as follows:
2071///
2072/// id \<NSDraggingInfo> anyObjectThatImplementsNSDraggingInfo;
2073class ObjCProtocolDecl : public ObjCContainerDecl,
2074 public Redeclarable<ObjCProtocolDecl> {
2075 struct DefinitionData {
2076 // The declaration that defines this protocol.
2077 ObjCProtocolDecl *Definition;
2078
2079 /// Referenced protocols
2080 ObjCProtocolList ReferencedProtocols;
2081 };
2082
2083 /// Contains a pointer to the data associated with this class,
2084 /// which will be NULL if this class has not yet been defined.
2085 ///
2086 /// The bit indicates when we don't need to check for out-of-date
2087 /// declarations. It will be set unless modules are enabled.
2088 llvm::PointerIntPair<DefinitionData *, 1, bool> Data;
2089
2090 ObjCProtocolDecl(ASTContext &C, DeclContext *DC, IdentifierInfo *Id,
2091 SourceLocation nameLoc, SourceLocation atStartLoc,
2092 ObjCProtocolDecl *PrevDecl);
2093
2094 void anchor() override;
2095
2096 DefinitionData &data() const {
2097 assert(Data.getPointer() && "Objective-C protocol has no definition!")((Data.getPointer() && "Objective-C protocol has no definition!"
) ? static_cast<void> (0) : __assert_fail ("Data.getPointer() && \"Objective-C protocol has no definition!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclObjC.h"
, 2097, __PRETTY_FUNCTION__))
;
2098 return *Data.getPointer();
2099 }
2100
2101 void allocateDefinitionData();
2102
2103 using redeclarable_base = Redeclarable<ObjCProtocolDecl>;
2104
2105 ObjCProtocolDecl *getNextRedeclarationImpl() override {
2106 return getNextRedeclaration();
2107 }
2108
2109 ObjCProtocolDecl *getPreviousDeclImpl() override {
2110 return getPreviousDecl();
2111 }
2112
2113 ObjCProtocolDecl *getMostRecentDeclImpl() override {
2114 return getMostRecentDecl();
2115 }
2116
2117public:
2118 friend class ASTDeclReader;
2119 friend class ASTDeclWriter;
2120 friend class ASTReader;
2121
2122 static ObjCProtocolDecl *Create(ASTContext &C, DeclContext *DC,
2123 IdentifierInfo *Id,
2124 SourceLocation nameLoc,
2125 SourceLocation atStartLoc,
2126 ObjCProtocolDecl *PrevDecl);
2127
2128 static ObjCProtocolDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2129
2130 const ObjCProtocolList &getReferencedProtocols() const {
2131 assert(hasDefinition() && "No definition available!")((hasDefinition() && "No definition available!") ? static_cast
<void> (0) : __assert_fail ("hasDefinition() && \"No definition available!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclObjC.h"
, 2131, __PRETTY_FUNCTION__))
;
2132 return data().ReferencedProtocols;
2133 }
2134
2135 using protocol_iterator = ObjCProtocolList::iterator;
2136 using protocol_range = llvm::iterator_range<protocol_iterator>;
2137
2138 protocol_range protocols() const {
2139 return protocol_range(protocol_begin(), protocol_end());
2140 }
2141
2142 protocol_iterator protocol_begin() const {
2143 if (!hasDefinition())
2144 return protocol_iterator();
2145
2146 return data().ReferencedProtocols.begin();
2147 }
2148
2149 protocol_iterator protocol_end() const {
2150 if (!hasDefinition())
2151 return protocol_iterator();
2152
2153 return data().ReferencedProtocols.end();
2154 }
2155
2156 using protocol_loc_iterator = ObjCProtocolList::loc_iterator;
2157 using protocol_loc_range = llvm::iterator_range<protocol_loc_iterator>;
2158
2159 protocol_loc_range protocol_locs() const {
2160 return protocol_loc_range(protocol_loc_begin(), protocol_loc_end());
2161 }
2162
2163 protocol_loc_iterator protocol_loc_begin() const {
2164 if (!hasDefinition())
2165 return protocol_loc_iterator();
2166
2167 return data().ReferencedProtocols.loc_begin();
2168 }
2169
2170 protocol_loc_iterator protocol_loc_end() const {
2171 if (!hasDefinition())
2172 return protocol_loc_iterator();
2173
2174 return data().ReferencedProtocols.loc_end();
2175 }
2176
2177 unsigned protocol_size() const {
2178 if (!hasDefinition())
2179 return 0;
2180
2181 return data().ReferencedProtocols.size();
2182 }
2183
2184 /// setProtocolList - Set the list of protocols that this interface
2185 /// implements.
2186 void setProtocolList(ObjCProtocolDecl *const*List, unsigned Num,
2187 const SourceLocation *Locs, ASTContext &C) {
2188 assert(hasDefinition() && "Protocol is not defined")((hasDefinition() && "Protocol is not defined") ? static_cast
<void> (0) : __assert_fail ("hasDefinition() && \"Protocol is not defined\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclObjC.h"
, 2188, __PRETTY_FUNCTION__))
;
2189 data().ReferencedProtocols.set(List, Num, Locs, C);
2190 }
2191
2192 ObjCProtocolDecl *lookupProtocolNamed(IdentifierInfo *PName);
2193
2194 // Lookup a method. First, we search locally. If a method isn't
2195 // found, we search referenced protocols and class categories.
2196 ObjCMethodDecl *lookupMethod(Selector Sel, bool isInstance) const;
2197
2198 ObjCMethodDecl *lookupInstanceMethod(Selector Sel) const {
2199 return lookupMethod(Sel, true/*isInstance*/);
2200 }
2201
2202 ObjCMethodDecl *lookupClassMethod(Selector Sel) const {
2203 return lookupMethod(Sel, false/*isInstance*/);
2204 }
2205
2206 /// Determine whether this protocol has a definition.
2207 bool hasDefinition() const {
2208 // If the name of this protocol is out-of-date, bring it up-to-date, which
2209 // might bring in a definition.
2210 // Note: a null value indicates that we don't have a definition and that
2211 // modules are enabled.
2212 if (!Data.getOpaqueValue())
2213 getMostRecentDecl();
2214
2215 return Data.getPointer();
2216 }
2217
2218 /// Retrieve the definition of this protocol, if any.
2219 ObjCProtocolDecl *getDefinition() {
2220 return hasDefinition()? Data.getPointer()->Definition : nullptr;
2221 }
2222
2223 /// Retrieve the definition of this protocol, if any.
2224 const ObjCProtocolDecl *getDefinition() const {
2225 return hasDefinition()? Data.getPointer()->Definition : nullptr;
2226 }
2227
2228 /// Determine whether this particular declaration is also the
2229 /// definition.
2230 bool isThisDeclarationADefinition() const {
2231 return getDefinition() == this;
2232 }
2233
2234 /// Starts the definition of this Objective-C protocol.
2235 void startDefinition();
2236
2237 /// Produce a name to be used for protocol's metadata. It comes either via
2238 /// objc_runtime_name attribute or protocol name.
2239 StringRef getObjCRuntimeNameAsString() const;
2240
2241 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
2242 if (isThisDeclarationADefinition())
2243 return ObjCContainerDecl::getSourceRange();
2244
2245 return SourceRange(getAtStartLoc(), getLocation());
2246 }
2247
2248 using redecl_range = redeclarable_base::redecl_range;
2249 using redecl_iterator = redeclarable_base::redecl_iterator;
2250
2251 using redeclarable_base::redecls_begin;
2252 using redeclarable_base::redecls_end;
2253 using redeclarable_base::redecls;
2254 using redeclarable_base::getPreviousDecl;
2255 using redeclarable_base::getMostRecentDecl;
2256 using redeclarable_base::isFirstDecl;
2257
2258 /// Retrieves the canonical declaration of this Objective-C protocol.
2259 ObjCProtocolDecl *getCanonicalDecl() override { return getFirstDecl(); }
2260 const ObjCProtocolDecl *getCanonicalDecl() const { return getFirstDecl(); }
2261
2262 void collectPropertiesToImplement(PropertyMap &PM,
2263 PropertyDeclOrder &PO) const override;
2264
2265 void collectInheritedProtocolProperties(const ObjCPropertyDecl *Property,
2266 ProtocolPropertySet &PS,
2267 PropertyDeclOrder &PO) const;
2268
2269 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2270 static bool classofKind(Kind K) { return K == ObjCProtocol; }
2271};
2272
2273/// ObjCCategoryDecl - Represents a category declaration. A category allows
2274/// you to add methods to an existing class (without subclassing or modifying
2275/// the original class interface or implementation:-). Categories don't allow
2276/// you to add instance data. The following example adds "myMethod" to all
2277/// NSView's within a process:
2278///
2279/// \@interface NSView (MyViewMethods)
2280/// - myMethod;
2281/// \@end
2282///
2283/// Categories also allow you to split the implementation of a class across
2284/// several files (a feature more naturally supported in C++).
2285///
2286/// Categories were originally inspired by dynamic languages such as Common
2287/// Lisp and Smalltalk. More traditional class-based languages (C++, Java)
2288/// don't support this level of dynamism, which is both powerful and dangerous.
2289class ObjCCategoryDecl : public ObjCContainerDecl {
2290 /// Interface belonging to this category
2291 ObjCInterfaceDecl *ClassInterface;
2292
2293 /// The type parameters associated with this category, if any.
2294 ObjCTypeParamList *TypeParamList = nullptr;
2295
2296 /// referenced protocols in this category.
2297 ObjCProtocolList ReferencedProtocols;
2298
2299 /// Next category belonging to this class.
2300 /// FIXME: this should not be a singly-linked list. Move storage elsewhere.
2301 ObjCCategoryDecl *NextClassCategory = nullptr;
2302
2303 /// The location of the category name in this declaration.
2304 SourceLocation CategoryNameLoc;
2305
2306 /// class extension may have private ivars.
2307 SourceLocation IvarLBraceLoc;
2308 SourceLocation IvarRBraceLoc;
2309
2310 ObjCCategoryDecl(DeclContext *DC, SourceLocation AtLoc,
2311 SourceLocation ClassNameLoc, SourceLocation CategoryNameLoc,
2312 IdentifierInfo *Id, ObjCInterfaceDecl *IDecl,
2313 ObjCTypeParamList *typeParamList,
2314 SourceLocation IvarLBraceLoc = SourceLocation(),
2315 SourceLocation IvarRBraceLoc = SourceLocation());
2316
2317 void anchor() override;
2318
2319public:
2320 friend class ASTDeclReader;
2321 friend class ASTDeclWriter;
2322
2323 static ObjCCategoryDecl *Create(ASTContext &C, DeclContext *DC,
2324 SourceLocation AtLoc,
2325 SourceLocation ClassNameLoc,
2326 SourceLocation CategoryNameLoc,
2327 IdentifierInfo *Id,
2328 ObjCInterfaceDecl *IDecl,
2329 ObjCTypeParamList *typeParamList,
2330 SourceLocation IvarLBraceLoc=SourceLocation(),
2331 SourceLocation IvarRBraceLoc=SourceLocation());
2332 static ObjCCategoryDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2333
2334 ObjCInterfaceDecl *getClassInterface() { return ClassInterface; }
2335 const ObjCInterfaceDecl *getClassInterface() const { return ClassInterface; }
2336
2337 /// Retrieve the type parameter list associated with this category or
2338 /// extension.
2339 ObjCTypeParamList *getTypeParamList() const { return TypeParamList; }
2340
2341 /// Set the type parameters of this category.
2342 ///
2343 /// This function is used by the AST importer, which must import the type
2344 /// parameters after creating their DeclContext to avoid loops.
2345 void setTypeParamList(ObjCTypeParamList *TPL);
2346
2347
2348 ObjCCategoryImplDecl *getImplementation() const;
2349 void setImplementation(ObjCCategoryImplDecl *ImplD);
2350
2351 /// setProtocolList - Set the list of protocols that this interface
2352 /// implements.
2353 void setProtocolList(ObjCProtocolDecl *const*List, unsigned Num,
2354 const SourceLocation *Locs, ASTContext &C) {
2355 ReferencedProtocols.set(List, Num, Locs, C);
2356 }
2357
2358 const ObjCProtocolList &getReferencedProtocols() const {
2359 return ReferencedProtocols;
2360 }
2361
2362 using protocol_iterator = ObjCProtocolList::iterator;
2363 using protocol_range = llvm::iterator_range<protocol_iterator>;
2364
2365 protocol_range protocols() const {
2366 return protocol_range(protocol_begin(), protocol_end());
2367 }
2368
2369 protocol_iterator protocol_begin() const {
2370 return ReferencedProtocols.begin();
2371 }
2372
2373 protocol_iterator protocol_end() const { return ReferencedProtocols.end(); }
2374 unsigned protocol_size() const { return ReferencedProtocols.size(); }
2375
2376 using protocol_loc_iterator = ObjCProtocolList::loc_iterator;
2377 using protocol_loc_range = llvm::iterator_range<protocol_loc_iterator>;
2378
2379 protocol_loc_range protocol_locs() const {
2380 return protocol_loc_range(protocol_loc_begin(), protocol_loc_end());
2381 }
2382
2383 protocol_loc_iterator protocol_loc_begin() const {
2384 return ReferencedProtocols.loc_begin();
2385 }
2386
2387 protocol_loc_iterator protocol_loc_end() const {
2388 return ReferencedProtocols.loc_end();
2389 }
2390
2391 ObjCCategoryDecl *getNextClassCategory() const { return NextClassCategory; }
2392
2393 /// Retrieve the pointer to the next stored category (or extension),
2394 /// which may be hidden.
2395 ObjCCategoryDecl *getNextClassCategoryRaw() const {
2396 return NextClassCategory;
2397 }
2398
2399 bool IsClassExtension() const { return getIdentifier() == nullptr; }
2400
2401 using ivar_iterator = specific_decl_iterator<ObjCIvarDecl>;
2402 using ivar_range = llvm::iterator_range<specific_decl_iterator<ObjCIvarDecl>>;
2403
2404 ivar_range ivars() const { return ivar_range(ivar_begin(), ivar_end()); }
2405
2406 ivar_iterator ivar_begin() const {
2407 return ivar_iterator(decls_begin());
2408 }
2409
2410 ivar_iterator ivar_end() const {
2411 return ivar_iterator(decls_end());
2412 }
2413
2414 unsigned ivar_size() const {
2415 return std::distance(ivar_begin(), ivar_end());
2416 }
2417
2418 bool ivar_empty() const {
2419 return ivar_begin() == ivar_end();
2420 }
2421
2422 SourceLocation getCategoryNameLoc() const { return CategoryNameLoc; }
2423 void setCategoryNameLoc(SourceLocation Loc) { CategoryNameLoc = Loc; }
2424
2425 void setIvarLBraceLoc(SourceLocation Loc) { IvarLBraceLoc = Loc; }
2426 SourceLocation getIvarLBraceLoc() const { return IvarLBraceLoc; }
2427 void setIvarRBraceLoc(SourceLocation Loc) { IvarRBraceLoc = Loc; }
2428 SourceLocation getIvarRBraceLoc() const { return IvarRBraceLoc; }
2429
2430 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2431 static bool classofKind(Kind K) { return K == ObjCCategory; }
2432};
2433
2434class ObjCImplDecl : public ObjCContainerDecl {
2435 /// Class interface for this class/category implementation
2436 ObjCInterfaceDecl *ClassInterface;
2437
2438 void anchor() override;
2439
2440protected:
2441 ObjCImplDecl(Kind DK, DeclContext *DC,
2442 ObjCInterfaceDecl *classInterface,
2443 IdentifierInfo *Id,
2444 SourceLocation nameLoc, SourceLocation atStartLoc)
2445 : ObjCContainerDecl(DK, DC, Id, nameLoc, atStartLoc),
2446 ClassInterface(classInterface) {}
2447
2448public:
2449 const ObjCInterfaceDecl *getClassInterface() const { return ClassInterface; }
2450 ObjCInterfaceDecl *getClassInterface() { return ClassInterface; }
2451 void setClassInterface(ObjCInterfaceDecl *IFace);
2452
2453 void addInstanceMethod(ObjCMethodDecl *method) {
2454 // FIXME: Context should be set correctly before we get here.
2455 method->setLexicalDeclContext(this);
2456 addDecl(method);
2457 }
2458
2459 void addClassMethod(ObjCMethodDecl *method) {
2460 // FIXME: Context should be set correctly before we get here.
2461 method->setLexicalDeclContext(this);
2462 addDecl(method);
2463 }
2464
2465 void addPropertyImplementation(ObjCPropertyImplDecl *property);
2466
2467 ObjCPropertyImplDecl *FindPropertyImplDecl(IdentifierInfo *propertyId,
2468 ObjCPropertyQueryKind queryKind) const;
2469 ObjCPropertyImplDecl *FindPropertyImplIvarDecl(IdentifierInfo *ivarId) const;
2470
2471 // Iterator access to properties.
2472 using propimpl_iterator = specific_decl_iterator<ObjCPropertyImplDecl>;
2473 using propimpl_range =
2474 llvm::iterator_range<specific_decl_iterator<ObjCPropertyImplDecl>>;
2475
2476 propimpl_range property_impls() const {
2477 return propimpl_range(propimpl_begin(), propimpl_end());
2478 }
2479
2480 propimpl_iterator propimpl_begin() const {
2481 return propimpl_iterator(decls_begin());
2482 }
2483
2484 propimpl_iterator propimpl_end() const {
2485 return propimpl_iterator(decls_end());
2486 }
2487
2488 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2489
2490 static bool classofKind(Kind K) {
2491 return K >= firstObjCImpl && K <= lastObjCImpl;
2492 }
2493};
2494
2495/// ObjCCategoryImplDecl - An object of this class encapsulates a category
2496/// \@implementation declaration. If a category class has declaration of a
2497/// property, its implementation must be specified in the category's
2498/// \@implementation declaration. Example:
2499/// \@interface I \@end
2500/// \@interface I(CATEGORY)
2501/// \@property int p1, d1;
2502/// \@end
2503/// \@implementation I(CATEGORY)
2504/// \@dynamic p1,d1;
2505/// \@end
2506///
2507/// ObjCCategoryImplDecl
2508class ObjCCategoryImplDecl : public ObjCImplDecl {
2509 // Category name location
2510 SourceLocation CategoryNameLoc;
2511
2512 ObjCCategoryImplDecl(DeclContext *DC, IdentifierInfo *Id,
2513 ObjCInterfaceDecl *classInterface,
2514 SourceLocation nameLoc, SourceLocation atStartLoc,
2515 SourceLocation CategoryNameLoc)
2516 : ObjCImplDecl(ObjCCategoryImpl, DC, classInterface, Id,
2517 nameLoc, atStartLoc),
2518 CategoryNameLoc(CategoryNameLoc) {}
2519
2520 void anchor() override;
2521
2522public:
2523 friend class ASTDeclReader;
2524 friend class ASTDeclWriter;
2525
2526 static ObjCCategoryImplDecl *Create(ASTContext &C, DeclContext *DC,
2527 IdentifierInfo *Id,
2528 ObjCInterfaceDecl *classInterface,
2529 SourceLocation nameLoc,
2530 SourceLocation atStartLoc,
2531 SourceLocation CategoryNameLoc);
2532 static ObjCCategoryImplDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2533
2534 ObjCCategoryDecl *getCategoryDecl() const;
2535
2536 SourceLocation getCategoryNameLoc() const { return CategoryNameLoc; }
2537
2538 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2539 static bool classofKind(Kind K) { return K == ObjCCategoryImpl;}
2540};
2541
2542raw_ostream &operator<<(raw_ostream &OS, const ObjCCategoryImplDecl &CID);
2543
2544/// ObjCImplementationDecl - Represents a class definition - this is where
2545/// method definitions are specified. For example:
2546///
2547/// @code
2548/// \@implementation MyClass
2549/// - (void)myMethod { /* do something */ }
2550/// \@end
2551/// @endcode
2552///
2553/// In a non-fragile runtime, instance variables can appear in the class
2554/// interface, class extensions (nameless categories), and in the implementation
2555/// itself, as well as being synthesized as backing storage for properties.
2556///
2557/// In a fragile runtime, instance variables are specified in the class
2558/// interface, \em not in the implementation. Nevertheless (for legacy reasons),
2559/// we allow instance variables to be specified in the implementation. When
2560/// specified, they need to be \em identical to the interface.
2561class ObjCImplementationDecl : public ObjCImplDecl {
2562 /// Implementation Class's super class.
2563 ObjCInterfaceDecl *SuperClass;
2564 SourceLocation SuperLoc;
2565
2566 /// \@implementation may have private ivars.
2567 SourceLocation IvarLBraceLoc;
2568 SourceLocation IvarRBraceLoc;
2569
2570 /// Support for ivar initialization.
2571 /// The arguments used to initialize the ivars
2572 LazyCXXCtorInitializersPtr IvarInitializers;
2573 unsigned NumIvarInitializers = 0;
2574
2575 /// Do the ivars of this class require initialization other than
2576 /// zero-initialization?
2577 bool HasNonZeroConstructors : 1;
2578
2579 /// Do the ivars of this class require non-trivial destruction?
2580 bool HasDestructors : 1;
2581
2582 ObjCImplementationDecl(DeclContext *DC,
2583 ObjCInterfaceDecl *classInterface,
2584 ObjCInterfaceDecl *superDecl,
2585 SourceLocation nameLoc, SourceLocation atStartLoc,
2586 SourceLocation superLoc = SourceLocation(),
2587 SourceLocation IvarLBraceLoc=SourceLocation(),
2588 SourceLocation IvarRBraceLoc=SourceLocation())
2589 : ObjCImplDecl(ObjCImplementation, DC, classInterface,
2590 classInterface ? classInterface->getIdentifier()
2591 : nullptr,
2592 nameLoc, atStartLoc),
2593 SuperClass(superDecl), SuperLoc(superLoc),
2594 IvarLBraceLoc(IvarLBraceLoc), IvarRBraceLoc(IvarRBraceLoc),
2595 HasNonZeroConstructors(false), HasDestructors(false) {}
2596
2597 void anchor() override;
2598
2599public:
2600 friend class ASTDeclReader;
2601 friend class ASTDeclWriter;
2602
2603 static ObjCImplementationDecl *Create(ASTContext &C, DeclContext *DC,
2604 ObjCInterfaceDecl *classInterface,
2605 ObjCInterfaceDecl *superDecl,
2606 SourceLocation nameLoc,
2607 SourceLocation atStartLoc,
2608 SourceLocation superLoc = SourceLocation(),
2609 SourceLocation IvarLBraceLoc=SourceLocation(),
2610 SourceLocation IvarRBraceLoc=SourceLocation());
2611
2612 static ObjCImplementationDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2613
2614 /// init_iterator - Iterates through the ivar initializer list.
2615 using init_iterator = CXXCtorInitializer **;
2616
2617 /// init_const_iterator - Iterates through the ivar initializer list.
2618 using init_const_iterator = CXXCtorInitializer * const *;
2619
2620 using init_range = llvm::iterator_range<init_iterator>;
2621 using init_const_range = llvm::iterator_range<init_const_iterator>;
2622
2623 init_range inits() { return init_range(init_begin(), init_end()); }
2624
2625 init_const_range inits() const {
2626 return init_const_range(init_begin(), init_end());
2627 }
2628
2629 /// init_begin() - Retrieve an iterator to the first initializer.
2630 init_iterator init_begin() {
2631 const auto *ConstThis = this;
2632 return const_cast<init_iterator>(ConstThis->init_begin());
2633 }
2634
2635 /// begin() - Retrieve an iterator to the first initializer.
2636 init_const_iterator init_begin() const;
2637
2638 /// init_end() - Retrieve an iterator past the last initializer.
2639 init_iterator init_end() {
2640 return init_begin() + NumIvarInitializers;
2641 }
2642
2643 /// end() - Retrieve an iterator past the last initializer.
2644 init_const_iterator init_end() const {
2645 return init_begin() + NumIvarInitializers;
2646 }
2647
2648 /// getNumArgs - Number of ivars which must be initialized.
2649 unsigned getNumIvarInitializers() const {
2650 return NumIvarInitializers;
2651 }
2652
2653 void setNumIvarInitializers(unsigned numNumIvarInitializers) {
2654 NumIvarInitializers = numNumIvarInitializers;
2655 }
2656
2657 void setIvarInitializers(ASTContext &C,
2658 CXXCtorInitializer ** initializers,
2659 unsigned numInitializers);
2660
2661 /// Do any of the ivars of this class (not counting its base classes)
2662 /// require construction other than zero-initialization?
2663 bool hasNonZeroConstructors() const { return HasNonZeroConstructors; }
2664 void setHasNonZeroConstructors(bool val) { HasNonZeroConstructors = val; }
2665
2666 /// Do any of the ivars of this class (not counting its base classes)
2667 /// require non-trivial destruction?
2668 bool hasDestructors() const { return HasDestructors; }
2669 void setHasDestructors(bool val) { HasDestructors = val; }
2670
2671 /// getIdentifier - Get the identifier that names the class
2672 /// interface associated with this implementation.
2673 IdentifierInfo *getIdentifier() const {
2674 return getClassInterface()->getIdentifier();
2675 }
2676
2677 /// getName - Get the name of identifier for the class interface associated
2678 /// with this implementation as a StringRef.
2679 //
2680 // FIXME: This is a bad API, we are hiding NamedDecl::getName with a different
2681 // meaning.
2682 StringRef getName() const {
2683 assert(getIdentifier() && "Name is not a simple identifier")((getIdentifier() && "Name is not a simple identifier"
) ? static_cast<void> (0) : __assert_fail ("getIdentifier() && \"Name is not a simple identifier\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclObjC.h"
, 2683, __PRETTY_FUNCTION__))
;
2684 return getIdentifier()->getName();
2685 }
2686
2687 /// Get the name of the class associated with this interface.
2688 //
2689 // FIXME: Move to StringRef API.
2690 std::string getNameAsString() const {
2691 return getName();
2692 }
2693
2694 /// Produce a name to be used for class's metadata. It comes either via
2695 /// class's objc_runtime_name attribute or class name.
2696 StringRef getObjCRuntimeNameAsString() const;
2697
2698 const ObjCInterfaceDecl *getSuperClass() const { return SuperClass; }
2699 ObjCInterfaceDecl *getSuperClass() { return SuperClass; }
2700 SourceLocation getSuperClassLoc() const { return SuperLoc; }
2701
2702 void setSuperClass(ObjCInterfaceDecl * superCls) { SuperClass = superCls; }
2703
2704 void setIvarLBraceLoc(SourceLocation Loc) { IvarLBraceLoc = Loc; }
2705 SourceLocation getIvarLBraceLoc() const { return IvarLBraceLoc; }
2706 void setIvarRBraceLoc(SourceLocation Loc) { IvarRBraceLoc = Loc; }
2707 SourceLocation getIvarRBraceLoc() const { return IvarRBraceLoc; }
2708
2709 using ivar_iterator = specific_decl_iterator<ObjCIvarDecl>;
2710 using ivar_range = llvm::iterator_range<specific_decl_iterator<ObjCIvarDecl>>;
2711
2712 ivar_range ivars() const { return ivar_range(ivar_begin(), ivar_end()); }
2713
2714 ivar_iterator ivar_begin() const {
2715 return ivar_iterator(decls_begin());
2716 }
2717
2718 ivar_iterator ivar_end() const {
2719 return ivar_iterator(decls_end());
2720 }
2721
2722 unsigned ivar_size() const {
2723 return std::distance(ivar_begin(), ivar_end());
2724 }
2725
2726 bool ivar_empty() const {
2727 return ivar_begin() == ivar_end();
28
Calling 'operator=='
34
Returning from 'operator=='
35
Returning zero, which participates in a condition later
2728 }
2729
2730 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2731 static bool classofKind(Kind K) { return K == ObjCImplementation; }
2732};
2733
2734raw_ostream &operator<<(raw_ostream &OS, const ObjCImplementationDecl &ID);
2735
2736/// ObjCCompatibleAliasDecl - Represents alias of a class. This alias is
2737/// declared as \@compatibility_alias alias class.
2738class ObjCCompatibleAliasDecl : public NamedDecl {
2739 /// Class that this is an alias of.
2740 ObjCInterfaceDecl *AliasedClass;
2741
2742 ObjCCompatibleAliasDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2743 ObjCInterfaceDecl* aliasedClass)
2744 : NamedDecl(ObjCCompatibleAlias, DC, L, Id), AliasedClass(aliasedClass) {}
2745
2746 void anchor() override;
2747
2748public:
2749 static ObjCCompatibleAliasDecl *Create(ASTContext &C, DeclContext *DC,
2750 SourceLocation L, IdentifierInfo *Id,
2751 ObjCInterfaceDecl* aliasedClass);
2752
2753 static ObjCCompatibleAliasDecl *CreateDeserialized(ASTContext &C,
2754 unsigned ID);
2755
2756 const ObjCInterfaceDecl *getClassInterface() const { return AliasedClass; }
2757 ObjCInterfaceDecl *getClassInterface() { return AliasedClass; }
2758 void setClassInterface(ObjCInterfaceDecl *D) { AliasedClass = D; }
2759
2760 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2761 static bool classofKind(Kind K) { return K == ObjCCompatibleAlias; }
2762};
2763
2764/// ObjCPropertyImplDecl - Represents implementation declaration of a property
2765/// in a class or category implementation block. For example:
2766/// \@synthesize prop1 = ivar1;
2767///
2768class ObjCPropertyImplDecl : public Decl {
2769public:
2770 enum Kind {
2771 Synthesize,
2772 Dynamic
2773 };
2774
2775private:
2776 SourceLocation AtLoc; // location of \@synthesize or \@dynamic
2777
2778 /// For \@synthesize, the location of the ivar, if it was written in
2779 /// the source code.
2780 ///
2781 /// \code
2782 /// \@synthesize int a = b
2783 /// \endcode
2784 SourceLocation IvarLoc;
2785
2786 /// Property declaration being implemented
2787 ObjCPropertyDecl *PropertyDecl;
2788
2789 /// Null for \@dynamic. Required for \@synthesize.
2790 ObjCIvarDecl *PropertyIvarDecl;
2791
2792 /// The getter's definition, which has an empty body if synthesized.
2793 ObjCMethodDecl *GetterMethodDecl = nullptr;
2794 /// The getter's definition, which has an empty body if synthesized.
2795 ObjCMethodDecl *SetterMethodDecl = nullptr;
2796
2797 /// Null for \@dynamic. Non-null if property must be copy-constructed in
2798 /// getter.
2799 Expr *GetterCXXConstructor = nullptr;
2800
2801 /// Null for \@dynamic. Non-null if property has assignment operator to call
2802 /// in Setter synthesis.
2803 Expr *SetterCXXAssignment = nullptr;
2804
2805 ObjCPropertyImplDecl(DeclContext *DC, SourceLocation atLoc, SourceLocation L,
2806 ObjCPropertyDecl *property,
2807 Kind PK,
2808 ObjCIvarDecl *ivarDecl,
2809 SourceLocation ivarLoc)
2810 : Decl(ObjCPropertyImpl, DC, L), AtLoc(atLoc),
2811 IvarLoc(ivarLoc), PropertyDecl(property), PropertyIvarDecl(ivarDecl) {
2812 assert(PK == Dynamic || PropertyIvarDecl)((PK == Dynamic || PropertyIvarDecl) ? static_cast<void>
(0) : __assert_fail ("PK == Dynamic || PropertyIvarDecl", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclObjC.h"
, 2812, __PRETTY_FUNCTION__))
;
2813 }
2814
2815public:
2816 friend class ASTDeclReader;
2817
2818 static ObjCPropertyImplDecl *Create(ASTContext &C, DeclContext *DC,
2819 SourceLocation atLoc, SourceLocation L,
2820 ObjCPropertyDecl *property,
2821 Kind PK,
2822 ObjCIvarDecl *ivarDecl,
2823 SourceLocation ivarLoc);
2824
2825 static ObjCPropertyImplDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2826
2827 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2828
2829 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return AtLoc; }
2830 void setAtLoc(SourceLocation Loc) { AtLoc = Loc; }
2831
2832 ObjCPropertyDecl *getPropertyDecl() const {
2833 return PropertyDecl;
2834 }
2835 void setPropertyDecl(ObjCPropertyDecl *Prop) { PropertyDecl = Prop; }
2836
2837 Kind getPropertyImplementation() const {
2838 return PropertyIvarDecl ? Synthesize : Dynamic;
2839 }
2840
2841 ObjCIvarDecl *getPropertyIvarDecl() const {
2842 return PropertyIvarDecl;
2843 }
2844 SourceLocation getPropertyIvarDeclLoc() const { return IvarLoc; }
2845
2846 void setPropertyIvarDecl(ObjCIvarDecl *Ivar,
2847 SourceLocation IvarLoc) {
2848 PropertyIvarDecl = Ivar;
2849 this->IvarLoc = IvarLoc;
2850 }
2851
2852 /// For \@synthesize, returns true if an ivar name was explicitly
2853 /// specified.
2854 ///
2855 /// \code
2856 /// \@synthesize int a = b; // true
2857 /// \@synthesize int a; // false
2858 /// \endcode
2859 bool isIvarNameSpecified() const {
2860 return IvarLoc.isValid() && IvarLoc != getLocation();
2861 }
2862
2863 ObjCMethodDecl *getGetterMethodDecl() const { return GetterMethodDecl; }
2864 void setGetterMethodDecl(ObjCMethodDecl *MD) { GetterMethodDecl = MD; }
2865
2866 ObjCMethodDecl *getSetterMethodDecl() const { return SetterMethodDecl; }
2867 void setSetterMethodDecl(ObjCMethodDecl *MD) { SetterMethodDecl = MD; }
2868
2869 Expr *getGetterCXXConstructor() const {
2870 return GetterCXXConstructor;
2871 }
2872
2873 void setGetterCXXConstructor(Expr *getterCXXConstructor) {
2874 GetterCXXConstructor = getterCXXConstructor;
2875 }
2876
2877 Expr *getSetterCXXAssignment() const {
2878 return SetterCXXAssignment;
2879 }
2880
2881 void setSetterCXXAssignment(Expr *setterCXXAssignment) {
2882 SetterCXXAssignment = setterCXXAssignment;
2883 }
2884
2885 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2886 static bool classofKind(Decl::Kind K) { return K == ObjCPropertyImpl; }
2887};
2888
2889template<bool (*Filter)(ObjCCategoryDecl *)>
2890void
2891ObjCInterfaceDecl::filtered_category_iterator<Filter>::
2892findAcceptableCategory() {
2893 while (Current && !Filter(Current))
2894 Current = Current->getNextClassCategoryRaw();
2895}
2896
2897template<bool (*Filter)(ObjCCategoryDecl *)>
2898inline ObjCInterfaceDecl::filtered_category_iterator<Filter> &
2899ObjCInterfaceDecl::filtered_category_iterator<Filter>::operator++() {
2900 Current = Current->getNextClassCategoryRaw();
2901 findAcceptableCategory();
2902 return *this;
2903}
2904
2905inline bool ObjCInterfaceDecl::isVisibleCategory(ObjCCategoryDecl *Cat) {
2906 return !Cat->isHidden();
2907}
2908
2909inline bool ObjCInterfaceDecl::isVisibleExtension(ObjCCategoryDecl *Cat) {
2910 return Cat->IsClassExtension() && !Cat->isHidden();
2911}
2912
2913inline bool ObjCInterfaceDecl::isKnownExtension(ObjCCategoryDecl *Cat) {
2914 return Cat->IsClassExtension();
2915}
2916
2917} // namespace clang
2918
2919#endif // LLVM_CLANG_AST_DECLOBJC_H

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclBase.h

1//===- DeclBase.h - Base Classes for representing declarations --*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the Decl and DeclContext interfaces.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_DECLBASE_H
14#define LLVM_CLANG_AST_DECLBASE_H
15
16#include "clang/AST/ASTDumperUtils.h"
17#include "clang/AST/AttrIterator.h"
18#include "clang/AST/DeclarationName.h"
19#include "clang/Basic/IdentifierTable.h"
20#include "clang/Basic/LLVM.h"
21#include "clang/Basic/SourceLocation.h"
22#include "clang/Basic/Specifiers.h"
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/PointerIntPair.h"
25#include "llvm/ADT/PointerUnion.h"
26#include "llvm/ADT/iterator.h"
27#include "llvm/ADT/iterator_range.h"
28#include "llvm/Support/Casting.h"
29#include "llvm/Support/Compiler.h"
30#include "llvm/Support/PrettyStackTrace.h"
31#include "llvm/Support/VersionTuple.h"
32#include <algorithm>
33#include <cassert>
34#include <cstddef>
35#include <iterator>
36#include <string>
37#include <type_traits>
38#include <utility>
39
40namespace clang {
41
42class ASTContext;
43class ASTMutationListener;
44class Attr;
45class BlockDecl;
46class DeclContext;
47class ExternalSourceSymbolAttr;
48class FunctionDecl;
49class FunctionType;
50class IdentifierInfo;
51enum Linkage : unsigned char;
52class LinkageSpecDecl;
53class Module;
54class NamedDecl;
55class ObjCCategoryDecl;
56class ObjCCategoryImplDecl;
57class ObjCContainerDecl;
58class ObjCImplDecl;
59class ObjCImplementationDecl;
60class ObjCInterfaceDecl;
61class ObjCMethodDecl;
62class ObjCProtocolDecl;
63struct PrintingPolicy;
64class RecordDecl;
65class SourceManager;
66class Stmt;
67class StoredDeclsMap;
68class TemplateDecl;
69class TranslationUnitDecl;
70class UsingDirectiveDecl;
71
72/// Captures the result of checking the availability of a
73/// declaration.
74enum AvailabilityResult {
75 AR_Available = 0,
76 AR_NotYetIntroduced,
77 AR_Deprecated,
78 AR_Unavailable
79};
80
81/// Decl - This represents one declaration (or definition), e.g. a variable,
82/// typedef, function, struct, etc.
83///
84/// Note: There are objects tacked on before the *beginning* of Decl
85/// (and its subclasses) in its Decl::operator new(). Proper alignment
86/// of all subclasses (not requiring more than the alignment of Decl) is
87/// asserted in DeclBase.cpp.
88class alignas(8) Decl {
89public:
90 /// Lists the kind of concrete classes of Decl.
91 enum Kind {
92#define DECL(DERIVED, BASE) DERIVED,
93#define ABSTRACT_DECL(DECL)
94#define DECL_RANGE(BASE, START, END) \
95 first##BASE = START, last##BASE = END,
96#define LAST_DECL_RANGE(BASE, START, END) \
97 first##BASE = START, last##BASE = END
98#include "clang/AST/DeclNodes.inc"
99 };
100
101 /// A placeholder type used to construct an empty shell of a
102 /// decl-derived type that will be filled in later (e.g., by some
103 /// deserialization method).
104 struct EmptyShell {};
105
106 /// IdentifierNamespace - The different namespaces in which
107 /// declarations may appear. According to C99 6.2.3, there are
108 /// four namespaces, labels, tags, members and ordinary
109 /// identifiers. C++ describes lookup completely differently:
110 /// certain lookups merely "ignore" certain kinds of declarations,
111 /// usually based on whether the declaration is of a type, etc.
112 ///
113 /// These are meant as bitmasks, so that searches in
114 /// C++ can look into the "tag" namespace during ordinary lookup.
115 ///
116 /// Decl currently provides 15 bits of IDNS bits.
117 enum IdentifierNamespace {
118 /// Labels, declared with 'x:' and referenced with 'goto x'.
119 IDNS_Label = 0x0001,
120
121 /// Tags, declared with 'struct foo;' and referenced with
122 /// 'struct foo'. All tags are also types. This is what
123 /// elaborated-type-specifiers look for in C.
124 /// This also contains names that conflict with tags in the
125 /// same scope but that are otherwise ordinary names (non-type
126 /// template parameters and indirect field declarations).
127 IDNS_Tag = 0x0002,
128
129 /// Types, declared with 'struct foo', typedefs, etc.
130 /// This is what elaborated-type-specifiers look for in C++,
131 /// but note that it's ill-formed to find a non-tag.
132 IDNS_Type = 0x0004,
133
134 /// Members, declared with object declarations within tag
135 /// definitions. In C, these can only be found by "qualified"
136 /// lookup in member expressions. In C++, they're found by
137 /// normal lookup.
138 IDNS_Member = 0x0008,
139
140 /// Namespaces, declared with 'namespace foo {}'.
141 /// Lookup for nested-name-specifiers find these.
142 IDNS_Namespace = 0x0010,
143
144 /// Ordinary names. In C, everything that's not a label, tag,
145 /// member, or function-local extern ends up here.
146 IDNS_Ordinary = 0x0020,
147
148 /// Objective C \@protocol.
149 IDNS_ObjCProtocol = 0x0040,
150
151 /// This declaration is a friend function. A friend function
152 /// declaration is always in this namespace but may also be in
153 /// IDNS_Ordinary if it was previously declared.
154 IDNS_OrdinaryFriend = 0x0080,
155
156 /// This declaration is a friend class. A friend class
157 /// declaration is always in this namespace but may also be in
158 /// IDNS_Tag|IDNS_Type if it was previously declared.
159 IDNS_TagFriend = 0x0100,
160
161 /// This declaration is a using declaration. A using declaration
162 /// *introduces* a number of other declarations into the current
163 /// scope, and those declarations use the IDNS of their targets,
164 /// but the actual using declarations go in this namespace.
165 IDNS_Using = 0x0200,
166
167 /// This declaration is a C++ operator declared in a non-class
168 /// context. All such operators are also in IDNS_Ordinary.
169 /// C++ lexical operator lookup looks for these.
170 IDNS_NonMemberOperator = 0x0400,
171
172 /// This declaration is a function-local extern declaration of a
173 /// variable or function. This may also be IDNS_Ordinary if it
174 /// has been declared outside any function. These act mostly like
175 /// invisible friend declarations, but are also visible to unqualified
176 /// lookup within the scope of the declaring function.
177 IDNS_LocalExtern = 0x0800,
178
179 /// This declaration is an OpenMP user defined reduction construction.
180 IDNS_OMPReduction = 0x1000,
181
182 /// This declaration is an OpenMP user defined mapper.
183 IDNS_OMPMapper = 0x2000,
184 };
185
186 /// ObjCDeclQualifier - 'Qualifiers' written next to the return and
187 /// parameter types in method declarations. Other than remembering
188 /// them and mangling them into the method's signature string, these
189 /// are ignored by the compiler; they are consumed by certain
190 /// remote-messaging frameworks.
191 ///
192 /// in, inout, and out are mutually exclusive and apply only to
193 /// method parameters. bycopy and byref are mutually exclusive and
194 /// apply only to method parameters (?). oneway applies only to
195 /// results. All of these expect their corresponding parameter to
196 /// have a particular type. None of this is currently enforced by
197 /// clang.
198 ///
199 /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier.
200 enum ObjCDeclQualifier {
201 OBJC_TQ_None = 0x0,
202 OBJC_TQ_In = 0x1,
203 OBJC_TQ_Inout = 0x2,
204 OBJC_TQ_Out = 0x4,
205 OBJC_TQ_Bycopy = 0x8,
206 OBJC_TQ_Byref = 0x10,
207 OBJC_TQ_Oneway = 0x20,
208
209 /// The nullability qualifier is set when the nullability of the
210 /// result or parameter was expressed via a context-sensitive
211 /// keyword.
212 OBJC_TQ_CSNullability = 0x40
213 };
214
215 /// The kind of ownership a declaration has, for visibility purposes.
216 /// This enumeration is designed such that higher values represent higher
217 /// levels of name hiding.
218 enum class ModuleOwnershipKind : unsigned {
219 /// This declaration is not owned by a module.
220 Unowned,
221
222 /// This declaration has an owning module, but is globally visible
223 /// (typically because its owning module is visible and we know that
224 /// modules cannot later become hidden in this compilation).
225 /// After serialization and deserialization, this will be converted
226 /// to VisibleWhenImported.
227 Visible,
228
229 /// This declaration has an owning module, and is visible when that
230 /// module is imported.
231 VisibleWhenImported,
232
233 /// This declaration has an owning module, but is only visible to
234 /// lookups that occur within that module.
235 ModulePrivate
236 };
237
238protected:
239 /// The next declaration within the same lexical
240 /// DeclContext. These pointers form the linked list that is
241 /// traversed via DeclContext's decls_begin()/decls_end().
242 ///
243 /// The extra two bits are used for the ModuleOwnershipKind.
244 llvm::PointerIntPair<Decl *, 2, ModuleOwnershipKind> NextInContextAndBits;
245
246private:
247 friend class DeclContext;
248
249 struct MultipleDC {
250 DeclContext *SemanticDC;
251 DeclContext *LexicalDC;
252 };
253
254 /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
255 /// For declarations that don't contain C++ scope specifiers, it contains
256 /// the DeclContext where the Decl was declared.
257 /// For declarations with C++ scope specifiers, it contains a MultipleDC*
258 /// with the context where it semantically belongs (SemanticDC) and the
259 /// context where it was lexically declared (LexicalDC).
260 /// e.g.:
261 ///
262 /// namespace A {
263 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
264 /// }
265 /// void A::f(); // SemanticDC == namespace 'A'
266 /// // LexicalDC == global namespace
267 llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx;
268
269 bool isInSemaDC() const { return DeclCtx.is<DeclContext*>(); }
270 bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); }
271
272 MultipleDC *getMultipleDC() const {
273 return DeclCtx.get<MultipleDC*>();
274 }
275
276 DeclContext *getSemanticDC() const {
277 return DeclCtx.get<DeclContext*>();
278 }
279
280 /// Loc - The location of this decl.
281 SourceLocation Loc;
282
283 /// DeclKind - This indicates which class this is.
284 unsigned DeclKind : 7;
285
286 /// InvalidDecl - This indicates a semantic error occurred.
287 unsigned InvalidDecl : 1;
288
289 /// HasAttrs - This indicates whether the decl has attributes or not.
290 unsigned HasAttrs : 1;
291
292 /// Implicit - Whether this declaration was implicitly generated by
293 /// the implementation rather than explicitly written by the user.
294 unsigned Implicit : 1;
295
296 /// Whether this declaration was "used", meaning that a definition is
297 /// required.
298 unsigned Used : 1;
299
300 /// Whether this declaration was "referenced".
301 /// The difference with 'Used' is whether the reference appears in a
302 /// evaluated context or not, e.g. functions used in uninstantiated templates
303 /// are regarded as "referenced" but not "used".
304 unsigned Referenced : 1;
305
306 /// Whether this declaration is a top-level declaration (function,
307 /// global variable, etc.) that is lexically inside an objc container
308 /// definition.
309 unsigned TopLevelDeclInObjCContainer : 1;
310
311 /// Whether statistic collection is enabled.
312 static bool StatisticsEnabled;
313
314protected:
315 friend class ASTDeclReader;
316 friend class ASTDeclWriter;
317 friend class ASTNodeImporter;
318 friend class ASTReader;
319 friend class CXXClassMemberWrapper;
320 friend class LinkageComputer;
321 template<typename decl_type> friend class Redeclarable;
322
323 /// Access - Used by C++ decls for the access specifier.
324 // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
325 unsigned Access : 2;
326
327 /// Whether this declaration was loaded from an AST file.
328 unsigned FromASTFile : 1;
329
330 /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
331 unsigned IdentifierNamespace : 14;
332
333 /// If 0, we have not computed the linkage of this declaration.
334 /// Otherwise, it is the linkage + 1.
335 mutable unsigned CacheValidAndLinkage : 3;
336
337 /// Allocate memory for a deserialized declaration.
338 ///
339 /// This routine must be used to allocate memory for any declaration that is
340 /// deserialized from a module file.
341 ///
342 /// \param Size The size of the allocated object.
343 /// \param Ctx The context in which we will allocate memory.
344 /// \param ID The global ID of the deserialized declaration.
345 /// \param Extra The amount of extra space to allocate after the object.
346 void *operator new(std::size_t Size, const ASTContext &Ctx, unsigned ID,
347 std::size_t Extra = 0);
348
349 /// Allocate memory for a non-deserialized declaration.
350 void *operator new(std::size_t Size, const ASTContext &Ctx,
351 DeclContext *Parent, std::size_t Extra = 0);
352
353private:
354 bool AccessDeclContextSanity() const;
355
356 /// Get the module ownership kind to use for a local lexical child of \p DC,
357 /// which may be either a local or (rarely) an imported declaration.
358 static ModuleOwnershipKind getModuleOwnershipKindForChildOf(DeclContext *DC) {
359 if (DC) {
360 auto *D = cast<Decl>(DC);
361 auto MOK = D->getModuleOwnershipKind();
362 if (MOK != ModuleOwnershipKind::Unowned &&
363 (!D->isFromASTFile() || D->hasLocalOwningModuleStorage()))
364 return MOK;
365 // If D is not local and we have no local module storage, then we don't
366 // need to track module ownership at all.
367 }
368 return ModuleOwnershipKind::Unowned;
369 }
370
371public:
372 Decl() = delete;
373 Decl(const Decl&) = delete;
374 Decl(Decl &&) = delete;
375 Decl &operator=(const Decl&) = delete;
376 Decl &operator=(Decl&&) = delete;
377
378protected:
379 Decl(Kind DK, DeclContext *DC, SourceLocation L)
380 : NextInContextAndBits(nullptr, getModuleOwnershipKindForChildOf(DC)),
381 DeclCtx(DC), Loc(L), DeclKind(DK), InvalidDecl(false), HasAttrs(false),
382 Implicit(false), Used(false), Referenced(false),
383 TopLevelDeclInObjCContainer(false), Access(AS_none), FromASTFile(0),
384 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
385 CacheValidAndLinkage(0) {
386 if (StatisticsEnabled) add(DK);
387 }
388
389 Decl(Kind DK, EmptyShell Empty)
390 : DeclKind(DK), InvalidDecl(false), HasAttrs(false), Implicit(false),
391 Used(false), Referenced(false), TopLevelDeclInObjCContainer(false),
392 Access(AS_none), FromASTFile(0),
393 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
394 CacheValidAndLinkage(0) {
395 if (StatisticsEnabled) add(DK);
396 }
397
398 virtual ~Decl();
399
400 /// Update a potentially out-of-date declaration.
401 void updateOutOfDate(IdentifierInfo &II) const;
402
403 Linkage getCachedLinkage() const {
404 return Linkage(CacheValidAndLinkage - 1);
405 }
406
407 void setCachedLinkage(Linkage L) const {
408 CacheValidAndLinkage = L + 1;
409 }
410
411 bool hasCachedLinkage() const {
412 return CacheValidAndLinkage;
413 }
414
415public:
416 /// Source range that this declaration covers.
417 virtual SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
418 return SourceRange(getLocation(), getLocation());
419 }
420
421 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
422 return getSourceRange().getBegin();
423 }
424
425 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
426 return getSourceRange().getEnd();
427 }
428
429 SourceLocation getLocation() const { return Loc; }
430 void setLocation(SourceLocation L) { Loc = L; }
431
432 Kind getKind() const { return static_cast<Kind>(DeclKind); }
433 const char *getDeclKindName() const;
434
435 Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); }
436 const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();}
437
438 DeclContext *getDeclContext() {
439 if (isInSemaDC())
440 return getSemanticDC();
441 return getMultipleDC()->SemanticDC;
442 }
443 const DeclContext *getDeclContext() const {
444 return const_cast<Decl*>(this)->getDeclContext();
445 }
446
447 /// Find the innermost non-closure ancestor of this declaration,
448 /// walking up through blocks, lambdas, etc. If that ancestor is
449 /// not a code context (!isFunctionOrMethod()), returns null.
450 ///
451 /// A declaration may be its own non-closure context.
452 Decl *getNonClosureContext();
453 const Decl *getNonClosureContext() const {
454 return const_cast<Decl*>(this)->getNonClosureContext();
455 }
456
457 TranslationUnitDecl *getTranslationUnitDecl();
458 const TranslationUnitDecl *getTranslationUnitDecl() const {
459 return const_cast<Decl*>(this)->getTranslationUnitDecl();
460 }
461
462 bool isInAnonymousNamespace() const;
463
464 bool isInStdNamespace() const;
465
466 ASTContext &getASTContext() const LLVM_READONLY__attribute__((__pure__));
467
468 void setAccess(AccessSpecifier AS) {
469 Access = AS;
470 assert(AccessDeclContextSanity())((AccessDeclContextSanity()) ? static_cast<void> (0) : __assert_fail
("AccessDeclContextSanity()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclBase.h"
, 470, __PRETTY_FUNCTION__))
;
471 }
472
473 AccessSpecifier getAccess() const {
474 assert(AccessDeclContextSanity())((AccessDeclContextSanity()) ? static_cast<void> (0) : __assert_fail
("AccessDeclContextSanity()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclBase.h"
, 474, __PRETTY_FUNCTION__))
;
475 return AccessSpecifier(Access);
476 }
477
478 /// Retrieve the access specifier for this declaration, even though
479 /// it may not yet have been properly set.
480 AccessSpecifier getAccessUnsafe() const {
481 return AccessSpecifier(Access);
482 }
483
484 bool hasAttrs() const { return HasAttrs; }
485
486 void setAttrs(const AttrVec& Attrs) {
487 return setAttrsImpl(Attrs, getASTContext());
488 }
489
490 AttrVec &getAttrs() {
491 return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs());
492 }
493
494 const AttrVec &getAttrs() const;
495 void dropAttrs();
496 void addAttr(Attr *A);
497
498 using attr_iterator = AttrVec::const_iterator;
499 using attr_range = llvm::iterator_range<attr_iterator>;
500
501 attr_range attrs() const {
502 return attr_range(attr_begin(), attr_end());
503 }
504
505 attr_iterator attr_begin() const {
506 return hasAttrs() ? getAttrs().begin() : nullptr;
507 }
508 attr_iterator attr_end() const {
509 return hasAttrs() ? getAttrs().end() : nullptr;
510 }
511
512 template <typename T>
513 void dropAttr() {
514 if (!HasAttrs) return;
515
516 AttrVec &Vec = getAttrs();
517 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), isa<T, Attr*>), Vec.end());
518
519 if (Vec.empty())
520 HasAttrs = false;
521 }
522
523 template <typename T>
524 llvm::iterator_range<specific_attr_iterator<T>> specific_attrs() const {
525 return llvm::make_range(specific_attr_begin<T>(), specific_attr_end<T>());
526 }
527
528 template <typename T>
529 specific_attr_iterator<T> specific_attr_begin() const {
530 return specific_attr_iterator<T>(attr_begin());
531 }
532
533 template <typename T>
534 specific_attr_iterator<T> specific_attr_end() const {
535 return specific_attr_iterator<T>(attr_end());
536 }
537
538 template<typename T> T *getAttr() const {
539 return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : nullptr;
540 }
541
542 template<typename T> bool hasAttr() const {
543 return hasAttrs() && hasSpecificAttr<T>(getAttrs());
544 }
545
546 /// getMaxAlignment - return the maximum alignment specified by attributes
547 /// on this decl, 0 if there are none.
548 unsigned getMaxAlignment() const;
549
550 /// setInvalidDecl - Indicates the Decl had a semantic error. This
551 /// allows for graceful error recovery.
552 void setInvalidDecl(bool Invalid = true);
553 bool isInvalidDecl() const { return (bool) InvalidDecl; }
554
555 /// isImplicit - Indicates whether the declaration was implicitly
556 /// generated by the implementation. If false, this declaration
557 /// was written explicitly in the source code.
558 bool isImplicit() const { return Implicit; }
559 void setImplicit(bool I = true) { Implicit = I; }
560
561 /// Whether *any* (re-)declaration of the entity was used, meaning that
562 /// a definition is required.
563 ///
564 /// \param CheckUsedAttr When true, also consider the "used" attribute
565 /// (in addition to the "used" bit set by \c setUsed()) when determining
566 /// whether the function is used.
567 bool isUsed(bool CheckUsedAttr = true) const;
568
569 /// Set whether the declaration is used, in the sense of odr-use.
570 ///
571 /// This should only be used immediately after creating a declaration.
572 /// It intentionally doesn't notify any listeners.
573 void setIsUsed() { getCanonicalDecl()->Used = true; }
574
575 /// Mark the declaration used, in the sense of odr-use.
576 ///
577 /// This notifies any mutation listeners in addition to setting a bit
578 /// indicating the declaration is used.
579 void markUsed(ASTContext &C);
580
581 /// Whether any declaration of this entity was referenced.
582 bool isReferenced() const;
583
584 /// Whether this declaration was referenced. This should not be relied
585 /// upon for anything other than debugging.
586 bool isThisDeclarationReferenced() const { return Referenced; }
587
588 void setReferenced(bool R = true) { Referenced = R; }
589
590 /// Whether this declaration is a top-level declaration (function,
591 /// global variable, etc.) that is lexically inside an objc container
592 /// definition.
593 bool isTopLevelDeclInObjCContainer() const {
594 return TopLevelDeclInObjCContainer;
595 }
596
597 void setTopLevelDeclInObjCContainer(bool V = true) {
598 TopLevelDeclInObjCContainer = V;
599 }
600
601 /// Looks on this and related declarations for an applicable
602 /// external source symbol attribute.
603 ExternalSourceSymbolAttr *getExternalSourceSymbolAttr() const;
604
605 /// Whether this declaration was marked as being private to the
606 /// module in which it was defined.
607 bool isModulePrivate() const {
608 return getModuleOwnershipKind() == ModuleOwnershipKind::ModulePrivate;
609 }
610
611 /// Return true if this declaration has an attribute which acts as
612 /// definition of the entity, such as 'alias' or 'ifunc'.
613 bool hasDefiningAttr() const;
614
615 /// Return this declaration's defining attribute if it has one.
616 const Attr *getDefiningAttr() const;
617
618protected:
619 /// Specify that this declaration was marked as being private
620 /// to the module in which it was defined.
621 void setModulePrivate() {
622 // The module-private specifier has no effect on unowned declarations.
623 // FIXME: We should track this in some way for source fidelity.
624 if (getModuleOwnershipKind() == ModuleOwnershipKind::Unowned)
625 return;
626 setModuleOwnershipKind(ModuleOwnershipKind::ModulePrivate);
627 }
628
629 /// Set the owning module ID.
630 void setOwningModuleID(unsigned ID) {
631 assert(isFromASTFile() && "Only works on a deserialized declaration")((isFromASTFile() && "Only works on a deserialized declaration"
) ? static_cast<void> (0) : __assert_fail ("isFromASTFile() && \"Only works on a deserialized declaration\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclBase.h"
, 631, __PRETTY_FUNCTION__))
;
632 *((unsigned*)this - 2) = ID;
633 }
634
635public:
636 /// Determine the availability of the given declaration.
637 ///
638 /// This routine will determine the most restrictive availability of
639 /// the given declaration (e.g., preferring 'unavailable' to
640 /// 'deprecated').
641 ///
642 /// \param Message If non-NULL and the result is not \c
643 /// AR_Available, will be set to a (possibly empty) message
644 /// describing why the declaration has not been introduced, is
645 /// deprecated, or is unavailable.
646 ///
647 /// \param EnclosingVersion The version to compare with. If empty, assume the
648 /// deployment target version.
649 ///
650 /// \param RealizedPlatform If non-NULL and the availability result is found
651 /// in an available attribute it will set to the platform which is written in
652 /// the available attribute.
653 AvailabilityResult
654 getAvailability(std::string *Message = nullptr,
655 VersionTuple EnclosingVersion = VersionTuple(),
656 StringRef *RealizedPlatform = nullptr) const;
657
658 /// Retrieve the version of the target platform in which this
659 /// declaration was introduced.
660 ///
661 /// \returns An empty version tuple if this declaration has no 'introduced'
662 /// availability attributes, or the version tuple that's specified in the
663 /// attribute otherwise.
664 VersionTuple getVersionIntroduced() const;
665
666 /// Determine whether this declaration is marked 'deprecated'.
667 ///
668 /// \param Message If non-NULL and the declaration is deprecated,
669 /// this will be set to the message describing why the declaration
670 /// was deprecated (which may be empty).
671 bool isDeprecated(std::string *Message = nullptr) const {
672 return getAvailability(Message) == AR_Deprecated;
673 }
674
675 /// Determine whether this declaration is marked 'unavailable'.
676 ///
677 /// \param Message If non-NULL and the declaration is unavailable,
678 /// this will be set to the message describing why the declaration
679 /// was made unavailable (which may be empty).
680 bool isUnavailable(std::string *Message = nullptr) const {
681 return getAvailability(Message) == AR_Unavailable;
682 }
683
684 /// Determine whether this is a weak-imported symbol.
685 ///
686 /// Weak-imported symbols are typically marked with the
687 /// 'weak_import' attribute, but may also be marked with an
688 /// 'availability' attribute where we're targing a platform prior to
689 /// the introduction of this feature.
690 bool isWeakImported() const;
691
692 /// Determines whether this symbol can be weak-imported,
693 /// e.g., whether it would be well-formed to add the weak_import
694 /// attribute.
695 ///
696 /// \param IsDefinition Set to \c true to indicate that this
697 /// declaration cannot be weak-imported because it has a definition.
698 bool canBeWeakImported(bool &IsDefinition) const;
699
700 /// Determine whether this declaration came from an AST file (such as
701 /// a precompiled header or module) rather than having been parsed.
702 bool isFromASTFile() const { return FromASTFile; }
703
704 /// Retrieve the global declaration ID associated with this
705 /// declaration, which specifies where this Decl was loaded from.
706 unsigned getGlobalID() const {
707 if (isFromASTFile())
708 return *((const unsigned*)this - 1);
709 return 0;
710 }
711
712 /// Retrieve the global ID of the module that owns this particular
713 /// declaration.
714 unsigned getOwningModuleID() const {
715 if (isFromASTFile())
716 return *((const unsigned*)this - 2);
717 return 0;
718 }
719
720private:
721 Module *getOwningModuleSlow() const;
722
723protected:
724 bool hasLocalOwningModuleStorage() const;
725
726public:
727 /// Get the imported owning module, if this decl is from an imported
728 /// (non-local) module.
729 Module *getImportedOwningModule() const {
730 if (!isFromASTFile() || !hasOwningModule())
731 return nullptr;
732
733 return getOwningModuleSlow();
734 }
735
736 /// Get the local owning module, if known. Returns nullptr if owner is
737 /// not yet known or declaration is not from a module.
738 Module *getLocalOwningModule() const {
739 if (isFromASTFile() || !hasOwningModule())
740 return nullptr;
741
742 assert(hasLocalOwningModuleStorage() &&((hasLocalOwningModuleStorage() && "owned local decl but no local module storage"
) ? static_cast<void> (0) : __assert_fail ("hasLocalOwningModuleStorage() && \"owned local decl but no local module storage\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclBase.h"
, 743, __PRETTY_FUNCTION__))
743 "owned local decl but no local module storage")((hasLocalOwningModuleStorage() && "owned local decl but no local module storage"
) ? static_cast<void> (0) : __assert_fail ("hasLocalOwningModuleStorage() && \"owned local decl but no local module storage\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclBase.h"
, 743, __PRETTY_FUNCTION__))
;
744 return reinterpret_cast<Module *const *>(this)[-1];
745 }
746 void setLocalOwningModule(Module *M) {
747 assert(!isFromASTFile() && hasOwningModule() &&((!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage
() && "should not have a cached owning module") ? static_cast
<void> (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclBase.h"
, 749, __PRETTY_FUNCTION__))
748 hasLocalOwningModuleStorage() &&((!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage
() && "should not have a cached owning module") ? static_cast
<void> (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclBase.h"
, 749, __PRETTY_FUNCTION__))
749 "should not have a cached owning module")((!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage
() && "should not have a cached owning module") ? static_cast
<void> (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclBase.h"
, 749, __PRETTY_FUNCTION__))
;
750 reinterpret_cast<Module **>(this)[-1] = M;
751 }
752
753 /// Is this declaration owned by some module?
754 bool hasOwningModule() const {
755 return getModuleOwnershipKind() != ModuleOwnershipKind::Unowned;
756 }
757
758 /// Get the module that owns this declaration (for visibility purposes).
759 Module *getOwningModule() const {
760 return isFromASTFile() ? getImportedOwningModule() : getLocalOwningModule();
761 }
762
763 /// Get the module that owns this declaration for linkage purposes.
764 /// There only ever is such a module under the C++ Modules TS.
765 ///
766 /// \param IgnoreLinkage Ignore the linkage of the entity; assume that
767 /// all declarations in a global module fragment are unowned.
768 Module *getOwningModuleForLinkage(bool IgnoreLinkage = false) const;
769
770 /// Determine whether this declaration might be hidden from name
771 /// lookup. Note that the declaration might be visible even if this returns
772 /// \c false, if the owning module is visible within the query context.
773 // FIXME: Rename this to make it clearer what it does.
774 bool isHidden() const {
775 return (int)getModuleOwnershipKind() > (int)ModuleOwnershipKind::Visible;
776 }
777
778 /// Set that this declaration is globally visible, even if it came from a
779 /// module that is not visible.
780 void setVisibleDespiteOwningModule() {
781 if (isHidden())
782 setModuleOwnershipKind(ModuleOwnershipKind::Visible);
783 }
784
785 /// Get the kind of module ownership for this declaration.
786 ModuleOwnershipKind getModuleOwnershipKind() const {
787 return NextInContextAndBits.getInt();
788 }
789
790 /// Set whether this declaration is hidden from name lookup.
791 void setModuleOwnershipKind(ModuleOwnershipKind MOK) {
792 assert(!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&
MOK != ModuleOwnershipKind::Unowned && !isFromASTFile
() && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration"
) ? static_cast<void> (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclBase.h"
, 795, __PRETTY_FUNCTION__))
793 MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() &&((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&
MOK != ModuleOwnershipKind::Unowned && !isFromASTFile
() && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration"
) ? static_cast<void> (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclBase.h"
, 795, __PRETTY_FUNCTION__))
794 !hasLocalOwningModuleStorage()) &&((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&
MOK != ModuleOwnershipKind::Unowned && !isFromASTFile
() && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration"
) ? static_cast<void> (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclBase.h"
, 795, __PRETTY_FUNCTION__))
795 "no storage available for owning module for this declaration")((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&
MOK != ModuleOwnershipKind::Unowned && !isFromASTFile
() && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration"
) ? static_cast<void> (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclBase.h"
, 795, __PRETTY_FUNCTION__))
;
796 NextInContextAndBits.setInt(MOK);
797 }
798
799 unsigned getIdentifierNamespace() const {
800 return IdentifierNamespace;
801 }
802
803 bool isInIdentifierNamespace(unsigned NS) const {
804 return getIdentifierNamespace() & NS;
805 }
806
807 static unsigned getIdentifierNamespaceForKind(Kind DK);
808
809 bool hasTagIdentifierNamespace() const {
810 return isTagIdentifierNamespace(getIdentifierNamespace());
811 }
812
813 static bool isTagIdentifierNamespace(unsigned NS) {
814 // TagDecls have Tag and Type set and may also have TagFriend.
815 return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type);
816 }
817