Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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