SemaDeclObjC.cpp 115 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913
  1. //===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements semantic analysis for Objective C declarations.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Sema/SemaInternal.h"
  14. #include "clang/Sema/Lookup.h"
  15. #include "clang/Sema/ExternalSemaSource.h"
  16. #include "clang/Sema/Scope.h"
  17. #include "clang/Sema/ScopeInfo.h"
  18. #include "clang/AST/ASTConsumer.h"
  19. #include "clang/AST/Expr.h"
  20. #include "clang/AST/ExprObjC.h"
  21. #include "clang/AST/ASTContext.h"
  22. #include "clang/AST/DeclObjC.h"
  23. #include "clang/Basic/SourceManager.h"
  24. #include "clang/Sema/DeclSpec.h"
  25. #include "llvm/ADT/DenseSet.h"
  26. using namespace clang;
  27. /// Check whether the given method, which must be in the 'init'
  28. /// family, is a valid member of that family.
  29. ///
  30. /// \param receiverTypeIfCall - if null, check this as if declaring it;
  31. /// if non-null, check this as if making a call to it with the given
  32. /// receiver type
  33. ///
  34. /// \return true to indicate that there was an error and appropriate
  35. /// actions were taken
  36. bool Sema::checkInitMethod(ObjCMethodDecl *method,
  37. QualType receiverTypeIfCall) {
  38. if (method->isInvalidDecl()) return true;
  39. // This castAs is safe: methods that don't return an object
  40. // pointer won't be inferred as inits and will reject an explicit
  41. // objc_method_family(init).
  42. // We ignore protocols here. Should we? What about Class?
  43. const ObjCObjectType *result = method->getResultType()
  44. ->castAs<ObjCObjectPointerType>()->getObjectType();
  45. if (result->isObjCId()) {
  46. return false;
  47. } else if (result->isObjCClass()) {
  48. // fall through: always an error
  49. } else {
  50. ObjCInterfaceDecl *resultClass = result->getInterface();
  51. assert(resultClass && "unexpected object type!");
  52. // It's okay for the result type to still be a forward declaration
  53. // if we're checking an interface declaration.
  54. if (resultClass->isForwardDecl()) {
  55. if (receiverTypeIfCall.isNull() &&
  56. !isa<ObjCImplementationDecl>(method->getDeclContext()))
  57. return false;
  58. // Otherwise, we try to compare class types.
  59. } else {
  60. // If this method was declared in a protocol, we can't check
  61. // anything unless we have a receiver type that's an interface.
  62. const ObjCInterfaceDecl *receiverClass = 0;
  63. if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
  64. if (receiverTypeIfCall.isNull())
  65. return false;
  66. receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
  67. ->getInterfaceDecl();
  68. // This can be null for calls to e.g. id<Foo>.
  69. if (!receiverClass) return false;
  70. } else {
  71. receiverClass = method->getClassInterface();
  72. assert(receiverClass && "method not associated with a class!");
  73. }
  74. // If either class is a subclass of the other, it's fine.
  75. if (receiverClass->isSuperClassOf(resultClass) ||
  76. resultClass->isSuperClassOf(receiverClass))
  77. return false;
  78. }
  79. }
  80. SourceLocation loc = method->getLocation();
  81. // If we're in a system header, and this is not a call, just make
  82. // the method unusable.
  83. if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) {
  84. method->addAttr(new (Context) UnavailableAttr(loc, Context,
  85. "init method returns a type unrelated to its receiver type"));
  86. return true;
  87. }
  88. // Otherwise, it's an error.
  89. Diag(loc, diag::err_arc_init_method_unrelated_result_type);
  90. method->setInvalidDecl();
  91. return true;
  92. }
  93. bool Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
  94. const ObjCMethodDecl *Overridden,
  95. bool IsImplementation) {
  96. if (Overridden->hasRelatedResultType() &&
  97. !NewMethod->hasRelatedResultType()) {
  98. // This can only happen when the method follows a naming convention that
  99. // implies a related result type, and the original (overridden) method has
  100. // a suitable return type, but the new (overriding) method does not have
  101. // a suitable return type.
  102. QualType ResultType = NewMethod->getResultType();
  103. SourceRange ResultTypeRange;
  104. if (const TypeSourceInfo *ResultTypeInfo
  105. = NewMethod->getResultTypeSourceInfo())
  106. ResultTypeRange = ResultTypeInfo->getTypeLoc().getSourceRange();
  107. // Figure out which class this method is part of, if any.
  108. ObjCInterfaceDecl *CurrentClass
  109. = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
  110. if (!CurrentClass) {
  111. DeclContext *DC = NewMethod->getDeclContext();
  112. if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
  113. CurrentClass = Cat->getClassInterface();
  114. else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
  115. CurrentClass = Impl->getClassInterface();
  116. else if (ObjCCategoryImplDecl *CatImpl
  117. = dyn_cast<ObjCCategoryImplDecl>(DC))
  118. CurrentClass = CatImpl->getClassInterface();
  119. }
  120. if (CurrentClass) {
  121. Diag(NewMethod->getLocation(),
  122. diag::warn_related_result_type_compatibility_class)
  123. << Context.getObjCInterfaceType(CurrentClass)
  124. << ResultType
  125. << ResultTypeRange;
  126. } else {
  127. Diag(NewMethod->getLocation(),
  128. diag::warn_related_result_type_compatibility_protocol)
  129. << ResultType
  130. << ResultTypeRange;
  131. }
  132. Diag(Overridden->getLocation(), diag::note_related_result_type_overridden)
  133. << Overridden->getMethodFamily();
  134. }
  135. return false;
  136. }
  137. /// \brief Check a method declaration for compatibility with the Objective-C
  138. /// ARC conventions.
  139. static bool CheckARCMethodDecl(Sema &S, ObjCMethodDecl *method) {
  140. ObjCMethodFamily family = method->getMethodFamily();
  141. switch (family) {
  142. case OMF_None:
  143. case OMF_dealloc:
  144. case OMF_retain:
  145. case OMF_release:
  146. case OMF_autorelease:
  147. case OMF_retainCount:
  148. case OMF_self:
  149. case OMF_performSelector:
  150. return false;
  151. case OMF_init:
  152. // If the method doesn't obey the init rules, don't bother annotating it.
  153. if (S.checkInitMethod(method, QualType()))
  154. return true;
  155. method->addAttr(new (S.Context) NSConsumesSelfAttr(SourceLocation(),
  156. S.Context));
  157. // Don't add a second copy of this attribute, but otherwise don't
  158. // let it be suppressed.
  159. if (method->hasAttr<NSReturnsRetainedAttr>())
  160. return false;
  161. break;
  162. case OMF_alloc:
  163. case OMF_copy:
  164. case OMF_mutableCopy:
  165. case OMF_new:
  166. if (method->hasAttr<NSReturnsRetainedAttr>() ||
  167. method->hasAttr<NSReturnsNotRetainedAttr>() ||
  168. method->hasAttr<NSReturnsAutoreleasedAttr>())
  169. return false;
  170. break;
  171. }
  172. method->addAttr(new (S.Context) NSReturnsRetainedAttr(SourceLocation(),
  173. S.Context));
  174. return false;
  175. }
  176. static void DiagnoseObjCImplementedDeprecations(Sema &S,
  177. NamedDecl *ND,
  178. SourceLocation ImplLoc,
  179. int select) {
  180. if (ND && ND->isDeprecated()) {
  181. S.Diag(ImplLoc, diag::warn_deprecated_def) << select;
  182. if (select == 0)
  183. S.Diag(ND->getLocation(), diag::note_method_declared_at);
  184. else
  185. S.Diag(ND->getLocation(), diag::note_previous_decl) << "class";
  186. }
  187. }
  188. /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
  189. /// and user declared, in the method definition's AST.
  190. void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
  191. assert(getCurMethodDecl() == 0 && "Method parsing confused");
  192. ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
  193. // If we don't have a valid method decl, simply return.
  194. if (!MDecl)
  195. return;
  196. // Allow the rest of sema to find private method decl implementations.
  197. if (MDecl->isInstanceMethod())
  198. AddInstanceMethodToGlobalPool(MDecl, true);
  199. else
  200. AddFactoryMethodToGlobalPool(MDecl, true);
  201. // Allow all of Sema to see that we are entering a method definition.
  202. PushDeclContext(FnBodyScope, MDecl);
  203. PushFunctionScope();
  204. // Create Decl objects for each parameter, entrring them in the scope for
  205. // binding to their use.
  206. // Insert the invisible arguments, self and _cmd!
  207. MDecl->createImplicitParams(Context, MDecl->getClassInterface());
  208. PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
  209. PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
  210. // Introduce all of the other parameters into this scope.
  211. for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
  212. E = MDecl->param_end(); PI != E; ++PI) {
  213. ParmVarDecl *Param = (*PI);
  214. if (!Param->isInvalidDecl() &&
  215. RequireCompleteType(Param->getLocation(), Param->getType(),
  216. diag::err_typecheck_decl_incomplete_type))
  217. Param->setInvalidDecl();
  218. if ((*PI)->getIdentifier())
  219. PushOnScopeChains(*PI, FnBodyScope);
  220. }
  221. // In ARC, disallow definition of retain/release/autorelease/retainCount
  222. if (getLangOptions().ObjCAutoRefCount) {
  223. switch (MDecl->getMethodFamily()) {
  224. case OMF_retain:
  225. case OMF_retainCount:
  226. case OMF_release:
  227. case OMF_autorelease:
  228. Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
  229. << MDecl->getSelector();
  230. break;
  231. case OMF_None:
  232. case OMF_dealloc:
  233. case OMF_alloc:
  234. case OMF_init:
  235. case OMF_mutableCopy:
  236. case OMF_copy:
  237. case OMF_new:
  238. case OMF_self:
  239. case OMF_performSelector:
  240. break;
  241. }
  242. }
  243. // Warn on implementating deprecated methods under
  244. // -Wdeprecated-implementations flag.
  245. if (ObjCInterfaceDecl *IC = MDecl->getClassInterface())
  246. if (ObjCMethodDecl *IMD =
  247. IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod()))
  248. DiagnoseObjCImplementedDeprecations(*this,
  249. dyn_cast<NamedDecl>(IMD),
  250. MDecl->getLocation(), 0);
  251. }
  252. Decl *Sema::
  253. ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
  254. IdentifierInfo *ClassName, SourceLocation ClassLoc,
  255. IdentifierInfo *SuperName, SourceLocation SuperLoc,
  256. Decl * const *ProtoRefs, unsigned NumProtoRefs,
  257. const SourceLocation *ProtoLocs,
  258. SourceLocation EndProtoLoc, AttributeList *AttrList) {
  259. assert(ClassName && "Missing class identifier");
  260. // Check for another declaration kind with the same name.
  261. NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc,
  262. LookupOrdinaryName, ForRedeclaration);
  263. if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
  264. Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
  265. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  266. }
  267. ObjCInterfaceDecl* IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
  268. if (IDecl) {
  269. // Class already seen. Is it a forward declaration?
  270. if (!IDecl->isForwardDecl()) {
  271. IDecl->setInvalidDecl();
  272. Diag(AtInterfaceLoc, diag::err_duplicate_class_def)<<IDecl->getDeclName();
  273. Diag(IDecl->getLocation(), diag::note_previous_definition);
  274. // Return the previous class interface.
  275. // FIXME: don't leak the objects passed in!
  276. return IDecl;
  277. } else {
  278. IDecl->setLocation(AtInterfaceLoc);
  279. IDecl->setForwardDecl(false);
  280. IDecl->setClassLoc(ClassLoc);
  281. // If the forward decl was in a PCH, we need to write it again in a
  282. // dependent AST file.
  283. IDecl->setChangedSinceDeserialization(true);
  284. // Since this ObjCInterfaceDecl was created by a forward declaration,
  285. // we now add it to the DeclContext since it wasn't added before
  286. // (see ActOnForwardClassDeclaration).
  287. IDecl->setLexicalDeclContext(CurContext);
  288. CurContext->addDecl(IDecl);
  289. if (AttrList)
  290. ProcessDeclAttributeList(TUScope, IDecl, AttrList);
  291. }
  292. } else {
  293. IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc,
  294. ClassName, ClassLoc);
  295. if (AttrList)
  296. ProcessDeclAttributeList(TUScope, IDecl, AttrList);
  297. PushOnScopeChains(IDecl, TUScope);
  298. }
  299. if (SuperName) {
  300. // Check if a different kind of symbol declared in this scope.
  301. PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
  302. LookupOrdinaryName);
  303. if (!PrevDecl) {
  304. // Try to correct for a typo in the superclass name.
  305. TypoCorrection Corrected = CorrectTypo(
  306. DeclarationNameInfo(SuperName, SuperLoc), LookupOrdinaryName, TUScope,
  307. NULL, NULL, false, CTC_NoKeywords);
  308. if ((PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>())) {
  309. Diag(SuperLoc, diag::err_undef_superclass_suggest)
  310. << SuperName << ClassName << PrevDecl->getDeclName();
  311. Diag(PrevDecl->getLocation(), diag::note_previous_decl)
  312. << PrevDecl->getDeclName();
  313. }
  314. }
  315. if (PrevDecl == IDecl) {
  316. Diag(SuperLoc, diag::err_recursive_superclass)
  317. << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
  318. IDecl->setLocEnd(ClassLoc);
  319. } else {
  320. ObjCInterfaceDecl *SuperClassDecl =
  321. dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
  322. // Diagnose classes that inherit from deprecated classes.
  323. if (SuperClassDecl)
  324. (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
  325. if (PrevDecl && SuperClassDecl == 0) {
  326. // The previous declaration was not a class decl. Check if we have a
  327. // typedef. If we do, get the underlying class type.
  328. if (const TypedefNameDecl *TDecl =
  329. dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
  330. QualType T = TDecl->getUnderlyingType();
  331. if (T->isObjCObjectType()) {
  332. if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface())
  333. SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
  334. }
  335. }
  336. // This handles the following case:
  337. //
  338. // typedef int SuperClass;
  339. // @interface MyClass : SuperClass {} @end
  340. //
  341. if (!SuperClassDecl) {
  342. Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
  343. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  344. }
  345. }
  346. if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
  347. if (!SuperClassDecl)
  348. Diag(SuperLoc, diag::err_undef_superclass)
  349. << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
  350. else if (SuperClassDecl->isForwardDecl()) {
  351. Diag(SuperLoc, diag::err_forward_superclass)
  352. << SuperClassDecl->getDeclName() << ClassName
  353. << SourceRange(AtInterfaceLoc, ClassLoc);
  354. Diag(SuperClassDecl->getLocation(), diag::note_forward_class);
  355. SuperClassDecl = 0;
  356. }
  357. }
  358. IDecl->setSuperClass(SuperClassDecl);
  359. IDecl->setSuperClassLoc(SuperLoc);
  360. IDecl->setLocEnd(SuperLoc);
  361. }
  362. } else { // we have a root class.
  363. IDecl->setLocEnd(ClassLoc);
  364. }
  365. // Check then save referenced protocols.
  366. if (NumProtoRefs) {
  367. IDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
  368. ProtoLocs, Context);
  369. IDecl->setLocEnd(EndProtoLoc);
  370. }
  371. CheckObjCDeclScope(IDecl);
  372. return IDecl;
  373. }
  374. /// ActOnCompatiblityAlias - this action is called after complete parsing of
  375. /// @compatibility_alias declaration. It sets up the alias relationships.
  376. Decl *Sema::ActOnCompatiblityAlias(SourceLocation AtLoc,
  377. IdentifierInfo *AliasName,
  378. SourceLocation AliasLocation,
  379. IdentifierInfo *ClassName,
  380. SourceLocation ClassLocation) {
  381. // Look for previous declaration of alias name
  382. NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation,
  383. LookupOrdinaryName, ForRedeclaration);
  384. if (ADecl) {
  385. if (isa<ObjCCompatibleAliasDecl>(ADecl))
  386. Diag(AliasLocation, diag::warn_previous_alias_decl);
  387. else
  388. Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
  389. Diag(ADecl->getLocation(), diag::note_previous_declaration);
  390. return 0;
  391. }
  392. // Check for class declaration
  393. NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
  394. LookupOrdinaryName, ForRedeclaration);
  395. if (const TypedefNameDecl *TDecl =
  396. dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
  397. QualType T = TDecl->getUnderlyingType();
  398. if (T->isObjCObjectType()) {
  399. if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
  400. ClassName = IDecl->getIdentifier();
  401. CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
  402. LookupOrdinaryName, ForRedeclaration);
  403. }
  404. }
  405. }
  406. ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
  407. if (CDecl == 0) {
  408. Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
  409. if (CDeclU)
  410. Diag(CDeclU->getLocation(), diag::note_previous_declaration);
  411. return 0;
  412. }
  413. // Everything checked out, instantiate a new alias declaration AST.
  414. ObjCCompatibleAliasDecl *AliasDecl =
  415. ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
  416. if (!CheckObjCDeclScope(AliasDecl))
  417. PushOnScopeChains(AliasDecl, TUScope);
  418. return AliasDecl;
  419. }
  420. bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
  421. IdentifierInfo *PName,
  422. SourceLocation &Ploc, SourceLocation PrevLoc,
  423. const ObjCList<ObjCProtocolDecl> &PList) {
  424. bool res = false;
  425. for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
  426. E = PList.end(); I != E; ++I) {
  427. if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
  428. Ploc)) {
  429. if (PDecl->getIdentifier() == PName) {
  430. Diag(Ploc, diag::err_protocol_has_circular_dependency);
  431. Diag(PrevLoc, diag::note_previous_definition);
  432. res = true;
  433. }
  434. if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
  435. PDecl->getLocation(), PDecl->getReferencedProtocols()))
  436. res = true;
  437. }
  438. }
  439. return res;
  440. }
  441. Decl *
  442. Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
  443. IdentifierInfo *ProtocolName,
  444. SourceLocation ProtocolLoc,
  445. Decl * const *ProtoRefs,
  446. unsigned NumProtoRefs,
  447. const SourceLocation *ProtoLocs,
  448. SourceLocation EndProtoLoc,
  449. AttributeList *AttrList) {
  450. bool err = false;
  451. // FIXME: Deal with AttrList.
  452. assert(ProtocolName && "Missing protocol identifier");
  453. ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolName, ProtocolLoc);
  454. if (PDecl) {
  455. // Protocol already seen. Better be a forward protocol declaration
  456. if (!PDecl->isForwardDecl()) {
  457. Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
  458. Diag(PDecl->getLocation(), diag::note_previous_definition);
  459. // Just return the protocol we already had.
  460. // FIXME: don't leak the objects passed in!
  461. return PDecl;
  462. }
  463. ObjCList<ObjCProtocolDecl> PList;
  464. PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
  465. err = CheckForwardProtocolDeclarationForCircularDependency(
  466. ProtocolName, ProtocolLoc, PDecl->getLocation(), PList);
  467. // Make sure the cached decl gets a valid start location.
  468. PDecl->setLocation(AtProtoInterfaceLoc);
  469. PDecl->setForwardDecl(false);
  470. CurContext->addDecl(PDecl);
  471. // Repeat in dependent AST files.
  472. PDecl->setChangedSinceDeserialization(true);
  473. } else {
  474. PDecl = ObjCProtocolDecl::Create(Context, CurContext,
  475. AtProtoInterfaceLoc,ProtocolName);
  476. PushOnScopeChains(PDecl, TUScope);
  477. PDecl->setForwardDecl(false);
  478. }
  479. if (AttrList)
  480. ProcessDeclAttributeList(TUScope, PDecl, AttrList);
  481. if (!err && NumProtoRefs ) {
  482. /// Check then save referenced protocols.
  483. PDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
  484. ProtoLocs, Context);
  485. PDecl->setLocEnd(EndProtoLoc);
  486. }
  487. CheckObjCDeclScope(PDecl);
  488. return PDecl;
  489. }
  490. /// FindProtocolDeclaration - This routine looks up protocols and
  491. /// issues an error if they are not declared. It returns list of
  492. /// protocol declarations in its 'Protocols' argument.
  493. void
  494. Sema::FindProtocolDeclaration(bool WarnOnDeclarations,
  495. const IdentifierLocPair *ProtocolId,
  496. unsigned NumProtocols,
  497. SmallVectorImpl<Decl *> &Protocols) {
  498. for (unsigned i = 0; i != NumProtocols; ++i) {
  499. ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first,
  500. ProtocolId[i].second);
  501. if (!PDecl) {
  502. TypoCorrection Corrected = CorrectTypo(
  503. DeclarationNameInfo(ProtocolId[i].first, ProtocolId[i].second),
  504. LookupObjCProtocolName, TUScope, NULL, NULL, false, CTC_NoKeywords);
  505. if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>())) {
  506. Diag(ProtocolId[i].second, diag::err_undeclared_protocol_suggest)
  507. << ProtocolId[i].first << Corrected.getCorrection();
  508. Diag(PDecl->getLocation(), diag::note_previous_decl)
  509. << PDecl->getDeclName();
  510. }
  511. }
  512. if (!PDecl) {
  513. Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
  514. << ProtocolId[i].first;
  515. continue;
  516. }
  517. (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second);
  518. // If this is a forward declaration and we are supposed to warn in this
  519. // case, do it.
  520. if (WarnOnDeclarations && PDecl->isForwardDecl())
  521. Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
  522. << ProtocolId[i].first;
  523. Protocols.push_back(PDecl);
  524. }
  525. }
  526. /// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
  527. /// a class method in its extension.
  528. ///
  529. void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
  530. ObjCInterfaceDecl *ID) {
  531. if (!ID)
  532. return; // Possibly due to previous error
  533. llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
  534. for (ObjCInterfaceDecl::method_iterator i = ID->meth_begin(),
  535. e = ID->meth_end(); i != e; ++i) {
  536. ObjCMethodDecl *MD = *i;
  537. MethodMap[MD->getSelector()] = MD;
  538. }
  539. if (MethodMap.empty())
  540. return;
  541. for (ObjCCategoryDecl::method_iterator i = CAT->meth_begin(),
  542. e = CAT->meth_end(); i != e; ++i) {
  543. ObjCMethodDecl *Method = *i;
  544. const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
  545. if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
  546. Diag(Method->getLocation(), diag::err_duplicate_method_decl)
  547. << Method->getDeclName();
  548. Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
  549. }
  550. }
  551. }
  552. /// ActOnForwardProtocolDeclaration - Handle @protocol foo;
  553. Decl *
  554. Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
  555. const IdentifierLocPair *IdentList,
  556. unsigned NumElts,
  557. AttributeList *attrList) {
  558. SmallVector<ObjCProtocolDecl*, 32> Protocols;
  559. SmallVector<SourceLocation, 8> ProtoLocs;
  560. for (unsigned i = 0; i != NumElts; ++i) {
  561. IdentifierInfo *Ident = IdentList[i].first;
  562. ObjCProtocolDecl *PDecl = LookupProtocol(Ident, IdentList[i].second);
  563. bool isNew = false;
  564. if (PDecl == 0) { // Not already seen?
  565. PDecl = ObjCProtocolDecl::Create(Context, CurContext,
  566. IdentList[i].second, Ident);
  567. PushOnScopeChains(PDecl, TUScope, false);
  568. isNew = true;
  569. }
  570. if (attrList) {
  571. ProcessDeclAttributeList(TUScope, PDecl, attrList);
  572. if (!isNew)
  573. PDecl->setChangedSinceDeserialization(true);
  574. }
  575. Protocols.push_back(PDecl);
  576. ProtoLocs.push_back(IdentList[i].second);
  577. }
  578. ObjCForwardProtocolDecl *PDecl =
  579. ObjCForwardProtocolDecl::Create(Context, CurContext, AtProtocolLoc,
  580. Protocols.data(), Protocols.size(),
  581. ProtoLocs.data());
  582. CurContext->addDecl(PDecl);
  583. CheckObjCDeclScope(PDecl);
  584. return PDecl;
  585. }
  586. Decl *Sema::
  587. ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
  588. IdentifierInfo *ClassName, SourceLocation ClassLoc,
  589. IdentifierInfo *CategoryName,
  590. SourceLocation CategoryLoc,
  591. Decl * const *ProtoRefs,
  592. unsigned NumProtoRefs,
  593. const SourceLocation *ProtoLocs,
  594. SourceLocation EndProtoLoc) {
  595. ObjCCategoryDecl *CDecl;
  596. ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
  597. /// Check that class of this category is already completely declared.
  598. if (!IDecl || IDecl->isForwardDecl()) {
  599. // Create an invalid ObjCCategoryDecl to serve as context for
  600. // the enclosing method declarations. We mark the decl invalid
  601. // to make it clear that this isn't a valid AST.
  602. CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
  603. ClassLoc, CategoryLoc, CategoryName);
  604. CDecl->setInvalidDecl();
  605. Diag(ClassLoc, diag::err_undef_interface) << ClassName;
  606. return CDecl;
  607. }
  608. if (!CategoryName && IDecl->getImplementation()) {
  609. Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
  610. Diag(IDecl->getImplementation()->getLocation(),
  611. diag::note_implementation_declared);
  612. }
  613. CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
  614. ClassLoc, CategoryLoc, CategoryName);
  615. // FIXME: PushOnScopeChains?
  616. CurContext->addDecl(CDecl);
  617. CDecl->setClassInterface(IDecl);
  618. // Insert class extension to the list of class's categories.
  619. if (!CategoryName)
  620. CDecl->insertNextClassCategory();
  621. // If the interface is deprecated, warn about it.
  622. (void)DiagnoseUseOfDecl(IDecl, ClassLoc);
  623. if (CategoryName) {
  624. /// Check for duplicate interface declaration for this category
  625. ObjCCategoryDecl *CDeclChain;
  626. for (CDeclChain = IDecl->getCategoryList(); CDeclChain;
  627. CDeclChain = CDeclChain->getNextClassCategory()) {
  628. if (CDeclChain->getIdentifier() == CategoryName) {
  629. // Class extensions can be declared multiple times.
  630. Diag(CategoryLoc, diag::warn_dup_category_def)
  631. << ClassName << CategoryName;
  632. Diag(CDeclChain->getLocation(), diag::note_previous_definition);
  633. break;
  634. }
  635. }
  636. if (!CDeclChain)
  637. CDecl->insertNextClassCategory();
  638. }
  639. if (NumProtoRefs) {
  640. CDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
  641. ProtoLocs, Context);
  642. // Protocols in the class extension belong to the class.
  643. if (CDecl->IsClassExtension())
  644. IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl**)ProtoRefs,
  645. NumProtoRefs, Context);
  646. }
  647. CheckObjCDeclScope(CDecl);
  648. return CDecl;
  649. }
  650. /// ActOnStartCategoryImplementation - Perform semantic checks on the
  651. /// category implementation declaration and build an ObjCCategoryImplDecl
  652. /// object.
  653. Decl *Sema::ActOnStartCategoryImplementation(
  654. SourceLocation AtCatImplLoc,
  655. IdentifierInfo *ClassName, SourceLocation ClassLoc,
  656. IdentifierInfo *CatName, SourceLocation CatLoc) {
  657. ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
  658. ObjCCategoryDecl *CatIDecl = 0;
  659. if (IDecl) {
  660. CatIDecl = IDecl->FindCategoryDeclaration(CatName);
  661. if (!CatIDecl) {
  662. // Category @implementation with no corresponding @interface.
  663. // Create and install one.
  664. CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, SourceLocation(),
  665. SourceLocation(), SourceLocation(),
  666. CatName);
  667. CatIDecl->setClassInterface(IDecl);
  668. CatIDecl->insertNextClassCategory();
  669. }
  670. }
  671. ObjCCategoryImplDecl *CDecl =
  672. ObjCCategoryImplDecl::Create(Context, CurContext, AtCatImplLoc, CatName,
  673. IDecl);
  674. /// Check that class of this category is already completely declared.
  675. if (!IDecl || IDecl->isForwardDecl()) {
  676. Diag(ClassLoc, diag::err_undef_interface) << ClassName;
  677. CDecl->setInvalidDecl();
  678. }
  679. // FIXME: PushOnScopeChains?
  680. CurContext->addDecl(CDecl);
  681. /// Check that CatName, category name, is not used in another implementation.
  682. if (CatIDecl) {
  683. if (CatIDecl->getImplementation()) {
  684. Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
  685. << CatName;
  686. Diag(CatIDecl->getImplementation()->getLocation(),
  687. diag::note_previous_definition);
  688. } else {
  689. CatIDecl->setImplementation(CDecl);
  690. // Warn on implementating category of deprecated class under
  691. // -Wdeprecated-implementations flag.
  692. DiagnoseObjCImplementedDeprecations(*this,
  693. dyn_cast<NamedDecl>(IDecl),
  694. CDecl->getLocation(), 2);
  695. }
  696. }
  697. CheckObjCDeclScope(CDecl);
  698. return CDecl;
  699. }
  700. Decl *Sema::ActOnStartClassImplementation(
  701. SourceLocation AtClassImplLoc,
  702. IdentifierInfo *ClassName, SourceLocation ClassLoc,
  703. IdentifierInfo *SuperClassname,
  704. SourceLocation SuperClassLoc) {
  705. ObjCInterfaceDecl* IDecl = 0;
  706. // Check for another declaration kind with the same name.
  707. NamedDecl *PrevDecl
  708. = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
  709. ForRedeclaration);
  710. if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
  711. Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
  712. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  713. } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
  714. // If this is a forward declaration of an interface, warn.
  715. if (IDecl->isForwardDecl()) {
  716. Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
  717. IDecl = 0;
  718. }
  719. } else {
  720. // We did not find anything with the name ClassName; try to correct for
  721. // typos in the class name.
  722. TypoCorrection Corrected = CorrectTypo(
  723. DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope,
  724. NULL, NULL, false, CTC_NoKeywords);
  725. if ((IDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>())) {
  726. // Suggest the (potentially) correct interface name. However, put the
  727. // fix-it hint itself in a separate note, since changing the name in
  728. // the warning would make the fix-it change semantics.However, don't
  729. // provide a code-modification hint or use the typo name for recovery,
  730. // because this is just a warning. The program may actually be correct.
  731. DeclarationName CorrectedName = Corrected.getCorrection();
  732. Diag(ClassLoc, diag::warn_undef_interface_suggest)
  733. << ClassName << CorrectedName;
  734. Diag(IDecl->getLocation(), diag::note_previous_decl) << CorrectedName
  735. << FixItHint::CreateReplacement(ClassLoc, CorrectedName.getAsString());
  736. IDecl = 0;
  737. } else {
  738. Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
  739. }
  740. }
  741. // Check that super class name is valid class name
  742. ObjCInterfaceDecl* SDecl = 0;
  743. if (SuperClassname) {
  744. // Check if a different kind of symbol declared in this scope.
  745. PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
  746. LookupOrdinaryName);
  747. if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
  748. Diag(SuperClassLoc, diag::err_redefinition_different_kind)
  749. << SuperClassname;
  750. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  751. } else {
  752. SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
  753. if (!SDecl)
  754. Diag(SuperClassLoc, diag::err_undef_superclass)
  755. << SuperClassname << ClassName;
  756. else if (IDecl && IDecl->getSuperClass() != SDecl) {
  757. // This implementation and its interface do not have the same
  758. // super class.
  759. Diag(SuperClassLoc, diag::err_conflicting_super_class)
  760. << SDecl->getDeclName();
  761. Diag(SDecl->getLocation(), diag::note_previous_definition);
  762. }
  763. }
  764. }
  765. if (!IDecl) {
  766. // Legacy case of @implementation with no corresponding @interface.
  767. // Build, chain & install the interface decl into the identifier.
  768. // FIXME: Do we support attributes on the @implementation? If so we should
  769. // copy them over.
  770. IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
  771. ClassName, ClassLoc, false, true);
  772. IDecl->setSuperClass(SDecl);
  773. IDecl->setLocEnd(ClassLoc);
  774. PushOnScopeChains(IDecl, TUScope);
  775. } else {
  776. // Mark the interface as being completed, even if it was just as
  777. // @class ....;
  778. // declaration; the user cannot reopen it.
  779. IDecl->setForwardDecl(false);
  780. }
  781. ObjCImplementationDecl* IMPDecl =
  782. ObjCImplementationDecl::Create(Context, CurContext, AtClassImplLoc,
  783. IDecl, SDecl);
  784. if (CheckObjCDeclScope(IMPDecl))
  785. return IMPDecl;
  786. // Check that there is no duplicate implementation of this class.
  787. if (IDecl->getImplementation()) {
  788. // FIXME: Don't leak everything!
  789. Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
  790. Diag(IDecl->getImplementation()->getLocation(),
  791. diag::note_previous_definition);
  792. } else { // add it to the list.
  793. IDecl->setImplementation(IMPDecl);
  794. PushOnScopeChains(IMPDecl, TUScope);
  795. // Warn on implementating deprecated class under
  796. // -Wdeprecated-implementations flag.
  797. DiagnoseObjCImplementedDeprecations(*this,
  798. dyn_cast<NamedDecl>(IDecl),
  799. IMPDecl->getLocation(), 1);
  800. }
  801. return IMPDecl;
  802. }
  803. void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
  804. ObjCIvarDecl **ivars, unsigned numIvars,
  805. SourceLocation RBrace) {
  806. assert(ImpDecl && "missing implementation decl");
  807. ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
  808. if (!IDecl)
  809. return;
  810. /// Check case of non-existing @interface decl.
  811. /// (legacy objective-c @implementation decl without an @interface decl).
  812. /// Add implementations's ivar to the synthesize class's ivar list.
  813. if (IDecl->isImplicitInterfaceDecl()) {
  814. IDecl->setLocEnd(RBrace);
  815. // Add ivar's to class's DeclContext.
  816. for (unsigned i = 0, e = numIvars; i != e; ++i) {
  817. ivars[i]->setLexicalDeclContext(ImpDecl);
  818. IDecl->makeDeclVisibleInContext(ivars[i], false);
  819. ImpDecl->addDecl(ivars[i]);
  820. }
  821. return;
  822. }
  823. // If implementation has empty ivar list, just return.
  824. if (numIvars == 0)
  825. return;
  826. assert(ivars && "missing @implementation ivars");
  827. if (LangOpts.ObjCNonFragileABI2) {
  828. if (ImpDecl->getSuperClass())
  829. Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
  830. for (unsigned i = 0; i < numIvars; i++) {
  831. ObjCIvarDecl* ImplIvar = ivars[i];
  832. if (const ObjCIvarDecl *ClsIvar =
  833. IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
  834. Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
  835. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  836. continue;
  837. }
  838. // Instance ivar to Implementation's DeclContext.
  839. ImplIvar->setLexicalDeclContext(ImpDecl);
  840. IDecl->makeDeclVisibleInContext(ImplIvar, false);
  841. ImpDecl->addDecl(ImplIvar);
  842. }
  843. return;
  844. }
  845. // Check interface's Ivar list against those in the implementation.
  846. // names and types must match.
  847. //
  848. unsigned j = 0;
  849. ObjCInterfaceDecl::ivar_iterator
  850. IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
  851. for (; numIvars > 0 && IVI != IVE; ++IVI) {
  852. ObjCIvarDecl* ImplIvar = ivars[j++];
  853. ObjCIvarDecl* ClsIvar = *IVI;
  854. assert (ImplIvar && "missing implementation ivar");
  855. assert (ClsIvar && "missing class ivar");
  856. // First, make sure the types match.
  857. if (Context.getCanonicalType(ImplIvar->getType()) !=
  858. Context.getCanonicalType(ClsIvar->getType())) {
  859. Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
  860. << ImplIvar->getIdentifier()
  861. << ImplIvar->getType() << ClsIvar->getType();
  862. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  863. } else if (ImplIvar->isBitField() && ClsIvar->isBitField()) {
  864. Expr *ImplBitWidth = ImplIvar->getBitWidth();
  865. Expr *ClsBitWidth = ClsIvar->getBitWidth();
  866. if (ImplBitWidth->EvaluateAsInt(Context).getZExtValue() !=
  867. ClsBitWidth->EvaluateAsInt(Context).getZExtValue()) {
  868. Diag(ImplBitWidth->getLocStart(), diag::err_conflicting_ivar_bitwidth)
  869. << ImplIvar->getIdentifier();
  870. Diag(ClsBitWidth->getLocStart(), diag::note_previous_definition);
  871. }
  872. }
  873. // Make sure the names are identical.
  874. if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
  875. Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
  876. << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
  877. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  878. }
  879. --numIvars;
  880. }
  881. if (numIvars > 0)
  882. Diag(ivars[j]->getLocation(), diag::err_inconsistant_ivar_count);
  883. else if (IVI != IVE)
  884. Diag((*IVI)->getLocation(), diag::err_inconsistant_ivar_count);
  885. }
  886. void Sema::WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
  887. bool &IncompleteImpl, unsigned DiagID) {
  888. // No point warning no definition of method which is 'unavailable'.
  889. if (method->hasAttr<UnavailableAttr>())
  890. return;
  891. if (!IncompleteImpl) {
  892. Diag(ImpLoc, diag::warn_incomplete_impl);
  893. IncompleteImpl = true;
  894. }
  895. if (DiagID == diag::warn_unimplemented_protocol_method)
  896. Diag(ImpLoc, DiagID) << method->getDeclName();
  897. else
  898. Diag(method->getLocation(), DiagID) << method->getDeclName();
  899. }
  900. /// Determines if type B can be substituted for type A. Returns true if we can
  901. /// guarantee that anything that the user will do to an object of type A can
  902. /// also be done to an object of type B. This is trivially true if the two
  903. /// types are the same, or if B is a subclass of A. It becomes more complex
  904. /// in cases where protocols are involved.
  905. ///
  906. /// Object types in Objective-C describe the minimum requirements for an
  907. /// object, rather than providing a complete description of a type. For
  908. /// example, if A is a subclass of B, then B* may refer to an instance of A.
  909. /// The principle of substitutability means that we may use an instance of A
  910. /// anywhere that we may use an instance of B - it will implement all of the
  911. /// ivars of B and all of the methods of B.
  912. ///
  913. /// This substitutability is important when type checking methods, because
  914. /// the implementation may have stricter type definitions than the interface.
  915. /// The interface specifies minimum requirements, but the implementation may
  916. /// have more accurate ones. For example, a method may privately accept
  917. /// instances of B, but only publish that it accepts instances of A. Any
  918. /// object passed to it will be type checked against B, and so will implicitly
  919. /// by a valid A*. Similarly, a method may return a subclass of the class that
  920. /// it is declared as returning.
  921. ///
  922. /// This is most important when considering subclassing. A method in a
  923. /// subclass must accept any object as an argument that its superclass's
  924. /// implementation accepts. It may, however, accept a more general type
  925. /// without breaking substitutability (i.e. you can still use the subclass
  926. /// anywhere that you can use the superclass, but not vice versa). The
  927. /// converse requirement applies to return types: the return type for a
  928. /// subclass method must be a valid object of the kind that the superclass
  929. /// advertises, but it may be specified more accurately. This avoids the need
  930. /// for explicit down-casting by callers.
  931. ///
  932. /// Note: This is a stricter requirement than for assignment.
  933. static bool isObjCTypeSubstitutable(ASTContext &Context,
  934. const ObjCObjectPointerType *A,
  935. const ObjCObjectPointerType *B,
  936. bool rejectId) {
  937. // Reject a protocol-unqualified id.
  938. if (rejectId && B->isObjCIdType()) return false;
  939. // If B is a qualified id, then A must also be a qualified id and it must
  940. // implement all of the protocols in B. It may not be a qualified class.
  941. // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
  942. // stricter definition so it is not substitutable for id<A>.
  943. if (B->isObjCQualifiedIdType()) {
  944. return A->isObjCQualifiedIdType() &&
  945. Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
  946. QualType(B,0),
  947. false);
  948. }
  949. /*
  950. // id is a special type that bypasses type checking completely. We want a
  951. // warning when it is used in one place but not another.
  952. if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
  953. // If B is a qualified id, then A must also be a qualified id (which it isn't
  954. // if we've got this far)
  955. if (B->isObjCQualifiedIdType()) return false;
  956. */
  957. // Now we know that A and B are (potentially-qualified) class types. The
  958. // normal rules for assignment apply.
  959. return Context.canAssignObjCInterfaces(A, B);
  960. }
  961. static SourceRange getTypeRange(TypeSourceInfo *TSI) {
  962. return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
  963. }
  964. static bool CheckMethodOverrideReturn(Sema &S,
  965. ObjCMethodDecl *MethodImpl,
  966. ObjCMethodDecl *MethodDecl,
  967. bool IsProtocolMethodDecl,
  968. bool IsDeclaration,
  969. bool Warn) {
  970. if (IsProtocolMethodDecl &&
  971. (MethodDecl->getObjCDeclQualifier() !=
  972. MethodImpl->getObjCDeclQualifier())) {
  973. if (Warn) {
  974. S.Diag(MethodImpl->getLocation(),
  975. diag::warn_conflicting_ret_type_modifiers)
  976. << MethodImpl->getDeclName() << IsDeclaration
  977. << getTypeRange(MethodImpl->getResultTypeSourceInfo());
  978. S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
  979. << getTypeRange(MethodDecl->getResultTypeSourceInfo());
  980. }
  981. else
  982. return false;
  983. }
  984. if (S.Context.hasSameUnqualifiedType(MethodImpl->getResultType(),
  985. MethodDecl->getResultType()))
  986. return true;
  987. if (!Warn)
  988. return false;
  989. unsigned DiagID = diag::warn_conflicting_ret_types;
  990. // Mismatches between ObjC pointers go into a different warning
  991. // category, and sometimes they're even completely whitelisted.
  992. if (const ObjCObjectPointerType *ImplPtrTy =
  993. MethodImpl->getResultType()->getAs<ObjCObjectPointerType>()) {
  994. if (const ObjCObjectPointerType *IfacePtrTy =
  995. MethodDecl->getResultType()->getAs<ObjCObjectPointerType>()) {
  996. // Allow non-matching return types as long as they don't violate
  997. // the principle of substitutability. Specifically, we permit
  998. // return types that are subclasses of the declared return type,
  999. // or that are more-qualified versions of the declared type.
  1000. if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
  1001. return false;
  1002. DiagID = diag::warn_non_covariant_ret_types;
  1003. }
  1004. }
  1005. S.Diag(MethodImpl->getLocation(), DiagID)
  1006. << MethodImpl->getDeclName()
  1007. << MethodDecl->getResultType()
  1008. << MethodImpl->getResultType()
  1009. << IsDeclaration
  1010. << getTypeRange(MethodImpl->getResultTypeSourceInfo());
  1011. S.Diag(MethodDecl->getLocation(), diag::note_previous_definition)
  1012. << getTypeRange(MethodDecl->getResultTypeSourceInfo());
  1013. return false;
  1014. }
  1015. static bool CheckMethodOverrideParam(Sema &S,
  1016. ObjCMethodDecl *MethodImpl,
  1017. ObjCMethodDecl *MethodDecl,
  1018. ParmVarDecl *ImplVar,
  1019. ParmVarDecl *IfaceVar,
  1020. bool IsProtocolMethodDecl,
  1021. bool IsDeclaration,
  1022. bool Warn) {
  1023. if (IsProtocolMethodDecl &&
  1024. (ImplVar->getObjCDeclQualifier() !=
  1025. IfaceVar->getObjCDeclQualifier())) {
  1026. if (Warn) {
  1027. S.Diag(ImplVar->getLocation(),
  1028. diag::warn_conflicting_param_modifiers)
  1029. << getTypeRange(ImplVar->getTypeSourceInfo())
  1030. << MethodImpl->getDeclName() << IsDeclaration;
  1031. S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
  1032. << getTypeRange(IfaceVar->getTypeSourceInfo());
  1033. }
  1034. else
  1035. return false;
  1036. }
  1037. QualType ImplTy = ImplVar->getType();
  1038. QualType IfaceTy = IfaceVar->getType();
  1039. if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
  1040. return true;
  1041. if (!Warn)
  1042. return false;
  1043. unsigned DiagID = diag::warn_conflicting_param_types;
  1044. // Mismatches between ObjC pointers go into a different warning
  1045. // category, and sometimes they're even completely whitelisted.
  1046. if (const ObjCObjectPointerType *ImplPtrTy =
  1047. ImplTy->getAs<ObjCObjectPointerType>()) {
  1048. if (const ObjCObjectPointerType *IfacePtrTy =
  1049. IfaceTy->getAs<ObjCObjectPointerType>()) {
  1050. // Allow non-matching argument types as long as they don't
  1051. // violate the principle of substitutability. Specifically, the
  1052. // implementation must accept any objects that the superclass
  1053. // accepts, however it may also accept others.
  1054. if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
  1055. return false;
  1056. DiagID = diag::warn_non_contravariant_param_types;
  1057. }
  1058. }
  1059. S.Diag(ImplVar->getLocation(), DiagID)
  1060. << getTypeRange(ImplVar->getTypeSourceInfo())
  1061. << MethodImpl->getDeclName() << IfaceTy << ImplTy
  1062. << IsDeclaration;
  1063. S.Diag(IfaceVar->getLocation(), diag::note_previous_definition)
  1064. << getTypeRange(IfaceVar->getTypeSourceInfo());
  1065. return false;
  1066. }
  1067. /// In ARC, check whether the conventional meanings of the two methods
  1068. /// match. If they don't, it's a hard error.
  1069. static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
  1070. ObjCMethodDecl *decl) {
  1071. ObjCMethodFamily implFamily = impl->getMethodFamily();
  1072. ObjCMethodFamily declFamily = decl->getMethodFamily();
  1073. if (implFamily == declFamily) return false;
  1074. // Since conventions are sorted by selector, the only possibility is
  1075. // that the types differ enough to cause one selector or the other
  1076. // to fall out of the family.
  1077. assert(implFamily == OMF_None || declFamily == OMF_None);
  1078. // No further diagnostics required on invalid declarations.
  1079. if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
  1080. const ObjCMethodDecl *unmatched = impl;
  1081. ObjCMethodFamily family = declFamily;
  1082. unsigned errorID = diag::err_arc_lost_method_convention;
  1083. unsigned noteID = diag::note_arc_lost_method_convention;
  1084. if (declFamily == OMF_None) {
  1085. unmatched = decl;
  1086. family = implFamily;
  1087. errorID = diag::err_arc_gained_method_convention;
  1088. noteID = diag::note_arc_gained_method_convention;
  1089. }
  1090. // Indexes into a %select clause in the diagnostic.
  1091. enum FamilySelector {
  1092. F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
  1093. };
  1094. FamilySelector familySelector = FamilySelector();
  1095. switch (family) {
  1096. case OMF_None: llvm_unreachable("logic error, no method convention");
  1097. case OMF_retain:
  1098. case OMF_release:
  1099. case OMF_autorelease:
  1100. case OMF_dealloc:
  1101. case OMF_retainCount:
  1102. case OMF_self:
  1103. case OMF_performSelector:
  1104. // Mismatches for these methods don't change ownership
  1105. // conventions, so we don't care.
  1106. return false;
  1107. case OMF_init: familySelector = F_init; break;
  1108. case OMF_alloc: familySelector = F_alloc; break;
  1109. case OMF_copy: familySelector = F_copy; break;
  1110. case OMF_mutableCopy: familySelector = F_mutableCopy; break;
  1111. case OMF_new: familySelector = F_new; break;
  1112. }
  1113. enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
  1114. ReasonSelector reasonSelector;
  1115. // The only reason these methods don't fall within their families is
  1116. // due to unusual result types.
  1117. if (unmatched->getResultType()->isObjCObjectPointerType()) {
  1118. reasonSelector = R_UnrelatedReturn;
  1119. } else {
  1120. reasonSelector = R_NonObjectReturn;
  1121. }
  1122. S.Diag(impl->getLocation(), errorID) << familySelector << reasonSelector;
  1123. S.Diag(decl->getLocation(), noteID) << familySelector << reasonSelector;
  1124. return true;
  1125. }
  1126. void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
  1127. ObjCMethodDecl *MethodDecl,
  1128. bool IsProtocolMethodDecl,
  1129. bool IsDeclaration) {
  1130. if (getLangOptions().ObjCAutoRefCount &&
  1131. checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
  1132. return;
  1133. CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
  1134. IsProtocolMethodDecl, IsDeclaration, true);
  1135. for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
  1136. IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end();
  1137. IM != EM; ++IM, ++IF)
  1138. CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
  1139. IsProtocolMethodDecl, IsDeclaration, true);
  1140. if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
  1141. Diag(ImpMethodDecl->getLocation(), diag::warn_conflicting_variadic)
  1142. << IsDeclaration;
  1143. Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
  1144. }
  1145. }
  1146. /// WarnExactTypedMethods - This routine issues a warning if method
  1147. /// implementation declaration matches exactly that of its declaration.
  1148. void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
  1149. ObjCMethodDecl *MethodDecl,
  1150. bool IsProtocolMethodDecl) {
  1151. // don't issue warning when protocol method is optional because primary
  1152. // class is not required to implement it and it is safe for protocol
  1153. // to implement it.
  1154. if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
  1155. return;
  1156. // don't issue warning when primary class's method is
  1157. // depecated/unavailable.
  1158. if (MethodDecl->hasAttr<UnavailableAttr>() ||
  1159. MethodDecl->hasAttr<DeprecatedAttr>())
  1160. return;
  1161. bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
  1162. IsProtocolMethodDecl, false, false);
  1163. if (match)
  1164. for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
  1165. IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end();
  1166. IM != EM; ++IM, ++IF) {
  1167. match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
  1168. *IM, *IF,
  1169. IsProtocolMethodDecl, false, false);
  1170. if (!match)
  1171. break;
  1172. }
  1173. if (match)
  1174. match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
  1175. if (match) {
  1176. Diag(ImpMethodDecl->getLocation(),
  1177. diag::warn_category_method_impl_match);
  1178. Diag(MethodDecl->getLocation(), diag::note_method_declared_at);
  1179. }
  1180. }
  1181. /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
  1182. /// improve the efficiency of selector lookups and type checking by associating
  1183. /// with each protocol / interface / category the flattened instance tables. If
  1184. /// we used an immutable set to keep the table then it wouldn't add significant
  1185. /// memory cost and it would be handy for lookups.
  1186. /// CheckProtocolMethodDefs - This routine checks unimplemented methods
  1187. /// Declared in protocol, and those referenced by it.
  1188. void Sema::CheckProtocolMethodDefs(SourceLocation ImpLoc,
  1189. ObjCProtocolDecl *PDecl,
  1190. bool& IncompleteImpl,
  1191. const llvm::DenseSet<Selector> &InsMap,
  1192. const llvm::DenseSet<Selector> &ClsMap,
  1193. ObjCContainerDecl *CDecl) {
  1194. ObjCInterfaceDecl *IDecl;
  1195. if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl))
  1196. IDecl = C->getClassInterface();
  1197. else
  1198. IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
  1199. assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
  1200. ObjCInterfaceDecl *Super = IDecl->getSuperClass();
  1201. ObjCInterfaceDecl *NSIDecl = 0;
  1202. if (getLangOptions().NeXTRuntime) {
  1203. // check to see if class implements forwardInvocation method and objects
  1204. // of this class are derived from 'NSProxy' so that to forward requests
  1205. // from one object to another.
  1206. // Under such conditions, which means that every method possible is
  1207. // implemented in the class, we should not issue "Method definition not
  1208. // found" warnings.
  1209. // FIXME: Use a general GetUnarySelector method for this.
  1210. IdentifierInfo* II = &Context.Idents.get("forwardInvocation");
  1211. Selector fISelector = Context.Selectors.getSelector(1, &II);
  1212. if (InsMap.count(fISelector))
  1213. // Is IDecl derived from 'NSProxy'? If so, no instance methods
  1214. // need be implemented in the implementation.
  1215. NSIDecl = IDecl->lookupInheritedClass(&Context.Idents.get("NSProxy"));
  1216. }
  1217. // If a method lookup fails locally we still need to look and see if
  1218. // the method was implemented by a base class or an inherited
  1219. // protocol. This lookup is slow, but occurs rarely in correct code
  1220. // and otherwise would terminate in a warning.
  1221. // check unimplemented instance methods.
  1222. if (!NSIDecl)
  1223. for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
  1224. E = PDecl->instmeth_end(); I != E; ++I) {
  1225. ObjCMethodDecl *method = *I;
  1226. if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
  1227. !method->isSynthesized() && !InsMap.count(method->getSelector()) &&
  1228. (!Super ||
  1229. !Super->lookupInstanceMethod(method->getSelector()))) {
  1230. // Ugly, but necessary. Method declared in protcol might have
  1231. // have been synthesized due to a property declared in the class which
  1232. // uses the protocol.
  1233. ObjCMethodDecl *MethodInClass =
  1234. IDecl->lookupInstanceMethod(method->getSelector());
  1235. if (!MethodInClass || !MethodInClass->isSynthesized()) {
  1236. unsigned DIAG = diag::warn_unimplemented_protocol_method;
  1237. if (Diags.getDiagnosticLevel(DIAG, ImpLoc)
  1238. != Diagnostic::Ignored) {
  1239. WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG);
  1240. Diag(method->getLocation(), diag::note_method_declared_at);
  1241. Diag(CDecl->getLocation(), diag::note_required_for_protocol_at)
  1242. << PDecl->getDeclName();
  1243. }
  1244. }
  1245. }
  1246. }
  1247. // check unimplemented class methods
  1248. for (ObjCProtocolDecl::classmeth_iterator
  1249. I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
  1250. I != E; ++I) {
  1251. ObjCMethodDecl *method = *I;
  1252. if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
  1253. !ClsMap.count(method->getSelector()) &&
  1254. (!Super || !Super->lookupClassMethod(method->getSelector()))) {
  1255. unsigned DIAG = diag::warn_unimplemented_protocol_method;
  1256. if (Diags.getDiagnosticLevel(DIAG, ImpLoc) != Diagnostic::Ignored) {
  1257. WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG);
  1258. Diag(method->getLocation(), diag::note_method_declared_at);
  1259. Diag(IDecl->getLocation(), diag::note_required_for_protocol_at) <<
  1260. PDecl->getDeclName();
  1261. }
  1262. }
  1263. }
  1264. // Check on this protocols's referenced protocols, recursively.
  1265. for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
  1266. E = PDecl->protocol_end(); PI != E; ++PI)
  1267. CheckProtocolMethodDefs(ImpLoc, *PI, IncompleteImpl, InsMap, ClsMap, IDecl);
  1268. }
  1269. /// MatchAllMethodDeclarations - Check methods declared in interface
  1270. /// or protocol against those declared in their implementations.
  1271. ///
  1272. void Sema::MatchAllMethodDeclarations(const llvm::DenseSet<Selector> &InsMap,
  1273. const llvm::DenseSet<Selector> &ClsMap,
  1274. llvm::DenseSet<Selector> &InsMapSeen,
  1275. llvm::DenseSet<Selector> &ClsMapSeen,
  1276. ObjCImplDecl* IMPDecl,
  1277. ObjCContainerDecl* CDecl,
  1278. bool &IncompleteImpl,
  1279. bool ImmediateClass,
  1280. bool WarnExactMatch) {
  1281. // Check and see if instance methods in class interface have been
  1282. // implemented in the implementation class. If so, their types match.
  1283. for (ObjCInterfaceDecl::instmeth_iterator I = CDecl->instmeth_begin(),
  1284. E = CDecl->instmeth_end(); I != E; ++I) {
  1285. if (InsMapSeen.count((*I)->getSelector()))
  1286. continue;
  1287. InsMapSeen.insert((*I)->getSelector());
  1288. if (!(*I)->isSynthesized() &&
  1289. !InsMap.count((*I)->getSelector())) {
  1290. if (ImmediateClass)
  1291. WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl,
  1292. diag::note_undef_method_impl);
  1293. continue;
  1294. } else {
  1295. ObjCMethodDecl *ImpMethodDecl =
  1296. IMPDecl->getInstanceMethod((*I)->getSelector());
  1297. ObjCMethodDecl *MethodDecl =
  1298. CDecl->getInstanceMethod((*I)->getSelector());
  1299. assert(MethodDecl &&
  1300. "MethodDecl is null in ImplMethodsVsClassMethods");
  1301. // ImpMethodDecl may be null as in a @dynamic property.
  1302. if (ImpMethodDecl) {
  1303. if (!WarnExactMatch)
  1304. WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl,
  1305. isa<ObjCProtocolDecl>(CDecl));
  1306. else
  1307. WarnExactTypedMethods(ImpMethodDecl, MethodDecl,
  1308. isa<ObjCProtocolDecl>(CDecl));
  1309. }
  1310. }
  1311. }
  1312. // Check and see if class methods in class interface have been
  1313. // implemented in the implementation class. If so, their types match.
  1314. for (ObjCInterfaceDecl::classmeth_iterator
  1315. I = CDecl->classmeth_begin(), E = CDecl->classmeth_end(); I != E; ++I) {
  1316. if (ClsMapSeen.count((*I)->getSelector()))
  1317. continue;
  1318. ClsMapSeen.insert((*I)->getSelector());
  1319. if (!ClsMap.count((*I)->getSelector())) {
  1320. if (ImmediateClass)
  1321. WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl,
  1322. diag::note_undef_method_impl);
  1323. } else {
  1324. ObjCMethodDecl *ImpMethodDecl =
  1325. IMPDecl->getClassMethod((*I)->getSelector());
  1326. ObjCMethodDecl *MethodDecl =
  1327. CDecl->getClassMethod((*I)->getSelector());
  1328. if (!WarnExactMatch)
  1329. WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl,
  1330. isa<ObjCProtocolDecl>(CDecl));
  1331. else
  1332. WarnExactTypedMethods(ImpMethodDecl, MethodDecl,
  1333. isa<ObjCProtocolDecl>(CDecl));
  1334. }
  1335. }
  1336. if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
  1337. // Also methods in class extensions need be looked at next.
  1338. for (const ObjCCategoryDecl *ClsExtDecl = I->getFirstClassExtension();
  1339. ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension())
  1340. MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
  1341. IMPDecl,
  1342. const_cast<ObjCCategoryDecl *>(ClsExtDecl),
  1343. IncompleteImpl, false, WarnExactMatch);
  1344. // Check for any implementation of a methods declared in protocol.
  1345. for (ObjCInterfaceDecl::all_protocol_iterator
  1346. PI = I->all_referenced_protocol_begin(),
  1347. E = I->all_referenced_protocol_end(); PI != E; ++PI)
  1348. MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
  1349. IMPDecl,
  1350. (*PI), IncompleteImpl, false, WarnExactMatch);
  1351. // FIXME. For now, we are not checking for extact match of methods
  1352. // in category implementation and its primary class's super class.
  1353. if (!WarnExactMatch && I->getSuperClass())
  1354. MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
  1355. IMPDecl,
  1356. I->getSuperClass(), IncompleteImpl, false);
  1357. }
  1358. }
  1359. /// MatchMethodsInClassAndOneProtocol - This routine goes thru list of methods
  1360. /// declared in the class, and its class extensions. For each method which is
  1361. /// also declared in one of its qualifying protocols, they must type match or
  1362. /// it issues a warning.
  1363. static void MatchMethodsInClassAndOneProtocol(Sema &S,
  1364. const ObjCContainerDecl *IDecl,
  1365. Sema::ProtocolsMethodsMap &InstMethodsInProtocols,
  1366. Sema::ProtocolsMethodsMap &ClsMethodsInProtocols) {
  1367. for (ObjCInterfaceDecl::instmeth_iterator IM = IDecl->instmeth_begin(),
  1368. E = IDecl->instmeth_end(); IM != E; ++IM) {
  1369. Selector Sel = (*IM)->getSelector();
  1370. if (ObjCMethodDecl *ProtoMethodDecl = InstMethodsInProtocols[Sel]) {
  1371. ObjCMethodDecl *ClsMethodDecl = (*IM);
  1372. S.WarnConflictingTypedMethods(ClsMethodDecl,
  1373. ProtoMethodDecl, true, true);
  1374. }
  1375. }
  1376. for (ObjCInterfaceDecl::classmeth_iterator IM = IDecl->classmeth_begin(),
  1377. E = IDecl->classmeth_end(); IM != E; ++IM) {
  1378. Selector Sel = (*IM)->getSelector();
  1379. if (ObjCMethodDecl *ProtoMethodDecl = ClsMethodsInProtocols[Sel]) {
  1380. ObjCMethodDecl *ClsMethodDecl = (*IM);
  1381. S.WarnConflictingTypedMethods(ClsMethodDecl,
  1382. ProtoMethodDecl, true, true);
  1383. }
  1384. }
  1385. if (const ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl>(IDecl)) {
  1386. for (const ObjCCategoryDecl *ClsExtDecl = I->getFirstClassExtension();
  1387. ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension())
  1388. MatchMethodsInClassAndOneProtocol(S, ClsExtDecl, InstMethodsInProtocols,
  1389. ClsMethodsInProtocols);
  1390. }
  1391. }
  1392. /// CollectMethodsInProtocols - This routine collects all methods declared
  1393. /// in class's list and nested qualified protocols. Instance methods and
  1394. /// class methods have separate containers as they have identical selectors.
  1395. static void CollectMethodsInProtocols(const ObjCContainerDecl *ContDecl,
  1396. Sema::ProtocolsMethodsMap &InstMethodsInProtocols,
  1397. Sema::ProtocolsMethodsMap &ClsMethodsInProtocols) {
  1398. if (const ObjCInterfaceDecl *CDecl = dyn_cast<ObjCInterfaceDecl>(ContDecl)) {
  1399. for (ObjCInterfaceDecl::all_protocol_iterator
  1400. PI = CDecl->all_referenced_protocol_begin(),
  1401. E = CDecl->all_referenced_protocol_end(); PI != E; ++PI) {
  1402. ObjCProtocolDecl *PDecl = (*PI);
  1403. for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
  1404. E = PDecl->instmeth_end(); I != E; ++I) {
  1405. ObjCMethodDecl *method = *I;
  1406. ObjCMethodDecl *&ProtocolEntry =
  1407. InstMethodsInProtocols[method->getSelector()];
  1408. if (!ProtocolEntry)
  1409. ProtocolEntry = method;
  1410. }
  1411. for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
  1412. E = PDecl->classmeth_end(); I != E; ++I) {
  1413. ObjCMethodDecl *method = *I;
  1414. ObjCMethodDecl *&ProtocolEntry =
  1415. ClsMethodsInProtocols[method->getSelector()];
  1416. if (!ProtocolEntry)
  1417. ProtocolEntry = method;
  1418. }
  1419. for (ObjCProtocolDecl::protocol_iterator P = PDecl->protocol_begin(),
  1420. PE = PDecl->protocol_end(); P != PE; ++P)
  1421. CollectMethodsInProtocols(*P, InstMethodsInProtocols,
  1422. ClsMethodsInProtocols);
  1423. }
  1424. if (CDecl->getSuperClass())
  1425. CollectMethodsInProtocols(CDecl->getSuperClass(), InstMethodsInProtocols,
  1426. ClsMethodsInProtocols);
  1427. }
  1428. if (const ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(ContDecl)) {
  1429. for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
  1430. E = PDecl->instmeth_end(); I != E; ++I) {
  1431. ObjCMethodDecl *method = *I;
  1432. ObjCMethodDecl *&ProtocolEntry =
  1433. InstMethodsInProtocols[method->getSelector()];
  1434. if (!ProtocolEntry)
  1435. ProtocolEntry = method;
  1436. }
  1437. for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
  1438. E = PDecl->classmeth_end(); I != E; ++I) {
  1439. ObjCMethodDecl *method = *I;
  1440. ObjCMethodDecl *&ProtocolEntry =
  1441. ClsMethodsInProtocols[method->getSelector()];
  1442. if (!ProtocolEntry)
  1443. ProtocolEntry = method;
  1444. }
  1445. }
  1446. }
  1447. /// MatchMethodsInClassAndItsProtocol - Check that any redeclaration of
  1448. /// method in protocol in its qualified class match in their type and
  1449. /// issue warnings otherwise.
  1450. void Sema::MatchMethodsInClassAndItsProtocol(const ObjCInterfaceDecl *CDecl) {
  1451. ProtocolsMethodsMap InstMethodsInProtocols, ClsMethodsInProtocols;
  1452. CollectMethodsInProtocols(CDecl, InstMethodsInProtocols,
  1453. ClsMethodsInProtocols);
  1454. if (InstMethodsInProtocols.empty() && ClsMethodsInProtocols.empty())
  1455. return;
  1456. MatchMethodsInClassAndOneProtocol(*this, CDecl, InstMethodsInProtocols,
  1457. ClsMethodsInProtocols);
  1458. }
  1459. /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
  1460. /// category matches with those implemented in its primary class and
  1461. /// warns each time an exact match is found.
  1462. void Sema::CheckCategoryVsClassMethodMatches(
  1463. ObjCCategoryImplDecl *CatIMPDecl) {
  1464. llvm::DenseSet<Selector> InsMap, ClsMap;
  1465. for (ObjCImplementationDecl::instmeth_iterator
  1466. I = CatIMPDecl->instmeth_begin(),
  1467. E = CatIMPDecl->instmeth_end(); I!=E; ++I)
  1468. InsMap.insert((*I)->getSelector());
  1469. for (ObjCImplementationDecl::classmeth_iterator
  1470. I = CatIMPDecl->classmeth_begin(),
  1471. E = CatIMPDecl->classmeth_end(); I != E; ++I)
  1472. ClsMap.insert((*I)->getSelector());
  1473. if (InsMap.empty() && ClsMap.empty())
  1474. return;
  1475. // Get category's primary class.
  1476. ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
  1477. if (!CatDecl)
  1478. return;
  1479. ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
  1480. if (!IDecl)
  1481. return;
  1482. llvm::DenseSet<Selector> InsMapSeen, ClsMapSeen;
  1483. bool IncompleteImpl = false;
  1484. MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
  1485. CatIMPDecl, IDecl,
  1486. IncompleteImpl, false, true /*WarnExactMatch*/);
  1487. }
  1488. void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
  1489. ObjCContainerDecl* CDecl,
  1490. bool IncompleteImpl) {
  1491. llvm::DenseSet<Selector> InsMap;
  1492. // Check and see if instance methods in class interface have been
  1493. // implemented in the implementation class.
  1494. for (ObjCImplementationDecl::instmeth_iterator
  1495. I = IMPDecl->instmeth_begin(), E = IMPDecl->instmeth_end(); I!=E; ++I)
  1496. InsMap.insert((*I)->getSelector());
  1497. // Check and see if properties declared in the interface have either 1)
  1498. // an implementation or 2) there is a @synthesize/@dynamic implementation
  1499. // of the property in the @implementation.
  1500. if (isa<ObjCInterfaceDecl>(CDecl) &&
  1501. !(LangOpts.ObjCDefaultSynthProperties && LangOpts.ObjCNonFragileABI2))
  1502. DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, InsMap);
  1503. llvm::DenseSet<Selector> ClsMap;
  1504. for (ObjCImplementationDecl::classmeth_iterator
  1505. I = IMPDecl->classmeth_begin(),
  1506. E = IMPDecl->classmeth_end(); I != E; ++I)
  1507. ClsMap.insert((*I)->getSelector());
  1508. // Check for type conflict of methods declared in a class/protocol and
  1509. // its implementation; if any.
  1510. llvm::DenseSet<Selector> InsMapSeen, ClsMapSeen;
  1511. MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
  1512. IMPDecl, CDecl,
  1513. IncompleteImpl, true);
  1514. // Check for any type mismtch of methods declared in class
  1515. // and methods declared in protocol. Do this only when the class
  1516. // is being implementaed.
  1517. if (isa<ObjCImplementationDecl>(IMPDecl))
  1518. if (const ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl>(CDecl))
  1519. MatchMethodsInClassAndItsProtocol(I);
  1520. // check all methods implemented in category against those declared
  1521. // in its primary class.
  1522. if (ObjCCategoryImplDecl *CatDecl =
  1523. dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
  1524. CheckCategoryVsClassMethodMatches(CatDecl);
  1525. // Check the protocol list for unimplemented methods in the @implementation
  1526. // class.
  1527. // Check and see if class methods in class interface have been
  1528. // implemented in the implementation class.
  1529. if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
  1530. for (ObjCInterfaceDecl::all_protocol_iterator
  1531. PI = I->all_referenced_protocol_begin(),
  1532. E = I->all_referenced_protocol_end(); PI != E; ++PI)
  1533. CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
  1534. InsMap, ClsMap, I);
  1535. // Check class extensions (unnamed categories)
  1536. for (const ObjCCategoryDecl *Categories = I->getFirstClassExtension();
  1537. Categories; Categories = Categories->getNextClassExtension())
  1538. ImplMethodsVsClassMethods(S, IMPDecl,
  1539. const_cast<ObjCCategoryDecl*>(Categories),
  1540. IncompleteImpl);
  1541. } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
  1542. // For extended class, unimplemented methods in its protocols will
  1543. // be reported in the primary class.
  1544. if (!C->IsClassExtension()) {
  1545. for (ObjCCategoryDecl::protocol_iterator PI = C->protocol_begin(),
  1546. E = C->protocol_end(); PI != E; ++PI)
  1547. CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
  1548. InsMap, ClsMap, CDecl);
  1549. // Report unimplemented properties in the category as well.
  1550. // When reporting on missing setter/getters, do not report when
  1551. // setter/getter is implemented in category's primary class
  1552. // implementation.
  1553. if (ObjCInterfaceDecl *ID = C->getClassInterface())
  1554. if (ObjCImplDecl *IMP = ID->getImplementation()) {
  1555. for (ObjCImplementationDecl::instmeth_iterator
  1556. I = IMP->instmeth_begin(), E = IMP->instmeth_end(); I!=E; ++I)
  1557. InsMap.insert((*I)->getSelector());
  1558. }
  1559. DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, InsMap);
  1560. }
  1561. } else
  1562. assert(false && "invalid ObjCContainerDecl type.");
  1563. }
  1564. /// ActOnForwardClassDeclaration -
  1565. Decl *
  1566. Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
  1567. IdentifierInfo **IdentList,
  1568. SourceLocation *IdentLocs,
  1569. unsigned NumElts) {
  1570. SmallVector<ObjCInterfaceDecl*, 32> Interfaces;
  1571. for (unsigned i = 0; i != NumElts; ++i) {
  1572. // Check for another declaration kind with the same name.
  1573. NamedDecl *PrevDecl
  1574. = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
  1575. LookupOrdinaryName, ForRedeclaration);
  1576. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  1577. // Maybe we will complain about the shadowed template parameter.
  1578. DiagnoseTemplateParameterShadow(AtClassLoc, PrevDecl);
  1579. // Just pretend that we didn't see the previous declaration.
  1580. PrevDecl = 0;
  1581. }
  1582. if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
  1583. // GCC apparently allows the following idiom:
  1584. //
  1585. // typedef NSObject < XCElementTogglerP > XCElementToggler;
  1586. // @class XCElementToggler;
  1587. //
  1588. // FIXME: Make an extension?
  1589. TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
  1590. if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
  1591. Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
  1592. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  1593. } else {
  1594. // a forward class declaration matching a typedef name of a class refers
  1595. // to the underlying class.
  1596. if (const ObjCObjectType *OI =
  1597. TDD->getUnderlyingType()->getAs<ObjCObjectType>())
  1598. PrevDecl = OI->getInterface();
  1599. }
  1600. }
  1601. ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
  1602. if (!IDecl) { // Not already seen? Make a forward decl.
  1603. IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
  1604. IdentList[i], IdentLocs[i], true);
  1605. // Push the ObjCInterfaceDecl on the scope chain but do *not* add it to
  1606. // the current DeclContext. This prevents clients that walk DeclContext
  1607. // from seeing the imaginary ObjCInterfaceDecl until it is actually
  1608. // declared later (if at all). We also take care to explicitly make
  1609. // sure this declaration is visible for name lookup.
  1610. PushOnScopeChains(IDecl, TUScope, false);
  1611. CurContext->makeDeclVisibleInContext(IDecl, true);
  1612. }
  1613. Interfaces.push_back(IDecl);
  1614. }
  1615. assert(Interfaces.size() == NumElts);
  1616. ObjCClassDecl *CDecl = ObjCClassDecl::Create(Context, CurContext, AtClassLoc,
  1617. Interfaces.data(), IdentLocs,
  1618. Interfaces.size());
  1619. CurContext->addDecl(CDecl);
  1620. CheckObjCDeclScope(CDecl);
  1621. return CDecl;
  1622. }
  1623. static bool tryMatchRecordTypes(ASTContext &Context,
  1624. Sema::MethodMatchStrategy strategy,
  1625. const Type *left, const Type *right);
  1626. static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
  1627. QualType leftQT, QualType rightQT) {
  1628. const Type *left =
  1629. Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
  1630. const Type *right =
  1631. Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
  1632. if (left == right) return true;
  1633. // If we're doing a strict match, the types have to match exactly.
  1634. if (strategy == Sema::MMS_strict) return false;
  1635. if (left->isIncompleteType() || right->isIncompleteType()) return false;
  1636. // Otherwise, use this absurdly complicated algorithm to try to
  1637. // validate the basic, low-level compatibility of the two types.
  1638. // As a minimum, require the sizes and alignments to match.
  1639. if (Context.getTypeInfo(left) != Context.getTypeInfo(right))
  1640. return false;
  1641. // Consider all the kinds of non-dependent canonical types:
  1642. // - functions and arrays aren't possible as return and parameter types
  1643. // - vector types of equal size can be arbitrarily mixed
  1644. if (isa<VectorType>(left)) return isa<VectorType>(right);
  1645. if (isa<VectorType>(right)) return false;
  1646. // - references should only match references of identical type
  1647. // - structs, unions, and Objective-C objects must match more-or-less
  1648. // exactly
  1649. // - everything else should be a scalar
  1650. if (!left->isScalarType() || !right->isScalarType())
  1651. return tryMatchRecordTypes(Context, strategy, left, right);
  1652. // Make scalars agree in kind, except count bools as chars.
  1653. Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
  1654. Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
  1655. if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
  1656. if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
  1657. // Note that data member pointers and function member pointers don't
  1658. // intermix because of the size differences.
  1659. return (leftSK == rightSK);
  1660. }
  1661. static bool tryMatchRecordTypes(ASTContext &Context,
  1662. Sema::MethodMatchStrategy strategy,
  1663. const Type *lt, const Type *rt) {
  1664. assert(lt && rt && lt != rt);
  1665. if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
  1666. RecordDecl *left = cast<RecordType>(lt)->getDecl();
  1667. RecordDecl *right = cast<RecordType>(rt)->getDecl();
  1668. // Require union-hood to match.
  1669. if (left->isUnion() != right->isUnion()) return false;
  1670. // Require an exact match if either is non-POD.
  1671. if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
  1672. (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
  1673. return false;
  1674. // Require size and alignment to match.
  1675. if (Context.getTypeInfo(lt) != Context.getTypeInfo(rt)) return false;
  1676. // Require fields to match.
  1677. RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
  1678. RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
  1679. for (; li != le && ri != re; ++li, ++ri) {
  1680. if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
  1681. return false;
  1682. }
  1683. return (li == le && ri == re);
  1684. }
  1685. /// MatchTwoMethodDeclarations - Checks that two methods have matching type and
  1686. /// returns true, or false, accordingly.
  1687. /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
  1688. bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
  1689. const ObjCMethodDecl *right,
  1690. MethodMatchStrategy strategy) {
  1691. if (!matchTypes(Context, strategy,
  1692. left->getResultType(), right->getResultType()))
  1693. return false;
  1694. if (getLangOptions().ObjCAutoRefCount &&
  1695. (left->hasAttr<NSReturnsRetainedAttr>()
  1696. != right->hasAttr<NSReturnsRetainedAttr>() ||
  1697. left->hasAttr<NSConsumesSelfAttr>()
  1698. != right->hasAttr<NSConsumesSelfAttr>()))
  1699. return false;
  1700. ObjCMethodDecl::param_iterator
  1701. li = left->param_begin(), le = left->param_end(), ri = right->param_begin();
  1702. for (; li != le; ++li, ++ri) {
  1703. assert(ri != right->param_end() && "Param mismatch");
  1704. ParmVarDecl *lparm = *li, *rparm = *ri;
  1705. if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
  1706. return false;
  1707. if (getLangOptions().ObjCAutoRefCount &&
  1708. lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
  1709. return false;
  1710. }
  1711. return true;
  1712. }
  1713. /// \brief Read the contents of the method pool for a given selector from
  1714. /// external storage.
  1715. ///
  1716. /// This routine should only be called once, when the method pool has no entry
  1717. /// for this selector.
  1718. Sema::GlobalMethodPool::iterator Sema::ReadMethodPool(Selector Sel) {
  1719. assert(ExternalSource && "We need an external AST source");
  1720. assert(MethodPool.find(Sel) == MethodPool.end() &&
  1721. "Selector data already loaded into the method pool");
  1722. // Read the method list from the external source.
  1723. GlobalMethods Methods = ExternalSource->ReadMethodPool(Sel);
  1724. return MethodPool.insert(std::make_pair(Sel, Methods)).first;
  1725. }
  1726. void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
  1727. bool instance) {
  1728. GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
  1729. if (Pos == MethodPool.end()) {
  1730. if (ExternalSource)
  1731. Pos = ReadMethodPool(Method->getSelector());
  1732. else
  1733. Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
  1734. GlobalMethods())).first;
  1735. }
  1736. Method->setDefined(impl);
  1737. ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
  1738. if (Entry.Method == 0) {
  1739. // Haven't seen a method with this selector name yet - add it.
  1740. Entry.Method = Method;
  1741. Entry.Next = 0;
  1742. return;
  1743. }
  1744. // We've seen a method with this name, see if we have already seen this type
  1745. // signature.
  1746. for (ObjCMethodList *List = &Entry; List; List = List->Next) {
  1747. bool match = MatchTwoMethodDeclarations(Method, List->Method);
  1748. if (match) {
  1749. ObjCMethodDecl *PrevObjCMethod = List->Method;
  1750. PrevObjCMethod->setDefined(impl);
  1751. // If a method is deprecated, push it in the global pool.
  1752. // This is used for better diagnostics.
  1753. if (Method->isDeprecated()) {
  1754. if (!PrevObjCMethod->isDeprecated())
  1755. List->Method = Method;
  1756. }
  1757. // If new method is unavailable, push it into global pool
  1758. // unless previous one is deprecated.
  1759. if (Method->isUnavailable()) {
  1760. if (PrevObjCMethod->getAvailability() < AR_Deprecated)
  1761. List->Method = Method;
  1762. }
  1763. return;
  1764. }
  1765. }
  1766. // We have a new signature for an existing method - add it.
  1767. // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
  1768. ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
  1769. Entry.Next = new (Mem) ObjCMethodList(Method, Entry.Next);
  1770. }
  1771. /// Determines if this is an "acceptable" loose mismatch in the global
  1772. /// method pool. This exists mostly as a hack to get around certain
  1773. /// global mismatches which we can't afford to make warnings / errors.
  1774. /// Really, what we want is a way to take a method out of the global
  1775. /// method pool.
  1776. static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
  1777. ObjCMethodDecl *other) {
  1778. if (!chosen->isInstanceMethod())
  1779. return false;
  1780. Selector sel = chosen->getSelector();
  1781. if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
  1782. return false;
  1783. // Don't complain about mismatches for -length if the method we
  1784. // chose has an integral result type.
  1785. return (chosen->getResultType()->isIntegerType());
  1786. }
  1787. ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
  1788. bool receiverIdOrClass,
  1789. bool warn, bool instance) {
  1790. GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
  1791. if (Pos == MethodPool.end()) {
  1792. if (ExternalSource)
  1793. Pos = ReadMethodPool(Sel);
  1794. else
  1795. return 0;
  1796. }
  1797. ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
  1798. if (warn && MethList.Method && MethList.Next) {
  1799. bool issueDiagnostic = false, issueError = false;
  1800. // We support a warning which complains about *any* difference in
  1801. // method signature.
  1802. bool strictSelectorMatch =
  1803. (receiverIdOrClass && warn &&
  1804. (Diags.getDiagnosticLevel(diag::warn_strict_multiple_method_decl,
  1805. R.getBegin()) !=
  1806. Diagnostic::Ignored));
  1807. if (strictSelectorMatch)
  1808. for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next) {
  1809. if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method,
  1810. MMS_strict)) {
  1811. issueDiagnostic = true;
  1812. break;
  1813. }
  1814. }
  1815. // If we didn't see any strict differences, we won't see any loose
  1816. // differences. In ARC, however, we also need to check for loose
  1817. // mismatches, because most of them are errors.
  1818. if (!strictSelectorMatch ||
  1819. (issueDiagnostic && getLangOptions().ObjCAutoRefCount))
  1820. for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next) {
  1821. // This checks if the methods differ in type mismatch.
  1822. if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method,
  1823. MMS_loose) &&
  1824. !isAcceptableMethodMismatch(MethList.Method, Next->Method)) {
  1825. issueDiagnostic = true;
  1826. if (getLangOptions().ObjCAutoRefCount)
  1827. issueError = true;
  1828. break;
  1829. }
  1830. }
  1831. if (issueDiagnostic) {
  1832. if (issueError)
  1833. Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
  1834. else if (strictSelectorMatch)
  1835. Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
  1836. else
  1837. Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
  1838. Diag(MethList.Method->getLocStart(),
  1839. issueError ? diag::note_possibility : diag::note_using)
  1840. << MethList.Method->getSourceRange();
  1841. for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
  1842. Diag(Next->Method->getLocStart(), diag::note_also_found)
  1843. << Next->Method->getSourceRange();
  1844. }
  1845. }
  1846. return MethList.Method;
  1847. }
  1848. ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
  1849. GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
  1850. if (Pos == MethodPool.end())
  1851. return 0;
  1852. GlobalMethods &Methods = Pos->second;
  1853. if (Methods.first.Method && Methods.first.Method->isDefined())
  1854. return Methods.first.Method;
  1855. if (Methods.second.Method && Methods.second.Method->isDefined())
  1856. return Methods.second.Method;
  1857. return 0;
  1858. }
  1859. /// CompareMethodParamsInBaseAndSuper - This routine compares methods with
  1860. /// identical selector names in current and its super classes and issues
  1861. /// a warning if any of their argument types are incompatible.
  1862. void Sema::CompareMethodParamsInBaseAndSuper(Decl *ClassDecl,
  1863. ObjCMethodDecl *Method,
  1864. bool IsInstance) {
  1865. ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
  1866. if (ID == 0) return;
  1867. while (ObjCInterfaceDecl *SD = ID->getSuperClass()) {
  1868. ObjCMethodDecl *SuperMethodDecl =
  1869. SD->lookupMethod(Method->getSelector(), IsInstance);
  1870. if (SuperMethodDecl == 0) {
  1871. ID = SD;
  1872. continue;
  1873. }
  1874. ObjCMethodDecl::param_iterator ParamI = Method->param_begin(),
  1875. E = Method->param_end();
  1876. ObjCMethodDecl::param_iterator PrevI = SuperMethodDecl->param_begin();
  1877. for (; ParamI != E; ++ParamI, ++PrevI) {
  1878. // Number of parameters are the same and is guaranteed by selector match.
  1879. assert(PrevI != SuperMethodDecl->param_end() && "Param mismatch");
  1880. QualType T1 = Context.getCanonicalType((*ParamI)->getType());
  1881. QualType T2 = Context.getCanonicalType((*PrevI)->getType());
  1882. // If type of argument of method in this class does not match its
  1883. // respective argument type in the super class method, issue warning;
  1884. if (!Context.typesAreCompatible(T1, T2)) {
  1885. Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
  1886. << T1 << T2;
  1887. Diag(SuperMethodDecl->getLocation(), diag::note_previous_declaration);
  1888. return;
  1889. }
  1890. }
  1891. ID = SD;
  1892. }
  1893. }
  1894. /// DiagnoseDuplicateIvars -
  1895. /// Check for duplicate ivars in the entire class at the start of
  1896. /// @implementation. This becomes necesssary because class extension can
  1897. /// add ivars to a class in random order which will not be known until
  1898. /// class's @implementation is seen.
  1899. void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
  1900. ObjCInterfaceDecl *SID) {
  1901. for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
  1902. IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
  1903. ObjCIvarDecl* Ivar = (*IVI);
  1904. if (Ivar->isInvalidDecl())
  1905. continue;
  1906. if (IdentifierInfo *II = Ivar->getIdentifier()) {
  1907. ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
  1908. if (prevIvar) {
  1909. Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
  1910. Diag(prevIvar->getLocation(), diag::note_previous_declaration);
  1911. Ivar->setInvalidDecl();
  1912. }
  1913. }
  1914. }
  1915. }
  1916. // Note: For class/category implemenations, allMethods/allProperties is
  1917. // always null.
  1918. void Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd,
  1919. Decl *ClassDecl,
  1920. Decl **allMethods, unsigned allNum,
  1921. Decl **allProperties, unsigned pNum,
  1922. DeclGroupPtrTy *allTUVars, unsigned tuvNum) {
  1923. // FIXME: If we don't have a ClassDecl, we have an error. We should consider
  1924. // always passing in a decl. If the decl has an error, isInvalidDecl()
  1925. // should be true.
  1926. if (!ClassDecl)
  1927. return;
  1928. bool isInterfaceDeclKind =
  1929. isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
  1930. || isa<ObjCProtocolDecl>(ClassDecl);
  1931. bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
  1932. if (!isInterfaceDeclKind && AtEnd.isInvalid()) {
  1933. // FIXME: This is wrong. We shouldn't be pretending that there is
  1934. // an '@end' in the declaration.
  1935. SourceLocation L = ClassDecl->getLocation();
  1936. AtEnd.setBegin(L);
  1937. AtEnd.setEnd(L);
  1938. Diag(L, diag::err_missing_atend);
  1939. }
  1940. // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
  1941. llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
  1942. llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
  1943. for (unsigned i = 0; i < allNum; i++ ) {
  1944. ObjCMethodDecl *Method =
  1945. cast_or_null<ObjCMethodDecl>(allMethods[i]);
  1946. if (!Method) continue; // Already issued a diagnostic.
  1947. if (Method->isInstanceMethod()) {
  1948. /// Check for instance method of the same name with incompatible types
  1949. const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
  1950. bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
  1951. : false;
  1952. if ((isInterfaceDeclKind && PrevMethod && !match)
  1953. || (checkIdenticalMethods && match)) {
  1954. Diag(Method->getLocation(), diag::err_duplicate_method_decl)
  1955. << Method->getDeclName();
  1956. Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
  1957. Method->setInvalidDecl();
  1958. } else {
  1959. InsMap[Method->getSelector()] = Method;
  1960. /// The following allows us to typecheck messages to "id".
  1961. AddInstanceMethodToGlobalPool(Method);
  1962. // verify that the instance method conforms to the same definition of
  1963. // parent methods if it shadows one.
  1964. CompareMethodParamsInBaseAndSuper(ClassDecl, Method, true);
  1965. }
  1966. } else {
  1967. /// Check for class method of the same name with incompatible types
  1968. const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
  1969. bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
  1970. : false;
  1971. if ((isInterfaceDeclKind && PrevMethod && !match)
  1972. || (checkIdenticalMethods && match)) {
  1973. Diag(Method->getLocation(), diag::err_duplicate_method_decl)
  1974. << Method->getDeclName();
  1975. Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
  1976. Method->setInvalidDecl();
  1977. } else {
  1978. ClsMap[Method->getSelector()] = Method;
  1979. /// The following allows us to typecheck messages to "Class".
  1980. AddFactoryMethodToGlobalPool(Method);
  1981. // verify that the class method conforms to the same definition of
  1982. // parent methods if it shadows one.
  1983. CompareMethodParamsInBaseAndSuper(ClassDecl, Method, false);
  1984. }
  1985. }
  1986. }
  1987. if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
  1988. // Compares properties declared in this class to those of its
  1989. // super class.
  1990. ComparePropertiesInBaseAndSuper(I);
  1991. CompareProperties(I, I);
  1992. } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
  1993. // Categories are used to extend the class by declaring new methods.
  1994. // By the same token, they are also used to add new properties. No
  1995. // need to compare the added property to those in the class.
  1996. // Compare protocol properties with those in category
  1997. CompareProperties(C, C);
  1998. if (C->IsClassExtension()) {
  1999. ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
  2000. DiagnoseClassExtensionDupMethods(C, CCPrimary);
  2001. }
  2002. }
  2003. if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
  2004. if (CDecl->getIdentifier())
  2005. // ProcessPropertyDecl is responsible for diagnosing conflicts with any
  2006. // user-defined setter/getter. It also synthesizes setter/getter methods
  2007. // and adds them to the DeclContext and global method pools.
  2008. for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
  2009. E = CDecl->prop_end();
  2010. I != E; ++I)
  2011. ProcessPropertyDecl(*I, CDecl);
  2012. CDecl->setAtEndRange(AtEnd);
  2013. }
  2014. if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
  2015. IC->setAtEndRange(AtEnd);
  2016. if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
  2017. // Any property declared in a class extension might have user
  2018. // declared setter or getter in current class extension or one
  2019. // of the other class extensions. Mark them as synthesized as
  2020. // property will be synthesized when property with same name is
  2021. // seen in the @implementation.
  2022. for (const ObjCCategoryDecl *ClsExtDecl =
  2023. IDecl->getFirstClassExtension();
  2024. ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
  2025. for (ObjCContainerDecl::prop_iterator I = ClsExtDecl->prop_begin(),
  2026. E = ClsExtDecl->prop_end(); I != E; ++I) {
  2027. ObjCPropertyDecl *Property = (*I);
  2028. // Skip over properties declared @dynamic
  2029. if (const ObjCPropertyImplDecl *PIDecl
  2030. = IC->FindPropertyImplDecl(Property->getIdentifier()))
  2031. if (PIDecl->getPropertyImplementation()
  2032. == ObjCPropertyImplDecl::Dynamic)
  2033. continue;
  2034. for (const ObjCCategoryDecl *CExtDecl =
  2035. IDecl->getFirstClassExtension();
  2036. CExtDecl; CExtDecl = CExtDecl->getNextClassExtension()) {
  2037. if (ObjCMethodDecl *GetterMethod =
  2038. CExtDecl->getInstanceMethod(Property->getGetterName()))
  2039. GetterMethod->setSynthesized(true);
  2040. if (!Property->isReadOnly())
  2041. if (ObjCMethodDecl *SetterMethod =
  2042. CExtDecl->getInstanceMethod(Property->getSetterName()))
  2043. SetterMethod->setSynthesized(true);
  2044. }
  2045. }
  2046. }
  2047. if (LangOpts.ObjCDefaultSynthProperties &&
  2048. LangOpts.ObjCNonFragileABI2)
  2049. DefaultSynthesizeProperties(S, IC, IDecl);
  2050. ImplMethodsVsClassMethods(S, IC, IDecl);
  2051. AtomicPropertySetterGetterRules(IC, IDecl);
  2052. DiagnoseOwningPropertyGetterSynthesis(IC);
  2053. if (LangOpts.ObjCNonFragileABI2)
  2054. while (IDecl->getSuperClass()) {
  2055. DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
  2056. IDecl = IDecl->getSuperClass();
  2057. }
  2058. }
  2059. SetIvarInitializers(IC);
  2060. } else if (ObjCCategoryImplDecl* CatImplClass =
  2061. dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
  2062. CatImplClass->setAtEndRange(AtEnd);
  2063. // Find category interface decl and then check that all methods declared
  2064. // in this interface are implemented in the category @implementation.
  2065. if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
  2066. for (ObjCCategoryDecl *Categories = IDecl->getCategoryList();
  2067. Categories; Categories = Categories->getNextClassCategory()) {
  2068. if (Categories->getIdentifier() == CatImplClass->getIdentifier()) {
  2069. ImplMethodsVsClassMethods(S, CatImplClass, Categories);
  2070. break;
  2071. }
  2072. }
  2073. }
  2074. }
  2075. if (isInterfaceDeclKind) {
  2076. // Reject invalid vardecls.
  2077. for (unsigned i = 0; i != tuvNum; i++) {
  2078. DeclGroupRef DG = allTUVars[i].getAsVal<DeclGroupRef>();
  2079. for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
  2080. if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
  2081. if (!VDecl->hasExternalStorage())
  2082. Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
  2083. }
  2084. }
  2085. }
  2086. }
  2087. /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
  2088. /// objective-c's type qualifier from the parser version of the same info.
  2089. static Decl::ObjCDeclQualifier
  2090. CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
  2091. return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
  2092. }
  2093. static inline
  2094. bool containsInvalidMethodImplAttribute(const AttrVec &A) {
  2095. // The 'ibaction' attribute is allowed on method definitions because of
  2096. // how the IBAction macro is used on both method declarations and definitions.
  2097. // If the method definitions contains any other attributes, return true.
  2098. for (AttrVec::const_iterator i = A.begin(), e = A.end(); i != e; ++i)
  2099. if ((*i)->getKind() != attr::IBAction)
  2100. return true;
  2101. return false;
  2102. }
  2103. /// \brief Check whether the declared result type of the given Objective-C
  2104. /// method declaration is compatible with the method's class.
  2105. ///
  2106. static bool
  2107. CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
  2108. ObjCInterfaceDecl *CurrentClass) {
  2109. QualType ResultType = Method->getResultType();
  2110. SourceRange ResultTypeRange;
  2111. if (const TypeSourceInfo *ResultTypeInfo = Method->getResultTypeSourceInfo())
  2112. ResultTypeRange = ResultTypeInfo->getTypeLoc().getSourceRange();
  2113. // If an Objective-C method inherits its related result type, then its
  2114. // declared result type must be compatible with its own class type. The
  2115. // declared result type is compatible if:
  2116. if (const ObjCObjectPointerType *ResultObjectType
  2117. = ResultType->getAs<ObjCObjectPointerType>()) {
  2118. // - it is id or qualified id, or
  2119. if (ResultObjectType->isObjCIdType() ||
  2120. ResultObjectType->isObjCQualifiedIdType())
  2121. return false;
  2122. if (CurrentClass) {
  2123. if (ObjCInterfaceDecl *ResultClass
  2124. = ResultObjectType->getInterfaceDecl()) {
  2125. // - it is the same as the method's class type, or
  2126. if (CurrentClass == ResultClass)
  2127. return false;
  2128. // - it is a superclass of the method's class type
  2129. if (ResultClass->isSuperClassOf(CurrentClass))
  2130. return false;
  2131. }
  2132. }
  2133. }
  2134. return true;
  2135. }
  2136. namespace {
  2137. /// A helper class for searching for methods which a particular method
  2138. /// overrides.
  2139. class OverrideSearch {
  2140. Sema &S;
  2141. ObjCMethodDecl *Method;
  2142. llvm::SmallPtrSet<ObjCContainerDecl*, 8> Searched;
  2143. llvm::SmallPtrSet<ObjCMethodDecl*, 8> Overridden;
  2144. bool Recursive;
  2145. public:
  2146. OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
  2147. Selector selector = method->getSelector();
  2148. // Bypass this search if we've never seen an instance/class method
  2149. // with this selector before.
  2150. Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
  2151. if (it == S.MethodPool.end()) {
  2152. if (!S.ExternalSource) return;
  2153. it = S.ReadMethodPool(selector);
  2154. }
  2155. ObjCMethodList &list =
  2156. method->isInstanceMethod() ? it->second.first : it->second.second;
  2157. if (!list.Method) return;
  2158. ObjCContainerDecl *container
  2159. = cast<ObjCContainerDecl>(method->getDeclContext());
  2160. // Prevent the search from reaching this container again. This is
  2161. // important with categories, which override methods from the
  2162. // interface and each other.
  2163. Searched.insert(container);
  2164. searchFromContainer(container);
  2165. }
  2166. typedef llvm::SmallPtrSet<ObjCMethodDecl*,8>::iterator iterator;
  2167. iterator begin() const { return Overridden.begin(); }
  2168. iterator end() const { return Overridden.end(); }
  2169. private:
  2170. void searchFromContainer(ObjCContainerDecl *container) {
  2171. if (container->isInvalidDecl()) return;
  2172. switch (container->getDeclKind()) {
  2173. #define OBJCCONTAINER(type, base) \
  2174. case Decl::type: \
  2175. searchFrom(cast<type##Decl>(container)); \
  2176. break;
  2177. #define ABSTRACT_DECL(expansion)
  2178. #define DECL(type, base) \
  2179. case Decl::type:
  2180. #include "clang/AST/DeclNodes.inc"
  2181. llvm_unreachable("not an ObjC container!");
  2182. }
  2183. }
  2184. void searchFrom(ObjCProtocolDecl *protocol) {
  2185. // A method in a protocol declaration overrides declarations from
  2186. // referenced ("parent") protocols.
  2187. search(protocol->getReferencedProtocols());
  2188. }
  2189. void searchFrom(ObjCCategoryDecl *category) {
  2190. // A method in a category declaration overrides declarations from
  2191. // the main class and from protocols the category references.
  2192. search(category->getClassInterface());
  2193. search(category->getReferencedProtocols());
  2194. }
  2195. void searchFrom(ObjCCategoryImplDecl *impl) {
  2196. // A method in a category definition that has a category
  2197. // declaration overrides declarations from the category
  2198. // declaration.
  2199. if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
  2200. search(category);
  2201. // Otherwise it overrides declarations from the class.
  2202. } else {
  2203. search(impl->getClassInterface());
  2204. }
  2205. }
  2206. void searchFrom(ObjCInterfaceDecl *iface) {
  2207. // A method in a class declaration overrides declarations from
  2208. // - categories,
  2209. for (ObjCCategoryDecl *category = iface->getCategoryList();
  2210. category; category = category->getNextClassCategory())
  2211. search(category);
  2212. // - the super class, and
  2213. if (ObjCInterfaceDecl *super = iface->getSuperClass())
  2214. search(super);
  2215. // - any referenced protocols.
  2216. search(iface->getReferencedProtocols());
  2217. }
  2218. void searchFrom(ObjCImplementationDecl *impl) {
  2219. // A method in a class implementation overrides declarations from
  2220. // the class interface.
  2221. search(impl->getClassInterface());
  2222. }
  2223. void search(const ObjCProtocolList &protocols) {
  2224. for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
  2225. i != e; ++i)
  2226. search(*i);
  2227. }
  2228. void search(ObjCContainerDecl *container) {
  2229. // Abort if we've already searched this container.
  2230. if (!Searched.insert(container)) return;
  2231. // Check for a method in this container which matches this selector.
  2232. ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
  2233. Method->isInstanceMethod());
  2234. // If we find one, record it and bail out.
  2235. if (meth) {
  2236. Overridden.insert(meth);
  2237. return;
  2238. }
  2239. // Otherwise, search for methods that a hypothetical method here
  2240. // would have overridden.
  2241. // Note that we're now in a recursive case.
  2242. Recursive = true;
  2243. searchFromContainer(container);
  2244. }
  2245. };
  2246. }
  2247. Decl *Sema::ActOnMethodDeclaration(
  2248. Scope *S,
  2249. SourceLocation MethodLoc, SourceLocation EndLoc,
  2250. tok::TokenKind MethodType, Decl *ClassDecl,
  2251. ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
  2252. SourceLocation SelectorStartLoc,
  2253. Selector Sel,
  2254. // optional arguments. The number of types/arguments is obtained
  2255. // from the Sel.getNumArgs().
  2256. ObjCArgInfo *ArgInfo,
  2257. DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
  2258. AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
  2259. bool isVariadic, bool MethodDefinition) {
  2260. // Make sure we can establish a context for the method.
  2261. if (!ClassDecl) {
  2262. Diag(MethodLoc, diag::error_missing_method_context);
  2263. return 0;
  2264. }
  2265. QualType resultDeclType;
  2266. TypeSourceInfo *ResultTInfo = 0;
  2267. if (ReturnType) {
  2268. resultDeclType = GetTypeFromParser(ReturnType, &ResultTInfo);
  2269. // Methods cannot return interface types. All ObjC objects are
  2270. // passed by reference.
  2271. if (resultDeclType->isObjCObjectType()) {
  2272. Diag(MethodLoc, diag::err_object_cannot_be_passed_returned_by_value)
  2273. << 0 << resultDeclType;
  2274. return 0;
  2275. }
  2276. } else { // get the type for "id".
  2277. resultDeclType = Context.getObjCIdType();
  2278. Diag(MethodLoc, diag::warn_missing_method_return_type)
  2279. << FixItHint::CreateInsertion(SelectorStartLoc, "(id)");
  2280. }
  2281. ObjCMethodDecl* ObjCMethod =
  2282. ObjCMethodDecl::Create(Context, MethodLoc, EndLoc, Sel, resultDeclType,
  2283. ResultTInfo,
  2284. cast<DeclContext>(ClassDecl),
  2285. MethodType == tok::minus, isVariadic,
  2286. false, false,
  2287. MethodDeclKind == tok::objc_optional
  2288. ? ObjCMethodDecl::Optional
  2289. : ObjCMethodDecl::Required,
  2290. false);
  2291. SmallVector<ParmVarDecl*, 16> Params;
  2292. for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
  2293. QualType ArgType;
  2294. TypeSourceInfo *DI;
  2295. if (ArgInfo[i].Type == 0) {
  2296. ArgType = Context.getObjCIdType();
  2297. DI = 0;
  2298. } else {
  2299. ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
  2300. // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
  2301. ArgType = Context.getAdjustedParameterType(ArgType);
  2302. }
  2303. LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
  2304. LookupOrdinaryName, ForRedeclaration);
  2305. LookupName(R, S);
  2306. if (R.isSingleResult()) {
  2307. NamedDecl *PrevDecl = R.getFoundDecl();
  2308. if (S->isDeclScope(PrevDecl)) {
  2309. Diag(ArgInfo[i].NameLoc,
  2310. (MethodDefinition ? diag::warn_method_param_redefinition
  2311. : diag::warn_method_param_declaration))
  2312. << ArgInfo[i].Name;
  2313. Diag(PrevDecl->getLocation(),
  2314. diag::note_previous_declaration);
  2315. }
  2316. }
  2317. SourceLocation StartLoc = DI
  2318. ? DI->getTypeLoc().getBeginLoc()
  2319. : ArgInfo[i].NameLoc;
  2320. ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
  2321. ArgInfo[i].NameLoc, ArgInfo[i].Name,
  2322. ArgType, DI, SC_None, SC_None);
  2323. Param->setObjCMethodScopeInfo(i);
  2324. Param->setObjCDeclQualifier(
  2325. CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
  2326. // Apply the attributes to the parameter.
  2327. ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
  2328. S->AddDecl(Param);
  2329. IdResolver.AddDecl(Param);
  2330. Params.push_back(Param);
  2331. }
  2332. for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
  2333. ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
  2334. QualType ArgType = Param->getType();
  2335. if (ArgType.isNull())
  2336. ArgType = Context.getObjCIdType();
  2337. else
  2338. // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
  2339. ArgType = Context.getAdjustedParameterType(ArgType);
  2340. if (ArgType->isObjCObjectType()) {
  2341. Diag(Param->getLocation(),
  2342. diag::err_object_cannot_be_passed_returned_by_value)
  2343. << 1 << ArgType;
  2344. Param->setInvalidDecl();
  2345. }
  2346. Param->setDeclContext(ObjCMethod);
  2347. Params.push_back(Param);
  2348. }
  2349. ObjCMethod->setMethodParams(Context, Params.data(), Params.size(),
  2350. Sel.getNumArgs());
  2351. ObjCMethod->setObjCDeclQualifier(
  2352. CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
  2353. if (AttrList)
  2354. ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
  2355. // Add the method now.
  2356. const ObjCMethodDecl *PrevMethod = 0;
  2357. if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
  2358. if (MethodType == tok::minus) {
  2359. PrevMethod = ImpDecl->getInstanceMethod(Sel);
  2360. ImpDecl->addInstanceMethod(ObjCMethod);
  2361. } else {
  2362. PrevMethod = ImpDecl->getClassMethod(Sel);
  2363. ImpDecl->addClassMethod(ObjCMethod);
  2364. }
  2365. if (ObjCMethod->hasAttrs() &&
  2366. containsInvalidMethodImplAttribute(ObjCMethod->getAttrs()))
  2367. Diag(EndLoc, diag::warn_attribute_method_def);
  2368. } else {
  2369. cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
  2370. }
  2371. if (PrevMethod) {
  2372. // You can never have two method definitions with the same name.
  2373. Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
  2374. << ObjCMethod->getDeclName();
  2375. Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
  2376. }
  2377. // If this Objective-C method does not have a related result type, but we
  2378. // are allowed to infer related result types, try to do so based on the
  2379. // method family.
  2380. ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
  2381. if (!CurrentClass) {
  2382. if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
  2383. CurrentClass = Cat->getClassInterface();
  2384. else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
  2385. CurrentClass = Impl->getClassInterface();
  2386. else if (ObjCCategoryImplDecl *CatImpl
  2387. = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
  2388. CurrentClass = CatImpl->getClassInterface();
  2389. }
  2390. bool isRelatedResultTypeCompatible =
  2391. (getLangOptions().ObjCInferRelatedResultType &&
  2392. !CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass));
  2393. // Search for overridden methods and merge information down from them.
  2394. OverrideSearch overrides(*this, ObjCMethod);
  2395. for (OverrideSearch::iterator
  2396. i = overrides.begin(), e = overrides.end(); i != e; ++i) {
  2397. ObjCMethodDecl *overridden = *i;
  2398. // Propagate down the 'related result type' bit from overridden methods.
  2399. if (isRelatedResultTypeCompatible && overridden->hasRelatedResultType())
  2400. ObjCMethod->SetRelatedResultType();
  2401. // Then merge the declarations.
  2402. mergeObjCMethodDecls(ObjCMethod, overridden);
  2403. }
  2404. bool ARCError = false;
  2405. if (getLangOptions().ObjCAutoRefCount)
  2406. ARCError = CheckARCMethodDecl(*this, ObjCMethod);
  2407. if (!ARCError && isRelatedResultTypeCompatible &&
  2408. !ObjCMethod->hasRelatedResultType()) {
  2409. bool InferRelatedResultType = false;
  2410. switch (ObjCMethod->getMethodFamily()) {
  2411. case OMF_None:
  2412. case OMF_copy:
  2413. case OMF_dealloc:
  2414. case OMF_mutableCopy:
  2415. case OMF_release:
  2416. case OMF_retainCount:
  2417. case OMF_performSelector:
  2418. break;
  2419. case OMF_alloc:
  2420. case OMF_new:
  2421. InferRelatedResultType = ObjCMethod->isClassMethod();
  2422. break;
  2423. case OMF_init:
  2424. case OMF_autorelease:
  2425. case OMF_retain:
  2426. case OMF_self:
  2427. InferRelatedResultType = ObjCMethod->isInstanceMethod();
  2428. break;
  2429. }
  2430. if (InferRelatedResultType)
  2431. ObjCMethod->SetRelatedResultType();
  2432. }
  2433. return ObjCMethod;
  2434. }
  2435. bool Sema::CheckObjCDeclScope(Decl *D) {
  2436. if (isa<TranslationUnitDecl>(CurContext->getRedeclContext()))
  2437. return false;
  2438. Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
  2439. D->setInvalidDecl();
  2440. return true;
  2441. }
  2442. /// Called whenever @defs(ClassName) is encountered in the source. Inserts the
  2443. /// instance variables of ClassName into Decls.
  2444. void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
  2445. IdentifierInfo *ClassName,
  2446. SmallVectorImpl<Decl*> &Decls) {
  2447. // Check that ClassName is a valid class
  2448. ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
  2449. if (!Class) {
  2450. Diag(DeclStart, diag::err_undef_interface) << ClassName;
  2451. return;
  2452. }
  2453. if (LangOpts.ObjCNonFragileABI) {
  2454. Diag(DeclStart, diag::err_atdef_nonfragile_interface);
  2455. return;
  2456. }
  2457. // Collect the instance variables
  2458. SmallVector<const ObjCIvarDecl*, 32> Ivars;
  2459. Context.DeepCollectObjCIvars(Class, true, Ivars);
  2460. // For each ivar, create a fresh ObjCAtDefsFieldDecl.
  2461. for (unsigned i = 0; i < Ivars.size(); i++) {
  2462. const FieldDecl* ID = cast<FieldDecl>(Ivars[i]);
  2463. RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
  2464. Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
  2465. /*FIXME: StartL=*/ID->getLocation(),
  2466. ID->getLocation(),
  2467. ID->getIdentifier(), ID->getType(),
  2468. ID->getBitWidth());
  2469. Decls.push_back(FD);
  2470. }
  2471. // Introduce all of these fields into the appropriate scope.
  2472. for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
  2473. D != Decls.end(); ++D) {
  2474. FieldDecl *FD = cast<FieldDecl>(*D);
  2475. if (getLangOptions().CPlusPlus)
  2476. PushOnScopeChains(cast<FieldDecl>(FD), S);
  2477. else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
  2478. Record->addDecl(FD);
  2479. }
  2480. }
  2481. /// \brief Build a type-check a new Objective-C exception variable declaration.
  2482. VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
  2483. SourceLocation StartLoc,
  2484. SourceLocation IdLoc,
  2485. IdentifierInfo *Id,
  2486. bool Invalid) {
  2487. // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
  2488. // duration shall not be qualified by an address-space qualifier."
  2489. // Since all parameters have automatic store duration, they can not have
  2490. // an address space.
  2491. if (T.getAddressSpace() != 0) {
  2492. Diag(IdLoc, diag::err_arg_with_address_space);
  2493. Invalid = true;
  2494. }
  2495. // An @catch parameter must be an unqualified object pointer type;
  2496. // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
  2497. if (Invalid) {
  2498. // Don't do any further checking.
  2499. } else if (T->isDependentType()) {
  2500. // Okay: we don't know what this type will instantiate to.
  2501. } else if (!T->isObjCObjectPointerType()) {
  2502. Invalid = true;
  2503. Diag(IdLoc ,diag::err_catch_param_not_objc_type);
  2504. } else if (T->isObjCQualifiedIdType()) {
  2505. Invalid = true;
  2506. Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
  2507. }
  2508. VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
  2509. T, TInfo, SC_None, SC_None);
  2510. New->setExceptionVariable(true);
  2511. if (Invalid)
  2512. New->setInvalidDecl();
  2513. return New;
  2514. }
  2515. Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
  2516. const DeclSpec &DS = D.getDeclSpec();
  2517. // We allow the "register" storage class on exception variables because
  2518. // GCC did, but we drop it completely. Any other storage class is an error.
  2519. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
  2520. Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
  2521. << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
  2522. } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
  2523. Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
  2524. << DS.getStorageClassSpec();
  2525. }
  2526. if (D.getDeclSpec().isThreadSpecified())
  2527. Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
  2528. D.getMutableDeclSpec().ClearStorageClassSpecs();
  2529. DiagnoseFunctionSpecifiers(D);
  2530. // Check that there are no default arguments inside the type of this
  2531. // exception object (C++ only).
  2532. if (getLangOptions().CPlusPlus)
  2533. CheckExtraCXXDefaultArguments(D);
  2534. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  2535. QualType ExceptionType = TInfo->getType();
  2536. VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
  2537. D.getSourceRange().getBegin(),
  2538. D.getIdentifierLoc(),
  2539. D.getIdentifier(),
  2540. D.isInvalidType());
  2541. // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
  2542. if (D.getCXXScopeSpec().isSet()) {
  2543. Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
  2544. << D.getCXXScopeSpec().getRange();
  2545. New->setInvalidDecl();
  2546. }
  2547. // Add the parameter declaration into this scope.
  2548. S->AddDecl(New);
  2549. if (D.getIdentifier())
  2550. IdResolver.AddDecl(New);
  2551. ProcessDeclAttributes(S, New, D);
  2552. if (New->hasAttr<BlocksAttr>())
  2553. Diag(New->getLocation(), diag::err_block_on_nonlocal);
  2554. return New;
  2555. }
  2556. /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
  2557. /// initialization.
  2558. void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
  2559. SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
  2560. for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
  2561. Iv= Iv->getNextIvar()) {
  2562. QualType QT = Context.getBaseElementType(Iv->getType());
  2563. if (QT->isRecordType())
  2564. Ivars.push_back(Iv);
  2565. }
  2566. }
  2567. void Sema::DiagnoseUseOfUnimplementedSelectors() {
  2568. // Load referenced selectors from the external source.
  2569. if (ExternalSource) {
  2570. SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
  2571. ExternalSource->ReadReferencedSelectors(Sels);
  2572. for (unsigned I = 0, N = Sels.size(); I != N; ++I)
  2573. ReferencedSelectors[Sels[I].first] = Sels[I].second;
  2574. }
  2575. // Warning will be issued only when selector table is
  2576. // generated (which means there is at lease one implementation
  2577. // in the TU). This is to match gcc's behavior.
  2578. if (ReferencedSelectors.empty() ||
  2579. !Context.AnyObjCImplementation())
  2580. return;
  2581. for (llvm::DenseMap<Selector, SourceLocation>::iterator S =
  2582. ReferencedSelectors.begin(),
  2583. E = ReferencedSelectors.end(); S != E; ++S) {
  2584. Selector Sel = (*S).first;
  2585. if (!LookupImplementedMethodInGlobalPool(Sel))
  2586. Diag((*S).second, diag::warn_unimplemented_selector) << Sel;
  2587. }
  2588. return;
  2589. }