Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name DeclObjC.cpp -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 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-17/lib/clang/17 -I tools/clang/lib/AST -I /build/source/clang/lib/AST -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-17/lib/clang/17/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2023-05-10-133810-16478-1 -x c++ /build/source/clang/lib/AST/DeclObjC.cpp

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

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