SemaDeclObjC.cpp 211 KB

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