SemaDeclObjC.cpp 200 KB

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