SemaDeclObjC.cpp 200 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082
  1. //===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements semantic analysis for Objective C declarations.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "TypeLocBuilder.h"
  13. #include "clang/AST/ASTConsumer.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTMutationListener.h"
  16. #include "clang/AST/DeclObjC.h"
  17. #include "clang/AST/Expr.h"
  18. #include "clang/AST/ExprObjC.h"
  19. #include "clang/AST/RecursiveASTVisitor.h"
  20. #include "clang/Basic/SourceManager.h"
  21. #include "clang/Sema/DeclSpec.h"
  22. #include "clang/Sema/Lookup.h"
  23. #include "clang/Sema/Scope.h"
  24. #include "clang/Sema/ScopeInfo.h"
  25. #include "clang/Sema/SemaInternal.h"
  26. #include "llvm/ADT/DenseMap.h"
  27. #include "llvm/ADT/DenseSet.h"
  28. using namespace clang;
  29. /// Check whether the given method, which must be in the 'init'
  30. /// family, is a valid member of that family.
  31. ///
  32. /// \param receiverTypeIfCall - if null, check this as if declaring it;
  33. /// if non-null, check this as if making a call to it with the given
  34. /// receiver type
  35. ///
  36. /// \return true to indicate that there was an error and appropriate
  37. /// actions were taken
  38. bool Sema::checkInitMethod(ObjCMethodDecl *method,
  39. QualType receiverTypeIfCall) {
  40. if (method->isInvalidDecl()) return true;
  41. // This castAs is safe: methods that don't return an object
  42. // pointer won't be inferred as inits and will reject an explicit
  43. // objc_method_family(init).
  44. // We ignore protocols here. Should we? What about Class?
  45. const ObjCObjectType *result =
  46. method->getReturnType()->castAs<ObjCObjectPointerType>()->getObjectType();
  47. if (result->isObjCId()) {
  48. return false;
  49. } else if (result->isObjCClass()) {
  50. // fall through: always an error
  51. } else {
  52. ObjCInterfaceDecl *resultClass = result->getInterface();
  53. assert(resultClass && "unexpected object type!");
  54. // It's okay for the result type to still be a forward declaration
  55. // if we're checking an interface declaration.
  56. if (!resultClass->hasDefinition()) {
  57. if (receiverTypeIfCall.isNull() &&
  58. !isa<ObjCImplementationDecl>(method->getDeclContext()))
  59. return false;
  60. // Otherwise, we try to compare class types.
  61. } else {
  62. // If this method was declared in a protocol, we can't check
  63. // anything unless we have a receiver type that's an interface.
  64. const ObjCInterfaceDecl *receiverClass = nullptr;
  65. if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
  66. if (receiverTypeIfCall.isNull())
  67. return false;
  68. receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
  69. ->getInterfaceDecl();
  70. // This can be null for calls to e.g. id<Foo>.
  71. if (!receiverClass) return false;
  72. } else {
  73. receiverClass = method->getClassInterface();
  74. assert(receiverClass && "method not associated with a class!");
  75. }
  76. // If either class is a subclass of the other, it's fine.
  77. if (receiverClass->isSuperClassOf(resultClass) ||
  78. resultClass->isSuperClassOf(receiverClass))
  79. return false;
  80. }
  81. }
  82. SourceLocation loc = method->getLocation();
  83. // If we're in a system header, and this is not a call, just make
  84. // the method unusable.
  85. if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) {
  86. method->addAttr(UnavailableAttr::CreateImplicit(Context, "",
  87. UnavailableAttr::IR_ARCInitReturnsUnrelated, loc));
  88. return true;
  89. }
  90. // Otherwise, it's an error.
  91. Diag(loc, diag::err_arc_init_method_unrelated_result_type);
  92. method->setInvalidDecl();
  93. return true;
  94. }
  95. /// Issue a warning if the parameter of the overridden method is non-escaping
  96. /// but the parameter of the overriding method is not.
  97. static bool diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD,
  98. Sema &S) {
  99. if (OldD->hasAttr<NoEscapeAttr>() && !NewD->hasAttr<NoEscapeAttr>()) {
  100. S.Diag(NewD->getLocation(), diag::warn_overriding_method_missing_noescape);
  101. S.Diag(OldD->getLocation(), diag::note_overridden_marked_noescape);
  102. return false;
  103. }
  104. return true;
  105. }
  106. /// Produce additional diagnostics if a category conforms to a protocol that
  107. /// defines a method taking a non-escaping parameter.
  108. static void diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD,
  109. const ObjCCategoryDecl *CD,
  110. const ObjCProtocolDecl *PD, Sema &S) {
  111. if (!diagnoseNoescape(NewD, OldD, S))
  112. S.Diag(CD->getLocation(), diag::note_cat_conform_to_noescape_prot)
  113. << CD->IsClassExtension() << PD
  114. << cast<ObjCMethodDecl>(NewD->getDeclContext());
  115. }
  116. void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
  117. const ObjCMethodDecl *Overridden) {
  118. if (Overridden->hasRelatedResultType() &&
  119. !NewMethod->hasRelatedResultType()) {
  120. // This can only happen when the method follows a naming convention that
  121. // implies a related result type, and the original (overridden) method has
  122. // a suitable return type, but the new (overriding) method does not have
  123. // a suitable return type.
  124. QualType ResultType = NewMethod->getReturnType();
  125. SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange();
  126. // Figure out which class this method is part of, if any.
  127. ObjCInterfaceDecl *CurrentClass
  128. = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
  129. if (!CurrentClass) {
  130. DeclContext *DC = NewMethod->getDeclContext();
  131. if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
  132. CurrentClass = Cat->getClassInterface();
  133. else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
  134. CurrentClass = Impl->getClassInterface();
  135. else if (ObjCCategoryImplDecl *CatImpl
  136. = dyn_cast<ObjCCategoryImplDecl>(DC))
  137. CurrentClass = CatImpl->getClassInterface();
  138. }
  139. if (CurrentClass) {
  140. Diag(NewMethod->getLocation(),
  141. diag::warn_related_result_type_compatibility_class)
  142. << Context.getObjCInterfaceType(CurrentClass)
  143. << ResultType
  144. << ResultTypeRange;
  145. } else {
  146. Diag(NewMethod->getLocation(),
  147. diag::warn_related_result_type_compatibility_protocol)
  148. << ResultType
  149. << ResultTypeRange;
  150. }
  151. if (ObjCMethodFamily Family = Overridden->getMethodFamily())
  152. Diag(Overridden->getLocation(),
  153. diag::note_related_result_type_family)
  154. << /*overridden method*/ 0
  155. << Family;
  156. else
  157. Diag(Overridden->getLocation(),
  158. diag::note_related_result_type_overridden);
  159. }
  160. if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
  161. Overridden->hasAttr<NSReturnsRetainedAttr>())) {
  162. Diag(NewMethod->getLocation(),
  163. getLangOpts().ObjCAutoRefCount
  164. ? diag::err_nsreturns_retained_attribute_mismatch
  165. : diag::warn_nsreturns_retained_attribute_mismatch)
  166. << 1;
  167. Diag(Overridden->getLocation(), diag::note_previous_decl) << "method";
  168. }
  169. if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
  170. Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
  171. Diag(NewMethod->getLocation(),
  172. getLangOpts().ObjCAutoRefCount
  173. ? diag::err_nsreturns_retained_attribute_mismatch
  174. : diag::warn_nsreturns_retained_attribute_mismatch)
  175. << 0;
  176. Diag(Overridden->getLocation(), diag::note_previous_decl) << "method";
  177. }
  178. ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(),
  179. oe = Overridden->param_end();
  180. for (ObjCMethodDecl::param_iterator ni = NewMethod->param_begin(),
  181. ne = NewMethod->param_end();
  182. ni != ne && oi != oe; ++ni, ++oi) {
  183. const ParmVarDecl *oldDecl = (*oi);
  184. ParmVarDecl *newDecl = (*ni);
  185. if (newDecl->hasAttr<NSConsumedAttr>() !=
  186. oldDecl->hasAttr<NSConsumedAttr>()) {
  187. Diag(newDecl->getLocation(),
  188. getLangOpts().ObjCAutoRefCount
  189. ? diag::err_nsconsumed_attribute_mismatch
  190. : diag::warn_nsconsumed_attribute_mismatch);
  191. Diag(oldDecl->getLocation(), diag::note_previous_decl) << "parameter";
  192. }
  193. diagnoseNoescape(newDecl, oldDecl, *this);
  194. }
  195. }
  196. /// Check a method declaration for compatibility with the Objective-C
  197. /// ARC conventions.
  198. bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) {
  199. ObjCMethodFamily family = method->getMethodFamily();
  200. switch (family) {
  201. case OMF_None:
  202. case OMF_finalize:
  203. case OMF_retain:
  204. case OMF_release:
  205. case OMF_autorelease:
  206. case OMF_retainCount:
  207. case OMF_self:
  208. case OMF_initialize:
  209. case OMF_performSelector:
  210. return false;
  211. case OMF_dealloc:
  212. if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) {
  213. SourceRange ResultTypeRange = method->getReturnTypeSourceRange();
  214. if (ResultTypeRange.isInvalid())
  215. Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
  216. << method->getReturnType()
  217. << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
  218. else
  219. Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
  220. << method->getReturnType()
  221. << FixItHint::CreateReplacement(ResultTypeRange, "void");
  222. return true;
  223. }
  224. return false;
  225. case OMF_init:
  226. // If the method doesn't obey the init rules, don't bother annotating it.
  227. if (checkInitMethod(method, QualType()))
  228. return true;
  229. method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context));
  230. // Don't add a second copy of this attribute, but otherwise don't
  231. // let it be suppressed.
  232. if (method->hasAttr<NSReturnsRetainedAttr>())
  233. return false;
  234. break;
  235. case OMF_alloc:
  236. case OMF_copy:
  237. case OMF_mutableCopy:
  238. case OMF_new:
  239. if (method->hasAttr<NSReturnsRetainedAttr>() ||
  240. method->hasAttr<NSReturnsNotRetainedAttr>() ||
  241. method->hasAttr<NSReturnsAutoreleasedAttr>())
  242. return false;
  243. break;
  244. }
  245. method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context));
  246. return false;
  247. }
  248. static void DiagnoseObjCImplementedDeprecations(Sema &S, const NamedDecl *ND,
  249. SourceLocation ImplLoc) {
  250. if (!ND)
  251. return;
  252. bool IsCategory = false;
  253. StringRef RealizedPlatform;
  254. AvailabilityResult Availability = ND->getAvailability(
  255. /*Message=*/nullptr, /*EnclosingVersion=*/VersionTuple(),
  256. &RealizedPlatform);
  257. if (Availability != AR_Deprecated) {
  258. if (isa<ObjCMethodDecl>(ND)) {
  259. if (Availability != AR_Unavailable)
  260. return;
  261. if (RealizedPlatform.empty())
  262. RealizedPlatform = S.Context.getTargetInfo().getPlatformName();
  263. // Warn about implementing unavailable methods, unless the unavailable
  264. // is for an app extension.
  265. if (RealizedPlatform.endswith("_app_extension"))
  266. return;
  267. S.Diag(ImplLoc, diag::warn_unavailable_def);
  268. S.Diag(ND->getLocation(), diag::note_method_declared_at)
  269. << ND->getDeclName();
  270. return;
  271. }
  272. if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND)) {
  273. if (!CD->getClassInterface()->isDeprecated())
  274. return;
  275. ND = CD->getClassInterface();
  276. IsCategory = true;
  277. } else
  278. return;
  279. }
  280. S.Diag(ImplLoc, diag::warn_deprecated_def)
  281. << (isa<ObjCMethodDecl>(ND)
  282. ? /*Method*/ 0
  283. : isa<ObjCCategoryDecl>(ND) || IsCategory ? /*Category*/ 2
  284. : /*Class*/ 1);
  285. if (isa<ObjCMethodDecl>(ND))
  286. S.Diag(ND->getLocation(), diag::note_method_declared_at)
  287. << ND->getDeclName();
  288. else
  289. S.Diag(ND->getLocation(), diag::note_previous_decl)
  290. << (isa<ObjCCategoryDecl>(ND) ? "category" : "class");
  291. }
  292. /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
  293. /// pool.
  294. void Sema::AddAnyMethodToGlobalPool(Decl *D) {
  295. ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
  296. // If we don't have a valid method decl, simply return.
  297. if (!MDecl)
  298. return;
  299. if (MDecl->isInstanceMethod())
  300. AddInstanceMethodToGlobalPool(MDecl, true);
  301. else
  302. AddFactoryMethodToGlobalPool(MDecl, true);
  303. }
  304. /// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
  305. /// has explicit ownership attribute; false otherwise.
  306. static bool
  307. HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) {
  308. QualType T = Param->getType();
  309. if (const PointerType *PT = T->getAs<PointerType>()) {
  310. T = PT->getPointeeType();
  311. } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
  312. T = RT->getPointeeType();
  313. } else {
  314. return true;
  315. }
  316. // If we have a lifetime qualifier, but it's local, we must have
  317. // inferred it. So, it is implicit.
  318. return !T.getLocalQualifiers().hasObjCLifetime();
  319. }
  320. /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
  321. /// and user declared, in the method definition's AST.
  322. void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
  323. ImplicitlyRetainedSelfLocs.clear();
  324. assert((getCurMethodDecl() == nullptr) && "Methodparsing confused");
  325. ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
  326. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  327. // If we don't have a valid method decl, simply return.
  328. if (!MDecl)
  329. return;
  330. QualType ResultType = MDecl->getReturnType();
  331. if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
  332. !MDecl->isInvalidDecl() &&
  333. RequireCompleteType(MDecl->getLocation(), ResultType,
  334. diag::err_func_def_incomplete_result))
  335. MDecl->setInvalidDecl();
  336. // Allow all of Sema to see that we are entering a method definition.
  337. PushDeclContext(FnBodyScope, MDecl);
  338. PushFunctionScope();
  339. // Create Decl objects for each parameter, entrring them in the scope for
  340. // binding to their use.
  341. // Insert the invisible arguments, self and _cmd!
  342. MDecl->createImplicitParams(Context, MDecl->getClassInterface());
  343. PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
  344. PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
  345. // The ObjC parser requires parameter names so there's no need to check.
  346. CheckParmsForFunctionDef(MDecl->parameters(),
  347. /*CheckParameterNames=*/false);
  348. // Introduce all of the other parameters into this scope.
  349. for (auto *Param : MDecl->parameters()) {
  350. if (!Param->isInvalidDecl() &&
  351. getLangOpts().ObjCAutoRefCount &&
  352. !HasExplicitOwnershipAttr(*this, Param))
  353. Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
  354. Param->getType();
  355. if (Param->getIdentifier())
  356. PushOnScopeChains(Param, FnBodyScope);
  357. }
  358. // In ARC, disallow definition of retain/release/autorelease/retainCount
  359. if (getLangOpts().ObjCAutoRefCount) {
  360. switch (MDecl->getMethodFamily()) {
  361. case OMF_retain:
  362. case OMF_retainCount:
  363. case OMF_release:
  364. case OMF_autorelease:
  365. Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
  366. << 0 << MDecl->getSelector();
  367. break;
  368. case OMF_None:
  369. case OMF_dealloc:
  370. case OMF_finalize:
  371. case OMF_alloc:
  372. case OMF_init:
  373. case OMF_mutableCopy:
  374. case OMF_copy:
  375. case OMF_new:
  376. case OMF_self:
  377. case OMF_initialize:
  378. case OMF_performSelector:
  379. break;
  380. }
  381. }
  382. // Warn on deprecated methods under -Wdeprecated-implementations,
  383. // and prepare for warning on missing super calls.
  384. if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
  385. ObjCMethodDecl *IMD =
  386. IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
  387. if (IMD) {
  388. ObjCImplDecl *ImplDeclOfMethodDef =
  389. dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
  390. ObjCContainerDecl *ContDeclOfMethodDecl =
  391. dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
  392. ObjCImplDecl *ImplDeclOfMethodDecl = nullptr;
  393. if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
  394. ImplDeclOfMethodDecl = OID->getImplementation();
  395. else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) {
  396. if (CD->IsClassExtension()) {
  397. if (ObjCInterfaceDecl *OID = CD->getClassInterface())
  398. ImplDeclOfMethodDecl = OID->getImplementation();
  399. } else
  400. ImplDeclOfMethodDecl = CD->getImplementation();
  401. }
  402. // No need to issue deprecated warning if deprecated mehod in class/category
  403. // is being implemented in its own implementation (no overriding is involved).
  404. if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef)
  405. DiagnoseObjCImplementedDeprecations(*this, IMD, MDecl->getLocation());
  406. }
  407. if (MDecl->getMethodFamily() == OMF_init) {
  408. if (MDecl->isDesignatedInitializerForTheInterface()) {
  409. getCurFunction()->ObjCIsDesignatedInit = true;
  410. getCurFunction()->ObjCWarnForNoDesignatedInitChain =
  411. IC->getSuperClass() != nullptr;
  412. } else if (IC->hasDesignatedInitializers()) {
  413. getCurFunction()->ObjCIsSecondaryInit = true;
  414. getCurFunction()->ObjCWarnForNoInitDelegation = true;
  415. }
  416. }
  417. // If this is "dealloc" or "finalize", set some bit here.
  418. // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
  419. // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
  420. // Only do this if the current class actually has a superclass.
  421. if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
  422. ObjCMethodFamily Family = MDecl->getMethodFamily();
  423. if (Family == OMF_dealloc) {
  424. if (!(getLangOpts().ObjCAutoRefCount ||
  425. getLangOpts().getGC() == LangOptions::GCOnly))
  426. getCurFunction()->ObjCShouldCallSuper = true;
  427. } else if (Family == OMF_finalize) {
  428. if (Context.getLangOpts().getGC() != LangOptions::NonGC)
  429. getCurFunction()->ObjCShouldCallSuper = true;
  430. } else {
  431. const ObjCMethodDecl *SuperMethod =
  432. SuperClass->lookupMethod(MDecl->getSelector(),
  433. MDecl->isInstanceMethod());
  434. getCurFunction()->ObjCShouldCallSuper =
  435. (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
  436. }
  437. }
  438. }
  439. }
  440. namespace {
  441. // Callback to only accept typo corrections that are Objective-C classes.
  442. // If an ObjCInterfaceDecl* is given to the constructor, then the validation
  443. // function will reject corrections to that class.
  444. class ObjCInterfaceValidatorCCC final : public CorrectionCandidateCallback {
  445. public:
  446. ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
  447. explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
  448. : CurrentIDecl(IDecl) {}
  449. bool ValidateCandidate(const TypoCorrection &candidate) override {
  450. ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
  451. return ID && !declaresSameEntity(ID, CurrentIDecl);
  452. }
  453. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  454. return llvm::make_unique<ObjCInterfaceValidatorCCC>(*this);
  455. }
  456. private:
  457. ObjCInterfaceDecl *CurrentIDecl;
  458. };
  459. } // end anonymous namespace
  460. static void diagnoseUseOfProtocols(Sema &TheSema,
  461. ObjCContainerDecl *CD,
  462. ObjCProtocolDecl *const *ProtoRefs,
  463. unsigned NumProtoRefs,
  464. const SourceLocation *ProtoLocs) {
  465. assert(ProtoRefs);
  466. // Diagnose availability in the context of the ObjC container.
  467. Sema::ContextRAII SavedContext(TheSema, CD);
  468. for (unsigned i = 0; i < NumProtoRefs; ++i) {
  469. (void)TheSema.DiagnoseUseOfDecl(ProtoRefs[i], ProtoLocs[i],
  470. /*UnknownObjCClass=*/nullptr,
  471. /*ObjCPropertyAccess=*/false,
  472. /*AvoidPartialAvailabilityChecks=*/true);
  473. }
  474. }
  475. void Sema::
  476. ActOnSuperClassOfClassInterface(Scope *S,
  477. SourceLocation AtInterfaceLoc,
  478. ObjCInterfaceDecl *IDecl,
  479. IdentifierInfo *ClassName,
  480. SourceLocation ClassLoc,
  481. IdentifierInfo *SuperName,
  482. SourceLocation SuperLoc,
  483. ArrayRef<ParsedType> SuperTypeArgs,
  484. SourceRange SuperTypeArgsRange) {
  485. // Check if a different kind of symbol declared in this scope.
  486. NamedDecl *PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
  487. LookupOrdinaryName);
  488. if (!PrevDecl) {
  489. // Try to correct for a typo in the superclass name without correcting
  490. // to the class we're defining.
  491. ObjCInterfaceValidatorCCC CCC(IDecl);
  492. if (TypoCorrection Corrected = CorrectTypo(
  493. DeclarationNameInfo(SuperName, SuperLoc), LookupOrdinaryName,
  494. TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
  495. diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
  496. << SuperName << ClassName);
  497. PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
  498. }
  499. }
  500. if (declaresSameEntity(PrevDecl, IDecl)) {
  501. Diag(SuperLoc, diag::err_recursive_superclass)
  502. << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
  503. IDecl->setEndOfDefinitionLoc(ClassLoc);
  504. } else {
  505. ObjCInterfaceDecl *SuperClassDecl =
  506. dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
  507. QualType SuperClassType;
  508. // Diagnose classes that inherit from deprecated classes.
  509. if (SuperClassDecl) {
  510. (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
  511. SuperClassType = Context.getObjCInterfaceType(SuperClassDecl);
  512. }
  513. if (PrevDecl && !SuperClassDecl) {
  514. // The previous declaration was not a class decl. Check if we have a
  515. // typedef. If we do, get the underlying class type.
  516. if (const TypedefNameDecl *TDecl =
  517. dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
  518. QualType T = TDecl->getUnderlyingType();
  519. if (T->isObjCObjectType()) {
  520. if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
  521. SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
  522. SuperClassType = Context.getTypeDeclType(TDecl);
  523. // This handles the following case:
  524. // @interface NewI @end
  525. // typedef NewI DeprI __attribute__((deprecated("blah")))
  526. // @interface SI : DeprI /* warn here */ @end
  527. (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
  528. }
  529. }
  530. }
  531. // This handles the following case:
  532. //
  533. // typedef int SuperClass;
  534. // @interface MyClass : SuperClass {} @end
  535. //
  536. if (!SuperClassDecl) {
  537. Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
  538. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  539. }
  540. }
  541. if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
  542. if (!SuperClassDecl)
  543. Diag(SuperLoc, diag::err_undef_superclass)
  544. << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
  545. else if (RequireCompleteType(SuperLoc,
  546. SuperClassType,
  547. diag::err_forward_superclass,
  548. SuperClassDecl->getDeclName(),
  549. ClassName,
  550. SourceRange(AtInterfaceLoc, ClassLoc))) {
  551. SuperClassDecl = nullptr;
  552. SuperClassType = QualType();
  553. }
  554. }
  555. if (SuperClassType.isNull()) {
  556. assert(!SuperClassDecl && "Failed to set SuperClassType?");
  557. return;
  558. }
  559. // Handle type arguments on the superclass.
  560. TypeSourceInfo *SuperClassTInfo = nullptr;
  561. if (!SuperTypeArgs.empty()) {
  562. TypeResult fullSuperClassType = actOnObjCTypeArgsAndProtocolQualifiers(
  563. S,
  564. SuperLoc,
  565. CreateParsedType(SuperClassType,
  566. nullptr),
  567. SuperTypeArgsRange.getBegin(),
  568. SuperTypeArgs,
  569. SuperTypeArgsRange.getEnd(),
  570. SourceLocation(),
  571. { },
  572. { },
  573. SourceLocation());
  574. if (!fullSuperClassType.isUsable())
  575. return;
  576. SuperClassType = GetTypeFromParser(fullSuperClassType.get(),
  577. &SuperClassTInfo);
  578. }
  579. if (!SuperClassTInfo) {
  580. SuperClassTInfo = Context.getTrivialTypeSourceInfo(SuperClassType,
  581. SuperLoc);
  582. }
  583. IDecl->setSuperClass(SuperClassTInfo);
  584. IDecl->setEndOfDefinitionLoc(SuperClassTInfo->getTypeLoc().getEndLoc());
  585. }
  586. }
  587. DeclResult Sema::actOnObjCTypeParam(Scope *S,
  588. ObjCTypeParamVariance variance,
  589. SourceLocation varianceLoc,
  590. unsigned index,
  591. IdentifierInfo *paramName,
  592. SourceLocation paramLoc,
  593. SourceLocation colonLoc,
  594. ParsedType parsedTypeBound) {
  595. // If there was an explicitly-provided type bound, check it.
  596. TypeSourceInfo *typeBoundInfo = nullptr;
  597. if (parsedTypeBound) {
  598. // The type bound can be any Objective-C pointer type.
  599. QualType typeBound = GetTypeFromParser(parsedTypeBound, &typeBoundInfo);
  600. if (typeBound->isObjCObjectPointerType()) {
  601. // okay
  602. } else if (typeBound->isObjCObjectType()) {
  603. // The user forgot the * on an Objective-C pointer type, e.g.,
  604. // "T : NSView".
  605. SourceLocation starLoc = getLocForEndOfToken(
  606. typeBoundInfo->getTypeLoc().getEndLoc());
  607. Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
  608. diag::err_objc_type_param_bound_missing_pointer)
  609. << typeBound << paramName
  610. << FixItHint::CreateInsertion(starLoc, " *");
  611. // Create a new type location builder so we can update the type
  612. // location information we have.
  613. TypeLocBuilder builder;
  614. builder.pushFullCopy(typeBoundInfo->getTypeLoc());
  615. // Create the Objective-C pointer type.
  616. typeBound = Context.getObjCObjectPointerType(typeBound);
  617. ObjCObjectPointerTypeLoc newT
  618. = builder.push<ObjCObjectPointerTypeLoc>(typeBound);
  619. newT.setStarLoc(starLoc);
  620. // Form the new type source information.
  621. typeBoundInfo = builder.getTypeSourceInfo(Context, typeBound);
  622. } else {
  623. // Not a valid type bound.
  624. Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
  625. diag::err_objc_type_param_bound_nonobject)
  626. << typeBound << paramName;
  627. // Forget the bound; we'll default to id later.
  628. typeBoundInfo = nullptr;
  629. }
  630. // Type bounds cannot have qualifiers (even indirectly) or explicit
  631. // nullability.
  632. if (typeBoundInfo) {
  633. QualType typeBound = typeBoundInfo->getType();
  634. TypeLoc qual = typeBoundInfo->getTypeLoc().findExplicitQualifierLoc();
  635. if (qual || typeBound.hasQualifiers()) {
  636. bool diagnosed = false;
  637. SourceRange rangeToRemove;
  638. if (qual) {
  639. if (auto attr = qual.getAs<AttributedTypeLoc>()) {
  640. rangeToRemove = attr.getLocalSourceRange();
  641. if (attr.getTypePtr()->getImmediateNullability()) {
  642. Diag(attr.getBeginLoc(),
  643. diag::err_objc_type_param_bound_explicit_nullability)
  644. << paramName << typeBound
  645. << FixItHint::CreateRemoval(rangeToRemove);
  646. diagnosed = true;
  647. }
  648. }
  649. }
  650. if (!diagnosed) {
  651. Diag(qual ? qual.getBeginLoc()
  652. : typeBoundInfo->getTypeLoc().getBeginLoc(),
  653. diag::err_objc_type_param_bound_qualified)
  654. << paramName << typeBound
  655. << typeBound.getQualifiers().getAsString()
  656. << FixItHint::CreateRemoval(rangeToRemove);
  657. }
  658. // If the type bound has qualifiers other than CVR, we need to strip
  659. // them or we'll probably assert later when trying to apply new
  660. // qualifiers.
  661. Qualifiers quals = typeBound.getQualifiers();
  662. quals.removeCVRQualifiers();
  663. if (!quals.empty()) {
  664. typeBoundInfo =
  665. Context.getTrivialTypeSourceInfo(typeBound.getUnqualifiedType());
  666. }
  667. }
  668. }
  669. }
  670. // If there was no explicit type bound (or we removed it due to an error),
  671. // use 'id' instead.
  672. if (!typeBoundInfo) {
  673. colonLoc = SourceLocation();
  674. typeBoundInfo = Context.getTrivialTypeSourceInfo(Context.getObjCIdType());
  675. }
  676. // Create the type parameter.
  677. return ObjCTypeParamDecl::Create(Context, CurContext, variance, varianceLoc,
  678. index, paramLoc, paramName, colonLoc,
  679. typeBoundInfo);
  680. }
  681. ObjCTypeParamList *Sema::actOnObjCTypeParamList(Scope *S,
  682. SourceLocation lAngleLoc,
  683. ArrayRef<Decl *> typeParamsIn,
  684. SourceLocation rAngleLoc) {
  685. // We know that the array only contains Objective-C type parameters.
  686. ArrayRef<ObjCTypeParamDecl *>
  687. typeParams(
  688. reinterpret_cast<ObjCTypeParamDecl * const *>(typeParamsIn.data()),
  689. typeParamsIn.size());
  690. // Diagnose redeclarations of type parameters.
  691. // We do this now because Objective-C type parameters aren't pushed into
  692. // scope until later (after the instance variable block), but we want the
  693. // diagnostics to occur right after we parse the type parameter list.
  694. llvm::SmallDenseMap<IdentifierInfo *, ObjCTypeParamDecl *> knownParams;
  695. for (auto typeParam : typeParams) {
  696. auto known = knownParams.find(typeParam->getIdentifier());
  697. if (known != knownParams.end()) {
  698. Diag(typeParam->getLocation(), diag::err_objc_type_param_redecl)
  699. << typeParam->getIdentifier()
  700. << SourceRange(known->second->getLocation());
  701. typeParam->setInvalidDecl();
  702. } else {
  703. knownParams.insert(std::make_pair(typeParam->getIdentifier(), typeParam));
  704. // Push the type parameter into scope.
  705. PushOnScopeChains(typeParam, S, /*AddToContext=*/false);
  706. }
  707. }
  708. // Create the parameter list.
  709. return ObjCTypeParamList::create(Context, lAngleLoc, typeParams, rAngleLoc);
  710. }
  711. void Sema::popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList) {
  712. for (auto typeParam : *typeParamList) {
  713. if (!typeParam->isInvalidDecl()) {
  714. S->RemoveDecl(typeParam);
  715. IdResolver.RemoveDecl(typeParam);
  716. }
  717. }
  718. }
  719. namespace {
  720. /// The context in which an Objective-C type parameter list occurs, for use
  721. /// in diagnostics.
  722. enum class TypeParamListContext {
  723. ForwardDeclaration,
  724. Definition,
  725. Category,
  726. Extension
  727. };
  728. } // end anonymous namespace
  729. /// Check consistency between two Objective-C type parameter lists, e.g.,
  730. /// between a category/extension and an \@interface or between an \@class and an
  731. /// \@interface.
  732. static bool checkTypeParamListConsistency(Sema &S,
  733. ObjCTypeParamList *prevTypeParams,
  734. ObjCTypeParamList *newTypeParams,
  735. TypeParamListContext newContext) {
  736. // If the sizes don't match, complain about that.
  737. if (prevTypeParams->size() != newTypeParams->size()) {
  738. SourceLocation diagLoc;
  739. if (newTypeParams->size() > prevTypeParams->size()) {
  740. diagLoc = newTypeParams->begin()[prevTypeParams->size()]->getLocation();
  741. } else {
  742. diagLoc = S.getLocForEndOfToken(newTypeParams->back()->getEndLoc());
  743. }
  744. S.Diag(diagLoc, diag::err_objc_type_param_arity_mismatch)
  745. << static_cast<unsigned>(newContext)
  746. << (newTypeParams->size() > prevTypeParams->size())
  747. << prevTypeParams->size()
  748. << newTypeParams->size();
  749. return true;
  750. }
  751. // Match up the type parameters.
  752. for (unsigned i = 0, n = prevTypeParams->size(); i != n; ++i) {
  753. ObjCTypeParamDecl *prevTypeParam = prevTypeParams->begin()[i];
  754. ObjCTypeParamDecl *newTypeParam = newTypeParams->begin()[i];
  755. // Check for consistency of the variance.
  756. if (newTypeParam->getVariance() != prevTypeParam->getVariance()) {
  757. if (newTypeParam->getVariance() == ObjCTypeParamVariance::Invariant &&
  758. newContext != TypeParamListContext::Definition) {
  759. // When the new type parameter is invariant and is not part
  760. // of the definition, just propagate the variance.
  761. newTypeParam->setVariance(prevTypeParam->getVariance());
  762. } else if (prevTypeParam->getVariance()
  763. == ObjCTypeParamVariance::Invariant &&
  764. !(isa<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) &&
  765. cast<ObjCInterfaceDecl>(prevTypeParam->getDeclContext())
  766. ->getDefinition() == prevTypeParam->getDeclContext())) {
  767. // When the old parameter is invariant and was not part of the
  768. // definition, just ignore the difference because it doesn't
  769. // matter.
  770. } else {
  771. {
  772. // Diagnose the conflict and update the second declaration.
  773. SourceLocation diagLoc = newTypeParam->getVarianceLoc();
  774. if (diagLoc.isInvalid())
  775. diagLoc = newTypeParam->getBeginLoc();
  776. auto diag = S.Diag(diagLoc,
  777. diag::err_objc_type_param_variance_conflict)
  778. << static_cast<unsigned>(newTypeParam->getVariance())
  779. << newTypeParam->getDeclName()
  780. << static_cast<unsigned>(prevTypeParam->getVariance())
  781. << prevTypeParam->getDeclName();
  782. switch (prevTypeParam->getVariance()) {
  783. case ObjCTypeParamVariance::Invariant:
  784. diag << FixItHint::CreateRemoval(newTypeParam->getVarianceLoc());
  785. break;
  786. case ObjCTypeParamVariance::Covariant:
  787. case ObjCTypeParamVariance::Contravariant: {
  788. StringRef newVarianceStr
  789. = prevTypeParam->getVariance() == ObjCTypeParamVariance::Covariant
  790. ? "__covariant"
  791. : "__contravariant";
  792. if (newTypeParam->getVariance()
  793. == ObjCTypeParamVariance::Invariant) {
  794. diag << FixItHint::CreateInsertion(newTypeParam->getBeginLoc(),
  795. (newVarianceStr + " ").str());
  796. } else {
  797. diag << FixItHint::CreateReplacement(newTypeParam->getVarianceLoc(),
  798. newVarianceStr);
  799. }
  800. }
  801. }
  802. }
  803. S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
  804. << prevTypeParam->getDeclName();
  805. // Override the variance.
  806. newTypeParam->setVariance(prevTypeParam->getVariance());
  807. }
  808. }
  809. // If the bound types match, there's nothing to do.
  810. if (S.Context.hasSameType(prevTypeParam->getUnderlyingType(),
  811. newTypeParam->getUnderlyingType()))
  812. continue;
  813. // If the new type parameter's bound was explicit, complain about it being
  814. // different from the original.
  815. if (newTypeParam->hasExplicitBound()) {
  816. SourceRange newBoundRange = newTypeParam->getTypeSourceInfo()
  817. ->getTypeLoc().getSourceRange();
  818. S.Diag(newBoundRange.getBegin(), diag::err_objc_type_param_bound_conflict)
  819. << newTypeParam->getUnderlyingType()
  820. << newTypeParam->getDeclName()
  821. << prevTypeParam->hasExplicitBound()
  822. << prevTypeParam->getUnderlyingType()
  823. << (newTypeParam->getDeclName() == prevTypeParam->getDeclName())
  824. << prevTypeParam->getDeclName()
  825. << FixItHint::CreateReplacement(
  826. newBoundRange,
  827. prevTypeParam->getUnderlyingType().getAsString(
  828. S.Context.getPrintingPolicy()));
  829. S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
  830. << prevTypeParam->getDeclName();
  831. // Override the new type parameter's bound type with the previous type,
  832. // so that it's consistent.
  833. newTypeParam->setTypeSourceInfo(
  834. S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
  835. continue;
  836. }
  837. // The new type parameter got the implicit bound of 'id'. That's okay for
  838. // categories and extensions (overwrite it later), but not for forward
  839. // declarations and @interfaces, because those must be standalone.
  840. if (newContext == TypeParamListContext::ForwardDeclaration ||
  841. newContext == TypeParamListContext::Definition) {
  842. // Diagnose this problem for forward declarations and definitions.
  843. SourceLocation insertionLoc
  844. = S.getLocForEndOfToken(newTypeParam->getLocation());
  845. std::string newCode
  846. = " : " + prevTypeParam->getUnderlyingType().getAsString(
  847. S.Context.getPrintingPolicy());
  848. S.Diag(newTypeParam->getLocation(),
  849. diag::err_objc_type_param_bound_missing)
  850. << prevTypeParam->getUnderlyingType()
  851. << newTypeParam->getDeclName()
  852. << (newContext == TypeParamListContext::ForwardDeclaration)
  853. << FixItHint::CreateInsertion(insertionLoc, newCode);
  854. S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
  855. << prevTypeParam->getDeclName();
  856. }
  857. // Update the new type parameter's bound to match the previous one.
  858. newTypeParam->setTypeSourceInfo(
  859. S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
  860. }
  861. return false;
  862. }
  863. Decl *Sema::ActOnStartClassInterface(
  864. Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
  865. SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
  866. IdentifierInfo *SuperName, SourceLocation SuperLoc,
  867. ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
  868. Decl *const *ProtoRefs, unsigned NumProtoRefs,
  869. const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
  870. const ParsedAttributesView &AttrList) {
  871. assert(ClassName && "Missing class identifier");
  872. // Check for another declaration kind with the same name.
  873. NamedDecl *PrevDecl =
  874. LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
  875. forRedeclarationInCurContext());
  876. if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
  877. Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
  878. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  879. }
  880. // Create a declaration to describe this @interface.
  881. ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
  882. if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
  883. // A previous decl with a different name is because of
  884. // @compatibility_alias, for example:
  885. // \code
  886. // @class NewImage;
  887. // @compatibility_alias OldImage NewImage;
  888. // \endcode
  889. // A lookup for 'OldImage' will return the 'NewImage' decl.
  890. //
  891. // In such a case use the real declaration name, instead of the alias one,
  892. // otherwise we will break IdentifierResolver and redecls-chain invariants.
  893. // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
  894. // has been aliased.
  895. ClassName = PrevIDecl->getIdentifier();
  896. }
  897. // If there was a forward declaration with type parameters, check
  898. // for consistency.
  899. if (PrevIDecl) {
  900. if (ObjCTypeParamList *prevTypeParamList = PrevIDecl->getTypeParamList()) {
  901. if (typeParamList) {
  902. // Both have type parameter lists; check for consistency.
  903. if (checkTypeParamListConsistency(*this, prevTypeParamList,
  904. typeParamList,
  905. TypeParamListContext::Definition)) {
  906. typeParamList = nullptr;
  907. }
  908. } else {
  909. Diag(ClassLoc, diag::err_objc_parameterized_forward_class_first)
  910. << ClassName;
  911. Diag(prevTypeParamList->getLAngleLoc(), diag::note_previous_decl)
  912. << ClassName;
  913. // Clone the type parameter list.
  914. SmallVector<ObjCTypeParamDecl *, 4> clonedTypeParams;
  915. for (auto typeParam : *prevTypeParamList) {
  916. clonedTypeParams.push_back(
  917. ObjCTypeParamDecl::Create(
  918. Context,
  919. CurContext,
  920. typeParam->getVariance(),
  921. SourceLocation(),
  922. typeParam->getIndex(),
  923. SourceLocation(),
  924. typeParam->getIdentifier(),
  925. SourceLocation(),
  926. Context.getTrivialTypeSourceInfo(typeParam->getUnderlyingType())));
  927. }
  928. typeParamList = ObjCTypeParamList::create(Context,
  929. SourceLocation(),
  930. clonedTypeParams,
  931. SourceLocation());
  932. }
  933. }
  934. }
  935. ObjCInterfaceDecl *IDecl
  936. = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
  937. typeParamList, PrevIDecl, ClassLoc);
  938. if (PrevIDecl) {
  939. // Class already seen. Was it a definition?
  940. if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
  941. Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
  942. << PrevIDecl->getDeclName();
  943. Diag(Def->getLocation(), diag::note_previous_definition);
  944. IDecl->setInvalidDecl();
  945. }
  946. }
  947. ProcessDeclAttributeList(TUScope, IDecl, AttrList);
  948. AddPragmaAttributes(TUScope, IDecl);
  949. PushOnScopeChains(IDecl, TUScope);
  950. // Start the definition of this class. If we're in a redefinition case, there
  951. // may already be a definition, so we'll end up adding to it.
  952. if (!IDecl->hasDefinition())
  953. IDecl->startDefinition();
  954. if (SuperName) {
  955. // Diagnose availability in the context of the @interface.
  956. ContextRAII SavedContext(*this, IDecl);
  957. ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl,
  958. ClassName, ClassLoc,
  959. SuperName, SuperLoc, SuperTypeArgs,
  960. SuperTypeArgsRange);
  961. } else { // we have a root class.
  962. IDecl->setEndOfDefinitionLoc(ClassLoc);
  963. }
  964. // Check then save referenced protocols.
  965. if (NumProtoRefs) {
  966. diagnoseUseOfProtocols(*this, IDecl, (ObjCProtocolDecl*const*)ProtoRefs,
  967. NumProtoRefs, ProtoLocs);
  968. IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
  969. ProtoLocs, Context);
  970. IDecl->setEndOfDefinitionLoc(EndProtoLoc);
  971. }
  972. CheckObjCDeclScope(IDecl);
  973. return ActOnObjCContainerStartDefinition(IDecl);
  974. }
  975. /// ActOnTypedefedProtocols - this action finds protocol list as part of the
  976. /// typedef'ed use for a qualified super class and adds them to the list
  977. /// of the protocols.
  978. void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
  979. SmallVectorImpl<SourceLocation> &ProtocolLocs,
  980. IdentifierInfo *SuperName,
  981. SourceLocation SuperLoc) {
  982. if (!SuperName)
  983. return;
  984. NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
  985. LookupOrdinaryName);
  986. if (!IDecl)
  987. return;
  988. if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
  989. QualType T = TDecl->getUnderlyingType();
  990. if (T->isObjCObjectType())
  991. if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>()) {
  992. ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end());
  993. // FIXME: Consider whether this should be an invalid loc since the loc
  994. // is not actually pointing to a protocol name reference but to the
  995. // typedef reference. Note that the base class name loc is also pointing
  996. // at the typedef.
  997. ProtocolLocs.append(OPT->getNumProtocols(), SuperLoc);
  998. }
  999. }
  1000. }
  1001. /// ActOnCompatibilityAlias - this action is called after complete parsing of
  1002. /// a \@compatibility_alias declaration. It sets up the alias relationships.
  1003. Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
  1004. IdentifierInfo *AliasName,
  1005. SourceLocation AliasLocation,
  1006. IdentifierInfo *ClassName,
  1007. SourceLocation ClassLocation) {
  1008. // Look for previous declaration of alias name
  1009. NamedDecl *ADecl =
  1010. LookupSingleName(TUScope, AliasName, AliasLocation, LookupOrdinaryName,
  1011. forRedeclarationInCurContext());
  1012. if (ADecl) {
  1013. Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
  1014. Diag(ADecl->getLocation(), diag::note_previous_declaration);
  1015. return nullptr;
  1016. }
  1017. // Check for class declaration
  1018. NamedDecl *CDeclU =
  1019. LookupSingleName(TUScope, ClassName, ClassLocation, LookupOrdinaryName,
  1020. forRedeclarationInCurContext());
  1021. if (const TypedefNameDecl *TDecl =
  1022. dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
  1023. QualType T = TDecl->getUnderlyingType();
  1024. if (T->isObjCObjectType()) {
  1025. if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
  1026. ClassName = IDecl->getIdentifier();
  1027. CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
  1028. LookupOrdinaryName,
  1029. forRedeclarationInCurContext());
  1030. }
  1031. }
  1032. }
  1033. ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
  1034. if (!CDecl) {
  1035. Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
  1036. if (CDeclU)
  1037. Diag(CDeclU->getLocation(), diag::note_previous_declaration);
  1038. return nullptr;
  1039. }
  1040. // Everything checked out, instantiate a new alias declaration AST.
  1041. ObjCCompatibleAliasDecl *AliasDecl =
  1042. ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
  1043. if (!CheckObjCDeclScope(AliasDecl))
  1044. PushOnScopeChains(AliasDecl, TUScope);
  1045. return AliasDecl;
  1046. }
  1047. bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
  1048. IdentifierInfo *PName,
  1049. SourceLocation &Ploc, SourceLocation PrevLoc,
  1050. const ObjCList<ObjCProtocolDecl> &PList) {
  1051. bool res = false;
  1052. for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
  1053. E = PList.end(); I != E; ++I) {
  1054. if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
  1055. Ploc)) {
  1056. if (PDecl->getIdentifier() == PName) {
  1057. Diag(Ploc, diag::err_protocol_has_circular_dependency);
  1058. Diag(PrevLoc, diag::note_previous_definition);
  1059. res = true;
  1060. }
  1061. if (!PDecl->hasDefinition())
  1062. continue;
  1063. if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
  1064. PDecl->getLocation(), PDecl->getReferencedProtocols()))
  1065. res = true;
  1066. }
  1067. }
  1068. return res;
  1069. }
  1070. Decl *Sema::ActOnStartProtocolInterface(
  1071. SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
  1072. SourceLocation ProtocolLoc, Decl *const *ProtoRefs, unsigned NumProtoRefs,
  1073. const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
  1074. const ParsedAttributesView &AttrList) {
  1075. bool err = false;
  1076. // FIXME: Deal with AttrList.
  1077. assert(ProtocolName && "Missing protocol identifier");
  1078. ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
  1079. forRedeclarationInCurContext());
  1080. ObjCProtocolDecl *PDecl = nullptr;
  1081. if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
  1082. // If we already have a definition, complain.
  1083. Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
  1084. Diag(Def->getLocation(), diag::note_previous_definition);
  1085. // Create a new protocol that is completely distinct from previous
  1086. // declarations, and do not make this protocol available for name lookup.
  1087. // That way, we'll end up completely ignoring the duplicate.
  1088. // FIXME: Can we turn this into an error?
  1089. PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
  1090. ProtocolLoc, AtProtoInterfaceLoc,
  1091. /*PrevDecl=*/nullptr);
  1092. // If we are using modules, add the decl to the context in order to
  1093. // serialize something meaningful.
  1094. if (getLangOpts().Modules)
  1095. PushOnScopeChains(PDecl, TUScope);
  1096. PDecl->startDefinition();
  1097. } else {
  1098. if (PrevDecl) {
  1099. // Check for circular dependencies among protocol declarations. This can
  1100. // only happen if this protocol was forward-declared.
  1101. ObjCList<ObjCProtocolDecl> PList;
  1102. PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
  1103. err = CheckForwardProtocolDeclarationForCircularDependency(
  1104. ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
  1105. }
  1106. // Create the new declaration.
  1107. PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
  1108. ProtocolLoc, AtProtoInterfaceLoc,
  1109. /*PrevDecl=*/PrevDecl);
  1110. PushOnScopeChains(PDecl, TUScope);
  1111. PDecl->startDefinition();
  1112. }
  1113. ProcessDeclAttributeList(TUScope, PDecl, AttrList);
  1114. AddPragmaAttributes(TUScope, PDecl);
  1115. // Merge attributes from previous declarations.
  1116. if (PrevDecl)
  1117. mergeDeclAttributes(PDecl, PrevDecl);
  1118. if (!err && NumProtoRefs ) {
  1119. /// Check then save referenced protocols.
  1120. diagnoseUseOfProtocols(*this, PDecl, (ObjCProtocolDecl*const*)ProtoRefs,
  1121. NumProtoRefs, ProtoLocs);
  1122. PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
  1123. ProtoLocs, Context);
  1124. }
  1125. CheckObjCDeclScope(PDecl);
  1126. return ActOnObjCContainerStartDefinition(PDecl);
  1127. }
  1128. static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
  1129. ObjCProtocolDecl *&UndefinedProtocol) {
  1130. if (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden()) {
  1131. UndefinedProtocol = PDecl;
  1132. return true;
  1133. }
  1134. for (auto *PI : PDecl->protocols())
  1135. if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
  1136. UndefinedProtocol = PI;
  1137. return true;
  1138. }
  1139. return false;
  1140. }
  1141. /// FindProtocolDeclaration - This routine looks up protocols and
  1142. /// issues an error if they are not declared. It returns list of
  1143. /// protocol declarations in its 'Protocols' argument.
  1144. void
  1145. Sema::FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
  1146. ArrayRef<IdentifierLocPair> ProtocolId,
  1147. SmallVectorImpl<Decl *> &Protocols) {
  1148. for (const IdentifierLocPair &Pair : ProtocolId) {
  1149. ObjCProtocolDecl *PDecl = LookupProtocol(Pair.first, Pair.second);
  1150. if (!PDecl) {
  1151. DeclFilterCCC<ObjCProtocolDecl> CCC{};
  1152. TypoCorrection Corrected = CorrectTypo(
  1153. DeclarationNameInfo(Pair.first, Pair.second), LookupObjCProtocolName,
  1154. TUScope, nullptr, CCC, CTK_ErrorRecovery);
  1155. if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
  1156. diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
  1157. << Pair.first);
  1158. }
  1159. if (!PDecl) {
  1160. Diag(Pair.second, diag::err_undeclared_protocol) << Pair.first;
  1161. continue;
  1162. }
  1163. // If this is a forward protocol declaration, get its definition.
  1164. if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
  1165. PDecl = PDecl->getDefinition();
  1166. // For an objc container, delay protocol reference checking until after we
  1167. // can set the objc decl as the availability context, otherwise check now.
  1168. if (!ForObjCContainer) {
  1169. (void)DiagnoseUseOfDecl(PDecl, Pair.second);
  1170. }
  1171. // If this is a forward declaration and we are supposed to warn in this
  1172. // case, do it.
  1173. // FIXME: Recover nicely in the hidden case.
  1174. ObjCProtocolDecl *UndefinedProtocol;
  1175. if (WarnOnDeclarations &&
  1176. NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
  1177. Diag(Pair.second, diag::warn_undef_protocolref) << Pair.first;
  1178. Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
  1179. << UndefinedProtocol;
  1180. }
  1181. Protocols.push_back(PDecl);
  1182. }
  1183. }
  1184. namespace {
  1185. // Callback to only accept typo corrections that are either
  1186. // Objective-C protocols or valid Objective-C type arguments.
  1187. class ObjCTypeArgOrProtocolValidatorCCC final
  1188. : public CorrectionCandidateCallback {
  1189. ASTContext &Context;
  1190. Sema::LookupNameKind LookupKind;
  1191. public:
  1192. ObjCTypeArgOrProtocolValidatorCCC(ASTContext &context,
  1193. Sema::LookupNameKind lookupKind)
  1194. : Context(context), LookupKind(lookupKind) { }
  1195. bool ValidateCandidate(const TypoCorrection &candidate) override {
  1196. // If we're allowed to find protocols and we have a protocol, accept it.
  1197. if (LookupKind != Sema::LookupOrdinaryName) {
  1198. if (candidate.getCorrectionDeclAs<ObjCProtocolDecl>())
  1199. return true;
  1200. }
  1201. // If we're allowed to find type names and we have one, accept it.
  1202. if (LookupKind != Sema::LookupObjCProtocolName) {
  1203. // If we have a type declaration, we might accept this result.
  1204. if (auto typeDecl = candidate.getCorrectionDeclAs<TypeDecl>()) {
  1205. // If we found a tag declaration outside of C++, skip it. This
  1206. // can happy because we look for any name when there is no
  1207. // bias to protocol or type names.
  1208. if (isa<RecordDecl>(typeDecl) && !Context.getLangOpts().CPlusPlus)
  1209. return false;
  1210. // Make sure the type is something we would accept as a type
  1211. // argument.
  1212. auto type = Context.getTypeDeclType(typeDecl);
  1213. if (type->isObjCObjectPointerType() ||
  1214. type->isBlockPointerType() ||
  1215. type->isDependentType() ||
  1216. type->isObjCObjectType())
  1217. return true;
  1218. return false;
  1219. }
  1220. // If we have an Objective-C class type, accept it; there will
  1221. // be another fix to add the '*'.
  1222. if (candidate.getCorrectionDeclAs<ObjCInterfaceDecl>())
  1223. return true;
  1224. return false;
  1225. }
  1226. return false;
  1227. }
  1228. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  1229. return llvm::make_unique<ObjCTypeArgOrProtocolValidatorCCC>(*this);
  1230. }
  1231. };
  1232. } // end anonymous namespace
  1233. void Sema::DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
  1234. SourceLocation ProtocolLoc,
  1235. IdentifierInfo *TypeArgId,
  1236. SourceLocation TypeArgLoc,
  1237. bool SelectProtocolFirst) {
  1238. Diag(TypeArgLoc, diag::err_objc_type_args_and_protocols)
  1239. << SelectProtocolFirst << TypeArgId << ProtocolId
  1240. << SourceRange(ProtocolLoc);
  1241. }
  1242. void Sema::actOnObjCTypeArgsOrProtocolQualifiers(
  1243. Scope *S,
  1244. ParsedType baseType,
  1245. SourceLocation lAngleLoc,
  1246. ArrayRef<IdentifierInfo *> identifiers,
  1247. ArrayRef<SourceLocation> identifierLocs,
  1248. SourceLocation rAngleLoc,
  1249. SourceLocation &typeArgsLAngleLoc,
  1250. SmallVectorImpl<ParsedType> &typeArgs,
  1251. SourceLocation &typeArgsRAngleLoc,
  1252. SourceLocation &protocolLAngleLoc,
  1253. SmallVectorImpl<Decl *> &protocols,
  1254. SourceLocation &protocolRAngleLoc,
  1255. bool warnOnIncompleteProtocols) {
  1256. // Local function that updates the declaration specifiers with
  1257. // protocol information.
  1258. unsigned numProtocolsResolved = 0;
  1259. auto resolvedAsProtocols = [&] {
  1260. assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols");
  1261. // Determine whether the base type is a parameterized class, in
  1262. // which case we want to warn about typos such as
  1263. // "NSArray<NSObject>" (that should be NSArray<NSObject *>).
  1264. ObjCInterfaceDecl *baseClass = nullptr;
  1265. QualType base = GetTypeFromParser(baseType, nullptr);
  1266. bool allAreTypeNames = false;
  1267. SourceLocation firstClassNameLoc;
  1268. if (!base.isNull()) {
  1269. if (const auto *objcObjectType = base->getAs<ObjCObjectType>()) {
  1270. baseClass = objcObjectType->getInterface();
  1271. if (baseClass) {
  1272. if (auto typeParams = baseClass->getTypeParamList()) {
  1273. if (typeParams->size() == numProtocolsResolved) {
  1274. // Note that we should be looking for type names, too.
  1275. allAreTypeNames = true;
  1276. }
  1277. }
  1278. }
  1279. }
  1280. }
  1281. for (unsigned i = 0, n = protocols.size(); i != n; ++i) {
  1282. ObjCProtocolDecl *&proto
  1283. = reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]);
  1284. // For an objc container, delay protocol reference checking until after we
  1285. // can set the objc decl as the availability context, otherwise check now.
  1286. if (!warnOnIncompleteProtocols) {
  1287. (void)DiagnoseUseOfDecl(proto, identifierLocs[i]);
  1288. }
  1289. // If this is a forward protocol declaration, get its definition.
  1290. if (!proto->isThisDeclarationADefinition() && proto->getDefinition())
  1291. proto = proto->getDefinition();
  1292. // If this is a forward declaration and we are supposed to warn in this
  1293. // case, do it.
  1294. // FIXME: Recover nicely in the hidden case.
  1295. ObjCProtocolDecl *forwardDecl = nullptr;
  1296. if (warnOnIncompleteProtocols &&
  1297. NestedProtocolHasNoDefinition(proto, forwardDecl)) {
  1298. Diag(identifierLocs[i], diag::warn_undef_protocolref)
  1299. << proto->getDeclName();
  1300. Diag(forwardDecl->getLocation(), diag::note_protocol_decl_undefined)
  1301. << forwardDecl;
  1302. }
  1303. // If everything this far has been a type name (and we care
  1304. // about such things), check whether this name refers to a type
  1305. // as well.
  1306. if (allAreTypeNames) {
  1307. if (auto *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
  1308. LookupOrdinaryName)) {
  1309. if (isa<ObjCInterfaceDecl>(decl)) {
  1310. if (firstClassNameLoc.isInvalid())
  1311. firstClassNameLoc = identifierLocs[i];
  1312. } else if (!isa<TypeDecl>(decl)) {
  1313. // Not a type.
  1314. allAreTypeNames = false;
  1315. }
  1316. } else {
  1317. allAreTypeNames = false;
  1318. }
  1319. }
  1320. }
  1321. // All of the protocols listed also have type names, and at least
  1322. // one is an Objective-C class name. Check whether all of the
  1323. // protocol conformances are declared by the base class itself, in
  1324. // which case we warn.
  1325. if (allAreTypeNames && firstClassNameLoc.isValid()) {
  1326. llvm::SmallPtrSet<ObjCProtocolDecl*, 8> knownProtocols;
  1327. Context.CollectInheritedProtocols(baseClass, knownProtocols);
  1328. bool allProtocolsDeclared = true;
  1329. for (auto proto : protocols) {
  1330. if (knownProtocols.count(static_cast<ObjCProtocolDecl *>(proto)) == 0) {
  1331. allProtocolsDeclared = false;
  1332. break;
  1333. }
  1334. }
  1335. if (allProtocolsDeclared) {
  1336. Diag(firstClassNameLoc, diag::warn_objc_redundant_qualified_class_type)
  1337. << baseClass->getDeclName() << SourceRange(lAngleLoc, rAngleLoc)
  1338. << FixItHint::CreateInsertion(getLocForEndOfToken(firstClassNameLoc),
  1339. " *");
  1340. }
  1341. }
  1342. protocolLAngleLoc = lAngleLoc;
  1343. protocolRAngleLoc = rAngleLoc;
  1344. assert(protocols.size() == identifierLocs.size());
  1345. };
  1346. // Attempt to resolve all of the identifiers as protocols.
  1347. for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
  1348. ObjCProtocolDecl *proto = LookupProtocol(identifiers[i], identifierLocs[i]);
  1349. protocols.push_back(proto);
  1350. if (proto)
  1351. ++numProtocolsResolved;
  1352. }
  1353. // If all of the names were protocols, these were protocol qualifiers.
  1354. if (numProtocolsResolved == identifiers.size())
  1355. return resolvedAsProtocols();
  1356. // Attempt to resolve all of the identifiers as type names or
  1357. // Objective-C class names. The latter is technically ill-formed,
  1358. // but is probably something like \c NSArray<NSView *> missing the
  1359. // \c*.
  1360. typedef llvm::PointerUnion<TypeDecl *, ObjCInterfaceDecl *> TypeOrClassDecl;
  1361. SmallVector<TypeOrClassDecl, 4> typeDecls;
  1362. unsigned numTypeDeclsResolved = 0;
  1363. for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
  1364. NamedDecl *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
  1365. LookupOrdinaryName);
  1366. if (!decl) {
  1367. typeDecls.push_back(TypeOrClassDecl());
  1368. continue;
  1369. }
  1370. if (auto typeDecl = dyn_cast<TypeDecl>(decl)) {
  1371. typeDecls.push_back(typeDecl);
  1372. ++numTypeDeclsResolved;
  1373. continue;
  1374. }
  1375. if (auto objcClass = dyn_cast<ObjCInterfaceDecl>(decl)) {
  1376. typeDecls.push_back(objcClass);
  1377. ++numTypeDeclsResolved;
  1378. continue;
  1379. }
  1380. typeDecls.push_back(TypeOrClassDecl());
  1381. }
  1382. AttributeFactory attrFactory;
  1383. // Local function that forms a reference to the given type or
  1384. // Objective-C class declaration.
  1385. auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc)
  1386. -> TypeResult {
  1387. // Form declaration specifiers. They simply refer to the type.
  1388. DeclSpec DS(attrFactory);
  1389. const char* prevSpec; // unused
  1390. unsigned diagID; // unused
  1391. QualType type;
  1392. if (auto *actualTypeDecl = typeDecl.dyn_cast<TypeDecl *>())
  1393. type = Context.getTypeDeclType(actualTypeDecl);
  1394. else
  1395. type = Context.getObjCInterfaceType(typeDecl.get<ObjCInterfaceDecl *>());
  1396. TypeSourceInfo *parsedTSInfo = Context.getTrivialTypeSourceInfo(type, loc);
  1397. ParsedType parsedType = CreateParsedType(type, parsedTSInfo);
  1398. DS.SetTypeSpecType(DeclSpec::TST_typename, loc, prevSpec, diagID,
  1399. parsedType, Context.getPrintingPolicy());
  1400. // Use the identifier location for the type source range.
  1401. DS.SetRangeStart(loc);
  1402. DS.SetRangeEnd(loc);
  1403. // Form the declarator.
  1404. Declarator D(DS, DeclaratorContext::TypeNameContext);
  1405. // If we have a typedef of an Objective-C class type that is missing a '*',
  1406. // add the '*'.
  1407. if (type->getAs<ObjCInterfaceType>()) {
  1408. SourceLocation starLoc = getLocForEndOfToken(loc);
  1409. D.AddTypeInfo(DeclaratorChunk::getPointer(/*TypeQuals=*/0, starLoc,
  1410. SourceLocation(),
  1411. SourceLocation(),
  1412. SourceLocation(),
  1413. SourceLocation(),
  1414. SourceLocation()),
  1415. starLoc);
  1416. // Diagnose the missing '*'.
  1417. Diag(loc, diag::err_objc_type_arg_missing_star)
  1418. << type
  1419. << FixItHint::CreateInsertion(starLoc, " *");
  1420. }
  1421. // Convert this to a type.
  1422. return ActOnTypeName(S, D);
  1423. };
  1424. // Local function that updates the declaration specifiers with
  1425. // type argument information.
  1426. auto resolvedAsTypeDecls = [&] {
  1427. // We did not resolve these as protocols.
  1428. protocols.clear();
  1429. assert(numTypeDeclsResolved == identifiers.size() && "Unresolved type decl");
  1430. // Map type declarations to type arguments.
  1431. for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
  1432. // Map type reference to a type.
  1433. TypeResult type = resolveTypeReference(typeDecls[i], identifierLocs[i]);
  1434. if (!type.isUsable()) {
  1435. typeArgs.clear();
  1436. return;
  1437. }
  1438. typeArgs.push_back(type.get());
  1439. }
  1440. typeArgsLAngleLoc = lAngleLoc;
  1441. typeArgsRAngleLoc = rAngleLoc;
  1442. };
  1443. // If all of the identifiers can be resolved as type names or
  1444. // Objective-C class names, we have type arguments.
  1445. if (numTypeDeclsResolved == identifiers.size())
  1446. return resolvedAsTypeDecls();
  1447. // Error recovery: some names weren't found, or we have a mix of
  1448. // type and protocol names. Go resolve all of the unresolved names
  1449. // and complain if we can't find a consistent answer.
  1450. LookupNameKind lookupKind = LookupAnyName;
  1451. for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
  1452. // If we already have a protocol or type. Check whether it is the
  1453. // right thing.
  1454. if (protocols[i] || typeDecls[i]) {
  1455. // If we haven't figured out whether we want types or protocols
  1456. // yet, try to figure it out from this name.
  1457. if (lookupKind == LookupAnyName) {
  1458. // If this name refers to both a protocol and a type (e.g., \c
  1459. // NSObject), don't conclude anything yet.
  1460. if (protocols[i] && typeDecls[i])
  1461. continue;
  1462. // Otherwise, let this name decide whether we'll be correcting
  1463. // toward types or protocols.
  1464. lookupKind = protocols[i] ? LookupObjCProtocolName
  1465. : LookupOrdinaryName;
  1466. continue;
  1467. }
  1468. // If we want protocols and we have a protocol, there's nothing
  1469. // more to do.
  1470. if (lookupKind == LookupObjCProtocolName && protocols[i])
  1471. continue;
  1472. // If we want types and we have a type declaration, there's
  1473. // nothing more to do.
  1474. if (lookupKind == LookupOrdinaryName && typeDecls[i])
  1475. continue;
  1476. // We have a conflict: some names refer to protocols and others
  1477. // refer to types.
  1478. DiagnoseTypeArgsAndProtocols(identifiers[0], identifierLocs[0],
  1479. identifiers[i], identifierLocs[i],
  1480. protocols[i] != nullptr);
  1481. protocols.clear();
  1482. typeArgs.clear();
  1483. return;
  1484. }
  1485. // Perform typo correction on the name.
  1486. ObjCTypeArgOrProtocolValidatorCCC CCC(Context, lookupKind);
  1487. TypoCorrection corrected =
  1488. CorrectTypo(DeclarationNameInfo(identifiers[i], identifierLocs[i]),
  1489. lookupKind, S, nullptr, CCC, CTK_ErrorRecovery);
  1490. if (corrected) {
  1491. // Did we find a protocol?
  1492. if (auto proto = corrected.getCorrectionDeclAs<ObjCProtocolDecl>()) {
  1493. diagnoseTypo(corrected,
  1494. PDiag(diag::err_undeclared_protocol_suggest)
  1495. << identifiers[i]);
  1496. lookupKind = LookupObjCProtocolName;
  1497. protocols[i] = proto;
  1498. ++numProtocolsResolved;
  1499. continue;
  1500. }
  1501. // Did we find a type?
  1502. if (auto typeDecl = corrected.getCorrectionDeclAs<TypeDecl>()) {
  1503. diagnoseTypo(corrected,
  1504. PDiag(diag::err_unknown_typename_suggest)
  1505. << identifiers[i]);
  1506. lookupKind = LookupOrdinaryName;
  1507. typeDecls[i] = typeDecl;
  1508. ++numTypeDeclsResolved;
  1509. continue;
  1510. }
  1511. // Did we find an Objective-C class?
  1512. if (auto objcClass = corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
  1513. diagnoseTypo(corrected,
  1514. PDiag(diag::err_unknown_type_or_class_name_suggest)
  1515. << identifiers[i] << true);
  1516. lookupKind = LookupOrdinaryName;
  1517. typeDecls[i] = objcClass;
  1518. ++numTypeDeclsResolved;
  1519. continue;
  1520. }
  1521. }
  1522. // We couldn't find anything.
  1523. Diag(identifierLocs[i],
  1524. (lookupKind == LookupAnyName ? diag::err_objc_type_arg_missing
  1525. : lookupKind == LookupObjCProtocolName ? diag::err_undeclared_protocol
  1526. : diag::err_unknown_typename))
  1527. << identifiers[i];
  1528. protocols.clear();
  1529. typeArgs.clear();
  1530. return;
  1531. }
  1532. // If all of the names were (corrected to) protocols, these were
  1533. // protocol qualifiers.
  1534. if (numProtocolsResolved == identifiers.size())
  1535. return resolvedAsProtocols();
  1536. // Otherwise, all of the names were (corrected to) types.
  1537. assert(numTypeDeclsResolved == identifiers.size() && "Not all types?");
  1538. return resolvedAsTypeDecls();
  1539. }
  1540. /// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
  1541. /// a class method in its extension.
  1542. ///
  1543. void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
  1544. ObjCInterfaceDecl *ID) {
  1545. if (!ID)
  1546. return; // Possibly due to previous error
  1547. llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
  1548. for (auto *MD : ID->methods())
  1549. MethodMap[MD->getSelector()] = MD;
  1550. if (MethodMap.empty())
  1551. return;
  1552. for (const auto *Method : CAT->methods()) {
  1553. const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
  1554. if (PrevMethod &&
  1555. (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
  1556. !MatchTwoMethodDeclarations(Method, PrevMethod)) {
  1557. Diag(Method->getLocation(), diag::err_duplicate_method_decl)
  1558. << Method->getDeclName();
  1559. Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
  1560. }
  1561. }
  1562. }
  1563. /// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
  1564. Sema::DeclGroupPtrTy
  1565. Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
  1566. ArrayRef<IdentifierLocPair> IdentList,
  1567. const ParsedAttributesView &attrList) {
  1568. SmallVector<Decl *, 8> DeclsInGroup;
  1569. for (const IdentifierLocPair &IdentPair : IdentList) {
  1570. IdentifierInfo *Ident = IdentPair.first;
  1571. ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentPair.second,
  1572. forRedeclarationInCurContext());
  1573. ObjCProtocolDecl *PDecl
  1574. = ObjCProtocolDecl::Create(Context, CurContext, Ident,
  1575. IdentPair.second, AtProtocolLoc,
  1576. PrevDecl);
  1577. PushOnScopeChains(PDecl, TUScope);
  1578. CheckObjCDeclScope(PDecl);
  1579. ProcessDeclAttributeList(TUScope, PDecl, attrList);
  1580. AddPragmaAttributes(TUScope, PDecl);
  1581. if (PrevDecl)
  1582. mergeDeclAttributes(PDecl, PrevDecl);
  1583. DeclsInGroup.push_back(PDecl);
  1584. }
  1585. return BuildDeclaratorGroup(DeclsInGroup);
  1586. }
  1587. Decl *Sema::ActOnStartCategoryInterface(
  1588. SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
  1589. SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
  1590. IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
  1591. Decl *const *ProtoRefs, unsigned NumProtoRefs,
  1592. const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
  1593. const ParsedAttributesView &AttrList) {
  1594. ObjCCategoryDecl *CDecl;
  1595. ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
  1596. /// Check that class of this category is already completely declared.
  1597. if (!IDecl
  1598. || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
  1599. diag::err_category_forward_interface,
  1600. CategoryName == nullptr)) {
  1601. // Create an invalid ObjCCategoryDecl to serve as context for
  1602. // the enclosing method declarations. We mark the decl invalid
  1603. // to make it clear that this isn't a valid AST.
  1604. CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
  1605. ClassLoc, CategoryLoc, CategoryName,
  1606. IDecl, typeParamList);
  1607. CDecl->setInvalidDecl();
  1608. CurContext->addDecl(CDecl);
  1609. if (!IDecl)
  1610. Diag(ClassLoc, diag::err_undef_interface) << ClassName;
  1611. return ActOnObjCContainerStartDefinition(CDecl);
  1612. }
  1613. if (!CategoryName && IDecl->getImplementation()) {
  1614. Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
  1615. Diag(IDecl->getImplementation()->getLocation(),
  1616. diag::note_implementation_declared);
  1617. }
  1618. if (CategoryName) {
  1619. /// Check for duplicate interface declaration for this category
  1620. if (ObjCCategoryDecl *Previous
  1621. = IDecl->FindCategoryDeclaration(CategoryName)) {
  1622. // Class extensions can be declared multiple times, categories cannot.
  1623. Diag(CategoryLoc, diag::warn_dup_category_def)
  1624. << ClassName << CategoryName;
  1625. Diag(Previous->getLocation(), diag::note_previous_definition);
  1626. }
  1627. }
  1628. // If we have a type parameter list, check it.
  1629. if (typeParamList) {
  1630. if (auto prevTypeParamList = IDecl->getTypeParamList()) {
  1631. if (checkTypeParamListConsistency(*this, prevTypeParamList, typeParamList,
  1632. CategoryName
  1633. ? TypeParamListContext::Category
  1634. : TypeParamListContext::Extension))
  1635. typeParamList = nullptr;
  1636. } else {
  1637. Diag(typeParamList->getLAngleLoc(),
  1638. diag::err_objc_parameterized_category_nonclass)
  1639. << (CategoryName != nullptr)
  1640. << ClassName
  1641. << typeParamList->getSourceRange();
  1642. typeParamList = nullptr;
  1643. }
  1644. }
  1645. CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
  1646. ClassLoc, CategoryLoc, CategoryName, IDecl,
  1647. typeParamList);
  1648. // FIXME: PushOnScopeChains?
  1649. CurContext->addDecl(CDecl);
  1650. // Process the attributes before looking at protocols to ensure that the
  1651. // availability attribute is attached to the category to provide availability
  1652. // checking for protocol uses.
  1653. ProcessDeclAttributeList(TUScope, CDecl, AttrList);
  1654. AddPragmaAttributes(TUScope, CDecl);
  1655. if (NumProtoRefs) {
  1656. diagnoseUseOfProtocols(*this, CDecl, (ObjCProtocolDecl*const*)ProtoRefs,
  1657. NumProtoRefs, ProtoLocs);
  1658. CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
  1659. ProtoLocs, Context);
  1660. // Protocols in the class extension belong to the class.
  1661. if (CDecl->IsClassExtension())
  1662. IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
  1663. NumProtoRefs, Context);
  1664. }
  1665. CheckObjCDeclScope(CDecl);
  1666. return ActOnObjCContainerStartDefinition(CDecl);
  1667. }
  1668. /// ActOnStartCategoryImplementation - Perform semantic checks on the
  1669. /// category implementation declaration and build an ObjCCategoryImplDecl
  1670. /// object.
  1671. Decl *Sema::ActOnStartCategoryImplementation(
  1672. SourceLocation AtCatImplLoc,
  1673. IdentifierInfo *ClassName, SourceLocation ClassLoc,
  1674. IdentifierInfo *CatName, SourceLocation CatLoc,
  1675. const ParsedAttributesView &Attrs) {
  1676. ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
  1677. ObjCCategoryDecl *CatIDecl = nullptr;
  1678. if (IDecl && IDecl->hasDefinition()) {
  1679. CatIDecl = IDecl->FindCategoryDeclaration(CatName);
  1680. if (!CatIDecl) {
  1681. // Category @implementation with no corresponding @interface.
  1682. // Create and install one.
  1683. CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
  1684. ClassLoc, CatLoc,
  1685. CatName, IDecl,
  1686. /*typeParamList=*/nullptr);
  1687. CatIDecl->setImplicit();
  1688. }
  1689. }
  1690. ObjCCategoryImplDecl *CDecl =
  1691. ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
  1692. ClassLoc, AtCatImplLoc, CatLoc);
  1693. /// Check that class of this category is already completely declared.
  1694. if (!IDecl) {
  1695. Diag(ClassLoc, diag::err_undef_interface) << ClassName;
  1696. CDecl->setInvalidDecl();
  1697. } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
  1698. diag::err_undef_interface)) {
  1699. CDecl->setInvalidDecl();
  1700. }
  1701. ProcessDeclAttributeList(TUScope, CDecl, Attrs);
  1702. AddPragmaAttributes(TUScope, CDecl);
  1703. // FIXME: PushOnScopeChains?
  1704. CurContext->addDecl(CDecl);
  1705. // If the interface has the objc_runtime_visible attribute, we
  1706. // cannot implement a category for it.
  1707. if (IDecl && IDecl->hasAttr<ObjCRuntimeVisibleAttr>()) {
  1708. Diag(ClassLoc, diag::err_objc_runtime_visible_category)
  1709. << IDecl->getDeclName();
  1710. }
  1711. /// Check that CatName, category name, is not used in another implementation.
  1712. if (CatIDecl) {
  1713. if (CatIDecl->getImplementation()) {
  1714. Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
  1715. << CatName;
  1716. Diag(CatIDecl->getImplementation()->getLocation(),
  1717. diag::note_previous_definition);
  1718. CDecl->setInvalidDecl();
  1719. } else {
  1720. CatIDecl->setImplementation(CDecl);
  1721. // Warn on implementating category of deprecated class under
  1722. // -Wdeprecated-implementations flag.
  1723. DiagnoseObjCImplementedDeprecations(*this, CatIDecl,
  1724. CDecl->getLocation());
  1725. }
  1726. }
  1727. CheckObjCDeclScope(CDecl);
  1728. return ActOnObjCContainerStartDefinition(CDecl);
  1729. }
  1730. Decl *Sema::ActOnStartClassImplementation(
  1731. SourceLocation AtClassImplLoc,
  1732. IdentifierInfo *ClassName, SourceLocation ClassLoc,
  1733. IdentifierInfo *SuperClassname,
  1734. SourceLocation SuperClassLoc,
  1735. const ParsedAttributesView &Attrs) {
  1736. ObjCInterfaceDecl *IDecl = nullptr;
  1737. // Check for another declaration kind with the same name.
  1738. NamedDecl *PrevDecl
  1739. = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
  1740. forRedeclarationInCurContext());
  1741. if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
  1742. Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
  1743. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  1744. } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
  1745. // FIXME: This will produce an error if the definition of the interface has
  1746. // been imported from a module but is not visible.
  1747. RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
  1748. diag::warn_undef_interface);
  1749. } else {
  1750. // We did not find anything with the name ClassName; try to correct for
  1751. // typos in the class name.
  1752. ObjCInterfaceValidatorCCC CCC{};
  1753. TypoCorrection Corrected =
  1754. CorrectTypo(DeclarationNameInfo(ClassName, ClassLoc),
  1755. LookupOrdinaryName, TUScope, nullptr, CCC, CTK_NonError);
  1756. if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
  1757. // Suggest the (potentially) correct interface name. Don't provide a
  1758. // code-modification hint or use the typo name for recovery, because
  1759. // this is just a warning. The program may actually be correct.
  1760. diagnoseTypo(Corrected,
  1761. PDiag(diag::warn_undef_interface_suggest) << ClassName,
  1762. /*ErrorRecovery*/false);
  1763. } else {
  1764. Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
  1765. }
  1766. }
  1767. // Check that super class name is valid class name
  1768. ObjCInterfaceDecl *SDecl = nullptr;
  1769. if (SuperClassname) {
  1770. // Check if a different kind of symbol declared in this scope.
  1771. PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
  1772. LookupOrdinaryName);
  1773. if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
  1774. Diag(SuperClassLoc, diag::err_redefinition_different_kind)
  1775. << SuperClassname;
  1776. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  1777. } else {
  1778. SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
  1779. if (SDecl && !SDecl->hasDefinition())
  1780. SDecl = nullptr;
  1781. if (!SDecl)
  1782. Diag(SuperClassLoc, diag::err_undef_superclass)
  1783. << SuperClassname << ClassName;
  1784. else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
  1785. // This implementation and its interface do not have the same
  1786. // super class.
  1787. Diag(SuperClassLoc, diag::err_conflicting_super_class)
  1788. << SDecl->getDeclName();
  1789. Diag(SDecl->getLocation(), diag::note_previous_definition);
  1790. }
  1791. }
  1792. }
  1793. if (!IDecl) {
  1794. // Legacy case of @implementation with no corresponding @interface.
  1795. // Build, chain & install the interface decl into the identifier.
  1796. // FIXME: Do we support attributes on the @implementation? If so we should
  1797. // copy them over.
  1798. IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
  1799. ClassName, /*typeParamList=*/nullptr,
  1800. /*PrevDecl=*/nullptr, ClassLoc,
  1801. true);
  1802. AddPragmaAttributes(TUScope, IDecl);
  1803. IDecl->startDefinition();
  1804. if (SDecl) {
  1805. IDecl->setSuperClass(Context.getTrivialTypeSourceInfo(
  1806. Context.getObjCInterfaceType(SDecl),
  1807. SuperClassLoc));
  1808. IDecl->setEndOfDefinitionLoc(SuperClassLoc);
  1809. } else {
  1810. IDecl->setEndOfDefinitionLoc(ClassLoc);
  1811. }
  1812. PushOnScopeChains(IDecl, TUScope);
  1813. } else {
  1814. // Mark the interface as being completed, even if it was just as
  1815. // @class ....;
  1816. // declaration; the user cannot reopen it.
  1817. if (!IDecl->hasDefinition())
  1818. IDecl->startDefinition();
  1819. }
  1820. ObjCImplementationDecl* IMPDecl =
  1821. ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
  1822. ClassLoc, AtClassImplLoc, SuperClassLoc);
  1823. ProcessDeclAttributeList(TUScope, IMPDecl, Attrs);
  1824. AddPragmaAttributes(TUScope, IMPDecl);
  1825. if (CheckObjCDeclScope(IMPDecl))
  1826. return ActOnObjCContainerStartDefinition(IMPDecl);
  1827. // Check that there is no duplicate implementation of this class.
  1828. if (IDecl->getImplementation()) {
  1829. // FIXME: Don't leak everything!
  1830. Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
  1831. Diag(IDecl->getImplementation()->getLocation(),
  1832. diag::note_previous_definition);
  1833. IMPDecl->setInvalidDecl();
  1834. } else { // add it to the list.
  1835. IDecl->setImplementation(IMPDecl);
  1836. PushOnScopeChains(IMPDecl, TUScope);
  1837. // Warn on implementating deprecated class under
  1838. // -Wdeprecated-implementations flag.
  1839. DiagnoseObjCImplementedDeprecations(*this, IDecl, IMPDecl->getLocation());
  1840. }
  1841. // If the superclass has the objc_runtime_visible attribute, we
  1842. // cannot implement a subclass of it.
  1843. if (IDecl->getSuperClass() &&
  1844. IDecl->getSuperClass()->hasAttr<ObjCRuntimeVisibleAttr>()) {
  1845. Diag(ClassLoc, diag::err_objc_runtime_visible_subclass)
  1846. << IDecl->getDeclName()
  1847. << IDecl->getSuperClass()->getDeclName();
  1848. }
  1849. return ActOnObjCContainerStartDefinition(IMPDecl);
  1850. }
  1851. Sema::DeclGroupPtrTy
  1852. Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
  1853. SmallVector<Decl *, 64> DeclsInGroup;
  1854. DeclsInGroup.reserve(Decls.size() + 1);
  1855. for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
  1856. Decl *Dcl = Decls[i];
  1857. if (!Dcl)
  1858. continue;
  1859. if (Dcl->getDeclContext()->isFileContext())
  1860. Dcl->setTopLevelDeclInObjCContainer();
  1861. DeclsInGroup.push_back(Dcl);
  1862. }
  1863. DeclsInGroup.push_back(ObjCImpDecl);
  1864. return BuildDeclaratorGroup(DeclsInGroup);
  1865. }
  1866. void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
  1867. ObjCIvarDecl **ivars, unsigned numIvars,
  1868. SourceLocation RBrace) {
  1869. assert(ImpDecl && "missing implementation decl");
  1870. ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
  1871. if (!IDecl)
  1872. return;
  1873. /// Check case of non-existing \@interface decl.
  1874. /// (legacy objective-c \@implementation decl without an \@interface decl).
  1875. /// Add implementations's ivar to the synthesize class's ivar list.
  1876. if (IDecl->isImplicitInterfaceDecl()) {
  1877. IDecl->setEndOfDefinitionLoc(RBrace);
  1878. // Add ivar's to class's DeclContext.
  1879. for (unsigned i = 0, e = numIvars; i != e; ++i) {
  1880. ivars[i]->setLexicalDeclContext(ImpDecl);
  1881. IDecl->makeDeclVisibleInContext(ivars[i]);
  1882. ImpDecl->addDecl(ivars[i]);
  1883. }
  1884. return;
  1885. }
  1886. // If implementation has empty ivar list, just return.
  1887. if (numIvars == 0)
  1888. return;
  1889. assert(ivars && "missing @implementation ivars");
  1890. if (LangOpts.ObjCRuntime.isNonFragile()) {
  1891. if (ImpDecl->getSuperClass())
  1892. Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
  1893. for (unsigned i = 0; i < numIvars; i++) {
  1894. ObjCIvarDecl* ImplIvar = ivars[i];
  1895. if (const ObjCIvarDecl *ClsIvar =
  1896. IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
  1897. Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
  1898. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  1899. continue;
  1900. }
  1901. // Check class extensions (unnamed categories) for duplicate ivars.
  1902. for (const auto *CDecl : IDecl->visible_extensions()) {
  1903. if (const ObjCIvarDecl *ClsExtIvar =
  1904. CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
  1905. Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
  1906. Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
  1907. continue;
  1908. }
  1909. }
  1910. // Instance ivar to Implementation's DeclContext.
  1911. ImplIvar->setLexicalDeclContext(ImpDecl);
  1912. IDecl->makeDeclVisibleInContext(ImplIvar);
  1913. ImpDecl->addDecl(ImplIvar);
  1914. }
  1915. return;
  1916. }
  1917. // Check interface's Ivar list against those in the implementation.
  1918. // names and types must match.
  1919. //
  1920. unsigned j = 0;
  1921. ObjCInterfaceDecl::ivar_iterator
  1922. IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
  1923. for (; numIvars > 0 && IVI != IVE; ++IVI) {
  1924. ObjCIvarDecl* ImplIvar = ivars[j++];
  1925. ObjCIvarDecl* ClsIvar = *IVI;
  1926. assert (ImplIvar && "missing implementation ivar");
  1927. assert (ClsIvar && "missing class ivar");
  1928. // First, make sure the types match.
  1929. if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
  1930. Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
  1931. << ImplIvar->getIdentifier()
  1932. << ImplIvar->getType() << ClsIvar->getType();
  1933. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  1934. } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
  1935. ImplIvar->getBitWidthValue(Context) !=
  1936. ClsIvar->getBitWidthValue(Context)) {
  1937. Diag(ImplIvar->getBitWidth()->getBeginLoc(),
  1938. diag::err_conflicting_ivar_bitwidth)
  1939. << ImplIvar->getIdentifier();
  1940. Diag(ClsIvar->getBitWidth()->getBeginLoc(),
  1941. diag::note_previous_definition);
  1942. }
  1943. // Make sure the names are identical.
  1944. if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
  1945. Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
  1946. << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
  1947. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  1948. }
  1949. --numIvars;
  1950. }
  1951. if (numIvars > 0)
  1952. Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
  1953. else if (IVI != IVE)
  1954. Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
  1955. }
  1956. static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc,
  1957. ObjCMethodDecl *method,
  1958. bool &IncompleteImpl,
  1959. unsigned DiagID,
  1960. NamedDecl *NeededFor = nullptr) {
  1961. // No point warning no definition of method which is 'unavailable'.
  1962. if (method->getAvailability() == AR_Unavailable)
  1963. return;
  1964. // FIXME: For now ignore 'IncompleteImpl'.
  1965. // Previously we grouped all unimplemented methods under a single
  1966. // warning, but some users strongly voiced that they would prefer
  1967. // separate warnings. We will give that approach a try, as that
  1968. // matches what we do with protocols.
  1969. {
  1970. const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID);
  1971. B << method;
  1972. if (NeededFor)
  1973. B << NeededFor;
  1974. }
  1975. // Issue a note to the original declaration.
  1976. SourceLocation MethodLoc = method->getBeginLoc();
  1977. if (MethodLoc.isValid())
  1978. S.Diag(MethodLoc, diag::note_method_declared_at) << method;
  1979. }
  1980. /// Determines if type B can be substituted for type A. Returns true if we can
  1981. /// guarantee that anything that the user will do to an object of type A can
  1982. /// also be done to an object of type B. This is trivially true if the two
  1983. /// types are the same, or if B is a subclass of A. It becomes more complex
  1984. /// in cases where protocols are involved.
  1985. ///
  1986. /// Object types in Objective-C describe the minimum requirements for an
  1987. /// object, rather than providing a complete description of a type. For
  1988. /// example, if A is a subclass of B, then B* may refer to an instance of A.
  1989. /// The principle of substitutability means that we may use an instance of A
  1990. /// anywhere that we may use an instance of B - it will implement all of the
  1991. /// ivars of B and all of the methods of B.
  1992. ///
  1993. /// This substitutability is important when type checking methods, because
  1994. /// the implementation may have stricter type definitions than the interface.
  1995. /// The interface specifies minimum requirements, but the implementation may
  1996. /// have more accurate ones. For example, a method may privately accept
  1997. /// instances of B, but only publish that it accepts instances of A. Any
  1998. /// object passed to it will be type checked against B, and so will implicitly
  1999. /// by a valid A*. Similarly, a method may return a subclass of the class that
  2000. /// it is declared as returning.
  2001. ///
  2002. /// This is most important when considering subclassing. A method in a
  2003. /// subclass must accept any object as an argument that its superclass's
  2004. /// implementation accepts. It may, however, accept a more general type
  2005. /// without breaking substitutability (i.e. you can still use the subclass
  2006. /// anywhere that you can use the superclass, but not vice versa). The
  2007. /// converse requirement applies to return types: the return type for a
  2008. /// subclass method must be a valid object of the kind that the superclass
  2009. /// advertises, but it may be specified more accurately. This avoids the need
  2010. /// for explicit down-casting by callers.
  2011. ///
  2012. /// Note: This is a stricter requirement than for assignment.
  2013. static bool isObjCTypeSubstitutable(ASTContext &Context,
  2014. const ObjCObjectPointerType *A,
  2015. const ObjCObjectPointerType *B,
  2016. bool rejectId) {
  2017. // Reject a protocol-unqualified id.
  2018. if (rejectId && B->isObjCIdType()) return false;
  2019. // If B is a qualified id, then A must also be a qualified id and it must
  2020. // implement all of the protocols in B. It may not be a qualified class.
  2021. // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
  2022. // stricter definition so it is not substitutable for id<A>.
  2023. if (B->isObjCQualifiedIdType()) {
  2024. return A->isObjCQualifiedIdType() &&
  2025. Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
  2026. QualType(B,0),
  2027. false);
  2028. }
  2029. /*
  2030. // id is a special type that bypasses type checking completely. We want a
  2031. // warning when it is used in one place but not another.
  2032. if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
  2033. // If B is a qualified id, then A must also be a qualified id (which it isn't
  2034. // if we've got this far)
  2035. if (B->isObjCQualifiedIdType()) return false;
  2036. */
  2037. // Now we know that A and B are (potentially-qualified) class types. The
  2038. // normal rules for assignment apply.
  2039. return Context.canAssignObjCInterfaces(A, B);
  2040. }
  2041. static SourceRange getTypeRange(TypeSourceInfo *TSI) {
  2042. return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
  2043. }
  2044. /// Determine whether two set of Objective-C declaration qualifiers conflict.
  2045. static bool objcModifiersConflict(Decl::ObjCDeclQualifier x,
  2046. Decl::ObjCDeclQualifier y) {
  2047. return (x & ~Decl::OBJC_TQ_CSNullability) !=
  2048. (y & ~Decl::OBJC_TQ_CSNullability);
  2049. }
  2050. static bool CheckMethodOverrideReturn(Sema &S,
  2051. ObjCMethodDecl *MethodImpl,
  2052. ObjCMethodDecl *MethodDecl,
  2053. bool IsProtocolMethodDecl,
  2054. bool IsOverridingMode,
  2055. bool Warn) {
  2056. if (IsProtocolMethodDecl &&
  2057. objcModifiersConflict(MethodDecl->getObjCDeclQualifier(),
  2058. MethodImpl->getObjCDeclQualifier())) {
  2059. if (Warn) {
  2060. S.Diag(MethodImpl->getLocation(),
  2061. (IsOverridingMode
  2062. ? diag::warn_conflicting_overriding_ret_type_modifiers
  2063. : diag::warn_conflicting_ret_type_modifiers))
  2064. << MethodImpl->getDeclName()
  2065. << MethodImpl->getReturnTypeSourceRange();
  2066. S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
  2067. << MethodDecl->getReturnTypeSourceRange();
  2068. }
  2069. else
  2070. return false;
  2071. }
  2072. if (Warn && IsOverridingMode &&
  2073. !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
  2074. !S.Context.hasSameNullabilityTypeQualifier(MethodImpl->getReturnType(),
  2075. MethodDecl->getReturnType(),
  2076. false)) {
  2077. auto nullabilityMethodImpl =
  2078. *MethodImpl->getReturnType()->getNullability(S.Context);
  2079. auto nullabilityMethodDecl =
  2080. *MethodDecl->getReturnType()->getNullability(S.Context);
  2081. S.Diag(MethodImpl->getLocation(),
  2082. diag::warn_conflicting_nullability_attr_overriding_ret_types)
  2083. << DiagNullabilityKind(
  2084. nullabilityMethodImpl,
  2085. ((MethodImpl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2086. != 0))
  2087. << DiagNullabilityKind(
  2088. nullabilityMethodDecl,
  2089. ((MethodDecl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2090. != 0));
  2091. S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
  2092. }
  2093. if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
  2094. MethodDecl->getReturnType()))
  2095. return true;
  2096. if (!Warn)
  2097. return false;
  2098. unsigned DiagID =
  2099. IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
  2100. : diag::warn_conflicting_ret_types;
  2101. // Mismatches between ObjC pointers go into a different warning
  2102. // category, and sometimes they're even completely whitelisted.
  2103. if (const ObjCObjectPointerType *ImplPtrTy =
  2104. MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
  2105. if (const ObjCObjectPointerType *IfacePtrTy =
  2106. MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
  2107. // Allow non-matching return types as long as they don't violate
  2108. // the principle of substitutability. Specifically, we permit
  2109. // return types that are subclasses of the declared return type,
  2110. // or that are more-qualified versions of the declared type.
  2111. if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
  2112. return false;
  2113. DiagID =
  2114. IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
  2115. : diag::warn_non_covariant_ret_types;
  2116. }
  2117. }
  2118. S.Diag(MethodImpl->getLocation(), DiagID)
  2119. << MethodImpl->getDeclName() << MethodDecl->getReturnType()
  2120. << MethodImpl->getReturnType()
  2121. << MethodImpl->getReturnTypeSourceRange();
  2122. S.Diag(MethodDecl->getLocation(), IsOverridingMode
  2123. ? diag::note_previous_declaration
  2124. : diag::note_previous_definition)
  2125. << MethodDecl->getReturnTypeSourceRange();
  2126. return false;
  2127. }
  2128. static bool CheckMethodOverrideParam(Sema &S,
  2129. ObjCMethodDecl *MethodImpl,
  2130. ObjCMethodDecl *MethodDecl,
  2131. ParmVarDecl *ImplVar,
  2132. ParmVarDecl *IfaceVar,
  2133. bool IsProtocolMethodDecl,
  2134. bool IsOverridingMode,
  2135. bool Warn) {
  2136. if (IsProtocolMethodDecl &&
  2137. objcModifiersConflict(ImplVar->getObjCDeclQualifier(),
  2138. IfaceVar->getObjCDeclQualifier())) {
  2139. if (Warn) {
  2140. if (IsOverridingMode)
  2141. S.Diag(ImplVar->getLocation(),
  2142. diag::warn_conflicting_overriding_param_modifiers)
  2143. << getTypeRange(ImplVar->getTypeSourceInfo())
  2144. << MethodImpl->getDeclName();
  2145. else S.Diag(ImplVar->getLocation(),
  2146. diag::warn_conflicting_param_modifiers)
  2147. << getTypeRange(ImplVar->getTypeSourceInfo())
  2148. << MethodImpl->getDeclName();
  2149. S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
  2150. << getTypeRange(IfaceVar->getTypeSourceInfo());
  2151. }
  2152. else
  2153. return false;
  2154. }
  2155. QualType ImplTy = ImplVar->getType();
  2156. QualType IfaceTy = IfaceVar->getType();
  2157. if (Warn && IsOverridingMode &&
  2158. !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
  2159. !S.Context.hasSameNullabilityTypeQualifier(ImplTy, IfaceTy, true)) {
  2160. S.Diag(ImplVar->getLocation(),
  2161. diag::warn_conflicting_nullability_attr_overriding_param_types)
  2162. << DiagNullabilityKind(
  2163. *ImplTy->getNullability(S.Context),
  2164. ((ImplVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2165. != 0))
  2166. << DiagNullabilityKind(
  2167. *IfaceTy->getNullability(S.Context),
  2168. ((IfaceVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2169. != 0));
  2170. S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration);
  2171. }
  2172. if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
  2173. return true;
  2174. if (!Warn)
  2175. return false;
  2176. unsigned DiagID =
  2177. IsOverridingMode ? diag::warn_conflicting_overriding_param_types
  2178. : diag::warn_conflicting_param_types;
  2179. // Mismatches between ObjC pointers go into a different warning
  2180. // category, and sometimes they're even completely whitelisted.
  2181. if (const ObjCObjectPointerType *ImplPtrTy =
  2182. ImplTy->getAs<ObjCObjectPointerType>()) {
  2183. if (const ObjCObjectPointerType *IfacePtrTy =
  2184. IfaceTy->getAs<ObjCObjectPointerType>()) {
  2185. // Allow non-matching argument types as long as they don't
  2186. // violate the principle of substitutability. Specifically, the
  2187. // implementation must accept any objects that the superclass
  2188. // accepts, however it may also accept others.
  2189. if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
  2190. return false;
  2191. DiagID =
  2192. IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
  2193. : diag::warn_non_contravariant_param_types;
  2194. }
  2195. }
  2196. S.Diag(ImplVar->getLocation(), DiagID)
  2197. << getTypeRange(ImplVar->getTypeSourceInfo())
  2198. << MethodImpl->getDeclName() << IfaceTy << ImplTy;
  2199. S.Diag(IfaceVar->getLocation(),
  2200. (IsOverridingMode ? diag::note_previous_declaration
  2201. : diag::note_previous_definition))
  2202. << getTypeRange(IfaceVar->getTypeSourceInfo());
  2203. return false;
  2204. }
  2205. /// In ARC, check whether the conventional meanings of the two methods
  2206. /// match. If they don't, it's a hard error.
  2207. static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
  2208. ObjCMethodDecl *decl) {
  2209. ObjCMethodFamily implFamily = impl->getMethodFamily();
  2210. ObjCMethodFamily declFamily = decl->getMethodFamily();
  2211. if (implFamily == declFamily) return false;
  2212. // Since conventions are sorted by selector, the only possibility is
  2213. // that the types differ enough to cause one selector or the other
  2214. // to fall out of the family.
  2215. assert(implFamily == OMF_None || declFamily == OMF_None);
  2216. // No further diagnostics required on invalid declarations.
  2217. if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
  2218. const ObjCMethodDecl *unmatched = impl;
  2219. ObjCMethodFamily family = declFamily;
  2220. unsigned errorID = diag::err_arc_lost_method_convention;
  2221. unsigned noteID = diag::note_arc_lost_method_convention;
  2222. if (declFamily == OMF_None) {
  2223. unmatched = decl;
  2224. family = implFamily;
  2225. errorID = diag::err_arc_gained_method_convention;
  2226. noteID = diag::note_arc_gained_method_convention;
  2227. }
  2228. // Indexes into a %select clause in the diagnostic.
  2229. enum FamilySelector {
  2230. F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
  2231. };
  2232. FamilySelector familySelector = FamilySelector();
  2233. switch (family) {
  2234. case OMF_None: llvm_unreachable("logic error, no method convention");
  2235. case OMF_retain:
  2236. case OMF_release:
  2237. case OMF_autorelease:
  2238. case OMF_dealloc:
  2239. case OMF_finalize:
  2240. case OMF_retainCount:
  2241. case OMF_self:
  2242. case OMF_initialize:
  2243. case OMF_performSelector:
  2244. // Mismatches for these methods don't change ownership
  2245. // conventions, so we don't care.
  2246. return false;
  2247. case OMF_init: familySelector = F_init; break;
  2248. case OMF_alloc: familySelector = F_alloc; break;
  2249. case OMF_copy: familySelector = F_copy; break;
  2250. case OMF_mutableCopy: familySelector = F_mutableCopy; break;
  2251. case OMF_new: familySelector = F_new; break;
  2252. }
  2253. enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
  2254. ReasonSelector reasonSelector;
  2255. // The only reason these methods don't fall within their families is
  2256. // due to unusual result types.
  2257. if (unmatched->getReturnType()->isObjCObjectPointerType()) {
  2258. reasonSelector = R_UnrelatedReturn;
  2259. } else {
  2260. reasonSelector = R_NonObjectReturn;
  2261. }
  2262. S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
  2263. S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
  2264. return true;
  2265. }
  2266. void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
  2267. ObjCMethodDecl *MethodDecl,
  2268. bool IsProtocolMethodDecl) {
  2269. if (getLangOpts().ObjCAutoRefCount &&
  2270. checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
  2271. return;
  2272. CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
  2273. IsProtocolMethodDecl, false,
  2274. true);
  2275. for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
  2276. IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
  2277. EF = MethodDecl->param_end();
  2278. IM != EM && IF != EF; ++IM, ++IF) {
  2279. CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
  2280. IsProtocolMethodDecl, false, true);
  2281. }
  2282. if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
  2283. Diag(ImpMethodDecl->getLocation(),
  2284. diag::warn_conflicting_variadic);
  2285. Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
  2286. }
  2287. }
  2288. void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
  2289. ObjCMethodDecl *Overridden,
  2290. bool IsProtocolMethodDecl) {
  2291. CheckMethodOverrideReturn(*this, Method, Overridden,
  2292. IsProtocolMethodDecl, true,
  2293. true);
  2294. for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
  2295. IF = Overridden->param_begin(), EM = Method->param_end(),
  2296. EF = Overridden->param_end();
  2297. IM != EM && IF != EF; ++IM, ++IF) {
  2298. CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
  2299. IsProtocolMethodDecl, true, true);
  2300. }
  2301. if (Method->isVariadic() != Overridden->isVariadic()) {
  2302. Diag(Method->getLocation(),
  2303. diag::warn_conflicting_overriding_variadic);
  2304. Diag(Overridden->getLocation(), diag::note_previous_declaration);
  2305. }
  2306. }
  2307. /// WarnExactTypedMethods - This routine issues a warning if method
  2308. /// implementation declaration matches exactly that of its declaration.
  2309. void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
  2310. ObjCMethodDecl *MethodDecl,
  2311. bool IsProtocolMethodDecl) {
  2312. // don't issue warning when protocol method is optional because primary
  2313. // class is not required to implement it and it is safe for protocol
  2314. // to implement it.
  2315. if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
  2316. return;
  2317. // don't issue warning when primary class's method is
  2318. // depecated/unavailable.
  2319. if (MethodDecl->hasAttr<UnavailableAttr>() ||
  2320. MethodDecl->hasAttr<DeprecatedAttr>())
  2321. return;
  2322. bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
  2323. IsProtocolMethodDecl, false, false);
  2324. if (match)
  2325. for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
  2326. IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
  2327. EF = MethodDecl->param_end();
  2328. IM != EM && IF != EF; ++IM, ++IF) {
  2329. match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
  2330. *IM, *IF,
  2331. IsProtocolMethodDecl, false, false);
  2332. if (!match)
  2333. break;
  2334. }
  2335. if (match)
  2336. match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
  2337. if (match)
  2338. match = !(MethodDecl->isClassMethod() &&
  2339. MethodDecl->getSelector() == GetNullarySelector("load", Context));
  2340. if (match) {
  2341. Diag(ImpMethodDecl->getLocation(),
  2342. diag::warn_category_method_impl_match);
  2343. Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
  2344. << MethodDecl->getDeclName();
  2345. }
  2346. }
  2347. /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
  2348. /// improve the efficiency of selector lookups and type checking by associating
  2349. /// with each protocol / interface / category the flattened instance tables. If
  2350. /// we used an immutable set to keep the table then it wouldn't add significant
  2351. /// memory cost and it would be handy for lookups.
  2352. typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
  2353. typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
  2354. static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
  2355. ProtocolNameSet &PNS) {
  2356. if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
  2357. PNS.insert(PDecl->getIdentifier());
  2358. for (const auto *PI : PDecl->protocols())
  2359. findProtocolsWithExplicitImpls(PI, PNS);
  2360. }
  2361. /// Recursively populates a set with all conformed protocols in a class
  2362. /// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
  2363. /// attribute.
  2364. static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
  2365. ProtocolNameSet &PNS) {
  2366. if (!Super)
  2367. return;
  2368. for (const auto *I : Super->all_referenced_protocols())
  2369. findProtocolsWithExplicitImpls(I, PNS);
  2370. findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
  2371. }
  2372. /// CheckProtocolMethodDefs - This routine checks unimplemented methods
  2373. /// Declared in protocol, and those referenced by it.
  2374. static void CheckProtocolMethodDefs(Sema &S,
  2375. SourceLocation ImpLoc,
  2376. ObjCProtocolDecl *PDecl,
  2377. bool& IncompleteImpl,
  2378. const Sema::SelectorSet &InsMap,
  2379. const Sema::SelectorSet &ClsMap,
  2380. ObjCContainerDecl *CDecl,
  2381. LazyProtocolNameSet &ProtocolsExplictImpl) {
  2382. ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
  2383. ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
  2384. : dyn_cast<ObjCInterfaceDecl>(CDecl);
  2385. assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
  2386. ObjCInterfaceDecl *Super = IDecl->getSuperClass();
  2387. ObjCInterfaceDecl *NSIDecl = nullptr;
  2388. // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
  2389. // then we should check if any class in the super class hierarchy also
  2390. // conforms to this protocol, either directly or via protocol inheritance.
  2391. // If so, we can skip checking this protocol completely because we
  2392. // know that a parent class already satisfies this protocol.
  2393. //
  2394. // Note: we could generalize this logic for all protocols, and merely
  2395. // add the limit on looking at the super class chain for just
  2396. // specially marked protocols. This may be a good optimization. This
  2397. // change is restricted to 'objc_protocol_requires_explicit_implementation'
  2398. // protocols for now for controlled evaluation.
  2399. if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
  2400. if (!ProtocolsExplictImpl) {
  2401. ProtocolsExplictImpl.reset(new ProtocolNameSet);
  2402. findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
  2403. }
  2404. if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) !=
  2405. ProtocolsExplictImpl->end())
  2406. return;
  2407. // If no super class conforms to the protocol, we should not search
  2408. // for methods in the super class to implicitly satisfy the protocol.
  2409. Super = nullptr;
  2410. }
  2411. if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
  2412. // check to see if class implements forwardInvocation method and objects
  2413. // of this class are derived from 'NSProxy' so that to forward requests
  2414. // from one object to another.
  2415. // Under such conditions, which means that every method possible is
  2416. // implemented in the class, we should not issue "Method definition not
  2417. // found" warnings.
  2418. // FIXME: Use a general GetUnarySelector method for this.
  2419. IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
  2420. Selector fISelector = S.Context.Selectors.getSelector(1, &II);
  2421. if (InsMap.count(fISelector))
  2422. // Is IDecl derived from 'NSProxy'? If so, no instance methods
  2423. // need be implemented in the implementation.
  2424. NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
  2425. }
  2426. // If this is a forward protocol declaration, get its definition.
  2427. if (!PDecl->isThisDeclarationADefinition() &&
  2428. PDecl->getDefinition())
  2429. PDecl = PDecl->getDefinition();
  2430. // If a method lookup fails locally we still need to look and see if
  2431. // the method was implemented by a base class or an inherited
  2432. // protocol. This lookup is slow, but occurs rarely in correct code
  2433. // and otherwise would terminate in a warning.
  2434. // check unimplemented instance methods.
  2435. if (!NSIDecl)
  2436. for (auto *method : PDecl->instance_methods()) {
  2437. if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
  2438. !method->isPropertyAccessor() &&
  2439. !InsMap.count(method->getSelector()) &&
  2440. (!Super || !Super->lookupMethod(method->getSelector(),
  2441. true /* instance */,
  2442. false /* shallowCategory */,
  2443. true /* followsSuper */,
  2444. nullptr /* category */))) {
  2445. // If a method is not implemented in the category implementation but
  2446. // has been declared in its primary class, superclass,
  2447. // or in one of their protocols, no need to issue the warning.
  2448. // This is because method will be implemented in the primary class
  2449. // or one of its super class implementation.
  2450. // Ugly, but necessary. Method declared in protocol might have
  2451. // have been synthesized due to a property declared in the class which
  2452. // uses the protocol.
  2453. if (ObjCMethodDecl *MethodInClass =
  2454. IDecl->lookupMethod(method->getSelector(),
  2455. true /* instance */,
  2456. true /* shallowCategoryLookup */,
  2457. false /* followSuper */))
  2458. if (C || MethodInClass->isPropertyAccessor())
  2459. continue;
  2460. unsigned DIAG = diag::warn_unimplemented_protocol_method;
  2461. if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
  2462. WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
  2463. PDecl);
  2464. }
  2465. }
  2466. }
  2467. // check unimplemented class methods
  2468. for (auto *method : PDecl->class_methods()) {
  2469. if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
  2470. !ClsMap.count(method->getSelector()) &&
  2471. (!Super || !Super->lookupMethod(method->getSelector(),
  2472. false /* class method */,
  2473. false /* shallowCategoryLookup */,
  2474. true /* followSuper */,
  2475. nullptr /* category */))) {
  2476. // See above comment for instance method lookups.
  2477. if (C && IDecl->lookupMethod(method->getSelector(),
  2478. false /* class */,
  2479. true /* shallowCategoryLookup */,
  2480. false /* followSuper */))
  2481. continue;
  2482. unsigned DIAG = diag::warn_unimplemented_protocol_method;
  2483. if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
  2484. WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
  2485. }
  2486. }
  2487. }
  2488. // Check on this protocols's referenced protocols, recursively.
  2489. for (auto *PI : PDecl->protocols())
  2490. CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
  2491. CDecl, ProtocolsExplictImpl);
  2492. }
  2493. /// MatchAllMethodDeclarations - Check methods declared in interface
  2494. /// or protocol against those declared in their implementations.
  2495. ///
  2496. void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
  2497. const SelectorSet &ClsMap,
  2498. SelectorSet &InsMapSeen,
  2499. SelectorSet &ClsMapSeen,
  2500. ObjCImplDecl* IMPDecl,
  2501. ObjCContainerDecl* CDecl,
  2502. bool &IncompleteImpl,
  2503. bool ImmediateClass,
  2504. bool WarnCategoryMethodImpl) {
  2505. // Check and see if instance methods in class interface have been
  2506. // implemented in the implementation class. If so, their types match.
  2507. for (auto *I : CDecl->instance_methods()) {
  2508. if (!InsMapSeen.insert(I->getSelector()).second)
  2509. continue;
  2510. if (!I->isPropertyAccessor() &&
  2511. !InsMap.count(I->getSelector())) {
  2512. if (ImmediateClass)
  2513. WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
  2514. diag::warn_undef_method_impl);
  2515. continue;
  2516. } else {
  2517. ObjCMethodDecl *ImpMethodDecl =
  2518. IMPDecl->getInstanceMethod(I->getSelector());
  2519. assert(CDecl->getInstanceMethod(I->getSelector(), true/*AllowHidden*/) &&
  2520. "Expected to find the method through lookup as well");
  2521. // ImpMethodDecl may be null as in a @dynamic property.
  2522. if (ImpMethodDecl) {
  2523. if (!WarnCategoryMethodImpl)
  2524. WarnConflictingTypedMethods(ImpMethodDecl, I,
  2525. isa<ObjCProtocolDecl>(CDecl));
  2526. else if (!I->isPropertyAccessor())
  2527. WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
  2528. }
  2529. }
  2530. }
  2531. // Check and see if class methods in class interface have been
  2532. // implemented in the implementation class. If so, their types match.
  2533. for (auto *I : CDecl->class_methods()) {
  2534. if (!ClsMapSeen.insert(I->getSelector()).second)
  2535. continue;
  2536. if (!I->isPropertyAccessor() &&
  2537. !ClsMap.count(I->getSelector())) {
  2538. if (ImmediateClass)
  2539. WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
  2540. diag::warn_undef_method_impl);
  2541. } else {
  2542. ObjCMethodDecl *ImpMethodDecl =
  2543. IMPDecl->getClassMethod(I->getSelector());
  2544. assert(CDecl->getClassMethod(I->getSelector(), true/*AllowHidden*/) &&
  2545. "Expected to find the method through lookup as well");
  2546. // ImpMethodDecl may be null as in a @dynamic property.
  2547. if (ImpMethodDecl) {
  2548. if (!WarnCategoryMethodImpl)
  2549. WarnConflictingTypedMethods(ImpMethodDecl, I,
  2550. isa<ObjCProtocolDecl>(CDecl));
  2551. else if (!I->isPropertyAccessor())
  2552. WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
  2553. }
  2554. }
  2555. }
  2556. if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
  2557. // Also, check for methods declared in protocols inherited by
  2558. // this protocol.
  2559. for (auto *PI : PD->protocols())
  2560. MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
  2561. IMPDecl, PI, IncompleteImpl, false,
  2562. WarnCategoryMethodImpl);
  2563. }
  2564. if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
  2565. // when checking that methods in implementation match their declaration,
  2566. // i.e. when WarnCategoryMethodImpl is false, check declarations in class
  2567. // extension; as well as those in categories.
  2568. if (!WarnCategoryMethodImpl) {
  2569. for (auto *Cat : I->visible_categories())
  2570. MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
  2571. IMPDecl, Cat, IncompleteImpl,
  2572. ImmediateClass && Cat->IsClassExtension(),
  2573. WarnCategoryMethodImpl);
  2574. } else {
  2575. // Also methods in class extensions need be looked at next.
  2576. for (auto *Ext : I->visible_extensions())
  2577. MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
  2578. IMPDecl, Ext, IncompleteImpl, false,
  2579. WarnCategoryMethodImpl);
  2580. }
  2581. // Check for any implementation of a methods declared in protocol.
  2582. for (auto *PI : I->all_referenced_protocols())
  2583. MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
  2584. IMPDecl, PI, IncompleteImpl, false,
  2585. WarnCategoryMethodImpl);
  2586. // FIXME. For now, we are not checking for exact match of methods
  2587. // in category implementation and its primary class's super class.
  2588. if (!WarnCategoryMethodImpl && I->getSuperClass())
  2589. MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
  2590. IMPDecl,
  2591. I->getSuperClass(), IncompleteImpl, false);
  2592. }
  2593. }
  2594. /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
  2595. /// category matches with those implemented in its primary class and
  2596. /// warns each time an exact match is found.
  2597. void Sema::CheckCategoryVsClassMethodMatches(
  2598. ObjCCategoryImplDecl *CatIMPDecl) {
  2599. // Get category's primary class.
  2600. ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
  2601. if (!CatDecl)
  2602. return;
  2603. ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
  2604. if (!IDecl)
  2605. return;
  2606. ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
  2607. SelectorSet InsMap, ClsMap;
  2608. for (const auto *I : CatIMPDecl->instance_methods()) {
  2609. Selector Sel = I->getSelector();
  2610. // When checking for methods implemented in the category, skip over
  2611. // those declared in category class's super class. This is because
  2612. // the super class must implement the method.
  2613. if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
  2614. continue;
  2615. InsMap.insert(Sel);
  2616. }
  2617. for (const auto *I : CatIMPDecl->class_methods()) {
  2618. Selector Sel = I->getSelector();
  2619. if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
  2620. continue;
  2621. ClsMap.insert(Sel);
  2622. }
  2623. if (InsMap.empty() && ClsMap.empty())
  2624. return;
  2625. SelectorSet InsMapSeen, ClsMapSeen;
  2626. bool IncompleteImpl = false;
  2627. MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
  2628. CatIMPDecl, IDecl,
  2629. IncompleteImpl, false,
  2630. true /*WarnCategoryMethodImpl*/);
  2631. }
  2632. void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
  2633. ObjCContainerDecl* CDecl,
  2634. bool IncompleteImpl) {
  2635. SelectorSet InsMap;
  2636. // Check and see if instance methods in class interface have been
  2637. // implemented in the implementation class.
  2638. for (const auto *I : IMPDecl->instance_methods())
  2639. InsMap.insert(I->getSelector());
  2640. // Add the selectors for getters/setters of @dynamic properties.
  2641. for (const auto *PImpl : IMPDecl->property_impls()) {
  2642. // We only care about @dynamic implementations.
  2643. if (PImpl->getPropertyImplementation() != ObjCPropertyImplDecl::Dynamic)
  2644. continue;
  2645. const auto *P = PImpl->getPropertyDecl();
  2646. if (!P) continue;
  2647. InsMap.insert(P->getGetterName());
  2648. if (!P->getSetterName().isNull())
  2649. InsMap.insert(P->getSetterName());
  2650. }
  2651. // Check and see if properties declared in the interface have either 1)
  2652. // an implementation or 2) there is a @synthesize/@dynamic implementation
  2653. // of the property in the @implementation.
  2654. if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
  2655. bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
  2656. LangOpts.ObjCRuntime.isNonFragile() &&
  2657. !IDecl->isObjCRequiresPropertyDefs();
  2658. DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
  2659. }
  2660. // Diagnose null-resettable synthesized setters.
  2661. diagnoseNullResettableSynthesizedSetters(IMPDecl);
  2662. SelectorSet ClsMap;
  2663. for (const auto *I : IMPDecl->class_methods())
  2664. ClsMap.insert(I->getSelector());
  2665. // Check for type conflict of methods declared in a class/protocol and
  2666. // its implementation; if any.
  2667. SelectorSet InsMapSeen, ClsMapSeen;
  2668. MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
  2669. IMPDecl, CDecl,
  2670. IncompleteImpl, true);
  2671. // check all methods implemented in category against those declared
  2672. // in its primary class.
  2673. if (ObjCCategoryImplDecl *CatDecl =
  2674. dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
  2675. CheckCategoryVsClassMethodMatches(CatDecl);
  2676. // Check the protocol list for unimplemented methods in the @implementation
  2677. // class.
  2678. // Check and see if class methods in class interface have been
  2679. // implemented in the implementation class.
  2680. LazyProtocolNameSet ExplicitImplProtocols;
  2681. if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
  2682. for (auto *PI : I->all_referenced_protocols())
  2683. CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl,
  2684. InsMap, ClsMap, I, ExplicitImplProtocols);
  2685. } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
  2686. // For extended class, unimplemented methods in its protocols will
  2687. // be reported in the primary class.
  2688. if (!C->IsClassExtension()) {
  2689. for (auto *P : C->protocols())
  2690. CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P,
  2691. IncompleteImpl, InsMap, ClsMap, CDecl,
  2692. ExplicitImplProtocols);
  2693. DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
  2694. /*SynthesizeProperties=*/false);
  2695. }
  2696. } else
  2697. llvm_unreachable("invalid ObjCContainerDecl type.");
  2698. }
  2699. Sema::DeclGroupPtrTy
  2700. Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
  2701. IdentifierInfo **IdentList,
  2702. SourceLocation *IdentLocs,
  2703. ArrayRef<ObjCTypeParamList *> TypeParamLists,
  2704. unsigned NumElts) {
  2705. SmallVector<Decl *, 8> DeclsInGroup;
  2706. for (unsigned i = 0; i != NumElts; ++i) {
  2707. // Check for another declaration kind with the same name.
  2708. NamedDecl *PrevDecl
  2709. = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
  2710. LookupOrdinaryName, forRedeclarationInCurContext());
  2711. if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
  2712. // GCC apparently allows the following idiom:
  2713. //
  2714. // typedef NSObject < XCElementTogglerP > XCElementToggler;
  2715. // @class XCElementToggler;
  2716. //
  2717. // Here we have chosen to ignore the forward class declaration
  2718. // with a warning. Since this is the implied behavior.
  2719. TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
  2720. if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
  2721. Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
  2722. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  2723. } else {
  2724. // a forward class declaration matching a typedef name of a class refers
  2725. // to the underlying class. Just ignore the forward class with a warning
  2726. // as this will force the intended behavior which is to lookup the
  2727. // typedef name.
  2728. if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
  2729. Diag(AtClassLoc, diag::warn_forward_class_redefinition)
  2730. << IdentList[i];
  2731. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  2732. continue;
  2733. }
  2734. }
  2735. }
  2736. // Create a declaration to describe this forward declaration.
  2737. ObjCInterfaceDecl *PrevIDecl
  2738. = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
  2739. IdentifierInfo *ClassName = IdentList[i];
  2740. if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
  2741. // A previous decl with a different name is because of
  2742. // @compatibility_alias, for example:
  2743. // \code
  2744. // @class NewImage;
  2745. // @compatibility_alias OldImage NewImage;
  2746. // \endcode
  2747. // A lookup for 'OldImage' will return the 'NewImage' decl.
  2748. //
  2749. // In such a case use the real declaration name, instead of the alias one,
  2750. // otherwise we will break IdentifierResolver and redecls-chain invariants.
  2751. // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
  2752. // has been aliased.
  2753. ClassName = PrevIDecl->getIdentifier();
  2754. }
  2755. // If this forward declaration has type parameters, compare them with the
  2756. // type parameters of the previous declaration.
  2757. ObjCTypeParamList *TypeParams = TypeParamLists[i];
  2758. if (PrevIDecl && TypeParams) {
  2759. if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) {
  2760. // Check for consistency with the previous declaration.
  2761. if (checkTypeParamListConsistency(
  2762. *this, PrevTypeParams, TypeParams,
  2763. TypeParamListContext::ForwardDeclaration)) {
  2764. TypeParams = nullptr;
  2765. }
  2766. } else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
  2767. // The @interface does not have type parameters. Complain.
  2768. Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class)
  2769. << ClassName
  2770. << TypeParams->getSourceRange();
  2771. Diag(Def->getLocation(), diag::note_defined_here)
  2772. << ClassName;
  2773. TypeParams = nullptr;
  2774. }
  2775. }
  2776. ObjCInterfaceDecl *IDecl
  2777. = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
  2778. ClassName, TypeParams, PrevIDecl,
  2779. IdentLocs[i]);
  2780. IDecl->setAtEndRange(IdentLocs[i]);
  2781. PushOnScopeChains(IDecl, TUScope);
  2782. CheckObjCDeclScope(IDecl);
  2783. DeclsInGroup.push_back(IDecl);
  2784. }
  2785. return BuildDeclaratorGroup(DeclsInGroup);
  2786. }
  2787. static bool tryMatchRecordTypes(ASTContext &Context,
  2788. Sema::MethodMatchStrategy strategy,
  2789. const Type *left, const Type *right);
  2790. static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
  2791. QualType leftQT, QualType rightQT) {
  2792. const Type *left =
  2793. Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
  2794. const Type *right =
  2795. Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
  2796. if (left == right) return true;
  2797. // If we're doing a strict match, the types have to match exactly.
  2798. if (strategy == Sema::MMS_strict) return false;
  2799. if (left->isIncompleteType() || right->isIncompleteType()) return false;
  2800. // Otherwise, use this absurdly complicated algorithm to try to
  2801. // validate the basic, low-level compatibility of the two types.
  2802. // As a minimum, require the sizes and alignments to match.
  2803. TypeInfo LeftTI = Context.getTypeInfo(left);
  2804. TypeInfo RightTI = Context.getTypeInfo(right);
  2805. if (LeftTI.Width != RightTI.Width)
  2806. return false;
  2807. if (LeftTI.Align != RightTI.Align)
  2808. return false;
  2809. // Consider all the kinds of non-dependent canonical types:
  2810. // - functions and arrays aren't possible as return and parameter types
  2811. // - vector types of equal size can be arbitrarily mixed
  2812. if (isa<VectorType>(left)) return isa<VectorType>(right);
  2813. if (isa<VectorType>(right)) return false;
  2814. // - references should only match references of identical type
  2815. // - structs, unions, and Objective-C objects must match more-or-less
  2816. // exactly
  2817. // - everything else should be a scalar
  2818. if (!left->isScalarType() || !right->isScalarType())
  2819. return tryMatchRecordTypes(Context, strategy, left, right);
  2820. // Make scalars agree in kind, except count bools as chars, and group
  2821. // all non-member pointers together.
  2822. Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
  2823. Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
  2824. if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
  2825. if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
  2826. if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
  2827. leftSK = Type::STK_ObjCObjectPointer;
  2828. if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
  2829. rightSK = Type::STK_ObjCObjectPointer;
  2830. // Note that data member pointers and function member pointers don't
  2831. // intermix because of the size differences.
  2832. return (leftSK == rightSK);
  2833. }
  2834. static bool tryMatchRecordTypes(ASTContext &Context,
  2835. Sema::MethodMatchStrategy strategy,
  2836. const Type *lt, const Type *rt) {
  2837. assert(lt && rt && lt != rt);
  2838. if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
  2839. RecordDecl *left = cast<RecordType>(lt)->getDecl();
  2840. RecordDecl *right = cast<RecordType>(rt)->getDecl();
  2841. // Require union-hood to match.
  2842. if (left->isUnion() != right->isUnion()) return false;
  2843. // Require an exact match if either is non-POD.
  2844. if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
  2845. (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
  2846. return false;
  2847. // Require size and alignment to match.
  2848. TypeInfo LeftTI = Context.getTypeInfo(lt);
  2849. TypeInfo RightTI = Context.getTypeInfo(rt);
  2850. if (LeftTI.Width != RightTI.Width)
  2851. return false;
  2852. if (LeftTI.Align != RightTI.Align)
  2853. return false;
  2854. // Require fields to match.
  2855. RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
  2856. RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
  2857. for (; li != le && ri != re; ++li, ++ri) {
  2858. if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
  2859. return false;
  2860. }
  2861. return (li == le && ri == re);
  2862. }
  2863. /// MatchTwoMethodDeclarations - Checks that two methods have matching type and
  2864. /// returns true, or false, accordingly.
  2865. /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
  2866. bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
  2867. const ObjCMethodDecl *right,
  2868. MethodMatchStrategy strategy) {
  2869. if (!matchTypes(Context, strategy, left->getReturnType(),
  2870. right->getReturnType()))
  2871. return false;
  2872. // If either is hidden, it is not considered to match.
  2873. if (left->isHidden() || right->isHidden())
  2874. return false;
  2875. if (getLangOpts().ObjCAutoRefCount &&
  2876. (left->hasAttr<NSReturnsRetainedAttr>()
  2877. != right->hasAttr<NSReturnsRetainedAttr>() ||
  2878. left->hasAttr<NSConsumesSelfAttr>()
  2879. != right->hasAttr<NSConsumesSelfAttr>()))
  2880. return false;
  2881. ObjCMethodDecl::param_const_iterator
  2882. li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
  2883. re = right->param_end();
  2884. for (; li != le && ri != re; ++li, ++ri) {
  2885. assert(ri != right->param_end() && "Param mismatch");
  2886. const ParmVarDecl *lparm = *li, *rparm = *ri;
  2887. if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
  2888. return false;
  2889. if (getLangOpts().ObjCAutoRefCount &&
  2890. lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
  2891. return false;
  2892. }
  2893. return true;
  2894. }
  2895. static bool isMethodContextSameForKindofLookup(ObjCMethodDecl *Method,
  2896. ObjCMethodDecl *MethodInList) {
  2897. auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
  2898. auto *MethodInListProtocol =
  2899. dyn_cast<ObjCProtocolDecl>(MethodInList->getDeclContext());
  2900. // If this method belongs to a protocol but the method in list does not, or
  2901. // vice versa, we say the context is not the same.
  2902. if ((MethodProtocol && !MethodInListProtocol) ||
  2903. (!MethodProtocol && MethodInListProtocol))
  2904. return false;
  2905. if (MethodProtocol && MethodInListProtocol)
  2906. return true;
  2907. ObjCInterfaceDecl *MethodInterface = Method->getClassInterface();
  2908. ObjCInterfaceDecl *MethodInListInterface =
  2909. MethodInList->getClassInterface();
  2910. return MethodInterface == MethodInListInterface;
  2911. }
  2912. void Sema::addMethodToGlobalList(ObjCMethodList *List,
  2913. ObjCMethodDecl *Method) {
  2914. // Record at the head of the list whether there were 0, 1, or >= 2 methods
  2915. // inside categories.
  2916. if (ObjCCategoryDecl *CD =
  2917. dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
  2918. if (!CD->IsClassExtension() && List->getBits() < 2)
  2919. List->setBits(List->getBits() + 1);
  2920. // If the list is empty, make it a singleton list.
  2921. if (List->getMethod() == nullptr) {
  2922. List->setMethod(Method);
  2923. List->setNext(nullptr);
  2924. return;
  2925. }
  2926. // We've seen a method with this name, see if we have already seen this type
  2927. // signature.
  2928. ObjCMethodList *Previous = List;
  2929. ObjCMethodList *ListWithSameDeclaration = nullptr;
  2930. for (; List; Previous = List, List = List->getNext()) {
  2931. // If we are building a module, keep all of the methods.
  2932. if (getLangOpts().isCompilingModule())
  2933. continue;
  2934. bool SameDeclaration = MatchTwoMethodDeclarations(Method,
  2935. List->getMethod());
  2936. // Looking for method with a type bound requires the correct context exists.
  2937. // We need to insert a method into the list if the context is different.
  2938. // If the method's declaration matches the list
  2939. // a> the method belongs to a different context: we need to insert it, in
  2940. // order to emit the availability message, we need to prioritize over
  2941. // availability among the methods with the same declaration.
  2942. // b> the method belongs to the same context: there is no need to insert a
  2943. // new entry.
  2944. // If the method's declaration does not match the list, we insert it to the
  2945. // end.
  2946. if (!SameDeclaration ||
  2947. !isMethodContextSameForKindofLookup(Method, List->getMethod())) {
  2948. // Even if two method types do not match, we would like to say
  2949. // there is more than one declaration so unavailability/deprecated
  2950. // warning is not too noisy.
  2951. if (!Method->isDefined())
  2952. List->setHasMoreThanOneDecl(true);
  2953. // For methods with the same declaration, the one that is deprecated
  2954. // should be put in the front for better diagnostics.
  2955. if (Method->isDeprecated() && SameDeclaration &&
  2956. !ListWithSameDeclaration && !List->getMethod()->isDeprecated())
  2957. ListWithSameDeclaration = List;
  2958. if (Method->isUnavailable() && SameDeclaration &&
  2959. !ListWithSameDeclaration &&
  2960. List->getMethod()->getAvailability() < AR_Deprecated)
  2961. ListWithSameDeclaration = List;
  2962. continue;
  2963. }
  2964. ObjCMethodDecl *PrevObjCMethod = List->getMethod();
  2965. // Propagate the 'defined' bit.
  2966. if (Method->isDefined())
  2967. PrevObjCMethod->setDefined(true);
  2968. else {
  2969. // Objective-C doesn't allow an @interface for a class after its
  2970. // @implementation. So if Method is not defined and there already is
  2971. // an entry for this type signature, Method has to be for a different
  2972. // class than PrevObjCMethod.
  2973. List->setHasMoreThanOneDecl(true);
  2974. }
  2975. // If a method is deprecated, push it in the global pool.
  2976. // This is used for better diagnostics.
  2977. if (Method->isDeprecated()) {
  2978. if (!PrevObjCMethod->isDeprecated())
  2979. List->setMethod(Method);
  2980. }
  2981. // If the new method is unavailable, push it into global pool
  2982. // unless previous one is deprecated.
  2983. if (Method->isUnavailable()) {
  2984. if (PrevObjCMethod->getAvailability() < AR_Deprecated)
  2985. List->setMethod(Method);
  2986. }
  2987. return;
  2988. }
  2989. // We have a new signature for an existing method - add it.
  2990. // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
  2991. ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
  2992. // We insert it right before ListWithSameDeclaration.
  2993. if (ListWithSameDeclaration) {
  2994. auto *List = new (Mem) ObjCMethodList(*ListWithSameDeclaration);
  2995. // FIXME: should we clear the other bits in ListWithSameDeclaration?
  2996. ListWithSameDeclaration->setMethod(Method);
  2997. ListWithSameDeclaration->setNext(List);
  2998. return;
  2999. }
  3000. Previous->setNext(new (Mem) ObjCMethodList(Method));
  3001. }
  3002. /// Read the contents of the method pool for a given selector from
  3003. /// external storage.
  3004. void Sema::ReadMethodPool(Selector Sel) {
  3005. assert(ExternalSource && "We need an external AST source");
  3006. ExternalSource->ReadMethodPool(Sel);
  3007. }
  3008. void Sema::updateOutOfDateSelector(Selector Sel) {
  3009. if (!ExternalSource)
  3010. return;
  3011. ExternalSource->updateOutOfDateSelector(Sel);
  3012. }
  3013. void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
  3014. bool instance) {
  3015. // Ignore methods of invalid containers.
  3016. if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
  3017. return;
  3018. if (ExternalSource)
  3019. ReadMethodPool(Method->getSelector());
  3020. GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
  3021. if (Pos == MethodPool.end())
  3022. Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
  3023. GlobalMethods())).first;
  3024. Method->setDefined(impl);
  3025. ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
  3026. addMethodToGlobalList(&Entry, Method);
  3027. }
  3028. /// Determines if this is an "acceptable" loose mismatch in the global
  3029. /// method pool. This exists mostly as a hack to get around certain
  3030. /// global mismatches which we can't afford to make warnings / errors.
  3031. /// Really, what we want is a way to take a method out of the global
  3032. /// method pool.
  3033. static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
  3034. ObjCMethodDecl *other) {
  3035. if (!chosen->isInstanceMethod())
  3036. return false;
  3037. Selector sel = chosen->getSelector();
  3038. if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
  3039. return false;
  3040. // Don't complain about mismatches for -length if the method we
  3041. // chose has an integral result type.
  3042. return (chosen->getReturnType()->isIntegerType());
  3043. }
  3044. /// Return true if the given method is wthin the type bound.
  3045. static bool FilterMethodsByTypeBound(ObjCMethodDecl *Method,
  3046. const ObjCObjectType *TypeBound) {
  3047. if (!TypeBound)
  3048. return true;
  3049. if (TypeBound->isObjCId())
  3050. // FIXME: should we handle the case of bounding to id<A, B> differently?
  3051. return true;
  3052. auto *BoundInterface = TypeBound->getInterface();
  3053. assert(BoundInterface && "unexpected object type!");
  3054. // Check if the Method belongs to a protocol. We should allow any method
  3055. // defined in any protocol, because any subclass could adopt the protocol.
  3056. auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
  3057. if (MethodProtocol) {
  3058. return true;
  3059. }
  3060. // If the Method belongs to a class, check if it belongs to the class
  3061. // hierarchy of the class bound.
  3062. if (ObjCInterfaceDecl *MethodInterface = Method->getClassInterface()) {
  3063. // We allow methods declared within classes that are part of the hierarchy
  3064. // of the class bound (superclass of, subclass of, or the same as the class
  3065. // bound).
  3066. return MethodInterface == BoundInterface ||
  3067. MethodInterface->isSuperClassOf(BoundInterface) ||
  3068. BoundInterface->isSuperClassOf(MethodInterface);
  3069. }
  3070. llvm_unreachable("unknown method context");
  3071. }
  3072. /// We first select the type of the method: Instance or Factory, then collect
  3073. /// all methods with that type.
  3074. bool Sema::CollectMultipleMethodsInGlobalPool(
  3075. Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods,
  3076. bool InstanceFirst, bool CheckTheOther,
  3077. const ObjCObjectType *TypeBound) {
  3078. if (ExternalSource)
  3079. ReadMethodPool(Sel);
  3080. GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
  3081. if (Pos == MethodPool.end())
  3082. return false;
  3083. // Gather the non-hidden methods.
  3084. ObjCMethodList &MethList = InstanceFirst ? Pos->second.first :
  3085. Pos->second.second;
  3086. for (ObjCMethodList *M = &MethList; M; M = M->getNext())
  3087. if (M->getMethod() && !M->getMethod()->isHidden()) {
  3088. if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
  3089. Methods.push_back(M->getMethod());
  3090. }
  3091. // Return if we find any method with the desired kind.
  3092. if (!Methods.empty())
  3093. return Methods.size() > 1;
  3094. if (!CheckTheOther)
  3095. return false;
  3096. // Gather the other kind.
  3097. ObjCMethodList &MethList2 = InstanceFirst ? Pos->second.second :
  3098. Pos->second.first;
  3099. for (ObjCMethodList *M = &MethList2; M; M = M->getNext())
  3100. if (M->getMethod() && !M->getMethod()->isHidden()) {
  3101. if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
  3102. Methods.push_back(M->getMethod());
  3103. }
  3104. return Methods.size() > 1;
  3105. }
  3106. bool Sema::AreMultipleMethodsInGlobalPool(
  3107. Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R,
  3108. bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl *> &Methods) {
  3109. // Diagnose finding more than one method in global pool.
  3110. SmallVector<ObjCMethodDecl *, 4> FilteredMethods;
  3111. FilteredMethods.push_back(BestMethod);
  3112. for (auto *M : Methods)
  3113. if (M != BestMethod && !M->hasAttr<UnavailableAttr>())
  3114. FilteredMethods.push_back(M);
  3115. if (FilteredMethods.size() > 1)
  3116. DiagnoseMultipleMethodInGlobalPool(FilteredMethods, Sel, R,
  3117. receiverIdOrClass);
  3118. GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
  3119. // Test for no method in the pool which should not trigger any warning by
  3120. // caller.
  3121. if (Pos == MethodPool.end())
  3122. return true;
  3123. ObjCMethodList &MethList =
  3124. BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second;
  3125. return MethList.hasMoreThanOneDecl();
  3126. }
  3127. ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
  3128. bool receiverIdOrClass,
  3129. bool instance) {
  3130. if (ExternalSource)
  3131. ReadMethodPool(Sel);
  3132. GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
  3133. if (Pos == MethodPool.end())
  3134. return nullptr;
  3135. // Gather the non-hidden methods.
  3136. ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
  3137. SmallVector<ObjCMethodDecl *, 4> Methods;
  3138. for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
  3139. if (M->getMethod() && !M->getMethod()->isHidden())
  3140. return M->getMethod();
  3141. }
  3142. return nullptr;
  3143. }
  3144. void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
  3145. Selector Sel, SourceRange R,
  3146. bool receiverIdOrClass) {
  3147. // We found multiple methods, so we may have to complain.
  3148. bool issueDiagnostic = false, issueError = false;
  3149. // We support a warning which complains about *any* difference in
  3150. // method signature.
  3151. bool strictSelectorMatch =
  3152. receiverIdOrClass &&
  3153. !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin());
  3154. if (strictSelectorMatch) {
  3155. for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
  3156. if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
  3157. issueDiagnostic = true;
  3158. break;
  3159. }
  3160. }
  3161. }
  3162. // If we didn't see any strict differences, we won't see any loose
  3163. // differences. In ARC, however, we also need to check for loose
  3164. // mismatches, because most of them are errors.
  3165. if (!strictSelectorMatch ||
  3166. (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
  3167. for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
  3168. // This checks if the methods differ in type mismatch.
  3169. if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
  3170. !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
  3171. issueDiagnostic = true;
  3172. if (getLangOpts().ObjCAutoRefCount)
  3173. issueError = true;
  3174. break;
  3175. }
  3176. }
  3177. if (issueDiagnostic) {
  3178. if (issueError)
  3179. Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
  3180. else if (strictSelectorMatch)
  3181. Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
  3182. else
  3183. Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
  3184. Diag(Methods[0]->getBeginLoc(),
  3185. issueError ? diag::note_possibility : diag::note_using)
  3186. << Methods[0]->getSourceRange();
  3187. for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
  3188. Diag(Methods[I]->getBeginLoc(), diag::note_also_found)
  3189. << Methods[I]->getSourceRange();
  3190. }
  3191. }
  3192. }
  3193. ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
  3194. GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
  3195. if (Pos == MethodPool.end())
  3196. return nullptr;
  3197. GlobalMethods &Methods = Pos->second;
  3198. for (const ObjCMethodList *Method = &Methods.first; Method;
  3199. Method = Method->getNext())
  3200. if (Method->getMethod() &&
  3201. (Method->getMethod()->isDefined() ||
  3202. Method->getMethod()->isPropertyAccessor()))
  3203. return Method->getMethod();
  3204. for (const ObjCMethodList *Method = &Methods.second; Method;
  3205. Method = Method->getNext())
  3206. if (Method->getMethod() &&
  3207. (Method->getMethod()->isDefined() ||
  3208. Method->getMethod()->isPropertyAccessor()))
  3209. return Method->getMethod();
  3210. return nullptr;
  3211. }
  3212. static void
  3213. HelperSelectorsForTypoCorrection(
  3214. SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
  3215. StringRef Typo, const ObjCMethodDecl * Method) {
  3216. const unsigned MaxEditDistance = 1;
  3217. unsigned BestEditDistance = MaxEditDistance + 1;
  3218. std::string MethodName = Method->getSelector().getAsString();
  3219. unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
  3220. if (MinPossibleEditDistance > 0 &&
  3221. Typo.size() / MinPossibleEditDistance < 1)
  3222. return;
  3223. unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
  3224. if (EditDistance > MaxEditDistance)
  3225. return;
  3226. if (EditDistance == BestEditDistance)
  3227. BestMethod.push_back(Method);
  3228. else if (EditDistance < BestEditDistance) {
  3229. BestMethod.clear();
  3230. BestMethod.push_back(Method);
  3231. }
  3232. }
  3233. static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
  3234. QualType ObjectType) {
  3235. if (ObjectType.isNull())
  3236. return true;
  3237. if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
  3238. return true;
  3239. return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) !=
  3240. nullptr;
  3241. }
  3242. const ObjCMethodDecl *
  3243. Sema::SelectorsForTypoCorrection(Selector Sel,
  3244. QualType ObjectType) {
  3245. unsigned NumArgs = Sel.getNumArgs();
  3246. SmallVector<const ObjCMethodDecl *, 8> Methods;
  3247. bool ObjectIsId = true, ObjectIsClass = true;
  3248. if (ObjectType.isNull())
  3249. ObjectIsId = ObjectIsClass = false;
  3250. else if (!ObjectType->isObjCObjectPointerType())
  3251. return nullptr;
  3252. else if (const ObjCObjectPointerType *ObjCPtr =
  3253. ObjectType->getAsObjCInterfacePointerType()) {
  3254. ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
  3255. ObjectIsId = ObjectIsClass = false;
  3256. }
  3257. else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
  3258. ObjectIsClass = false;
  3259. else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
  3260. ObjectIsId = false;
  3261. else
  3262. return nullptr;
  3263. for (GlobalMethodPool::iterator b = MethodPool.begin(),
  3264. e = MethodPool.end(); b != e; b++) {
  3265. // instance methods
  3266. for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
  3267. if (M->getMethod() &&
  3268. (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
  3269. (M->getMethod()->getSelector() != Sel)) {
  3270. if (ObjectIsId)
  3271. Methods.push_back(M->getMethod());
  3272. else if (!ObjectIsClass &&
  3273. HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
  3274. ObjectType))
  3275. Methods.push_back(M->getMethod());
  3276. }
  3277. // class methods
  3278. for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
  3279. if (M->getMethod() &&
  3280. (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
  3281. (M->getMethod()->getSelector() != Sel)) {
  3282. if (ObjectIsClass)
  3283. Methods.push_back(M->getMethod());
  3284. else if (!ObjectIsId &&
  3285. HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
  3286. ObjectType))
  3287. Methods.push_back(M->getMethod());
  3288. }
  3289. }
  3290. SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
  3291. for (unsigned i = 0, e = Methods.size(); i < e; i++) {
  3292. HelperSelectorsForTypoCorrection(SelectedMethods,
  3293. Sel.getAsString(), Methods[i]);
  3294. }
  3295. return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
  3296. }
  3297. /// DiagnoseDuplicateIvars -
  3298. /// Check for duplicate ivars in the entire class at the start of
  3299. /// \@implementation. This becomes necesssary because class extension can
  3300. /// add ivars to a class in random order which will not be known until
  3301. /// class's \@implementation is seen.
  3302. void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
  3303. ObjCInterfaceDecl *SID) {
  3304. for (auto *Ivar : ID->ivars()) {
  3305. if (Ivar->isInvalidDecl())
  3306. continue;
  3307. if (IdentifierInfo *II = Ivar->getIdentifier()) {
  3308. ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
  3309. if (prevIvar) {
  3310. Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
  3311. Diag(prevIvar->getLocation(), diag::note_previous_declaration);
  3312. Ivar->setInvalidDecl();
  3313. }
  3314. }
  3315. }
  3316. }
  3317. /// Diagnose attempts to define ARC-__weak ivars when __weak is disabled.
  3318. static void DiagnoseWeakIvars(Sema &S, ObjCImplementationDecl *ID) {
  3319. if (S.getLangOpts().ObjCWeak) return;
  3320. for (auto ivar = ID->getClassInterface()->all_declared_ivar_begin();
  3321. ivar; ivar = ivar->getNextIvar()) {
  3322. if (ivar->isInvalidDecl()) continue;
  3323. if (ivar->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
  3324. if (S.getLangOpts().ObjCWeakRuntime) {
  3325. S.Diag(ivar->getLocation(), diag::err_arc_weak_disabled);
  3326. } else {
  3327. S.Diag(ivar->getLocation(), diag::err_arc_weak_no_runtime);
  3328. }
  3329. }
  3330. }
  3331. }
  3332. /// Diagnose attempts to use flexible array member with retainable object type.
  3333. static void DiagnoseRetainableFlexibleArrayMember(Sema &S,
  3334. ObjCInterfaceDecl *ID) {
  3335. if (!S.getLangOpts().ObjCAutoRefCount)
  3336. return;
  3337. for (auto ivar = ID->all_declared_ivar_begin(); ivar;
  3338. ivar = ivar->getNextIvar()) {
  3339. if (ivar->isInvalidDecl())
  3340. continue;
  3341. QualType IvarTy = ivar->getType();
  3342. if (IvarTy->isIncompleteArrayType() &&
  3343. (IvarTy.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) &&
  3344. IvarTy->isObjCLifetimeType()) {
  3345. S.Diag(ivar->getLocation(), diag::err_flexible_array_arc_retainable);
  3346. ivar->setInvalidDecl();
  3347. }
  3348. }
  3349. }
  3350. Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
  3351. switch (CurContext->getDeclKind()) {
  3352. case Decl::ObjCInterface:
  3353. return Sema::OCK_Interface;
  3354. case Decl::ObjCProtocol:
  3355. return Sema::OCK_Protocol;
  3356. case Decl::ObjCCategory:
  3357. if (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
  3358. return Sema::OCK_ClassExtension;
  3359. return Sema::OCK_Category;
  3360. case Decl::ObjCImplementation:
  3361. return Sema::OCK_Implementation;
  3362. case Decl::ObjCCategoryImpl:
  3363. return Sema::OCK_CategoryImplementation;
  3364. default:
  3365. return Sema::OCK_None;
  3366. }
  3367. }
  3368. static bool IsVariableSizedType(QualType T) {
  3369. if (T->isIncompleteArrayType())
  3370. return true;
  3371. const auto *RecordTy = T->getAs<RecordType>();
  3372. return (RecordTy && RecordTy->getDecl()->hasFlexibleArrayMember());
  3373. }
  3374. static void DiagnoseVariableSizedIvars(Sema &S, ObjCContainerDecl *OCD) {
  3375. ObjCInterfaceDecl *IntfDecl = nullptr;
  3376. ObjCInterfaceDecl::ivar_range Ivars = llvm::make_range(
  3377. ObjCInterfaceDecl::ivar_iterator(), ObjCInterfaceDecl::ivar_iterator());
  3378. if ((IntfDecl = dyn_cast<ObjCInterfaceDecl>(OCD))) {
  3379. Ivars = IntfDecl->ivars();
  3380. } else if (auto *ImplDecl = dyn_cast<ObjCImplementationDecl>(OCD)) {
  3381. IntfDecl = ImplDecl->getClassInterface();
  3382. Ivars = ImplDecl->ivars();
  3383. } else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(OCD)) {
  3384. if (CategoryDecl->IsClassExtension()) {
  3385. IntfDecl = CategoryDecl->getClassInterface();
  3386. Ivars = CategoryDecl->ivars();
  3387. }
  3388. }
  3389. // Check if variable sized ivar is in interface and visible to subclasses.
  3390. if (!isa<ObjCInterfaceDecl>(OCD)) {
  3391. for (auto ivar : Ivars) {
  3392. if (!ivar->isInvalidDecl() && IsVariableSizedType(ivar->getType())) {
  3393. S.Diag(ivar->getLocation(), diag::warn_variable_sized_ivar_visibility)
  3394. << ivar->getDeclName() << ivar->getType();
  3395. }
  3396. }
  3397. }
  3398. // Subsequent checks require interface decl.
  3399. if (!IntfDecl)
  3400. return;
  3401. // Check if variable sized ivar is followed by another ivar.
  3402. for (ObjCIvarDecl *ivar = IntfDecl->all_declared_ivar_begin(); ivar;
  3403. ivar = ivar->getNextIvar()) {
  3404. if (ivar->isInvalidDecl() || !ivar->getNextIvar())
  3405. continue;
  3406. QualType IvarTy = ivar->getType();
  3407. bool IsInvalidIvar = false;
  3408. if (IvarTy->isIncompleteArrayType()) {
  3409. S.Diag(ivar->getLocation(), diag::err_flexible_array_not_at_end)
  3410. << ivar->getDeclName() << IvarTy
  3411. << TTK_Class; // Use "class" for Obj-C.
  3412. IsInvalidIvar = true;
  3413. } else if (const RecordType *RecordTy = IvarTy->getAs<RecordType>()) {
  3414. if (RecordTy->getDecl()->hasFlexibleArrayMember()) {
  3415. S.Diag(ivar->getLocation(),
  3416. diag::err_objc_variable_sized_type_not_at_end)
  3417. << ivar->getDeclName() << IvarTy;
  3418. IsInvalidIvar = true;
  3419. }
  3420. }
  3421. if (IsInvalidIvar) {
  3422. S.Diag(ivar->getNextIvar()->getLocation(),
  3423. diag::note_next_ivar_declaration)
  3424. << ivar->getNextIvar()->getSynthesize();
  3425. ivar->setInvalidDecl();
  3426. }
  3427. }
  3428. // Check if ObjC container adds ivars after variable sized ivar in superclass.
  3429. // Perform the check only if OCD is the first container to declare ivars to
  3430. // avoid multiple warnings for the same ivar.
  3431. ObjCIvarDecl *FirstIvar =
  3432. (Ivars.begin() == Ivars.end()) ? nullptr : *Ivars.begin();
  3433. if (FirstIvar && (FirstIvar == IntfDecl->all_declared_ivar_begin())) {
  3434. const ObjCInterfaceDecl *SuperClass = IntfDecl->getSuperClass();
  3435. while (SuperClass && SuperClass->ivar_empty())
  3436. SuperClass = SuperClass->getSuperClass();
  3437. if (SuperClass) {
  3438. auto IvarIter = SuperClass->ivar_begin();
  3439. std::advance(IvarIter, SuperClass->ivar_size() - 1);
  3440. const ObjCIvarDecl *LastIvar = *IvarIter;
  3441. if (IsVariableSizedType(LastIvar->getType())) {
  3442. S.Diag(FirstIvar->getLocation(),
  3443. diag::warn_superclass_variable_sized_type_not_at_end)
  3444. << FirstIvar->getDeclName() << LastIvar->getDeclName()
  3445. << LastIvar->getType() << SuperClass->getDeclName();
  3446. S.Diag(LastIvar->getLocation(), diag::note_entity_declared_at)
  3447. << LastIvar->getDeclName();
  3448. }
  3449. }
  3450. }
  3451. }
  3452. // Note: For class/category implementations, allMethods is always null.
  3453. Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
  3454. ArrayRef<DeclGroupPtrTy> allTUVars) {
  3455. if (getObjCContainerKind() == Sema::OCK_None)
  3456. return nullptr;
  3457. assert(AtEnd.isValid() && "Invalid location for '@end'");
  3458. auto *OCD = cast<ObjCContainerDecl>(CurContext);
  3459. Decl *ClassDecl = OCD;
  3460. bool isInterfaceDeclKind =
  3461. isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
  3462. || isa<ObjCProtocolDecl>(ClassDecl);
  3463. bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
  3464. // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
  3465. llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
  3466. llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
  3467. for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
  3468. ObjCMethodDecl *Method =
  3469. cast_or_null<ObjCMethodDecl>(allMethods[i]);
  3470. if (!Method) continue; // Already issued a diagnostic.
  3471. if (Method->isInstanceMethod()) {
  3472. /// Check for instance method of the same name with incompatible types
  3473. const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
  3474. bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
  3475. : false;
  3476. if ((isInterfaceDeclKind && PrevMethod && !match)
  3477. || (checkIdenticalMethods && match)) {
  3478. Diag(Method->getLocation(), diag::err_duplicate_method_decl)
  3479. << Method->getDeclName();
  3480. Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
  3481. Method->setInvalidDecl();
  3482. } else {
  3483. if (PrevMethod) {
  3484. Method->setAsRedeclaration(PrevMethod);
  3485. if (!Context.getSourceManager().isInSystemHeader(
  3486. Method->getLocation()))
  3487. Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
  3488. << Method->getDeclName();
  3489. Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
  3490. }
  3491. InsMap[Method->getSelector()] = Method;
  3492. /// The following allows us to typecheck messages to "id".
  3493. AddInstanceMethodToGlobalPool(Method);
  3494. }
  3495. } else {
  3496. /// Check for class method of the same name with incompatible types
  3497. const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
  3498. bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
  3499. : false;
  3500. if ((isInterfaceDeclKind && PrevMethod && !match)
  3501. || (checkIdenticalMethods && match)) {
  3502. Diag(Method->getLocation(), diag::err_duplicate_method_decl)
  3503. << Method->getDeclName();
  3504. Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
  3505. Method->setInvalidDecl();
  3506. } else {
  3507. if (PrevMethod) {
  3508. Method->setAsRedeclaration(PrevMethod);
  3509. if (!Context.getSourceManager().isInSystemHeader(
  3510. Method->getLocation()))
  3511. Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
  3512. << Method->getDeclName();
  3513. Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
  3514. }
  3515. ClsMap[Method->getSelector()] = Method;
  3516. AddFactoryMethodToGlobalPool(Method);
  3517. }
  3518. }
  3519. }
  3520. if (isa<ObjCInterfaceDecl>(ClassDecl)) {
  3521. // Nothing to do here.
  3522. } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
  3523. // Categories are used to extend the class by declaring new methods.
  3524. // By the same token, they are also used to add new properties. No
  3525. // need to compare the added property to those in the class.
  3526. if (C->IsClassExtension()) {
  3527. ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
  3528. DiagnoseClassExtensionDupMethods(C, CCPrimary);
  3529. }
  3530. }
  3531. if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
  3532. if (CDecl->getIdentifier())
  3533. // ProcessPropertyDecl is responsible for diagnosing conflicts with any
  3534. // user-defined setter/getter. It also synthesizes setter/getter methods
  3535. // and adds them to the DeclContext and global method pools.
  3536. for (auto *I : CDecl->properties())
  3537. ProcessPropertyDecl(I);
  3538. CDecl->setAtEndRange(AtEnd);
  3539. }
  3540. if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
  3541. IC->setAtEndRange(AtEnd);
  3542. if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
  3543. // Any property declared in a class extension might have user
  3544. // declared setter or getter in current class extension or one
  3545. // of the other class extensions. Mark them as synthesized as
  3546. // property will be synthesized when property with same name is
  3547. // seen in the @implementation.
  3548. for (const auto *Ext : IDecl->visible_extensions()) {
  3549. for (const auto *Property : Ext->instance_properties()) {
  3550. // Skip over properties declared @dynamic
  3551. if (const ObjCPropertyImplDecl *PIDecl
  3552. = IC->FindPropertyImplDecl(Property->getIdentifier(),
  3553. Property->getQueryKind()))
  3554. if (PIDecl->getPropertyImplementation()
  3555. == ObjCPropertyImplDecl::Dynamic)
  3556. continue;
  3557. for (const auto *Ext : IDecl->visible_extensions()) {
  3558. if (ObjCMethodDecl *GetterMethod
  3559. = Ext->getInstanceMethod(Property->getGetterName()))
  3560. GetterMethod->setPropertyAccessor(true);
  3561. if (!Property->isReadOnly())
  3562. if (ObjCMethodDecl *SetterMethod
  3563. = Ext->getInstanceMethod(Property->getSetterName()))
  3564. SetterMethod->setPropertyAccessor(true);
  3565. }
  3566. }
  3567. }
  3568. ImplMethodsVsClassMethods(S, IC, IDecl);
  3569. AtomicPropertySetterGetterRules(IC, IDecl);
  3570. DiagnoseOwningPropertyGetterSynthesis(IC);
  3571. DiagnoseUnusedBackingIvarInAccessor(S, IC);
  3572. if (IDecl->hasDesignatedInitializers())
  3573. DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
  3574. DiagnoseWeakIvars(*this, IC);
  3575. DiagnoseRetainableFlexibleArrayMember(*this, IDecl);
  3576. bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
  3577. if (IDecl->getSuperClass() == nullptr) {
  3578. // This class has no superclass, so check that it has been marked with
  3579. // __attribute((objc_root_class)).
  3580. if (!HasRootClassAttr) {
  3581. SourceLocation DeclLoc(IDecl->getLocation());
  3582. SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc));
  3583. Diag(DeclLoc, diag::warn_objc_root_class_missing)
  3584. << IDecl->getIdentifier();
  3585. // See if NSObject is in the current scope, and if it is, suggest
  3586. // adding " : NSObject " to the class declaration.
  3587. NamedDecl *IF = LookupSingleName(TUScope,
  3588. NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
  3589. DeclLoc, LookupOrdinaryName);
  3590. ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
  3591. if (NSObjectDecl && NSObjectDecl->getDefinition()) {
  3592. Diag(SuperClassLoc, diag::note_objc_needs_superclass)
  3593. << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
  3594. } else {
  3595. Diag(SuperClassLoc, diag::note_objc_needs_superclass);
  3596. }
  3597. }
  3598. } else if (HasRootClassAttr) {
  3599. // Complain that only root classes may have this attribute.
  3600. Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
  3601. }
  3602. if (const ObjCInterfaceDecl *Super = IDecl->getSuperClass()) {
  3603. // An interface can subclass another interface with a
  3604. // objc_subclassing_restricted attribute when it has that attribute as
  3605. // well (because of interfaces imported from Swift). Therefore we have
  3606. // to check if we can subclass in the implementation as well.
  3607. if (IDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
  3608. Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
  3609. Diag(IC->getLocation(), diag::err_restricted_superclass_mismatch);
  3610. Diag(Super->getLocation(), diag::note_class_declared);
  3611. }
  3612. }
  3613. if (IDecl->hasAttr<ObjCClassStubAttr>())
  3614. Diag(IC->getLocation(), diag::err_implementation_of_class_stub);
  3615. if (LangOpts.ObjCRuntime.isNonFragile()) {
  3616. while (IDecl->getSuperClass()) {
  3617. DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
  3618. IDecl = IDecl->getSuperClass();
  3619. }
  3620. }
  3621. }
  3622. SetIvarInitializers(IC);
  3623. } else if (ObjCCategoryImplDecl* CatImplClass =
  3624. dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
  3625. CatImplClass->setAtEndRange(AtEnd);
  3626. // Find category interface decl and then check that all methods declared
  3627. // in this interface are implemented in the category @implementation.
  3628. if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
  3629. if (ObjCCategoryDecl *Cat
  3630. = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
  3631. ImplMethodsVsClassMethods(S, CatImplClass, Cat);
  3632. }
  3633. }
  3634. } else if (const auto *IntfDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
  3635. if (const ObjCInterfaceDecl *Super = IntfDecl->getSuperClass()) {
  3636. if (!IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
  3637. Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
  3638. Diag(IntfDecl->getLocation(), diag::err_restricted_superclass_mismatch);
  3639. Diag(Super->getLocation(), diag::note_class_declared);
  3640. }
  3641. }
  3642. if (IntfDecl->hasAttr<ObjCClassStubAttr>() &&
  3643. !IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>())
  3644. Diag(IntfDecl->getLocation(), diag::err_class_stub_subclassing_mismatch);
  3645. }
  3646. DiagnoseVariableSizedIvars(*this, OCD);
  3647. if (isInterfaceDeclKind) {
  3648. // Reject invalid vardecls.
  3649. for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
  3650. DeclGroupRef DG = allTUVars[i].get();
  3651. for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
  3652. if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
  3653. if (!VDecl->hasExternalStorage())
  3654. Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
  3655. }
  3656. }
  3657. }
  3658. ActOnObjCContainerFinishDefinition();
  3659. for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
  3660. DeclGroupRef DG = allTUVars[i].get();
  3661. for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
  3662. (*I)->setTopLevelDeclInObjCContainer();
  3663. Consumer.HandleTopLevelDeclInObjCContainer(DG);
  3664. }
  3665. ActOnDocumentableDecl(ClassDecl);
  3666. return ClassDecl;
  3667. }
  3668. /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
  3669. /// objective-c's type qualifier from the parser version of the same info.
  3670. static Decl::ObjCDeclQualifier
  3671. CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
  3672. return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
  3673. }
  3674. /// Check whether the declared result type of the given Objective-C
  3675. /// method declaration is compatible with the method's class.
  3676. ///
  3677. static Sema::ResultTypeCompatibilityKind
  3678. CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
  3679. ObjCInterfaceDecl *CurrentClass) {
  3680. QualType ResultType = Method->getReturnType();
  3681. // If an Objective-C method inherits its related result type, then its
  3682. // declared result type must be compatible with its own class type. The
  3683. // declared result type is compatible if:
  3684. if (const ObjCObjectPointerType *ResultObjectType
  3685. = ResultType->getAs<ObjCObjectPointerType>()) {
  3686. // - it is id or qualified id, or
  3687. if (ResultObjectType->isObjCIdType() ||
  3688. ResultObjectType->isObjCQualifiedIdType())
  3689. return Sema::RTC_Compatible;
  3690. if (CurrentClass) {
  3691. if (ObjCInterfaceDecl *ResultClass
  3692. = ResultObjectType->getInterfaceDecl()) {
  3693. // - it is the same as the method's class type, or
  3694. if (declaresSameEntity(CurrentClass, ResultClass))
  3695. return Sema::RTC_Compatible;
  3696. // - it is a superclass of the method's class type
  3697. if (ResultClass->isSuperClassOf(CurrentClass))
  3698. return Sema::RTC_Compatible;
  3699. }
  3700. } else {
  3701. // Any Objective-C pointer type might be acceptable for a protocol
  3702. // method; we just don't know.
  3703. return Sema::RTC_Unknown;
  3704. }
  3705. }
  3706. return Sema::RTC_Incompatible;
  3707. }
  3708. namespace {
  3709. /// A helper class for searching for methods which a particular method
  3710. /// overrides.
  3711. class OverrideSearch {
  3712. public:
  3713. const ObjCMethodDecl *Method;
  3714. llvm::SmallSetVector<ObjCMethodDecl*, 4> Overridden;
  3715. bool Recursive;
  3716. public:
  3717. OverrideSearch(Sema &S, const ObjCMethodDecl *method) : Method(method) {
  3718. Selector selector = method->getSelector();
  3719. // Bypass this search if we've never seen an instance/class method
  3720. // with this selector before.
  3721. Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
  3722. if (it == S.MethodPool.end()) {
  3723. if (!S.getExternalSource()) return;
  3724. S.ReadMethodPool(selector);
  3725. it = S.MethodPool.find(selector);
  3726. if (it == S.MethodPool.end())
  3727. return;
  3728. }
  3729. const ObjCMethodList &list =
  3730. method->isInstanceMethod() ? it->second.first : it->second.second;
  3731. if (!list.getMethod()) return;
  3732. const ObjCContainerDecl *container
  3733. = cast<ObjCContainerDecl>(method->getDeclContext());
  3734. // Prevent the search from reaching this container again. This is
  3735. // important with categories, which override methods from the
  3736. // interface and each other.
  3737. if (const ObjCCategoryDecl *Category =
  3738. dyn_cast<ObjCCategoryDecl>(container)) {
  3739. searchFromContainer(container);
  3740. if (const ObjCInterfaceDecl *Interface = Category->getClassInterface())
  3741. searchFromContainer(Interface);
  3742. } else {
  3743. searchFromContainer(container);
  3744. }
  3745. }
  3746. typedef decltype(Overridden)::iterator iterator;
  3747. iterator begin() const { return Overridden.begin(); }
  3748. iterator end() const { return Overridden.end(); }
  3749. private:
  3750. void searchFromContainer(const ObjCContainerDecl *container) {
  3751. if (container->isInvalidDecl()) return;
  3752. switch (container->getDeclKind()) {
  3753. #define OBJCCONTAINER(type, base) \
  3754. case Decl::type: \
  3755. searchFrom(cast<type##Decl>(container)); \
  3756. break;
  3757. #define ABSTRACT_DECL(expansion)
  3758. #define DECL(type, base) \
  3759. case Decl::type:
  3760. #include "clang/AST/DeclNodes.inc"
  3761. llvm_unreachable("not an ObjC container!");
  3762. }
  3763. }
  3764. void searchFrom(const ObjCProtocolDecl *protocol) {
  3765. if (!protocol->hasDefinition())
  3766. return;
  3767. // A method in a protocol declaration overrides declarations from
  3768. // referenced ("parent") protocols.
  3769. search(protocol->getReferencedProtocols());
  3770. }
  3771. void searchFrom(const ObjCCategoryDecl *category) {
  3772. // A method in a category declaration overrides declarations from
  3773. // the main class and from protocols the category references.
  3774. // The main class is handled in the constructor.
  3775. search(category->getReferencedProtocols());
  3776. }
  3777. void searchFrom(const ObjCCategoryImplDecl *impl) {
  3778. // A method in a category definition that has a category
  3779. // declaration overrides declarations from the category
  3780. // declaration.
  3781. if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
  3782. search(category);
  3783. if (ObjCInterfaceDecl *Interface = category->getClassInterface())
  3784. search(Interface);
  3785. // Otherwise it overrides declarations from the class.
  3786. } else if (const auto *Interface = impl->getClassInterface()) {
  3787. search(Interface);
  3788. }
  3789. }
  3790. void searchFrom(const ObjCInterfaceDecl *iface) {
  3791. // A method in a class declaration overrides declarations from
  3792. if (!iface->hasDefinition())
  3793. return;
  3794. // - categories,
  3795. for (auto *Cat : iface->known_categories())
  3796. search(Cat);
  3797. // - the super class, and
  3798. if (ObjCInterfaceDecl *super = iface->getSuperClass())
  3799. search(super);
  3800. // - any referenced protocols.
  3801. search(iface->getReferencedProtocols());
  3802. }
  3803. void searchFrom(const ObjCImplementationDecl *impl) {
  3804. // A method in a class implementation overrides declarations from
  3805. // the class interface.
  3806. if (const auto *Interface = impl->getClassInterface())
  3807. search(Interface);
  3808. }
  3809. void search(const ObjCProtocolList &protocols) {
  3810. for (const auto *Proto : protocols)
  3811. search(Proto);
  3812. }
  3813. void search(const ObjCContainerDecl *container) {
  3814. // Check for a method in this container which matches this selector.
  3815. ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
  3816. Method->isInstanceMethod(),
  3817. /*AllowHidden=*/true);
  3818. // If we find one, record it and bail out.
  3819. if (meth) {
  3820. Overridden.insert(meth);
  3821. return;
  3822. }
  3823. // Otherwise, search for methods that a hypothetical method here
  3824. // would have overridden.
  3825. // Note that we're now in a recursive case.
  3826. Recursive = true;
  3827. searchFromContainer(container);
  3828. }
  3829. };
  3830. } // end anonymous namespace
  3831. void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
  3832. ObjCInterfaceDecl *CurrentClass,
  3833. ResultTypeCompatibilityKind RTC) {
  3834. if (!ObjCMethod)
  3835. return;
  3836. // Search for overridden methods and merge information down from them.
  3837. OverrideSearch overrides(*this, ObjCMethod);
  3838. // Keep track if the method overrides any method in the class's base classes,
  3839. // its protocols, or its categories' protocols; we will keep that info
  3840. // in the ObjCMethodDecl.
  3841. // For this info, a method in an implementation is not considered as
  3842. // overriding the same method in the interface or its categories.
  3843. bool hasOverriddenMethodsInBaseOrProtocol = false;
  3844. for (ObjCMethodDecl *overridden : overrides) {
  3845. if (!hasOverriddenMethodsInBaseOrProtocol) {
  3846. if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
  3847. CurrentClass != overridden->getClassInterface() ||
  3848. overridden->isOverriding()) {
  3849. hasOverriddenMethodsInBaseOrProtocol = true;
  3850. } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
  3851. // OverrideSearch will return as "overridden" the same method in the
  3852. // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
  3853. // check whether a category of a base class introduced a method with the
  3854. // same selector, after the interface method declaration.
  3855. // To avoid unnecessary lookups in the majority of cases, we use the
  3856. // extra info bits in GlobalMethodPool to check whether there were any
  3857. // category methods with this selector.
  3858. GlobalMethodPool::iterator It =
  3859. MethodPool.find(ObjCMethod->getSelector());
  3860. if (It != MethodPool.end()) {
  3861. ObjCMethodList &List =
  3862. ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
  3863. unsigned CategCount = List.getBits();
  3864. if (CategCount > 0) {
  3865. // If the method is in a category we'll do lookup if there were at
  3866. // least 2 category methods recorded, otherwise only one will do.
  3867. if (CategCount > 1 ||
  3868. !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
  3869. OverrideSearch overrides(*this, overridden);
  3870. for (ObjCMethodDecl *SuperOverridden : overrides) {
  3871. if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
  3872. CurrentClass != SuperOverridden->getClassInterface()) {
  3873. hasOverriddenMethodsInBaseOrProtocol = true;
  3874. overridden->setOverriding(true);
  3875. break;
  3876. }
  3877. }
  3878. }
  3879. }
  3880. }
  3881. }
  3882. }
  3883. // Propagate down the 'related result type' bit from overridden methods.
  3884. if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
  3885. ObjCMethod->setRelatedResultType();
  3886. // Then merge the declarations.
  3887. mergeObjCMethodDecls(ObjCMethod, overridden);
  3888. if (ObjCMethod->isImplicit() && overridden->isImplicit())
  3889. continue; // Conflicting properties are detected elsewhere.
  3890. // Check for overriding methods
  3891. if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
  3892. isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
  3893. CheckConflictingOverridingMethod(ObjCMethod, overridden,
  3894. isa<ObjCProtocolDecl>(overridden->getDeclContext()));
  3895. if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
  3896. isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
  3897. !overridden->isImplicit() /* not meant for properties */) {
  3898. ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
  3899. E = ObjCMethod->param_end();
  3900. ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
  3901. PrevE = overridden->param_end();
  3902. for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
  3903. assert(PrevI != overridden->param_end() && "Param mismatch");
  3904. QualType T1 = Context.getCanonicalType((*ParamI)->getType());
  3905. QualType T2 = Context.getCanonicalType((*PrevI)->getType());
  3906. // If type of argument of method in this class does not match its
  3907. // respective argument type in the super class method, issue warning;
  3908. if (!Context.typesAreCompatible(T1, T2)) {
  3909. Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
  3910. << T1 << T2;
  3911. Diag(overridden->getLocation(), diag::note_previous_declaration);
  3912. break;
  3913. }
  3914. }
  3915. }
  3916. }
  3917. ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
  3918. }
  3919. /// Merge type nullability from for a redeclaration of the same entity,
  3920. /// producing the updated type of the redeclared entity.
  3921. static QualType mergeTypeNullabilityForRedecl(Sema &S, SourceLocation loc,
  3922. QualType type,
  3923. bool usesCSKeyword,
  3924. SourceLocation prevLoc,
  3925. QualType prevType,
  3926. bool prevUsesCSKeyword) {
  3927. // Determine the nullability of both types.
  3928. auto nullability = type->getNullability(S.Context);
  3929. auto prevNullability = prevType->getNullability(S.Context);
  3930. // Easy case: both have nullability.
  3931. if (nullability.hasValue() == prevNullability.hasValue()) {
  3932. // Neither has nullability; continue.
  3933. if (!nullability)
  3934. return type;
  3935. // The nullabilities are equivalent; do nothing.
  3936. if (*nullability == *prevNullability)
  3937. return type;
  3938. // Complain about mismatched nullability.
  3939. S.Diag(loc, diag::err_nullability_conflicting)
  3940. << DiagNullabilityKind(*nullability, usesCSKeyword)
  3941. << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword);
  3942. return type;
  3943. }
  3944. // If it's the redeclaration that has nullability, don't change anything.
  3945. if (nullability)
  3946. return type;
  3947. // Otherwise, provide the result with the same nullability.
  3948. return S.Context.getAttributedType(
  3949. AttributedType::getNullabilityAttrKind(*prevNullability),
  3950. type, type);
  3951. }
  3952. /// Merge information from the declaration of a method in the \@interface
  3953. /// (or a category/extension) into the corresponding method in the
  3954. /// @implementation (for a class or category).
  3955. static void mergeInterfaceMethodToImpl(Sema &S,
  3956. ObjCMethodDecl *method,
  3957. ObjCMethodDecl *prevMethod) {
  3958. // Merge the objc_requires_super attribute.
  3959. if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() &&
  3960. !method->hasAttr<ObjCRequiresSuperAttr>()) {
  3961. // merge the attribute into implementation.
  3962. method->addAttr(
  3963. ObjCRequiresSuperAttr::CreateImplicit(S.Context,
  3964. method->getLocation()));
  3965. }
  3966. // Merge nullability of the result type.
  3967. QualType newReturnType
  3968. = mergeTypeNullabilityForRedecl(
  3969. S, method->getReturnTypeSourceRange().getBegin(),
  3970. method->getReturnType(),
  3971. method->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
  3972. prevMethod->getReturnTypeSourceRange().getBegin(),
  3973. prevMethod->getReturnType(),
  3974. prevMethod->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
  3975. method->setReturnType(newReturnType);
  3976. // Handle each of the parameters.
  3977. unsigned numParams = method->param_size();
  3978. unsigned numPrevParams = prevMethod->param_size();
  3979. for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) {
  3980. ParmVarDecl *param = method->param_begin()[i];
  3981. ParmVarDecl *prevParam = prevMethod->param_begin()[i];
  3982. // Merge nullability.
  3983. QualType newParamType
  3984. = mergeTypeNullabilityForRedecl(
  3985. S, param->getLocation(), param->getType(),
  3986. param->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
  3987. prevParam->getLocation(), prevParam->getType(),
  3988. prevParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
  3989. param->setType(newParamType);
  3990. }
  3991. }
  3992. /// Verify that the method parameters/return value have types that are supported
  3993. /// by the x86 target.
  3994. static void checkObjCMethodX86VectorTypes(Sema &SemaRef,
  3995. const ObjCMethodDecl *Method) {
  3996. assert(SemaRef.getASTContext().getTargetInfo().getTriple().getArch() ==
  3997. llvm::Triple::x86 &&
  3998. "x86-specific check invoked for a different target");
  3999. SourceLocation Loc;
  4000. QualType T;
  4001. for (const ParmVarDecl *P : Method->parameters()) {
  4002. if (P->getType()->isVectorType()) {
  4003. Loc = P->getBeginLoc();
  4004. T = P->getType();
  4005. break;
  4006. }
  4007. }
  4008. if (Loc.isInvalid()) {
  4009. if (Method->getReturnType()->isVectorType()) {
  4010. Loc = Method->getReturnTypeSourceRange().getBegin();
  4011. T = Method->getReturnType();
  4012. } else
  4013. return;
  4014. }
  4015. // Vector parameters/return values are not supported by objc_msgSend on x86 in
  4016. // iOS < 9 and macOS < 10.11.
  4017. const auto &Triple = SemaRef.getASTContext().getTargetInfo().getTriple();
  4018. VersionTuple AcceptedInVersion;
  4019. if (Triple.getOS() == llvm::Triple::IOS)
  4020. AcceptedInVersion = VersionTuple(/*Major=*/9);
  4021. else if (Triple.isMacOSX())
  4022. AcceptedInVersion = VersionTuple(/*Major=*/10, /*Minor=*/11);
  4023. else
  4024. return;
  4025. if (SemaRef.getASTContext().getTargetInfo().getPlatformMinVersion() >=
  4026. AcceptedInVersion)
  4027. return;
  4028. SemaRef.Diag(Loc, diag::err_objc_method_unsupported_param_ret_type)
  4029. << T << (Method->getReturnType()->isVectorType() ? /*return value*/ 1
  4030. : /*parameter*/ 0)
  4031. << (Triple.isMacOSX() ? "macOS 10.11" : "iOS 9");
  4032. }
  4033. Decl *Sema::ActOnMethodDeclaration(
  4034. Scope *S, SourceLocation MethodLoc, SourceLocation EndLoc,
  4035. tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
  4036. ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
  4037. // optional arguments. The number of types/arguments is obtained
  4038. // from the Sel.getNumArgs().
  4039. ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
  4040. unsigned CNumArgs, // c-style args
  4041. const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodDeclKind,
  4042. bool isVariadic, bool MethodDefinition) {
  4043. // Make sure we can establish a context for the method.
  4044. if (!CurContext->isObjCContainer()) {
  4045. Diag(MethodLoc, diag::err_missing_method_context);
  4046. return nullptr;
  4047. }
  4048. Decl *ClassDecl = cast<ObjCContainerDecl>(CurContext);
  4049. QualType resultDeclType;
  4050. bool HasRelatedResultType = false;
  4051. TypeSourceInfo *ReturnTInfo = nullptr;
  4052. if (ReturnType) {
  4053. resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
  4054. if (CheckFunctionReturnType(resultDeclType, MethodLoc))
  4055. return nullptr;
  4056. QualType bareResultType = resultDeclType;
  4057. (void)AttributedType::stripOuterNullability(bareResultType);
  4058. HasRelatedResultType = (bareResultType == Context.getObjCInstanceType());
  4059. } else { // get the type for "id".
  4060. resultDeclType = Context.getObjCIdType();
  4061. Diag(MethodLoc, diag::warn_missing_method_return_type)
  4062. << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
  4063. }
  4064. ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
  4065. Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
  4066. MethodType == tok::minus, isVariadic,
  4067. /*isPropertyAccessor=*/false,
  4068. /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
  4069. MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
  4070. : ObjCMethodDecl::Required,
  4071. HasRelatedResultType);
  4072. SmallVector<ParmVarDecl*, 16> Params;
  4073. for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
  4074. QualType ArgType;
  4075. TypeSourceInfo *DI;
  4076. if (!ArgInfo[i].Type) {
  4077. ArgType = Context.getObjCIdType();
  4078. DI = nullptr;
  4079. } else {
  4080. ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
  4081. }
  4082. LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
  4083. LookupOrdinaryName, forRedeclarationInCurContext());
  4084. LookupName(R, S);
  4085. if (R.isSingleResult()) {
  4086. NamedDecl *PrevDecl = R.getFoundDecl();
  4087. if (S->isDeclScope(PrevDecl)) {
  4088. Diag(ArgInfo[i].NameLoc,
  4089. (MethodDefinition ? diag::warn_method_param_redefinition
  4090. : diag::warn_method_param_declaration))
  4091. << ArgInfo[i].Name;
  4092. Diag(PrevDecl->getLocation(),
  4093. diag::note_previous_declaration);
  4094. }
  4095. }
  4096. SourceLocation StartLoc = DI
  4097. ? DI->getTypeLoc().getBeginLoc()
  4098. : ArgInfo[i].NameLoc;
  4099. ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
  4100. ArgInfo[i].NameLoc, ArgInfo[i].Name,
  4101. ArgType, DI, SC_None);
  4102. Param->setObjCMethodScopeInfo(i);
  4103. Param->setObjCDeclQualifier(
  4104. CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
  4105. // Apply the attributes to the parameter.
  4106. ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
  4107. AddPragmaAttributes(TUScope, Param);
  4108. if (Param->hasAttr<BlocksAttr>()) {
  4109. Diag(Param->getLocation(), diag::err_block_on_nonlocal);
  4110. Param->setInvalidDecl();
  4111. }
  4112. S->AddDecl(Param);
  4113. IdResolver.AddDecl(Param);
  4114. Params.push_back(Param);
  4115. }
  4116. for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
  4117. ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
  4118. QualType ArgType = Param->getType();
  4119. if (ArgType.isNull())
  4120. ArgType = Context.getObjCIdType();
  4121. else
  4122. // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
  4123. ArgType = Context.getAdjustedParameterType(ArgType);
  4124. Param->setDeclContext(ObjCMethod);
  4125. Params.push_back(Param);
  4126. }
  4127. ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
  4128. ObjCMethod->setObjCDeclQualifier(
  4129. CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
  4130. ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
  4131. AddPragmaAttributes(TUScope, ObjCMethod);
  4132. // Add the method now.
  4133. const ObjCMethodDecl *PrevMethod = nullptr;
  4134. if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
  4135. if (MethodType == tok::minus) {
  4136. PrevMethod = ImpDecl->getInstanceMethod(Sel);
  4137. ImpDecl->addInstanceMethod(ObjCMethod);
  4138. } else {
  4139. PrevMethod = ImpDecl->getClassMethod(Sel);
  4140. ImpDecl->addClassMethod(ObjCMethod);
  4141. }
  4142. // Merge information from the @interface declaration into the
  4143. // @implementation.
  4144. if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) {
  4145. if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
  4146. ObjCMethod->isInstanceMethod())) {
  4147. mergeInterfaceMethodToImpl(*this, ObjCMethod, IMD);
  4148. // Warn about defining -dealloc in a category.
  4149. if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() &&
  4150. ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) {
  4151. Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
  4152. << ObjCMethod->getDeclName();
  4153. }
  4154. }
  4155. // Warn if a method declared in a protocol to which a category or
  4156. // extension conforms is non-escaping and the implementation's method is
  4157. // escaping.
  4158. for (auto *C : IDecl->visible_categories())
  4159. for (auto &P : C->protocols())
  4160. if (auto *IMD = P->lookupMethod(ObjCMethod->getSelector(),
  4161. ObjCMethod->isInstanceMethod())) {
  4162. assert(ObjCMethod->parameters().size() ==
  4163. IMD->parameters().size() &&
  4164. "Methods have different number of parameters");
  4165. auto OI = IMD->param_begin(), OE = IMD->param_end();
  4166. auto NI = ObjCMethod->param_begin();
  4167. for (; OI != OE; ++OI, ++NI)
  4168. diagnoseNoescape(*NI, *OI, C, P, *this);
  4169. }
  4170. }
  4171. } else {
  4172. cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
  4173. }
  4174. if (PrevMethod) {
  4175. // You can never have two method definitions with the same name.
  4176. Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
  4177. << ObjCMethod->getDeclName();
  4178. Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
  4179. ObjCMethod->setInvalidDecl();
  4180. return ObjCMethod;
  4181. }
  4182. // If this Objective-C method does not have a related result type, but we
  4183. // are allowed to infer related result types, try to do so based on the
  4184. // method family.
  4185. ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
  4186. if (!CurrentClass) {
  4187. if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
  4188. CurrentClass = Cat->getClassInterface();
  4189. else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
  4190. CurrentClass = Impl->getClassInterface();
  4191. else if (ObjCCategoryImplDecl *CatImpl
  4192. = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
  4193. CurrentClass = CatImpl->getClassInterface();
  4194. }
  4195. ResultTypeCompatibilityKind RTC
  4196. = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
  4197. CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
  4198. bool ARCError = false;
  4199. if (getLangOpts().ObjCAutoRefCount)
  4200. ARCError = CheckARCMethodDecl(ObjCMethod);
  4201. // Infer the related result type when possible.
  4202. if (!ARCError && RTC == Sema::RTC_Compatible &&
  4203. !ObjCMethod->hasRelatedResultType() &&
  4204. LangOpts.ObjCInferRelatedResultType) {
  4205. bool InferRelatedResultType = false;
  4206. switch (ObjCMethod->getMethodFamily()) {
  4207. case OMF_None:
  4208. case OMF_copy:
  4209. case OMF_dealloc:
  4210. case OMF_finalize:
  4211. case OMF_mutableCopy:
  4212. case OMF_release:
  4213. case OMF_retainCount:
  4214. case OMF_initialize:
  4215. case OMF_performSelector:
  4216. break;
  4217. case OMF_alloc:
  4218. case OMF_new:
  4219. InferRelatedResultType = ObjCMethod->isClassMethod();
  4220. break;
  4221. case OMF_init:
  4222. case OMF_autorelease:
  4223. case OMF_retain:
  4224. case OMF_self:
  4225. InferRelatedResultType = ObjCMethod->isInstanceMethod();
  4226. break;
  4227. }
  4228. if (InferRelatedResultType &&
  4229. !ObjCMethod->getReturnType()->isObjCIndependentClassType())
  4230. ObjCMethod->setRelatedResultType();
  4231. }
  4232. if (MethodDefinition &&
  4233. Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
  4234. checkObjCMethodX86VectorTypes(*this, ObjCMethod);
  4235. // + load method cannot have availability attributes. It get called on
  4236. // startup, so it has to have the availability of the deployment target.
  4237. if (const auto *attr = ObjCMethod->getAttr<AvailabilityAttr>()) {
  4238. if (ObjCMethod->isClassMethod() &&
  4239. ObjCMethod->getSelector().getAsString() == "load") {
  4240. Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
  4241. << 0;
  4242. ObjCMethod->dropAttr<AvailabilityAttr>();
  4243. }
  4244. }
  4245. ActOnDocumentableDecl(ObjCMethod);
  4246. return ObjCMethod;
  4247. }
  4248. bool Sema::CheckObjCDeclScope(Decl *D) {
  4249. // Following is also an error. But it is caused by a missing @end
  4250. // and diagnostic is issued elsewhere.
  4251. if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
  4252. return false;
  4253. // If we switched context to translation unit while we are still lexically in
  4254. // an objc container, it means the parser missed emitting an error.
  4255. if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
  4256. return false;
  4257. Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
  4258. D->setInvalidDecl();
  4259. return true;
  4260. }
  4261. /// Called whenever \@defs(ClassName) is encountered in the source. Inserts the
  4262. /// instance variables of ClassName into Decls.
  4263. void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
  4264. IdentifierInfo *ClassName,
  4265. SmallVectorImpl<Decl*> &Decls) {
  4266. // Check that ClassName is a valid class
  4267. ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
  4268. if (!Class) {
  4269. Diag(DeclStart, diag::err_undef_interface) << ClassName;
  4270. return;
  4271. }
  4272. if (LangOpts.ObjCRuntime.isNonFragile()) {
  4273. Diag(DeclStart, diag::err_atdef_nonfragile_interface);
  4274. return;
  4275. }
  4276. // Collect the instance variables
  4277. SmallVector<const ObjCIvarDecl*, 32> Ivars;
  4278. Context.DeepCollectObjCIvars(Class, true, Ivars);
  4279. // For each ivar, create a fresh ObjCAtDefsFieldDecl.
  4280. for (unsigned i = 0; i < Ivars.size(); i++) {
  4281. const FieldDecl* ID = Ivars[i];
  4282. RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
  4283. Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
  4284. /*FIXME: StartL=*/ID->getLocation(),
  4285. ID->getLocation(),
  4286. ID->getIdentifier(), ID->getType(),
  4287. ID->getBitWidth());
  4288. Decls.push_back(FD);
  4289. }
  4290. // Introduce all of these fields into the appropriate scope.
  4291. for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
  4292. D != Decls.end(); ++D) {
  4293. FieldDecl *FD = cast<FieldDecl>(*D);
  4294. if (getLangOpts().CPlusPlus)
  4295. PushOnScopeChains(FD, S);
  4296. else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
  4297. Record->addDecl(FD);
  4298. }
  4299. }
  4300. /// Build a type-check a new Objective-C exception variable declaration.
  4301. VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
  4302. SourceLocation StartLoc,
  4303. SourceLocation IdLoc,
  4304. IdentifierInfo *Id,
  4305. bool Invalid) {
  4306. // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
  4307. // duration shall not be qualified by an address-space qualifier."
  4308. // Since all parameters have automatic store duration, they can not have
  4309. // an address space.
  4310. if (T.getAddressSpace() != LangAS::Default) {
  4311. Diag(IdLoc, diag::err_arg_with_address_space);
  4312. Invalid = true;
  4313. }
  4314. // An @catch parameter must be an unqualified object pointer type;
  4315. // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
  4316. if (Invalid) {
  4317. // Don't do any further checking.
  4318. } else if (T->isDependentType()) {
  4319. // Okay: we don't know what this type will instantiate to.
  4320. } else if (T->isObjCQualifiedIdType()) {
  4321. Invalid = true;
  4322. Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
  4323. } else if (T->isObjCIdType()) {
  4324. // Okay: we don't know what this type will instantiate to.
  4325. } else if (!T->isObjCObjectPointerType()) {
  4326. Invalid = true;
  4327. Diag(IdLoc, diag::err_catch_param_not_objc_type);
  4328. } else if (!T->getAs<ObjCObjectPointerType>()->getInterfaceType()) {
  4329. Invalid = true;
  4330. Diag(IdLoc, diag::err_catch_param_not_objc_type);
  4331. }
  4332. VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
  4333. T, TInfo, SC_None);
  4334. New->setExceptionVariable(true);
  4335. // In ARC, infer 'retaining' for variables of retainable type.
  4336. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
  4337. Invalid = true;
  4338. if (Invalid)
  4339. New->setInvalidDecl();
  4340. return New;
  4341. }
  4342. Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
  4343. const DeclSpec &DS = D.getDeclSpec();
  4344. // We allow the "register" storage class on exception variables because
  4345. // GCC did, but we drop it completely. Any other storage class is an error.
  4346. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
  4347. Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
  4348. << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
  4349. } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
  4350. Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
  4351. << DeclSpec::getSpecifierName(SCS);
  4352. }
  4353. if (DS.isInlineSpecified())
  4354. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  4355. << getLangOpts().CPlusPlus17;
  4356. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  4357. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  4358. diag::err_invalid_thread)
  4359. << DeclSpec::getSpecifierName(TSCS);
  4360. D.getMutableDeclSpec().ClearStorageClassSpecs();
  4361. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  4362. // Check that there are no default arguments inside the type of this
  4363. // exception object (C++ only).
  4364. if (getLangOpts().CPlusPlus)
  4365. CheckExtraCXXDefaultArguments(D);
  4366. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  4367. QualType ExceptionType = TInfo->getType();
  4368. VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
  4369. D.getSourceRange().getBegin(),
  4370. D.getIdentifierLoc(),
  4371. D.getIdentifier(),
  4372. D.isInvalidType());
  4373. // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
  4374. if (D.getCXXScopeSpec().isSet()) {
  4375. Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
  4376. << D.getCXXScopeSpec().getRange();
  4377. New->setInvalidDecl();
  4378. }
  4379. // Add the parameter declaration into this scope.
  4380. S->AddDecl(New);
  4381. if (D.getIdentifier())
  4382. IdResolver.AddDecl(New);
  4383. ProcessDeclAttributes(S, New, D);
  4384. if (New->hasAttr<BlocksAttr>())
  4385. Diag(New->getLocation(), diag::err_block_on_nonlocal);
  4386. return New;
  4387. }
  4388. /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
  4389. /// initialization.
  4390. void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
  4391. SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
  4392. for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
  4393. Iv= Iv->getNextIvar()) {
  4394. QualType QT = Context.getBaseElementType(Iv->getType());
  4395. if (QT->isRecordType())
  4396. Ivars.push_back(Iv);
  4397. }
  4398. }
  4399. void Sema::DiagnoseUseOfUnimplementedSelectors() {
  4400. // Load referenced selectors from the external source.
  4401. if (ExternalSource) {
  4402. SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
  4403. ExternalSource->ReadReferencedSelectors(Sels);
  4404. for (unsigned I = 0, N = Sels.size(); I != N; ++I)
  4405. ReferencedSelectors[Sels[I].first] = Sels[I].second;
  4406. }
  4407. // Warning will be issued only when selector table is
  4408. // generated (which means there is at lease one implementation
  4409. // in the TU). This is to match gcc's behavior.
  4410. if (ReferencedSelectors.empty() ||
  4411. !Context.AnyObjCImplementation())
  4412. return;
  4413. for (auto &SelectorAndLocation : ReferencedSelectors) {
  4414. Selector Sel = SelectorAndLocation.first;
  4415. SourceLocation Loc = SelectorAndLocation.second;
  4416. if (!LookupImplementedMethodInGlobalPool(Sel))
  4417. Diag(Loc, diag::warn_unimplemented_selector) << Sel;
  4418. }
  4419. }
  4420. ObjCIvarDecl *
  4421. Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
  4422. const ObjCPropertyDecl *&PDecl) const {
  4423. if (Method->isClassMethod())
  4424. return nullptr;
  4425. const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
  4426. if (!IDecl)
  4427. return nullptr;
  4428. Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
  4429. /*shallowCategoryLookup=*/false,
  4430. /*followSuper=*/false);
  4431. if (!Method || !Method->isPropertyAccessor())
  4432. return nullptr;
  4433. if ((PDecl = Method->findPropertyDecl()))
  4434. if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
  4435. // property backing ivar must belong to property's class
  4436. // or be a private ivar in class's implementation.
  4437. // FIXME. fix the const-ness issue.
  4438. IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
  4439. IV->getIdentifier());
  4440. return IV;
  4441. }
  4442. return nullptr;
  4443. }
  4444. namespace {
  4445. /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
  4446. /// accessor references the backing ivar.
  4447. class UnusedBackingIvarChecker :
  4448. public RecursiveASTVisitor<UnusedBackingIvarChecker> {
  4449. public:
  4450. Sema &S;
  4451. const ObjCMethodDecl *Method;
  4452. const ObjCIvarDecl *IvarD;
  4453. bool AccessedIvar;
  4454. bool InvokedSelfMethod;
  4455. UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
  4456. const ObjCIvarDecl *IvarD)
  4457. : S(S), Method(Method), IvarD(IvarD),
  4458. AccessedIvar(false), InvokedSelfMethod(false) {
  4459. assert(IvarD);
  4460. }
  4461. bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
  4462. if (E->getDecl() == IvarD) {
  4463. AccessedIvar = true;
  4464. return false;
  4465. }
  4466. return true;
  4467. }
  4468. bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
  4469. if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
  4470. S.isSelfExpr(E->getInstanceReceiver(), Method)) {
  4471. InvokedSelfMethod = true;
  4472. }
  4473. return true;
  4474. }
  4475. };
  4476. } // end anonymous namespace
  4477. void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
  4478. const ObjCImplementationDecl *ImplD) {
  4479. if (S->hasUnrecoverableErrorOccurred())
  4480. return;
  4481. for (const auto *CurMethod : ImplD->instance_methods()) {
  4482. unsigned DIAG = diag::warn_unused_property_backing_ivar;
  4483. SourceLocation Loc = CurMethod->getLocation();
  4484. if (Diags.isIgnored(DIAG, Loc))
  4485. continue;
  4486. const ObjCPropertyDecl *PDecl;
  4487. const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
  4488. if (!IV)
  4489. continue;
  4490. UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
  4491. Checker.TraverseStmt(CurMethod->getBody());
  4492. if (Checker.AccessedIvar)
  4493. continue;
  4494. // Do not issue this warning if backing ivar is used somewhere and accessor
  4495. // implementation makes a self call. This is to prevent false positive in
  4496. // cases where the ivar is accessed by another method that the accessor
  4497. // delegates to.
  4498. if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
  4499. Diag(Loc, DIAG) << IV;
  4500. Diag(PDecl->getLocation(), diag::note_property_declare);
  4501. }
  4502. }
  4503. }