DeclObjC.cpp 86 KB

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