Bug Summary

File:clang/lib/AST/DeclObjC.cpp
Warning:line 1667, 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-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -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/llvm-toolchain-snapshot-14~++20220126111400+9b6c2ea30219/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-14~++20220126111400+9b6c2ea30219/clang/lib/AST -I /build/llvm-toolchain-snapshot-14~++20220126111400+9b6c2ea30219/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-14~++20220126111400+9b6c2ea30219/llvm/include -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-14/lib/clang/14.0.0/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/llvm-toolchain-snapshot-14~++20220126111400+9b6c2ea30219/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126111400+9b6c2ea30219/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126111400+9b6c2ea30219/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126111400+9b6c2ea30219/= -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 -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220126111400+9b6c2ea30219/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126111400+9b6c2ea30219/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126111400+9b6c2ea30219/= -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-2022-01-26-130535-15419-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220126111400+9b6c2ea30219/clang/lib/AST/DeclObjC.cpp

/build/llvm-toolchain-snapshot-14~++20220126111400+9b6c2ea30219/clang/lib/AST/DeclObjC.cpp

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

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

/build/llvm-toolchain-snapshot-14~++20220126111400+9b6c2ea30219/clang/include/clang/AST/DeclBase.h

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