SemaExprObjC.cpp 179 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634
  1. //===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements semantic analysis for Objective-C expressions.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Sema/SemaInternal.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/DeclObjC.h"
  16. #include "clang/AST/ExprObjC.h"
  17. #include "clang/AST/StmtVisitor.h"
  18. #include "clang/AST/TypeLoc.h"
  19. #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
  20. #include "clang/Edit/Commit.h"
  21. #include "clang/Edit/Rewriters.h"
  22. #include "clang/Lex/Preprocessor.h"
  23. #include "clang/Sema/Initialization.h"
  24. #include "clang/Sema/Lookup.h"
  25. #include "clang/Sema/Scope.h"
  26. #include "clang/Sema/ScopeInfo.h"
  27. #include "llvm/ADT/SmallString.h"
  28. using namespace clang;
  29. using namespace sema;
  30. using llvm::makeArrayRef;
  31. // HLSL Change Starts
  32. // No ObjC parse/sema support, so simply skip all of this compilation.
  33. // Here are enough stubs to link the current targets.
  34. #if 1
  35. ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
  36. Expr **strings,
  37. unsigned NumStrings) {
  38. llvm_unreachable("HLSL does not support ObjC constructs");
  39. }
  40. ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S) {
  41. llvm_unreachable("HLSL does not support ObjC constructs");
  42. }
  43. ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
  44. llvm_unreachable("HLSL does not support ObjC constructs");
  45. }
  46. ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
  47. SourceLocation ValueLoc,
  48. bool Value) {
  49. llvm_unreachable("HLSL does not support ObjC constructs");
  50. }
  51. ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
  52. llvm_unreachable("HLSL does not support ObjC constructs");
  53. }
  54. ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
  55. Expr *IndexExpr,
  56. ObjCMethodDecl *getterMethod,
  57. ObjCMethodDecl *setterMethod) {
  58. llvm_unreachable("HLSL does not support ObjC constructs");
  59. }
  60. ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
  61. llvm_unreachable("HLSL does not support ObjC constructs");
  62. }
  63. ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
  64. ObjCDictionaryElement *Elements,
  65. unsigned NumElements) {
  66. llvm_unreachable("HLSL does not support ObjC constructs");
  67. }
  68. ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
  69. TypeSourceInfo *EncodedTypeInfo,
  70. SourceLocation RParenLoc) {
  71. llvm_unreachable("HLSL does not support ObjC constructs");
  72. }
  73. ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
  74. SourceLocation EncodeLoc,
  75. SourceLocation LParenLoc,
  76. ParsedType ty,
  77. SourceLocation RParenLoc) {
  78. llvm_unreachable("HLSL does not support ObjC constructs");
  79. }
  80. ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
  81. SourceLocation AtLoc,
  82. SourceLocation SelLoc,
  83. SourceLocation LParenLoc,
  84. SourceLocation RParenLoc,
  85. bool WarnMultipleSelectors) {
  86. llvm_unreachable("HLSL does not support ObjC constructs");
  87. }
  88. ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
  89. SourceLocation AtLoc,
  90. SourceLocation ProtoLoc,
  91. SourceLocation LParenLoc,
  92. SourceLocation ProtoIdLoc,
  93. SourceLocation RParenLoc) {
  94. llvm_unreachable("HLSL does not support ObjC constructs");
  95. return ExprError();
  96. }
  97. /// Try to capture an implicit reference to 'self'.
  98. ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
  99. llvm_unreachable("HLSL does not support ObjC constructs");
  100. return nullptr;
  101. }
  102. QualType Sema::getMessageSendResultType(QualType ReceiverType,
  103. ObjCMethodDecl *Method,
  104. bool isClassMessage,
  105. bool isSuperMessage) {
  106. llvm_unreachable("HLSL does not support ObjC constructs");
  107. return QualType();
  108. }
  109. void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
  110. llvm_unreachable("HLSL does not support ObjC constructs");
  111. }
  112. void Sema::EmitRelatedResultTypeNote(const Expr *E) {
  113. llvm_unreachable("HLSL does not support ObjC constructs");
  114. }
  115. bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
  116. MultiExprArg Args,
  117. Selector Sel,
  118. ArrayRef<SourceLocation> SelectorLocs,
  119. ObjCMethodDecl *Method,
  120. bool isClassMessage, bool isSuperMessage,
  121. SourceLocation lbrac, SourceLocation rbrac,
  122. SourceRange RecRange,
  123. QualType &ReturnType, ExprValueKind &VK) {
  124. llvm_unreachable("HLSL does not support ObjC constructs");
  125. return false;
  126. }
  127. bool Sema::isSelfExpr(Expr *RExpr) {
  128. llvm_unreachable("HLSL does not support ObjC constructs");
  129. return false;
  130. }
  131. bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
  132. llvm_unreachable("HLSL does not support ObjC constructs");
  133. return false;
  134. }
  135. ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
  136. bool isInstance) {
  137. llvm_unreachable("HLSL does not support ObjC constructs");
  138. return nullptr;
  139. }
  140. ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
  141. const ObjCObjectPointerType *OPT,
  142. bool Instance)
  143. {
  144. llvm_unreachable("HLSL does not support ObjC constructs");
  145. return nullptr;
  146. }
  147. ExprResult Sema::
  148. HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
  149. Expr *BaseExpr, SourceLocation OpLoc,
  150. DeclarationName MemberName,
  151. SourceLocation MemberLoc,
  152. SourceLocation SuperLoc, QualType SuperType,
  153. bool Super) {
  154. llvm_unreachable("HLSL does not support ObjC constructs");
  155. return ExprError();
  156. }
  157. ExprResult Sema::
  158. ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
  159. IdentifierInfo &propertyName,
  160. SourceLocation receiverNameLoc,
  161. SourceLocation propertyNameLoc) {
  162. llvm_unreachable("HLSL does not support ObjC constructs");
  163. return ExprError();
  164. }
  165. Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
  166. IdentifierInfo *Name,
  167. SourceLocation NameLoc,
  168. bool IsSuper,
  169. bool HasTrailingDot,
  170. ParsedType &ReceiverType) {
  171. llvm_unreachable("HLSL does not support ObjC constructs");
  172. }
  173. ExprResult Sema::ActOnSuperMessage(Scope *S,
  174. SourceLocation SuperLoc,
  175. Selector Sel,
  176. SourceLocation LBracLoc,
  177. ArrayRef<SourceLocation> SelectorLocs,
  178. SourceLocation RBracLoc,
  179. MultiExprArg Args) {
  180. llvm_unreachable("HLSL does not support ObjC constructs");
  181. return ExprError();
  182. }
  183. ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
  184. bool isSuperReceiver,
  185. SourceLocation Loc,
  186. Selector Sel,
  187. ObjCMethodDecl *Method,
  188. MultiExprArg Args) {
  189. llvm_unreachable("HLSL does not support ObjC constructs");
  190. return ExprError();
  191. }
  192. ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
  193. QualType ReceiverType,
  194. SourceLocation SuperLoc,
  195. Selector Sel,
  196. ObjCMethodDecl *Method,
  197. SourceLocation LBracLoc,
  198. ArrayRef<SourceLocation> SelectorLocs,
  199. SourceLocation RBracLoc,
  200. MultiExprArg ArgsIn,
  201. bool isImplicit) {
  202. llvm_unreachable("HLSL does not support ObjC constructs");
  203. return ExprError();
  204. }
  205. ExprResult Sema::ActOnClassMessage(Scope *S,
  206. ParsedType Receiver,
  207. Selector Sel,
  208. SourceLocation LBracLoc,
  209. ArrayRef<SourceLocation> SelectorLocs,
  210. SourceLocation RBracLoc,
  211. MultiExprArg Args) {
  212. llvm_unreachable("HLSL does not support ObjC constructs");
  213. }
  214. ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
  215. QualType ReceiverType,
  216. SourceLocation Loc,
  217. Selector Sel,
  218. ObjCMethodDecl *Method,
  219. MultiExprArg Args) {
  220. llvm_unreachable("HLSL does not support ObjC constructs");
  221. }
  222. ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
  223. QualType ReceiverType,
  224. SourceLocation SuperLoc,
  225. Selector Sel,
  226. ObjCMethodDecl *Method,
  227. SourceLocation LBracLoc,
  228. ArrayRef<SourceLocation> SelectorLocs,
  229. SourceLocation RBracLoc,
  230. MultiExprArg ArgsIn,
  231. bool isImplicit) {
  232. llvm_unreachable("HLSL does not support ObjC constructs");
  233. }
  234. ExprResult Sema::ActOnInstanceMessage(Scope *S,
  235. Expr *Receiver,
  236. Selector Sel,
  237. SourceLocation LBracLoc,
  238. ArrayRef<SourceLocation> SelectorLocs,
  239. SourceLocation RBracLoc,
  240. MultiExprArg Args) {
  241. llvm_unreachable("HLSL does not support ObjC constructs");
  242. }
  243. bool Sema::isKnownName(StringRef name) {
  244. if (name.empty())
  245. return false;
  246. LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
  247. Sema::LookupOrdinaryName);
  248. return LookupName(R, TUScope, false);
  249. }
  250. void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
  251. llvm_unreachable("HLSL does not support ObjC constructs");
  252. }
  253. void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
  254. llvm_unreachable("HLSL does not support ObjC constructs");
  255. }
  256. bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
  257. CastKind &Kind) {
  258. llvm_unreachable("HLSL does not support ObjC constructs");
  259. }
  260. bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
  261. QualType DestType, QualType SrcType,
  262. ObjCInterfaceDecl *&RelatedClass,
  263. ObjCMethodDecl *&ClassMethod,
  264. ObjCMethodDecl *&InstanceMethod,
  265. TypedefNameDecl *&TDNDecl,
  266. bool CfToNs) {
  267. llvm_unreachable("HLSL does not support ObjC constructs");
  268. }
  269. bool
  270. Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
  271. QualType DestType, QualType SrcType,
  272. Expr *&SrcExpr) {
  273. llvm_unreachable("HLSL does not support ObjC constructs");
  274. }
  275. Sema::ARCConversionResult
  276. Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
  277. Expr *&castExpr, CheckedConversionKind CCK,
  278. bool DiagnoseCFAudited,
  279. BinaryOperatorKind Opc) {
  280. llvm_unreachable("HLSL does not support ObjC constructs");
  281. }
  282. /// Given that we saw an expression with the ARCUnbridgedCastTy
  283. /// placeholder type, complain bitterly.
  284. void Sema::diagnoseARCUnbridgedCast(Expr *e) {
  285. llvm_unreachable("HLSL does not support ObjC constructs");
  286. }
  287. /// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
  288. /// type, remove the placeholder cast.
  289. Expr *Sema::stripARCUnbridgedCast(Expr *e) {
  290. llvm_unreachable("HLSL does not support ObjC constructs");
  291. }
  292. bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
  293. QualType exprType) {
  294. llvm_unreachable("HLSL does not support ObjC constructs");
  295. }
  296. ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
  297. ObjCBridgeCastKind Kind,
  298. SourceLocation BridgeKeywordLoc,
  299. TypeSourceInfo *TSInfo,
  300. Expr *SubExpr) {
  301. llvm_unreachable("HLSL does not support ObjC constructs");
  302. }
  303. ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
  304. SourceLocation LParenLoc,
  305. ObjCBridgeCastKind Kind,
  306. SourceLocation BridgeKeywordLoc,
  307. ParsedType Type,
  308. SourceLocation RParenLoc,
  309. Expr *SubExpr) {
  310. llvm_unreachable("HLSL does not support ObjC constructs");
  311. }
  312. #else
  313. // HLSL Change Ends
  314. ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
  315. Expr **strings,
  316. unsigned NumStrings) {
  317. StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
  318. // Most ObjC strings are formed out of a single piece. However, we *can*
  319. // have strings formed out of multiple @ strings with multiple pptokens in
  320. // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
  321. // StringLiteral for ObjCStringLiteral to hold onto.
  322. StringLiteral *S = Strings[0];
  323. // If we have a multi-part string, merge it all together.
  324. if (NumStrings != 1) {
  325. // Concatenate objc strings.
  326. SmallString<128> StrBuf;
  327. SmallVector<SourceLocation, 8> StrLocs;
  328. for (unsigned i = 0; i != NumStrings; ++i) {
  329. S = Strings[i];
  330. // ObjC strings can't be wide or UTF.
  331. if (!S->isAscii()) {
  332. Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
  333. << S->getSourceRange();
  334. return true;
  335. }
  336. // Append the string.
  337. StrBuf += S->getString();
  338. // Get the locations of the string tokens.
  339. StrLocs.append(S->tokloc_begin(), S->tokloc_end());
  340. }
  341. // Create the aggregate string with the appropriate content and location
  342. // information.
  343. const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
  344. assert(CAT && "String literal not of constant array type!");
  345. QualType StrTy = Context.getConstantArrayType(
  346. CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1),
  347. CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers());
  348. S = StringLiteral::Create(Context, StrBuf, StringLiteral::Ascii,
  349. /*Pascal=*/false, StrTy, &StrLocs[0],
  350. StrLocs.size());
  351. }
  352. return BuildObjCStringLiteral(AtLocs[0], S);
  353. }
  354. ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
  355. // Verify that this composite string is acceptable for ObjC strings.
  356. if (CheckObjCString(S))
  357. return true;
  358. // Initialize the constant string interface lazily. This assumes
  359. // the NSString interface is seen in this translation unit. Note: We
  360. // don't use NSConstantString, since the runtime team considers this
  361. // interface private (even though it appears in the header files).
  362. QualType Ty = Context.getObjCConstantStringInterface();
  363. if (!Ty.isNull()) {
  364. Ty = Context.getObjCObjectPointerType(Ty);
  365. } else if (getLangOpts().NoConstantCFStrings) {
  366. IdentifierInfo *NSIdent=nullptr;
  367. std::string StringClass(getLangOpts().ObjCConstantStringClass);
  368. if (StringClass.empty())
  369. NSIdent = &Context.Idents.get("NSConstantString");
  370. else
  371. NSIdent = &Context.Idents.get(StringClass);
  372. NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
  373. LookupOrdinaryName);
  374. if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
  375. Context.setObjCConstantStringInterface(StrIF);
  376. Ty = Context.getObjCConstantStringInterface();
  377. Ty = Context.getObjCObjectPointerType(Ty);
  378. } else {
  379. // If there is no NSConstantString interface defined then treat this
  380. // as error and recover from it.
  381. Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
  382. << S->getSourceRange();
  383. Ty = Context.getObjCIdType();
  384. }
  385. } else {
  386. IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
  387. NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
  388. LookupOrdinaryName);
  389. if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
  390. Context.setObjCConstantStringInterface(StrIF);
  391. Ty = Context.getObjCConstantStringInterface();
  392. Ty = Context.getObjCObjectPointerType(Ty);
  393. } else {
  394. // If there is no NSString interface defined, implicitly declare
  395. // a @class NSString; and use that instead. This is to make sure
  396. // type of an NSString literal is represented correctly, instead of
  397. // being an 'id' type.
  398. Ty = Context.getObjCNSStringType();
  399. if (Ty.isNull()) {
  400. ObjCInterfaceDecl *NSStringIDecl =
  401. ObjCInterfaceDecl::Create (Context,
  402. Context.getTranslationUnitDecl(),
  403. SourceLocation(), NSIdent,
  404. nullptr, nullptr, SourceLocation());
  405. Ty = Context.getObjCInterfaceType(NSStringIDecl);
  406. Context.setObjCNSStringType(Ty);
  407. }
  408. Ty = Context.getObjCObjectPointerType(Ty);
  409. }
  410. }
  411. return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
  412. }
  413. /// \brief Emits an error if the given method does not exist, or if the return
  414. /// type is not an Objective-C object.
  415. static bool validateBoxingMethod(Sema &S, SourceLocation Loc,
  416. const ObjCInterfaceDecl *Class,
  417. Selector Sel, const ObjCMethodDecl *Method) {
  418. if (!Method) {
  419. // FIXME: Is there a better way to avoid quotes than using getName()?
  420. S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName();
  421. return false;
  422. }
  423. // Make sure the return type is reasonable.
  424. QualType ReturnType = Method->getReturnType();
  425. if (!ReturnType->isObjCObjectPointerType()) {
  426. S.Diag(Loc, diag::err_objc_literal_method_sig)
  427. << Sel;
  428. S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
  429. << ReturnType;
  430. return false;
  431. }
  432. return true;
  433. }
  434. /// \brief Retrieve the NSNumber factory method that should be used to create
  435. /// an Objective-C literal for the given type.
  436. static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
  437. QualType NumberType,
  438. bool isLiteral = false,
  439. SourceRange R = SourceRange()) {
  440. Optional<NSAPI::NSNumberLiteralMethodKind> Kind =
  441. S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
  442. if (!Kind) {
  443. if (isLiteral) {
  444. S.Diag(Loc, diag::err_invalid_nsnumber_type)
  445. << NumberType << R;
  446. }
  447. return nullptr;
  448. }
  449. // If we already looked up this method, we're done.
  450. if (S.NSNumberLiteralMethods[*Kind])
  451. return S.NSNumberLiteralMethods[*Kind];
  452. Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
  453. /*Instance=*/false);
  454. ASTContext &CX = S.Context;
  455. // Look up the NSNumber class, if we haven't done so already. It's cached
  456. // in the Sema instance.
  457. if (!S.NSNumberDecl) {
  458. IdentifierInfo *NSNumberId =
  459. S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber);
  460. NamedDecl *IF = S.LookupSingleName(S.TUScope, NSNumberId,
  461. Loc, Sema::LookupOrdinaryName);
  462. S.NSNumberDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
  463. if (!S.NSNumberDecl) {
  464. if (S.getLangOpts().DebuggerObjCLiteral) {
  465. // Create a stub definition of NSNumber.
  466. S.NSNumberDecl = ObjCInterfaceDecl::Create(CX,
  467. CX.getTranslationUnitDecl(),
  468. SourceLocation(), NSNumberId,
  469. nullptr, nullptr,
  470. SourceLocation());
  471. } else {
  472. // Otherwise, require a declaration of NSNumber.
  473. S.Diag(Loc, diag::err_undeclared_nsnumber);
  474. return nullptr;
  475. }
  476. } else if (!S.NSNumberDecl->hasDefinition()) {
  477. S.Diag(Loc, diag::err_undeclared_nsnumber);
  478. return nullptr;
  479. }
  480. }
  481. if (S.NSNumberPointer.isNull()) {
  482. // generate the pointer to NSNumber type.
  483. QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
  484. S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
  485. }
  486. // Look for the appropriate method within NSNumber.
  487. ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
  488. if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
  489. // create a stub definition this NSNumber factory method.
  490. TypeSourceInfo *ReturnTInfo = nullptr;
  491. Method =
  492. ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
  493. S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl,
  494. /*isInstance=*/false, /*isVariadic=*/false,
  495. /*isPropertyAccessor=*/false,
  496. /*isImplicitlyDeclared=*/true,
  497. /*isDefined=*/false, ObjCMethodDecl::Required,
  498. /*HasRelatedResultType=*/false);
  499. ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
  500. SourceLocation(), SourceLocation(),
  501. &CX.Idents.get("value"),
  502. NumberType, /*TInfo=*/nullptr,
  503. SC_None, nullptr);
  504. Method->setMethodParams(S.Context, value, None);
  505. }
  506. if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
  507. return nullptr;
  508. // Note: if the parameter type is out-of-line, we'll catch it later in the
  509. // implicit conversion.
  510. S.NSNumberLiteralMethods[*Kind] = Method;
  511. return Method;
  512. }
  513. /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
  514. /// numeric literal expression. Type of the expression will be "NSNumber *".
  515. ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
  516. // Determine the type of the literal.
  517. QualType NumberType = Number->getType();
  518. if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
  519. // In C, character literals have type 'int'. That's not the type we want
  520. // to use to determine the Objective-c literal kind.
  521. switch (Char->getKind()) {
  522. case CharacterLiteral::Ascii:
  523. NumberType = Context.CharTy;
  524. break;
  525. case CharacterLiteral::Wide:
  526. NumberType = Context.getWideCharType();
  527. break;
  528. case CharacterLiteral::UTF16:
  529. NumberType = Context.Char16Ty;
  530. break;
  531. case CharacterLiteral::UTF32:
  532. NumberType = Context.Char32Ty;
  533. break;
  534. }
  535. }
  536. // Look for the appropriate method within NSNumber.
  537. // Construct the literal.
  538. SourceRange NR(Number->getSourceRange());
  539. ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
  540. true, NR);
  541. if (!Method)
  542. return ExprError();
  543. // Convert the number to the type that the parameter expects.
  544. ParmVarDecl *ParamDecl = Method->parameters()[0];
  545. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  546. ParamDecl);
  547. ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
  548. SourceLocation(),
  549. Number);
  550. if (ConvertedNumber.isInvalid())
  551. return ExprError();
  552. Number = ConvertedNumber.get();
  553. // Use the effective source range of the literal, including the leading '@'.
  554. return MaybeBindToTemporary(
  555. new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
  556. SourceRange(AtLoc, NR.getEnd())));
  557. }
  558. ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
  559. SourceLocation ValueLoc,
  560. bool Value) {
  561. ExprResult Inner;
  562. if (getLangOpts().CPlusPlus) {
  563. Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
  564. } else {
  565. // C doesn't actually have a way to represent literal values of type
  566. // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
  567. Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
  568. Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
  569. CK_IntegralToBoolean);
  570. }
  571. return BuildObjCNumericLiteral(AtLoc, Inner.get());
  572. }
  573. /// \brief Check that the given expression is a valid element of an Objective-C
  574. /// collection literal.
  575. static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
  576. QualType T,
  577. bool ArrayLiteral = false) {
  578. // If the expression is type-dependent, there's nothing for us to do.
  579. if (Element->isTypeDependent())
  580. return Element;
  581. ExprResult Result = S.CheckPlaceholderExpr(Element);
  582. if (Result.isInvalid())
  583. return ExprError();
  584. Element = Result.get();
  585. // In C++, check for an implicit conversion to an Objective-C object pointer
  586. // type.
  587. if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
  588. InitializedEntity Entity
  589. = InitializedEntity::InitializeParameter(S.Context, T,
  590. /*Consumed=*/false);
  591. InitializationKind Kind
  592. = InitializationKind::CreateCopy(Element->getLocStart(),
  593. SourceLocation());
  594. InitializationSequence Seq(S, Entity, Kind, Element);
  595. if (!Seq.Failed())
  596. return Seq.Perform(S, Entity, Kind, Element);
  597. }
  598. Expr *OrigElement = Element;
  599. // Perform lvalue-to-rvalue conversion.
  600. Result = S.DefaultLvalueConversion(Element);
  601. if (Result.isInvalid())
  602. return ExprError();
  603. Element = Result.get();
  604. // Make sure that we have an Objective-C pointer type or block.
  605. if (!Element->getType()->isObjCObjectPointerType() &&
  606. !Element->getType()->isBlockPointerType()) {
  607. bool Recovered = false;
  608. // If this is potentially an Objective-C numeric literal, add the '@'.
  609. if (isa<IntegerLiteral>(OrigElement) ||
  610. isa<CharacterLiteral>(OrigElement) ||
  611. isa<FloatingLiteral>(OrigElement) ||
  612. isa<ObjCBoolLiteralExpr>(OrigElement) ||
  613. isa<CXXBoolLiteralExpr>(OrigElement)) {
  614. if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
  615. int Which = isa<CharacterLiteral>(OrigElement) ? 1
  616. : (isa<CXXBoolLiteralExpr>(OrigElement) ||
  617. isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
  618. : 3;
  619. S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
  620. << Which << OrigElement->getSourceRange()
  621. << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
  622. Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
  623. OrigElement);
  624. if (Result.isInvalid())
  625. return ExprError();
  626. Element = Result.get();
  627. Recovered = true;
  628. }
  629. }
  630. // If this is potentially an Objective-C string literal, add the '@'.
  631. else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
  632. if (String->isAscii()) {
  633. S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
  634. << 0 << OrigElement->getSourceRange()
  635. << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
  636. Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
  637. if (Result.isInvalid())
  638. return ExprError();
  639. Element = Result.get();
  640. Recovered = true;
  641. }
  642. }
  643. if (!Recovered) {
  644. S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
  645. << Element->getType();
  646. return ExprError();
  647. }
  648. }
  649. if (ArrayLiteral)
  650. if (ObjCStringLiteral *getString =
  651. dyn_cast<ObjCStringLiteral>(OrigElement)) {
  652. if (StringLiteral *SL = getString->getString()) {
  653. unsigned numConcat = SL->getNumConcatenated();
  654. if (numConcat > 1) {
  655. // Only warn if the concatenated string doesn't come from a macro.
  656. bool hasMacro = false;
  657. for (unsigned i = 0; i < numConcat ; ++i)
  658. if (SL->getStrTokenLoc(i).isMacroID()) {
  659. hasMacro = true;
  660. break;
  661. }
  662. if (!hasMacro)
  663. S.Diag(Element->getLocStart(),
  664. diag::warn_concatenated_nsarray_literal)
  665. << Element->getType();
  666. }
  667. }
  668. }
  669. // Make sure that the element has the type that the container factory
  670. // function expects.
  671. return S.PerformCopyInitialization(
  672. InitializedEntity::InitializeParameter(S.Context, T,
  673. /*Consumed=*/false),
  674. Element->getLocStart(), Element);
  675. }
  676. ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
  677. if (ValueExpr->isTypeDependent()) {
  678. ObjCBoxedExpr *BoxedExpr =
  679. new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR);
  680. return BoxedExpr;
  681. }
  682. ObjCMethodDecl *BoxingMethod = nullptr;
  683. QualType BoxedType;
  684. // Convert the expression to an RValue, so we can check for pointer types...
  685. ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
  686. if (RValue.isInvalid()) {
  687. return ExprError();
  688. }
  689. ValueExpr = RValue.get();
  690. QualType ValueType(ValueExpr->getType());
  691. if (const PointerType *PT = ValueType->getAs<PointerType>()) {
  692. QualType PointeeType = PT->getPointeeType();
  693. if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
  694. if (!NSStringDecl) {
  695. IdentifierInfo *NSStringId =
  696. NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
  697. NamedDecl *Decl = LookupSingleName(TUScope, NSStringId,
  698. SR.getBegin(), LookupOrdinaryName);
  699. NSStringDecl = dyn_cast_or_null<ObjCInterfaceDecl>(Decl);
  700. if (!NSStringDecl) {
  701. if (getLangOpts().DebuggerObjCLiteral) {
  702. // Support boxed expressions in the debugger w/o NSString declaration.
  703. DeclContext *TU = Context.getTranslationUnitDecl();
  704. NSStringDecl = ObjCInterfaceDecl::Create(Context, TU,
  705. SourceLocation(),
  706. NSStringId,
  707. nullptr, nullptr,
  708. SourceLocation());
  709. } else {
  710. Diag(SR.getBegin(), diag::err_undeclared_nsstring);
  711. return ExprError();
  712. }
  713. } else if (!NSStringDecl->hasDefinition()) {
  714. Diag(SR.getBegin(), diag::err_undeclared_nsstring);
  715. return ExprError();
  716. }
  717. assert(NSStringDecl && "NSStringDecl should not be NULL");
  718. QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
  719. NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
  720. }
  721. if (!StringWithUTF8StringMethod) {
  722. IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
  723. Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
  724. // Look for the appropriate method within NSString.
  725. BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
  726. if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
  727. // Debugger needs to work even if NSString hasn't been defined.
  728. TypeSourceInfo *ReturnTInfo = nullptr;
  729. ObjCMethodDecl *M = ObjCMethodDecl::Create(
  730. Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
  731. NSStringPointer, ReturnTInfo, NSStringDecl,
  732. /*isInstance=*/false, /*isVariadic=*/false,
  733. /*isPropertyAccessor=*/false,
  734. /*isImplicitlyDeclared=*/true,
  735. /*isDefined=*/false, ObjCMethodDecl::Required,
  736. /*HasRelatedResultType=*/false);
  737. QualType ConstCharType = Context.CharTy.withConst();
  738. ParmVarDecl *value =
  739. ParmVarDecl::Create(Context, M,
  740. SourceLocation(), SourceLocation(),
  741. &Context.Idents.get("value"),
  742. Context.getPointerType(ConstCharType),
  743. /*TInfo=*/nullptr,
  744. SC_None, nullptr);
  745. M->setMethodParams(Context, value, None);
  746. BoxingMethod = M;
  747. }
  748. if (!validateBoxingMethod(*this, SR.getBegin(), NSStringDecl,
  749. stringWithUTF8String, BoxingMethod))
  750. return ExprError();
  751. StringWithUTF8StringMethod = BoxingMethod;
  752. }
  753. BoxingMethod = StringWithUTF8StringMethod;
  754. BoxedType = NSStringPointer;
  755. }
  756. } else if (ValueType->isBuiltinType()) {
  757. // The other types we support are numeric, char and BOOL/bool. We could also
  758. // provide limited support for structure types, such as NSRange, NSRect, and
  759. // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
  760. // for more details.
  761. // Check for a top-level character literal.
  762. if (const CharacterLiteral *Char =
  763. dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
  764. // In C, character literals have type 'int'. That's not the type we want
  765. // to use to determine the Objective-c literal kind.
  766. switch (Char->getKind()) {
  767. case CharacterLiteral::Ascii:
  768. ValueType = Context.CharTy;
  769. break;
  770. case CharacterLiteral::Wide:
  771. ValueType = Context.getWideCharType();
  772. break;
  773. case CharacterLiteral::UTF16:
  774. ValueType = Context.Char16Ty;
  775. break;
  776. case CharacterLiteral::UTF32:
  777. ValueType = Context.Char32Ty;
  778. break;
  779. }
  780. }
  781. CheckForIntOverflow(ValueExpr);
  782. // FIXME: Do I need to do anything special with BoolTy expressions?
  783. // Look for the appropriate method within NSNumber.
  784. BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), ValueType);
  785. BoxedType = NSNumberPointer;
  786. } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
  787. if (!ET->getDecl()->isComplete()) {
  788. Diag(SR.getBegin(), diag::err_objc_incomplete_boxed_expression_type)
  789. << ValueType << ValueExpr->getSourceRange();
  790. return ExprError();
  791. }
  792. BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(),
  793. ET->getDecl()->getIntegerType());
  794. BoxedType = NSNumberPointer;
  795. } else if (ValueType->isObjCBoxableRecordType()) {
  796. // Support for structure types, that marked as objc_boxable
  797. // struct __attribute__((objc_boxable)) s { ... };
  798. // Look up the NSValue class, if we haven't done so already. It's cached
  799. // in the Sema instance.
  800. if (!NSValueDecl) {
  801. IdentifierInfo *NSValueId =
  802. NSAPIObj->getNSClassId(NSAPI::ClassId_NSValue);
  803. NamedDecl *IF = LookupSingleName(TUScope, NSValueId,
  804. SR.getBegin(), Sema::LookupOrdinaryName);
  805. NSValueDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
  806. if (!NSValueDecl) {
  807. if (getLangOpts().DebuggerObjCLiteral) {
  808. // Create a stub definition of NSValue.
  809. DeclContext *TU = Context.getTranslationUnitDecl();
  810. NSValueDecl = ObjCInterfaceDecl::Create(Context, TU,
  811. SourceLocation(), NSValueId,
  812. nullptr, nullptr,
  813. SourceLocation());
  814. } else {
  815. // Otherwise, require a declaration of NSValue.
  816. Diag(SR.getBegin(), diag::err_undeclared_nsvalue);
  817. return ExprError();
  818. }
  819. } else if (!NSValueDecl->hasDefinition()) {
  820. Diag(SR.getBegin(), diag::err_undeclared_nsvalue);
  821. return ExprError();
  822. }
  823. // generate the pointer to NSValue type.
  824. QualType NSValueObject = Context.getObjCInterfaceType(NSValueDecl);
  825. NSValuePointer = Context.getObjCObjectPointerType(NSValueObject);
  826. }
  827. if (!ValueWithBytesObjCTypeMethod) {
  828. IdentifierInfo *II[] = {
  829. &Context.Idents.get("valueWithBytes"),
  830. &Context.Idents.get("objCType")
  831. };
  832. Selector ValueWithBytesObjCType = Context.Selectors.getSelector(2, II);
  833. // Look for the appropriate method within NSValue.
  834. BoxingMethod = NSValueDecl->lookupClassMethod(ValueWithBytesObjCType);
  835. if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
  836. // Debugger needs to work even if NSValue hasn't been defined.
  837. TypeSourceInfo *ReturnTInfo = nullptr;
  838. ObjCMethodDecl *M = ObjCMethodDecl::Create(
  839. Context,
  840. SourceLocation(),
  841. SourceLocation(),
  842. ValueWithBytesObjCType,
  843. NSValuePointer,
  844. ReturnTInfo,
  845. NSValueDecl,
  846. /*isInstance=*/false,
  847. /*isVariadic=*/false,
  848. /*isPropertyAccessor=*/false,
  849. /*isImplicitlyDeclared=*/true,
  850. /*isDefined=*/false,
  851. ObjCMethodDecl::Required,
  852. /*HasRelatedResultType=*/false);
  853. SmallVector<ParmVarDecl *, 2> Params;
  854. ParmVarDecl *bytes =
  855. ParmVarDecl::Create(Context, M,
  856. SourceLocation(), SourceLocation(),
  857. &Context.Idents.get("bytes"),
  858. Context.VoidPtrTy.withConst(),
  859. /*TInfo=*/nullptr,
  860. SC_None, nullptr);
  861. Params.push_back(bytes);
  862. QualType ConstCharType = Context.CharTy.withConst();
  863. ParmVarDecl *type =
  864. ParmVarDecl::Create(Context, M,
  865. SourceLocation(), SourceLocation(),
  866. &Context.Idents.get("type"),
  867. Context.getPointerType(ConstCharType),
  868. /*TInfo=*/nullptr,
  869. SC_None, nullptr);
  870. Params.push_back(type);
  871. M->setMethodParams(Context, Params, None);
  872. BoxingMethod = M;
  873. }
  874. if (!validateBoxingMethod(*this, SR.getBegin(), NSValueDecl,
  875. ValueWithBytesObjCType, BoxingMethod))
  876. return ExprError();
  877. ValueWithBytesObjCTypeMethod = BoxingMethod;
  878. }
  879. if (!ValueType.isTriviallyCopyableType(Context)) {
  880. Diag(SR.getBegin(),
  881. diag::err_objc_non_trivially_copyable_boxed_expression_type)
  882. << ValueType << ValueExpr->getSourceRange();
  883. return ExprError();
  884. }
  885. BoxingMethod = ValueWithBytesObjCTypeMethod;
  886. BoxedType = NSValuePointer;
  887. }
  888. if (!BoxingMethod) {
  889. Diag(SR.getBegin(), diag::err_objc_illegal_boxed_expression_type)
  890. << ValueType << ValueExpr->getSourceRange();
  891. return ExprError();
  892. }
  893. DiagnoseUseOfDecl(BoxingMethod, SR.getBegin());
  894. ExprResult ConvertedValueExpr;
  895. if (ValueType->isObjCBoxableRecordType()) {
  896. InitializedEntity IE = InitializedEntity::InitializeTemporary(ValueType);
  897. ConvertedValueExpr = PerformCopyInitialization(IE, ValueExpr->getExprLoc(),
  898. ValueExpr);
  899. } else {
  900. // Convert the expression to the type that the parameter requires.
  901. ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0];
  902. InitializedEntity IE = InitializedEntity::InitializeParameter(Context,
  903. ParamDecl);
  904. ConvertedValueExpr = PerformCopyInitialization(IE, SourceLocation(),
  905. ValueExpr);
  906. }
  907. if (ConvertedValueExpr.isInvalid())
  908. return ExprError();
  909. ValueExpr = ConvertedValueExpr.get();
  910. ObjCBoxedExpr *BoxedExpr =
  911. new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
  912. BoxingMethod, SR);
  913. return MaybeBindToTemporary(BoxedExpr);
  914. }
  915. /// Build an ObjC subscript pseudo-object expression, given that
  916. /// that's supported by the runtime.
  917. ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
  918. Expr *IndexExpr,
  919. ObjCMethodDecl *getterMethod,
  920. ObjCMethodDecl *setterMethod) {
  921. assert(!LangOpts.isSubscriptPointerArithmetic());
  922. // We can't get dependent types here; our callers should have
  923. // filtered them out.
  924. assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
  925. "base or index cannot have dependent type here");
  926. // Filter out placeholders in the index. In theory, overloads could
  927. // be preserved here, although that might not actually work correctly.
  928. ExprResult Result = CheckPlaceholderExpr(IndexExpr);
  929. if (Result.isInvalid())
  930. return ExprError();
  931. IndexExpr = Result.get();
  932. // Perform lvalue-to-rvalue conversion on the base.
  933. Result = DefaultLvalueConversion(BaseExpr);
  934. if (Result.isInvalid())
  935. return ExprError();
  936. BaseExpr = Result.get();
  937. // Build the pseudo-object expression.
  938. return ObjCSubscriptRefExpr::Create(Context, BaseExpr, IndexExpr,
  939. Context.PseudoObjectTy, getterMethod,
  940. setterMethod, RB);
  941. }
  942. ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
  943. // Look up the NSArray class, if we haven't done so already.
  944. if (!NSArrayDecl) {
  945. NamedDecl *IF = LookupSingleName(TUScope,
  946. NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
  947. SR.getBegin(),
  948. LookupOrdinaryName);
  949. NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
  950. if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
  951. NSArrayDecl = ObjCInterfaceDecl::Create (Context,
  952. Context.getTranslationUnitDecl(),
  953. SourceLocation(),
  954. NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
  955. nullptr, nullptr, SourceLocation());
  956. if (!NSArrayDecl) {
  957. Diag(SR.getBegin(), diag::err_undeclared_nsarray);
  958. return ExprError();
  959. }
  960. }
  961. // Find the arrayWithObjects:count: method, if we haven't done so already.
  962. QualType IdT = Context.getObjCIdType();
  963. if (!ArrayWithObjectsMethod) {
  964. Selector
  965. Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
  966. ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
  967. if (!Method && getLangOpts().DebuggerObjCLiteral) {
  968. TypeSourceInfo *ReturnTInfo = nullptr;
  969. Method = ObjCMethodDecl::Create(
  970. Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
  971. Context.getTranslationUnitDecl(), false /*Instance*/,
  972. false /*isVariadic*/,
  973. /*isPropertyAccessor=*/false,
  974. /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
  975. ObjCMethodDecl::Required, false);
  976. SmallVector<ParmVarDecl *, 2> Params;
  977. ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
  978. SourceLocation(),
  979. SourceLocation(),
  980. &Context.Idents.get("objects"),
  981. Context.getPointerType(IdT),
  982. /*TInfo=*/nullptr,
  983. SC_None, nullptr);
  984. Params.push_back(objects);
  985. ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
  986. SourceLocation(),
  987. SourceLocation(),
  988. &Context.Idents.get("cnt"),
  989. Context.UnsignedLongTy,
  990. /*TInfo=*/nullptr, SC_None,
  991. nullptr);
  992. Params.push_back(cnt);
  993. Method->setMethodParams(Context, Params, None);
  994. }
  995. if (!validateBoxingMethod(*this, SR.getBegin(), NSArrayDecl, Sel, Method))
  996. return ExprError();
  997. // Dig out the type that all elements should be converted to.
  998. QualType T = Method->parameters()[0]->getType();
  999. const PointerType *PtrT = T->getAs<PointerType>();
  1000. if (!PtrT ||
  1001. !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
  1002. Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
  1003. << Sel;
  1004. Diag(Method->parameters()[0]->getLocation(),
  1005. diag::note_objc_literal_method_param)
  1006. << 0 << T
  1007. << Context.getPointerType(IdT.withConst());
  1008. return ExprError();
  1009. }
  1010. // Check that the 'count' parameter is integral.
  1011. if (!Method->parameters()[1]->getType()->isIntegerType()) {
  1012. Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
  1013. << Sel;
  1014. Diag(Method->parameters()[1]->getLocation(),
  1015. diag::note_objc_literal_method_param)
  1016. << 1
  1017. << Method->parameters()[1]->getType()
  1018. << "integral";
  1019. return ExprError();
  1020. }
  1021. // We've found a good +arrayWithObjects:count: method. Save it!
  1022. ArrayWithObjectsMethod = Method;
  1023. }
  1024. QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
  1025. QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
  1026. // Check that each of the elements provided is valid in a collection literal,
  1027. // performing conversions as necessary.
  1028. Expr **ElementsBuffer = Elements.data();
  1029. for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
  1030. ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
  1031. ElementsBuffer[I],
  1032. RequiredType, true);
  1033. if (Converted.isInvalid())
  1034. return ExprError();
  1035. ElementsBuffer[I] = Converted.get();
  1036. }
  1037. QualType Ty
  1038. = Context.getObjCObjectPointerType(
  1039. Context.getObjCInterfaceType(NSArrayDecl));
  1040. return MaybeBindToTemporary(
  1041. ObjCArrayLiteral::Create(Context, Elements, Ty,
  1042. ArrayWithObjectsMethod, SR));
  1043. }
  1044. ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
  1045. ObjCDictionaryElement *Elements,
  1046. unsigned NumElements) {
  1047. // Look up the NSDictionary class, if we haven't done so already.
  1048. if (!NSDictionaryDecl) {
  1049. NamedDecl *IF = LookupSingleName(TUScope,
  1050. NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
  1051. SR.getBegin(), LookupOrdinaryName);
  1052. NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
  1053. if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
  1054. NSDictionaryDecl = ObjCInterfaceDecl::Create (Context,
  1055. Context.getTranslationUnitDecl(),
  1056. SourceLocation(),
  1057. NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
  1058. nullptr, nullptr, SourceLocation());
  1059. if (!NSDictionaryDecl) {
  1060. Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
  1061. return ExprError();
  1062. }
  1063. }
  1064. // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
  1065. // so already.
  1066. QualType IdT = Context.getObjCIdType();
  1067. if (!DictionaryWithObjectsMethod) {
  1068. Selector Sel = NSAPIObj->getNSDictionarySelector(
  1069. NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
  1070. ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
  1071. if (!Method && getLangOpts().DebuggerObjCLiteral) {
  1072. Method = ObjCMethodDecl::Create(Context,
  1073. SourceLocation(), SourceLocation(), Sel,
  1074. IdT,
  1075. nullptr /*TypeSourceInfo */,
  1076. Context.getTranslationUnitDecl(),
  1077. false /*Instance*/, false/*isVariadic*/,
  1078. /*isPropertyAccessor=*/false,
  1079. /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
  1080. ObjCMethodDecl::Required,
  1081. false);
  1082. SmallVector<ParmVarDecl *, 3> Params;
  1083. ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
  1084. SourceLocation(),
  1085. SourceLocation(),
  1086. &Context.Idents.get("objects"),
  1087. Context.getPointerType(IdT),
  1088. /*TInfo=*/nullptr, SC_None,
  1089. nullptr);
  1090. Params.push_back(objects);
  1091. ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
  1092. SourceLocation(),
  1093. SourceLocation(),
  1094. &Context.Idents.get("keys"),
  1095. Context.getPointerType(IdT),
  1096. /*TInfo=*/nullptr, SC_None,
  1097. nullptr);
  1098. Params.push_back(keys);
  1099. ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
  1100. SourceLocation(),
  1101. SourceLocation(),
  1102. &Context.Idents.get("cnt"),
  1103. Context.UnsignedLongTy,
  1104. /*TInfo=*/nullptr, SC_None,
  1105. nullptr);
  1106. Params.push_back(cnt);
  1107. Method->setMethodParams(Context, Params, None);
  1108. }
  1109. if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
  1110. Method))
  1111. return ExprError();
  1112. // Dig out the type that all values should be converted to.
  1113. QualType ValueT = Method->parameters()[0]->getType();
  1114. const PointerType *PtrValue = ValueT->getAs<PointerType>();
  1115. if (!PtrValue ||
  1116. !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
  1117. Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
  1118. << Sel;
  1119. Diag(Method->parameters()[0]->getLocation(),
  1120. diag::note_objc_literal_method_param)
  1121. << 0 << ValueT
  1122. << Context.getPointerType(IdT.withConst());
  1123. return ExprError();
  1124. }
  1125. // Dig out the type that all keys should be converted to.
  1126. QualType KeyT = Method->parameters()[1]->getType();
  1127. const PointerType *PtrKey = KeyT->getAs<PointerType>();
  1128. if (!PtrKey ||
  1129. !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
  1130. IdT)) {
  1131. bool err = true;
  1132. if (PtrKey) {
  1133. if (QIDNSCopying.isNull()) {
  1134. // key argument of selector is id<NSCopying>?
  1135. if (ObjCProtocolDecl *NSCopyingPDecl =
  1136. LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
  1137. ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
  1138. QIDNSCopying =
  1139. Context.getObjCObjectType(Context.ObjCBuiltinIdTy, { },
  1140. llvm::makeArrayRef(
  1141. (ObjCProtocolDecl**) PQ,
  1142. 1),
  1143. false);
  1144. QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
  1145. }
  1146. }
  1147. if (!QIDNSCopying.isNull())
  1148. err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
  1149. QIDNSCopying);
  1150. }
  1151. if (err) {
  1152. Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
  1153. << Sel;
  1154. Diag(Method->parameters()[1]->getLocation(),
  1155. diag::note_objc_literal_method_param)
  1156. << 1 << KeyT
  1157. << Context.getPointerType(IdT.withConst());
  1158. return ExprError();
  1159. }
  1160. }
  1161. // Check that the 'count' parameter is integral.
  1162. QualType CountType = Method->parameters()[2]->getType();
  1163. if (!CountType->isIntegerType()) {
  1164. Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
  1165. << Sel;
  1166. Diag(Method->parameters()[2]->getLocation(),
  1167. diag::note_objc_literal_method_param)
  1168. << 2 << CountType
  1169. << "integral";
  1170. return ExprError();
  1171. }
  1172. // We've found a good +dictionaryWithObjects:keys:count: method; save it!
  1173. DictionaryWithObjectsMethod = Method;
  1174. }
  1175. QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
  1176. QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
  1177. QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
  1178. QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
  1179. // Check that each of the keys and values provided is valid in a collection
  1180. // literal, performing conversions as necessary.
  1181. bool HasPackExpansions = false;
  1182. for (unsigned I = 0, N = NumElements; I != N; ++I) {
  1183. // Check the key.
  1184. ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key,
  1185. KeyT);
  1186. if (Key.isInvalid())
  1187. return ExprError();
  1188. // Check the value.
  1189. ExprResult Value
  1190. = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
  1191. if (Value.isInvalid())
  1192. return ExprError();
  1193. Elements[I].Key = Key.get();
  1194. Elements[I].Value = Value.get();
  1195. if (Elements[I].EllipsisLoc.isInvalid())
  1196. continue;
  1197. if (!Elements[I].Key->containsUnexpandedParameterPack() &&
  1198. !Elements[I].Value->containsUnexpandedParameterPack()) {
  1199. Diag(Elements[I].EllipsisLoc,
  1200. diag::err_pack_expansion_without_parameter_packs)
  1201. << SourceRange(Elements[I].Key->getLocStart(),
  1202. Elements[I].Value->getLocEnd());
  1203. return ExprError();
  1204. }
  1205. HasPackExpansions = true;
  1206. }
  1207. QualType Ty
  1208. = Context.getObjCObjectPointerType(
  1209. Context.getObjCInterfaceType(NSDictionaryDecl));
  1210. return MaybeBindToTemporary(ObjCDictionaryLiteral::Create(
  1211. Context, makeArrayRef(Elements, NumElements), HasPackExpansions, Ty,
  1212. DictionaryWithObjectsMethod, SR));
  1213. }
  1214. ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
  1215. TypeSourceInfo *EncodedTypeInfo,
  1216. SourceLocation RParenLoc) {
  1217. QualType EncodedType = EncodedTypeInfo->getType();
  1218. QualType StrTy;
  1219. if (EncodedType->isDependentType())
  1220. StrTy = Context.DependentTy;
  1221. else {
  1222. if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
  1223. !EncodedType->isVoidType()) // void is handled too.
  1224. if (RequireCompleteType(AtLoc, EncodedType,
  1225. diag::err_incomplete_type_objc_at_encode,
  1226. EncodedTypeInfo->getTypeLoc()))
  1227. return ExprError();
  1228. std::string Str;
  1229. QualType NotEncodedT;
  1230. Context.getObjCEncodingForType(EncodedType, Str, nullptr, &NotEncodedT);
  1231. if (!NotEncodedT.isNull())
  1232. Diag(AtLoc, diag::warn_incomplete_encoded_type)
  1233. << EncodedType << NotEncodedT;
  1234. // The type of @encode is the same as the type of the corresponding string,
  1235. // which is an array type.
  1236. StrTy = Context.CharTy;
  1237. // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
  1238. if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
  1239. StrTy.addConst();
  1240. StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
  1241. ArrayType::Normal, 0);
  1242. }
  1243. return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
  1244. }
  1245. ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
  1246. SourceLocation EncodeLoc,
  1247. SourceLocation LParenLoc,
  1248. ParsedType ty,
  1249. SourceLocation RParenLoc) {
  1250. // FIXME: Preserve type source info ?
  1251. TypeSourceInfo *TInfo;
  1252. QualType EncodedType = GetTypeFromParser(ty, &TInfo);
  1253. if (!TInfo)
  1254. TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
  1255. PP.getLocForEndOfToken(LParenLoc));
  1256. return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
  1257. }
  1258. static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
  1259. SourceLocation AtLoc,
  1260. SourceLocation LParenLoc,
  1261. SourceLocation RParenLoc,
  1262. ObjCMethodDecl *Method,
  1263. ObjCMethodList &MethList) {
  1264. ObjCMethodList *M = &MethList;
  1265. bool Warned = false;
  1266. for (M = M->getNext(); M; M=M->getNext()) {
  1267. ObjCMethodDecl *MatchingMethodDecl = M->getMethod();
  1268. if (MatchingMethodDecl == Method ||
  1269. isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
  1270. MatchingMethodDecl->getSelector() != Method->getSelector())
  1271. continue;
  1272. if (!S.MatchTwoMethodDeclarations(Method,
  1273. MatchingMethodDecl, Sema::MMS_loose)) {
  1274. if (!Warned) {
  1275. Warned = true;
  1276. S.Diag(AtLoc, diag::warning_multiple_selectors)
  1277. << Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(")
  1278. << FixItHint::CreateInsertion(RParenLoc, ")");
  1279. S.Diag(Method->getLocation(), diag::note_method_declared_at)
  1280. << Method->getDeclName();
  1281. }
  1282. S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
  1283. << MatchingMethodDecl->getDeclName();
  1284. }
  1285. }
  1286. return Warned;
  1287. }
  1288. static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
  1289. ObjCMethodDecl *Method,
  1290. SourceLocation LParenLoc,
  1291. SourceLocation RParenLoc,
  1292. bool WarnMultipleSelectors) {
  1293. if (!WarnMultipleSelectors ||
  1294. S.Diags.isIgnored(diag::warning_multiple_selectors, SourceLocation()))
  1295. return;
  1296. bool Warned = false;
  1297. for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
  1298. e = S.MethodPool.end(); b != e; b++) {
  1299. // first, instance methods
  1300. ObjCMethodList &InstMethList = b->second.first;
  1301. if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
  1302. Method, InstMethList))
  1303. Warned = true;
  1304. // second, class methods
  1305. ObjCMethodList &ClsMethList = b->second.second;
  1306. if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
  1307. Method, ClsMethList) || Warned)
  1308. return;
  1309. }
  1310. }
  1311. ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
  1312. SourceLocation AtLoc,
  1313. SourceLocation SelLoc,
  1314. SourceLocation LParenLoc,
  1315. SourceLocation RParenLoc,
  1316. bool WarnMultipleSelectors) {
  1317. ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
  1318. SourceRange(LParenLoc, RParenLoc));
  1319. if (!Method)
  1320. Method = LookupFactoryMethodInGlobalPool(Sel,
  1321. SourceRange(LParenLoc, RParenLoc));
  1322. if (!Method) {
  1323. if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
  1324. Selector MatchedSel = OM->getSelector();
  1325. SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
  1326. RParenLoc.getLocWithOffset(-1));
  1327. Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
  1328. << Sel << MatchedSel
  1329. << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
  1330. } else
  1331. Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
  1332. } else
  1333. DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc,
  1334. WarnMultipleSelectors);
  1335. if (Method &&
  1336. Method->getImplementationControl() != ObjCMethodDecl::Optional &&
  1337. !getSourceManager().isInSystemHeader(Method->getLocation()))
  1338. ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
  1339. // In ARC, forbid the user from using @selector for
  1340. // retain/release/autorelease/dealloc/retainCount.
  1341. if (getLangOpts().ObjCAutoRefCount) {
  1342. switch (Sel.getMethodFamily()) {
  1343. case OMF_retain:
  1344. case OMF_release:
  1345. case OMF_autorelease:
  1346. case OMF_retainCount:
  1347. case OMF_dealloc:
  1348. Diag(AtLoc, diag::err_arc_illegal_selector) <<
  1349. Sel << SourceRange(LParenLoc, RParenLoc);
  1350. break;
  1351. case OMF_None:
  1352. case OMF_alloc:
  1353. case OMF_copy:
  1354. case OMF_finalize:
  1355. case OMF_init:
  1356. case OMF_mutableCopy:
  1357. case OMF_new:
  1358. case OMF_self:
  1359. case OMF_initialize:
  1360. case OMF_performSelector:
  1361. break;
  1362. }
  1363. }
  1364. QualType Ty = Context.getObjCSelType();
  1365. return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
  1366. }
  1367. ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
  1368. SourceLocation AtLoc,
  1369. SourceLocation ProtoLoc,
  1370. SourceLocation LParenLoc,
  1371. SourceLocation ProtoIdLoc,
  1372. SourceLocation RParenLoc) {
  1373. ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
  1374. if (!PDecl) {
  1375. Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
  1376. return true;
  1377. }
  1378. if (PDecl->hasDefinition())
  1379. PDecl = PDecl->getDefinition();
  1380. QualType Ty = Context.getObjCProtoType();
  1381. if (Ty.isNull())
  1382. return true;
  1383. Ty = Context.getObjCObjectPointerType(Ty);
  1384. return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
  1385. }
  1386. /// Try to capture an implicit reference to 'self'.
  1387. ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
  1388. DeclContext *DC = getFunctionLevelDeclContext();
  1389. // If we're not in an ObjC method, error out. Note that, unlike the
  1390. // C++ case, we don't require an instance method --- class methods
  1391. // still have a 'self', and we really do still need to capture it!
  1392. ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
  1393. if (!method)
  1394. return nullptr;
  1395. tryCaptureVariable(method->getSelfDecl(), Loc);
  1396. return method;
  1397. }
  1398. static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
  1399. QualType origType = T;
  1400. if (auto nullability = AttributedType::stripOuterNullability(T)) {
  1401. if (T == Context.getObjCInstanceType()) {
  1402. return Context.getAttributedType(
  1403. AttributedType::getNullabilityAttrKind(*nullability),
  1404. Context.getObjCIdType(),
  1405. Context.getObjCIdType());
  1406. }
  1407. return origType;
  1408. }
  1409. if (T == Context.getObjCInstanceType())
  1410. return Context.getObjCIdType();
  1411. return origType;
  1412. }
  1413. /// Determine the result type of a message send based on the receiver type,
  1414. /// method, and the kind of message send.
  1415. ///
  1416. /// This is the "base" result type, which will still need to be adjusted
  1417. /// to account for nullability.
  1418. static QualType getBaseMessageSendResultType(Sema &S,
  1419. QualType ReceiverType,
  1420. ObjCMethodDecl *Method,
  1421. bool isClassMessage,
  1422. bool isSuperMessage) {
  1423. assert(Method && "Must have a method");
  1424. if (!Method->hasRelatedResultType())
  1425. return Method->getSendResultType(ReceiverType);
  1426. ASTContext &Context = S.Context;
  1427. // Local function that transfers the nullability of the method's
  1428. // result type to the returned result.
  1429. auto transferNullability = [&](QualType type) -> QualType {
  1430. // If the method's result type has nullability, extract it.
  1431. if (auto nullability = Method->getSendResultType(ReceiverType)
  1432. ->getNullability(Context)){
  1433. // Strip off any outer nullability sugar from the provided type.
  1434. (void)AttributedType::stripOuterNullability(type);
  1435. // Form a new attributed type using the method result type's nullability.
  1436. return Context.getAttributedType(
  1437. AttributedType::getNullabilityAttrKind(*nullability),
  1438. type,
  1439. type);
  1440. }
  1441. return type;
  1442. };
  1443. // If a method has a related return type:
  1444. // - if the method found is an instance method, but the message send
  1445. // was a class message send, T is the declared return type of the method
  1446. // found
  1447. if (Method->isInstanceMethod() && isClassMessage)
  1448. return stripObjCInstanceType(Context,
  1449. Method->getSendResultType(ReceiverType));
  1450. // - if the receiver is super, T is a pointer to the class of the
  1451. // enclosing method definition
  1452. if (isSuperMessage) {
  1453. if (ObjCMethodDecl *CurMethod = S.getCurMethodDecl())
  1454. if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) {
  1455. return transferNullability(
  1456. Context.getObjCObjectPointerType(
  1457. Context.getObjCInterfaceType(Class)));
  1458. }
  1459. }
  1460. // - if the receiver is the name of a class U, T is a pointer to U
  1461. if (ReceiverType->getAsObjCInterfaceType())
  1462. return transferNullability(Context.getObjCObjectPointerType(ReceiverType));
  1463. // - if the receiver is of type Class or qualified Class type,
  1464. // T is the declared return type of the method.
  1465. if (ReceiverType->isObjCClassType() ||
  1466. ReceiverType->isObjCQualifiedClassType())
  1467. return stripObjCInstanceType(Context,
  1468. Method->getSendResultType(ReceiverType));
  1469. // - if the receiver is id, qualified id, Class, or qualified Class, T
  1470. // is the receiver type, otherwise
  1471. // - T is the type of the receiver expression.
  1472. return transferNullability(ReceiverType);
  1473. }
  1474. QualType Sema::getMessageSendResultType(QualType ReceiverType,
  1475. ObjCMethodDecl *Method,
  1476. bool isClassMessage,
  1477. bool isSuperMessage) {
  1478. // Produce the result type.
  1479. QualType resultType = getBaseMessageSendResultType(*this, ReceiverType,
  1480. Method,
  1481. isClassMessage,
  1482. isSuperMessage);
  1483. // If this is a class message, ignore the nullability of the receiver.
  1484. if (isClassMessage)
  1485. return resultType;
  1486. // Map the nullability of the result into a table index.
  1487. unsigned receiverNullabilityIdx = 0;
  1488. if (auto nullability = ReceiverType->getNullability(Context))
  1489. receiverNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
  1490. unsigned resultNullabilityIdx = 0;
  1491. if (auto nullability = resultType->getNullability(Context))
  1492. resultNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
  1493. // The table of nullability mappings, indexed by the receiver's nullability
  1494. // and then the result type's nullability.
  1495. static const uint8_t None = 0;
  1496. static const uint8_t NonNull = 1;
  1497. static const uint8_t Nullable = 2;
  1498. static const uint8_t Unspecified = 3;
  1499. static const uint8_t nullabilityMap[4][4] = {
  1500. // None NonNull Nullable Unspecified
  1501. /* None */ { None, None, Nullable, None },
  1502. /* NonNull */ { None, NonNull, Nullable, Unspecified },
  1503. /* Nullable */ { Nullable, Nullable, Nullable, Nullable },
  1504. /* Unspecified */ { None, Unspecified, Nullable, Unspecified }
  1505. };
  1506. unsigned newResultNullabilityIdx
  1507. = nullabilityMap[receiverNullabilityIdx][resultNullabilityIdx];
  1508. if (newResultNullabilityIdx == resultNullabilityIdx)
  1509. return resultType;
  1510. // Strip off the existing nullability. This removes as little type sugar as
  1511. // possible.
  1512. do {
  1513. if (auto attributed = dyn_cast<AttributedType>(resultType.getTypePtr())) {
  1514. resultType = attributed->getModifiedType();
  1515. } else {
  1516. resultType = resultType.getDesugaredType(Context);
  1517. }
  1518. } while (resultType->getNullability(Context));
  1519. // Add nullability back if needed.
  1520. if (newResultNullabilityIdx > 0) {
  1521. auto newNullability
  1522. = static_cast<NullabilityKind>(newResultNullabilityIdx-1);
  1523. return Context.getAttributedType(
  1524. AttributedType::getNullabilityAttrKind(newNullability),
  1525. resultType, resultType);
  1526. }
  1527. return resultType;
  1528. }
  1529. /// Look for an ObjC method whose result type exactly matches the given type.
  1530. static const ObjCMethodDecl *
  1531. findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
  1532. QualType instancetype) {
  1533. if (MD->getReturnType() == instancetype)
  1534. return MD;
  1535. // For these purposes, a method in an @implementation overrides a
  1536. // declaration in the @interface.
  1537. if (const ObjCImplDecl *impl =
  1538. dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
  1539. const ObjCContainerDecl *iface;
  1540. if (const ObjCCategoryImplDecl *catImpl =
  1541. dyn_cast<ObjCCategoryImplDecl>(impl)) {
  1542. iface = catImpl->getCategoryDecl();
  1543. } else {
  1544. iface = impl->getClassInterface();
  1545. }
  1546. const ObjCMethodDecl *ifaceMD =
  1547. iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
  1548. if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
  1549. }
  1550. SmallVector<const ObjCMethodDecl *, 4> overrides;
  1551. MD->getOverriddenMethods(overrides);
  1552. for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
  1553. if (const ObjCMethodDecl *result =
  1554. findExplicitInstancetypeDeclarer(overrides[i], instancetype))
  1555. return result;
  1556. }
  1557. return nullptr;
  1558. }
  1559. void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
  1560. // Only complain if we're in an ObjC method and the required return
  1561. // type doesn't match the method's declared return type.
  1562. ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
  1563. if (!MD || !MD->hasRelatedResultType() ||
  1564. Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
  1565. return;
  1566. // Look for a method overridden by this method which explicitly uses
  1567. // 'instancetype'.
  1568. if (const ObjCMethodDecl *overridden =
  1569. findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
  1570. SourceRange range = overridden->getReturnTypeSourceRange();
  1571. SourceLocation loc = range.getBegin();
  1572. if (loc.isInvalid())
  1573. loc = overridden->getLocation();
  1574. Diag(loc, diag::note_related_result_type_explicit)
  1575. << /*current method*/ 1 << range;
  1576. return;
  1577. }
  1578. // Otherwise, if we have an interesting method family, note that.
  1579. // This should always trigger if the above didn't.
  1580. if (ObjCMethodFamily family = MD->getMethodFamily())
  1581. Diag(MD->getLocation(), diag::note_related_result_type_family)
  1582. << /*current method*/ 1
  1583. << family;
  1584. }
  1585. void Sema::EmitRelatedResultTypeNote(const Expr *E) {
  1586. E = E->IgnoreParenImpCasts();
  1587. const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
  1588. if (!MsgSend)
  1589. return;
  1590. const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
  1591. if (!Method)
  1592. return;
  1593. if (!Method->hasRelatedResultType())
  1594. return;
  1595. if (Context.hasSameUnqualifiedType(
  1596. Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
  1597. return;
  1598. if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
  1599. Context.getObjCInstanceType()))
  1600. return;
  1601. Diag(Method->getLocation(), diag::note_related_result_type_inferred)
  1602. << Method->isInstanceMethod() << Method->getSelector()
  1603. << MsgSend->getType();
  1604. }
  1605. bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
  1606. MultiExprArg Args,
  1607. Selector Sel,
  1608. ArrayRef<SourceLocation> SelectorLocs,
  1609. ObjCMethodDecl *Method,
  1610. bool isClassMessage, bool isSuperMessage,
  1611. SourceLocation lbrac, SourceLocation rbrac,
  1612. SourceRange RecRange,
  1613. QualType &ReturnType, ExprValueKind &VK) {
  1614. SourceLocation SelLoc;
  1615. if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
  1616. SelLoc = SelectorLocs.front();
  1617. else
  1618. SelLoc = lbrac;
  1619. if (!Method) {
  1620. // Apply default argument promotion as for (C99 6.5.2.2p6).
  1621. for (unsigned i = 0, e = Args.size(); i != e; i++) {
  1622. if (Args[i]->isTypeDependent())
  1623. continue;
  1624. ExprResult result;
  1625. if (getLangOpts().DebuggerSupport) {
  1626. QualType paramTy; // ignored
  1627. result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
  1628. } else {
  1629. result = DefaultArgumentPromotion(Args[i]);
  1630. }
  1631. if (result.isInvalid())
  1632. return true;
  1633. Args[i] = result.get();
  1634. }
  1635. unsigned DiagID;
  1636. if (getLangOpts().ObjCAutoRefCount)
  1637. DiagID = diag::err_arc_method_not_found;
  1638. else
  1639. DiagID = isClassMessage ? diag::warn_class_method_not_found
  1640. : diag::warn_inst_method_not_found;
  1641. if (!getLangOpts().DebuggerSupport) {
  1642. const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
  1643. if (OMD && !OMD->isInvalidDecl()) {
  1644. if (getLangOpts().ObjCAutoRefCount)
  1645. DiagID = diag::error_method_not_found_with_typo;
  1646. else
  1647. DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
  1648. : diag::warn_instance_method_not_found_with_typo;
  1649. Selector MatchedSel = OMD->getSelector();
  1650. SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
  1651. if (MatchedSel.isUnarySelector())
  1652. Diag(SelLoc, DiagID)
  1653. << Sel<< isClassMessage << MatchedSel
  1654. << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
  1655. else
  1656. Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel;
  1657. }
  1658. else
  1659. Diag(SelLoc, DiagID)
  1660. << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
  1661. SelectorLocs.back());
  1662. // Find the class to which we are sending this message.
  1663. if (ReceiverType->isObjCObjectPointerType()) {
  1664. if (ObjCInterfaceDecl *ThisClass =
  1665. ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()) {
  1666. Diag(ThisClass->getLocation(), diag::note_receiver_class_declared);
  1667. if (!RecRange.isInvalid())
  1668. if (ThisClass->lookupClassMethod(Sel))
  1669. Diag(RecRange.getBegin(),diag::note_receiver_expr_here)
  1670. << FixItHint::CreateReplacement(RecRange,
  1671. ThisClass->getNameAsString());
  1672. }
  1673. }
  1674. }
  1675. // In debuggers, we want to use __unknown_anytype for these
  1676. // results so that clients can cast them.
  1677. if (getLangOpts().DebuggerSupport) {
  1678. ReturnType = Context.UnknownAnyTy;
  1679. } else {
  1680. ReturnType = Context.getObjCIdType();
  1681. }
  1682. VK = VK_RValue;
  1683. return false;
  1684. }
  1685. ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
  1686. isSuperMessage);
  1687. VK = Expr::getValueKindForType(Method->getReturnType());
  1688. unsigned NumNamedArgs = Sel.getNumArgs();
  1689. // Method might have more arguments than selector indicates. This is due
  1690. // to addition of c-style arguments in method.
  1691. if (Method->param_size() > Sel.getNumArgs())
  1692. NumNamedArgs = Method->param_size();
  1693. // FIXME. This need be cleaned up.
  1694. if (Args.size() < NumNamedArgs) {
  1695. Diag(SelLoc, diag::err_typecheck_call_too_few_args)
  1696. << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
  1697. return false;
  1698. }
  1699. // Compute the set of type arguments to be substituted into each parameter
  1700. // type.
  1701. Optional<ArrayRef<QualType>> typeArgs
  1702. = ReceiverType->getObjCSubstitutions(Method->getDeclContext());
  1703. bool IsError = false;
  1704. for (unsigned i = 0; i < NumNamedArgs; i++) {
  1705. // We can't do any type-checking on a type-dependent argument.
  1706. if (Args[i]->isTypeDependent())
  1707. continue;
  1708. Expr *argExpr = Args[i];
  1709. ParmVarDecl *param = Method->parameters()[i];
  1710. assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
  1711. // Strip the unbridged-cast placeholder expression off unless it's
  1712. // a consumed argument.
  1713. if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
  1714. !param->hasAttr<CFConsumedAttr>())
  1715. argExpr = stripARCUnbridgedCast(argExpr);
  1716. // If the parameter is __unknown_anytype, infer its type
  1717. // from the argument.
  1718. if (param->getType() == Context.UnknownAnyTy) {
  1719. QualType paramType;
  1720. ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
  1721. if (argE.isInvalid()) {
  1722. IsError = true;
  1723. } else {
  1724. Args[i] = argE.get();
  1725. // Update the parameter type in-place.
  1726. param->setType(paramType);
  1727. }
  1728. continue;
  1729. }
  1730. QualType origParamType = param->getType();
  1731. QualType paramType = param->getType();
  1732. if (typeArgs)
  1733. paramType = paramType.substObjCTypeArgs(
  1734. Context,
  1735. *typeArgs,
  1736. ObjCSubstitutionContext::Parameter);
  1737. if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
  1738. paramType,
  1739. diag::err_call_incomplete_argument, argExpr))
  1740. return true;
  1741. InitializedEntity Entity
  1742. = InitializedEntity::InitializeParameter(Context, param, paramType);
  1743. ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
  1744. if (ArgE.isInvalid())
  1745. IsError = true;
  1746. else {
  1747. Args[i] = ArgE.getAs<Expr>();
  1748. // If we are type-erasing a block to a block-compatible
  1749. // Objective-C pointer type, we may need to extend the lifetime
  1750. // of the block object.
  1751. if (typeArgs && Args[i]->isRValue() && paramType->isBlockPointerType() &&
  1752. origParamType->isBlockCompatibleObjCPointerType(Context)) {
  1753. ExprResult arg = Args[i];
  1754. maybeExtendBlockObject(arg);
  1755. Args[i] = arg.get();
  1756. }
  1757. }
  1758. }
  1759. // Promote additional arguments to variadic methods.
  1760. if (Method->isVariadic()) {
  1761. for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
  1762. if (Args[i]->isTypeDependent())
  1763. continue;
  1764. ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
  1765. nullptr);
  1766. IsError |= Arg.isInvalid();
  1767. Args[i] = Arg.get();
  1768. }
  1769. } else {
  1770. // Check for extra arguments to non-variadic methods.
  1771. if (Args.size() != NumNamedArgs) {
  1772. Diag(Args[NumNamedArgs]->getLocStart(),
  1773. diag::err_typecheck_call_too_many_args)
  1774. << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
  1775. << Method->getSourceRange()
  1776. << SourceRange(Args[NumNamedArgs]->getLocStart(),
  1777. Args.back()->getLocEnd());
  1778. }
  1779. }
  1780. DiagnoseSentinelCalls(Method, SelLoc, Args);
  1781. // Do additional checkings on method.
  1782. IsError |= CheckObjCMethodCall(
  1783. Method, SelLoc, makeArrayRef(Args.data(), Args.size()));
  1784. return IsError;
  1785. }
  1786. bool Sema::isSelfExpr(Expr *RExpr) {
  1787. // 'self' is objc 'self' in an objc method only.
  1788. ObjCMethodDecl *Method =
  1789. dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
  1790. return isSelfExpr(RExpr, Method);
  1791. }
  1792. bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
  1793. if (!method) return false;
  1794. receiver = receiver->IgnoreParenLValueCasts();
  1795. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
  1796. if (DRE->getDecl() == method->getSelfDecl())
  1797. return true;
  1798. return false;
  1799. }
  1800. /// LookupMethodInType - Look up a method in an ObjCObjectType.
  1801. ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
  1802. bool isInstance) {
  1803. const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
  1804. if (ObjCInterfaceDecl *iface = objType->getInterface()) {
  1805. // Look it up in the main interface (and categories, etc.)
  1806. if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
  1807. return method;
  1808. // Okay, look for "private" methods declared in any
  1809. // @implementations we've seen.
  1810. if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
  1811. return method;
  1812. }
  1813. // Check qualifiers.
  1814. for (const auto *I : objType->quals())
  1815. if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
  1816. return method;
  1817. return nullptr;
  1818. }
  1819. /// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
  1820. /// list of a qualified objective pointer type.
  1821. ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
  1822. const ObjCObjectPointerType *OPT,
  1823. bool Instance)
  1824. {
  1825. ObjCMethodDecl *MD = nullptr;
  1826. for (const auto *PROTO : OPT->quals()) {
  1827. if ((MD = PROTO->lookupMethod(Sel, Instance))) {
  1828. return MD;
  1829. }
  1830. }
  1831. return nullptr;
  1832. }
  1833. /// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
  1834. /// objective C interface. This is a property reference expression.
  1835. ExprResult Sema::
  1836. HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
  1837. Expr *BaseExpr, SourceLocation OpLoc,
  1838. DeclarationName MemberName,
  1839. SourceLocation MemberLoc,
  1840. SourceLocation SuperLoc, QualType SuperType,
  1841. bool Super) {
  1842. const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
  1843. ObjCInterfaceDecl *IFace = IFaceT->getDecl();
  1844. if (!MemberName.isIdentifier()) {
  1845. Diag(MemberLoc, diag::err_invalid_property_name)
  1846. << MemberName << QualType(OPT, 0);
  1847. return ExprError();
  1848. }
  1849. IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
  1850. SourceRange BaseRange = Super? SourceRange(SuperLoc)
  1851. : BaseExpr->getSourceRange();
  1852. if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
  1853. diag::err_property_not_found_forward_class,
  1854. MemberName, BaseRange))
  1855. return ExprError();
  1856. // Search for a declared property first.
  1857. if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
  1858. // Check whether we can reference this property.
  1859. if (DiagnoseUseOfDecl(PD, MemberLoc))
  1860. return ExprError();
  1861. if (Super)
  1862. return new (Context)
  1863. ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
  1864. OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
  1865. else
  1866. return new (Context)
  1867. ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
  1868. OK_ObjCProperty, MemberLoc, BaseExpr);
  1869. }
  1870. // Check protocols on qualified interfaces.
  1871. for (const auto *I : OPT->quals())
  1872. if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) {
  1873. // Check whether we can reference this property.
  1874. if (DiagnoseUseOfDecl(PD, MemberLoc))
  1875. return ExprError();
  1876. if (Super)
  1877. return new (Context) ObjCPropertyRefExpr(
  1878. PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
  1879. SuperLoc, SuperType);
  1880. else
  1881. return new (Context)
  1882. ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
  1883. OK_ObjCProperty, MemberLoc, BaseExpr);
  1884. }
  1885. // If that failed, look for an "implicit" property by seeing if the nullary
  1886. // selector is implemented.
  1887. // FIXME: The logic for looking up nullary and unary selectors should be
  1888. // shared with the code in ActOnInstanceMessage.
  1889. Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
  1890. ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
  1891. // May be founf in property's qualified list.
  1892. if (!Getter)
  1893. Getter = LookupMethodInQualifiedType(Sel, OPT, true);
  1894. // If this reference is in an @implementation, check for 'private' methods.
  1895. if (!Getter)
  1896. Getter = IFace->lookupPrivateMethod(Sel);
  1897. if (Getter) {
  1898. // Check if we can reference this property.
  1899. if (DiagnoseUseOfDecl(Getter, MemberLoc))
  1900. return ExprError();
  1901. }
  1902. // If we found a getter then this may be a valid dot-reference, we
  1903. // will look for the matching setter, in case it is needed.
  1904. Selector SetterSel =
  1905. SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
  1906. PP.getSelectorTable(), Member);
  1907. ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
  1908. // May be founf in property's qualified list.
  1909. if (!Setter)
  1910. Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
  1911. if (!Setter) {
  1912. // If this reference is in an @implementation, also check for 'private'
  1913. // methods.
  1914. Setter = IFace->lookupPrivateMethod(SetterSel);
  1915. }
  1916. if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
  1917. return ExprError();
  1918. // Special warning if member name used in a property-dot for a setter accessor
  1919. // does not use a property with same name; e.g. obj.X = ... for a property with
  1920. // name 'x'.
  1921. if (Setter && Setter->isImplicit() && Setter->isPropertyAccessor()
  1922. && !IFace->FindPropertyDeclaration(Member)) {
  1923. if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl()) {
  1924. // Do not warn if user is using property-dot syntax to make call to
  1925. // user named setter.
  1926. if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter))
  1927. Diag(MemberLoc,
  1928. diag::warn_property_access_suggest)
  1929. << MemberName << QualType(OPT, 0) << PDecl->getName()
  1930. << FixItHint::CreateReplacement(MemberLoc, PDecl->getName());
  1931. }
  1932. }
  1933. if (Getter || Setter) {
  1934. if (Super)
  1935. return new (Context)
  1936. ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
  1937. OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
  1938. else
  1939. return new (Context)
  1940. ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
  1941. OK_ObjCProperty, MemberLoc, BaseExpr);
  1942. }
  1943. // Attempt to correct for typos in property names.
  1944. if (TypoCorrection Corrected =
  1945. CorrectTypo(DeclarationNameInfo(MemberName, MemberLoc),
  1946. LookupOrdinaryName, nullptr, nullptr,
  1947. llvm::make_unique<DeclFilterCCC<ObjCPropertyDecl>>(),
  1948. CTK_ErrorRecovery, IFace, false, OPT)) {
  1949. diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
  1950. << MemberName << QualType(OPT, 0));
  1951. DeclarationName TypoResult = Corrected.getCorrection();
  1952. return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
  1953. TypoResult, MemberLoc,
  1954. SuperLoc, SuperType, Super);
  1955. }
  1956. ObjCInterfaceDecl *ClassDeclared;
  1957. if (ObjCIvarDecl *Ivar =
  1958. IFace->lookupInstanceVariable(Member, ClassDeclared)) {
  1959. QualType T = Ivar->getType();
  1960. if (const ObjCObjectPointerType * OBJPT =
  1961. T->getAsObjCInterfacePointerType()) {
  1962. if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
  1963. diag::err_property_not_as_forward_class,
  1964. MemberName, BaseExpr))
  1965. return ExprError();
  1966. }
  1967. Diag(MemberLoc,
  1968. diag::err_ivar_access_using_property_syntax_suggest)
  1969. << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
  1970. << FixItHint::CreateReplacement(OpLoc, "->");
  1971. return ExprError();
  1972. }
  1973. Diag(MemberLoc, diag::err_property_not_found)
  1974. << MemberName << QualType(OPT, 0);
  1975. if (Setter)
  1976. Diag(Setter->getLocation(), diag::note_getter_unavailable)
  1977. << MemberName << BaseExpr->getSourceRange();
  1978. return ExprError();
  1979. }
  1980. ExprResult Sema::
  1981. ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
  1982. IdentifierInfo &propertyName,
  1983. SourceLocation receiverNameLoc,
  1984. SourceLocation propertyNameLoc) {
  1985. IdentifierInfo *receiverNamePtr = &receiverName;
  1986. ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
  1987. receiverNameLoc);
  1988. QualType SuperType;
  1989. if (!IFace) {
  1990. // If the "receiver" is 'super' in a method, handle it as an expression-like
  1991. // property reference.
  1992. if (receiverNamePtr->isStr("super")) {
  1993. if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
  1994. if (auto classDecl = CurMethod->getClassInterface()) {
  1995. SuperType = QualType(classDecl->getSuperClassType(), 0);
  1996. if (CurMethod->isInstanceMethod()) {
  1997. if (SuperType.isNull()) {
  1998. // The current class does not have a superclass.
  1999. Diag(receiverNameLoc, diag::error_root_class_cannot_use_super)
  2000. << CurMethod->getClassInterface()->getIdentifier();
  2001. return ExprError();
  2002. }
  2003. QualType T = Context.getObjCObjectPointerType(SuperType);
  2004. return HandleExprPropertyRefExpr(T->castAs<ObjCObjectPointerType>(),
  2005. /*BaseExpr*/nullptr,
  2006. SourceLocation()/*OpLoc*/,
  2007. &propertyName,
  2008. propertyNameLoc,
  2009. receiverNameLoc, T, true);
  2010. }
  2011. // Otherwise, if this is a class method, try dispatching to our
  2012. // superclass.
  2013. IFace = CurMethod->getClassInterface()->getSuperClass();
  2014. }
  2015. }
  2016. }
  2017. if (!IFace) {
  2018. Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
  2019. << tok::l_paren;
  2020. return ExprError();
  2021. }
  2022. }
  2023. // Search for a declared property first.
  2024. Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
  2025. ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
  2026. // If this reference is in an @implementation, check for 'private' methods.
  2027. if (!Getter)
  2028. Getter = IFace->lookupPrivateClassMethod(Sel);
  2029. if (Getter) {
  2030. // FIXME: refactor/share with ActOnMemberReference().
  2031. // Check if we can reference this property.
  2032. if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
  2033. return ExprError();
  2034. }
  2035. // Look for the matching setter, in case it is needed.
  2036. Selector SetterSel =
  2037. SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
  2038. PP.getSelectorTable(),
  2039. &propertyName);
  2040. ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
  2041. if (!Setter) {
  2042. // If this reference is in an @implementation, also check for 'private'
  2043. // methods.
  2044. Setter = IFace->lookupPrivateClassMethod(SetterSel);
  2045. }
  2046. // Look through local category implementations associated with the class.
  2047. if (!Setter)
  2048. Setter = IFace->getCategoryClassMethod(SetterSel);
  2049. if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
  2050. return ExprError();
  2051. if (Getter || Setter) {
  2052. if (!SuperType.isNull())
  2053. return new (Context)
  2054. ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
  2055. OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
  2056. SuperType);
  2057. return new (Context) ObjCPropertyRefExpr(
  2058. Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
  2059. propertyNameLoc, receiverNameLoc, IFace);
  2060. }
  2061. return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
  2062. << &propertyName << Context.getObjCInterfaceType(IFace));
  2063. }
  2064. namespace {
  2065. class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
  2066. public:
  2067. ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
  2068. // Determine whether "super" is acceptable in the current context.
  2069. if (Method && Method->getClassInterface())
  2070. WantObjCSuper = Method->getClassInterface()->getSuperClass();
  2071. }
  2072. bool ValidateCandidate(const TypoCorrection &candidate) override {
  2073. return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
  2074. candidate.isKeyword("super");
  2075. }
  2076. };
  2077. }
  2078. Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
  2079. IdentifierInfo *Name,
  2080. SourceLocation NameLoc,
  2081. bool IsSuper,
  2082. bool HasTrailingDot,
  2083. ParsedType &ReceiverType) {
  2084. ReceiverType = ParsedType();
  2085. // If the identifier is "super" and there is no trailing dot, we're
  2086. // messaging super. If the identifier is "super" and there is a
  2087. // trailing dot, it's an instance message.
  2088. if (IsSuper && S->isInObjcMethodScope())
  2089. return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
  2090. LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
  2091. LookupName(Result, S);
  2092. switch (Result.getResultKind()) {
  2093. case LookupResult::NotFound:
  2094. // Normal name lookup didn't find anything. If we're in an
  2095. // Objective-C method, look for ivars. If we find one, we're done!
  2096. // FIXME: This is a hack. Ivar lookup should be part of normal
  2097. // lookup.
  2098. if (ObjCMethodDecl *Method = getCurMethodDecl()) {
  2099. if (!Method->getClassInterface()) {
  2100. // Fall back: let the parser try to parse it as an instance message.
  2101. return ObjCInstanceMessage;
  2102. }
  2103. ObjCInterfaceDecl *ClassDeclared;
  2104. if (Method->getClassInterface()->lookupInstanceVariable(Name,
  2105. ClassDeclared))
  2106. return ObjCInstanceMessage;
  2107. }
  2108. // Break out; we'll perform typo correction below.
  2109. break;
  2110. case LookupResult::NotFoundInCurrentInstantiation:
  2111. case LookupResult::FoundOverloaded:
  2112. case LookupResult::FoundUnresolvedValue:
  2113. case LookupResult::Ambiguous:
  2114. Result.suppressDiagnostics();
  2115. return ObjCInstanceMessage;
  2116. case LookupResult::Found: {
  2117. // If the identifier is a class or not, and there is a trailing dot,
  2118. // it's an instance message.
  2119. if (HasTrailingDot)
  2120. return ObjCInstanceMessage;
  2121. // We found something. If it's a type, then we have a class
  2122. // message. Otherwise, it's an instance message.
  2123. NamedDecl *ND = Result.getFoundDecl();
  2124. QualType T;
  2125. if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
  2126. T = Context.getObjCInterfaceType(Class);
  2127. else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
  2128. T = Context.getTypeDeclType(Type);
  2129. DiagnoseUseOfDecl(Type, NameLoc);
  2130. }
  2131. else
  2132. return ObjCInstanceMessage;
  2133. // We have a class message, and T is the type we're
  2134. // messaging. Build source-location information for it.
  2135. TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
  2136. ReceiverType = CreateParsedType(T, TSInfo);
  2137. return ObjCClassMessage;
  2138. }
  2139. }
  2140. if (TypoCorrection Corrected = CorrectTypo(
  2141. Result.getLookupNameInfo(), Result.getLookupKind(), S, nullptr,
  2142. llvm::make_unique<ObjCInterfaceOrSuperCCC>(getCurMethodDecl()),
  2143. CTK_ErrorRecovery, nullptr, false, nullptr, false)) {
  2144. if (Corrected.isKeyword()) {
  2145. // If we've found the keyword "super" (the only keyword that would be
  2146. // returned by CorrectTypo), this is a send to super.
  2147. diagnoseTypo(Corrected,
  2148. PDiag(diag::err_unknown_receiver_suggest) << Name);
  2149. return ObjCSuperMessage;
  2150. } else if (ObjCInterfaceDecl *Class =
  2151. Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
  2152. // If we found a declaration, correct when it refers to an Objective-C
  2153. // class.
  2154. diagnoseTypo(Corrected,
  2155. PDiag(diag::err_unknown_receiver_suggest) << Name);
  2156. QualType T = Context.getObjCInterfaceType(Class);
  2157. TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
  2158. ReceiverType = CreateParsedType(T, TSInfo);
  2159. return ObjCClassMessage;
  2160. }
  2161. }
  2162. // Fall back: let the parser try to parse it as an instance message.
  2163. return ObjCInstanceMessage;
  2164. }
  2165. ExprResult Sema::ActOnSuperMessage(Scope *S,
  2166. SourceLocation SuperLoc,
  2167. Selector Sel,
  2168. SourceLocation LBracLoc,
  2169. ArrayRef<SourceLocation> SelectorLocs,
  2170. SourceLocation RBracLoc,
  2171. MultiExprArg Args) {
  2172. // Determine whether we are inside a method or not.
  2173. ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
  2174. if (!Method) {
  2175. Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
  2176. return ExprError();
  2177. }
  2178. ObjCInterfaceDecl *Class = Method->getClassInterface();
  2179. if (!Class) {
  2180. Diag(SuperLoc, diag::error_no_super_class_message)
  2181. << Method->getDeclName();
  2182. return ExprError();
  2183. }
  2184. QualType SuperTy(Class->getSuperClassType(), 0);
  2185. if (SuperTy.isNull()) {
  2186. // The current class does not have a superclass.
  2187. Diag(SuperLoc, diag::error_root_class_cannot_use_super)
  2188. << Class->getIdentifier();
  2189. return ExprError();
  2190. }
  2191. // We are in a method whose class has a superclass, so 'super'
  2192. // is acting as a keyword.
  2193. if (Method->getSelector() == Sel)
  2194. getCurFunction()->ObjCShouldCallSuper = false;
  2195. if (Method->isInstanceMethod()) {
  2196. // Since we are in an instance method, this is an instance
  2197. // message to the superclass instance.
  2198. SuperTy = Context.getObjCObjectPointerType(SuperTy);
  2199. return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
  2200. Sel, /*Method=*/nullptr,
  2201. LBracLoc, SelectorLocs, RBracLoc, Args);
  2202. }
  2203. // Since we are in a class method, this is a class message to
  2204. // the superclass.
  2205. return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
  2206. SuperTy,
  2207. SuperLoc, Sel, /*Method=*/nullptr,
  2208. LBracLoc, SelectorLocs, RBracLoc, Args);
  2209. }
  2210. ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
  2211. bool isSuperReceiver,
  2212. SourceLocation Loc,
  2213. Selector Sel,
  2214. ObjCMethodDecl *Method,
  2215. MultiExprArg Args) {
  2216. TypeSourceInfo *receiverTypeInfo = nullptr;
  2217. if (!ReceiverType.isNull())
  2218. receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
  2219. return BuildClassMessage(receiverTypeInfo, ReceiverType,
  2220. /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
  2221. Sel, Method, Loc, Loc, Loc, Args,
  2222. /*isImplicit=*/true);
  2223. }
  2224. static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
  2225. unsigned DiagID,
  2226. bool (*refactor)(const ObjCMessageExpr *,
  2227. const NSAPI &, edit::Commit &)) {
  2228. SourceLocation MsgLoc = Msg->getExprLoc();
  2229. if (S.Diags.isIgnored(DiagID, MsgLoc))
  2230. return;
  2231. SourceManager &SM = S.SourceMgr;
  2232. edit::Commit ECommit(SM, S.LangOpts);
  2233. if (refactor(Msg,*S.NSAPIObj, ECommit)) {
  2234. DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
  2235. << Msg->getSelector() << Msg->getSourceRange();
  2236. // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
  2237. if (!ECommit.isCommitable())
  2238. return;
  2239. for (edit::Commit::edit_iterator
  2240. I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
  2241. const edit::Commit::Edit &Edit = *I;
  2242. switch (Edit.Kind) {
  2243. case edit::Commit::Act_Insert:
  2244. Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
  2245. Edit.Text,
  2246. Edit.BeforePrev));
  2247. break;
  2248. case edit::Commit::Act_InsertFromRange:
  2249. Builder.AddFixItHint(
  2250. FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
  2251. Edit.getInsertFromRange(SM),
  2252. Edit.BeforePrev));
  2253. break;
  2254. case edit::Commit::Act_Remove:
  2255. Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
  2256. break;
  2257. }
  2258. }
  2259. }
  2260. }
  2261. static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
  2262. applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
  2263. edit::rewriteObjCRedundantCallWithLiteral);
  2264. }
  2265. /// \brief Diagnose use of %s directive in an NSString which is being passed
  2266. /// as formatting string to formatting method.
  2267. static void
  2268. DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S,
  2269. ObjCMethodDecl *Method,
  2270. Selector Sel,
  2271. Expr **Args, unsigned NumArgs) {
  2272. unsigned Idx = 0;
  2273. bool Format = false;
  2274. ObjCStringFormatFamily SFFamily = Sel.getStringFormatFamily();
  2275. if (SFFamily == ObjCStringFormatFamily::SFF_NSString) {
  2276. Idx = 0;
  2277. Format = true;
  2278. }
  2279. else if (Method) {
  2280. for (const auto *I : Method->specific_attrs<FormatAttr>()) {
  2281. if (S.GetFormatNSStringIdx(I, Idx)) {
  2282. Format = true;
  2283. break;
  2284. }
  2285. }
  2286. }
  2287. if (!Format || NumArgs <= Idx)
  2288. return;
  2289. Expr *FormatExpr = Args[Idx];
  2290. if (ObjCStringLiteral *OSL =
  2291. dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) {
  2292. StringLiteral *FormatString = OSL->getString();
  2293. if (S.FormatStringHasSArg(FormatString)) {
  2294. S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
  2295. << "%s" << 0 << 0;
  2296. if (Method)
  2297. S.Diag(Method->getLocation(), diag::note_method_declared_at)
  2298. << Method->getDeclName();
  2299. }
  2300. }
  2301. }
  2302. /// \brief Build an Objective-C class message expression.
  2303. ///
  2304. /// This routine takes care of both normal class messages and
  2305. /// class messages to the superclass.
  2306. ///
  2307. /// \param ReceiverTypeInfo Type source information that describes the
  2308. /// receiver of this message. This may be NULL, in which case we are
  2309. /// sending to the superclass and \p SuperLoc must be a valid source
  2310. /// location.
  2311. /// \param ReceiverType The type of the object receiving the
  2312. /// message. When \p ReceiverTypeInfo is non-NULL, this is the same
  2313. /// type as that refers to. For a superclass send, this is the type of
  2314. /// the superclass.
  2315. ///
  2316. /// \param SuperLoc The location of the "super" keyword in a
  2317. /// superclass message.
  2318. ///
  2319. /// \param Sel The selector to which the message is being sent.
  2320. ///
  2321. /// \param Method The method that this class message is invoking, if
  2322. /// already known.
  2323. ///
  2324. /// \param LBracLoc The location of the opening square bracket ']'.
  2325. ///
  2326. /// \param RBracLoc The location of the closing square bracket ']'.
  2327. ///
  2328. /// \param ArgsIn The message arguments.
  2329. ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
  2330. QualType ReceiverType,
  2331. SourceLocation SuperLoc,
  2332. Selector Sel,
  2333. ObjCMethodDecl *Method,
  2334. SourceLocation LBracLoc,
  2335. ArrayRef<SourceLocation> SelectorLocs,
  2336. SourceLocation RBracLoc,
  2337. MultiExprArg ArgsIn,
  2338. bool isImplicit) {
  2339. SourceLocation Loc = SuperLoc.isValid()? SuperLoc
  2340. : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
  2341. if (LBracLoc.isInvalid()) {
  2342. Diag(Loc, diag::err_missing_open_square_message_send)
  2343. << FixItHint::CreateInsertion(Loc, "[");
  2344. LBracLoc = Loc;
  2345. }
  2346. SourceLocation SelLoc;
  2347. if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
  2348. SelLoc = SelectorLocs.front();
  2349. else
  2350. SelLoc = Loc;
  2351. if (ReceiverType->isDependentType()) {
  2352. // If the receiver type is dependent, we can't type-check anything
  2353. // at this point. Build a dependent expression.
  2354. unsigned NumArgs = ArgsIn.size();
  2355. Expr **Args = ArgsIn.data();
  2356. assert(SuperLoc.isInvalid() && "Message to super with dependent type");
  2357. return ObjCMessageExpr::Create(
  2358. Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel,
  2359. SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc,
  2360. isImplicit);
  2361. }
  2362. // Find the class to which we are sending this message.
  2363. ObjCInterfaceDecl *Class = nullptr;
  2364. const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
  2365. if (!ClassType || !(Class = ClassType->getInterface())) {
  2366. Diag(Loc, diag::err_invalid_receiver_class_message)
  2367. << ReceiverType;
  2368. return ExprError();
  2369. }
  2370. assert(Class && "We don't know which class we're messaging?");
  2371. // objc++ diagnoses during typename annotation.
  2372. if (!getLangOpts().CPlusPlus)
  2373. (void)DiagnoseUseOfDecl(Class, SelLoc);
  2374. // Find the method we are messaging.
  2375. if (!Method) {
  2376. SourceRange TypeRange
  2377. = SuperLoc.isValid()? SourceRange(SuperLoc)
  2378. : ReceiverTypeInfo->getTypeLoc().getSourceRange();
  2379. if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
  2380. (getLangOpts().ObjCAutoRefCount
  2381. ? diag::err_arc_receiver_forward_class
  2382. : diag::warn_receiver_forward_class),
  2383. TypeRange)) {
  2384. // A forward class used in messaging is treated as a 'Class'
  2385. Method = LookupFactoryMethodInGlobalPool(Sel,
  2386. SourceRange(LBracLoc, RBracLoc));
  2387. if (Method && !getLangOpts().ObjCAutoRefCount)
  2388. Diag(Method->getLocation(), diag::note_method_sent_forward_class)
  2389. << Method->getDeclName();
  2390. }
  2391. if (!Method)
  2392. Method = Class->lookupClassMethod(Sel);
  2393. // If we have an implementation in scope, check "private" methods.
  2394. if (!Method)
  2395. Method = Class->lookupPrivateClassMethod(Sel);
  2396. if (Method && DiagnoseUseOfDecl(Method, SelLoc))
  2397. return ExprError();
  2398. }
  2399. // Check the argument types and determine the result type.
  2400. QualType ReturnType;
  2401. ExprValueKind VK = VK_RValue;
  2402. unsigned NumArgs = ArgsIn.size();
  2403. Expr **Args = ArgsIn.data();
  2404. if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
  2405. Sel, SelectorLocs,
  2406. Method, true,
  2407. SuperLoc.isValid(), LBracLoc, RBracLoc,
  2408. SourceRange(),
  2409. ReturnType, VK))
  2410. return ExprError();
  2411. if (Method && !Method->getReturnType()->isVoidType() &&
  2412. RequireCompleteType(LBracLoc, Method->getReturnType(),
  2413. diag::err_illegal_message_expr_incomplete_type))
  2414. return ExprError();
  2415. // Warn about explicit call of +initialize on its own class. But not on 'super'.
  2416. if (Method && Method->getMethodFamily() == OMF_initialize) {
  2417. if (!SuperLoc.isValid()) {
  2418. const ObjCInterfaceDecl *ID =
  2419. dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext());
  2420. if (ID == Class) {
  2421. Diag(Loc, diag::warn_direct_initialize_call);
  2422. Diag(Method->getLocation(), diag::note_method_declared_at)
  2423. << Method->getDeclName();
  2424. }
  2425. }
  2426. else if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
  2427. // [super initialize] is allowed only within an +initialize implementation
  2428. if (CurMeth->getMethodFamily() != OMF_initialize) {
  2429. Diag(Loc, diag::warn_direct_super_initialize_call);
  2430. Diag(Method->getLocation(), diag::note_method_declared_at)
  2431. << Method->getDeclName();
  2432. Diag(CurMeth->getLocation(), diag::note_method_declared_at)
  2433. << CurMeth->getDeclName();
  2434. }
  2435. }
  2436. }
  2437. DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
  2438. // Construct the appropriate ObjCMessageExpr.
  2439. ObjCMessageExpr *Result;
  2440. if (SuperLoc.isValid())
  2441. Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
  2442. SuperLoc, /*IsInstanceSuper=*/false,
  2443. ReceiverType, Sel, SelectorLocs,
  2444. Method, makeArrayRef(Args, NumArgs),
  2445. RBracLoc, isImplicit);
  2446. else {
  2447. Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
  2448. ReceiverTypeInfo, Sel, SelectorLocs,
  2449. Method, makeArrayRef(Args, NumArgs),
  2450. RBracLoc, isImplicit);
  2451. if (!isImplicit)
  2452. checkCocoaAPI(*this, Result);
  2453. }
  2454. return MaybeBindToTemporary(Result);
  2455. }
  2456. // ActOnClassMessage - used for both unary and keyword messages.
  2457. // ArgExprs is optional - if it is present, the number of expressions
  2458. // is obtained from Sel.getNumArgs().
  2459. ExprResult Sema::ActOnClassMessage(Scope *S,
  2460. ParsedType Receiver,
  2461. Selector Sel,
  2462. SourceLocation LBracLoc,
  2463. ArrayRef<SourceLocation> SelectorLocs,
  2464. SourceLocation RBracLoc,
  2465. MultiExprArg Args) {
  2466. TypeSourceInfo *ReceiverTypeInfo;
  2467. QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
  2468. if (ReceiverType.isNull())
  2469. return ExprError();
  2470. if (!ReceiverTypeInfo)
  2471. ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
  2472. return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
  2473. /*SuperLoc=*/SourceLocation(), Sel,
  2474. /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
  2475. Args);
  2476. }
  2477. ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
  2478. QualType ReceiverType,
  2479. SourceLocation Loc,
  2480. Selector Sel,
  2481. ObjCMethodDecl *Method,
  2482. MultiExprArg Args) {
  2483. return BuildInstanceMessage(Receiver, ReceiverType,
  2484. /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
  2485. Sel, Method, Loc, Loc, Loc, Args,
  2486. /*isImplicit=*/true);
  2487. }
  2488. /// \brief Build an Objective-C instance message expression.
  2489. ///
  2490. /// This routine takes care of both normal instance messages and
  2491. /// instance messages to the superclass instance.
  2492. ///
  2493. /// \param Receiver The expression that computes the object that will
  2494. /// receive this message. This may be empty, in which case we are
  2495. /// sending to the superclass instance and \p SuperLoc must be a valid
  2496. /// source location.
  2497. ///
  2498. /// \param ReceiverType The (static) type of the object receiving the
  2499. /// message. When a \p Receiver expression is provided, this is the
  2500. /// same type as that expression. For a superclass instance send, this
  2501. /// is a pointer to the type of the superclass.
  2502. ///
  2503. /// \param SuperLoc The location of the "super" keyword in a
  2504. /// superclass instance message.
  2505. ///
  2506. /// \param Sel The selector to which the message is being sent.
  2507. ///
  2508. /// \param Method The method that this instance message is invoking, if
  2509. /// already known.
  2510. ///
  2511. /// \param LBracLoc The location of the opening square bracket ']'.
  2512. ///
  2513. /// \param RBracLoc The location of the closing square bracket ']'.
  2514. ///
  2515. /// \param ArgsIn The message arguments.
  2516. ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
  2517. QualType ReceiverType,
  2518. SourceLocation SuperLoc,
  2519. Selector Sel,
  2520. ObjCMethodDecl *Method,
  2521. SourceLocation LBracLoc,
  2522. ArrayRef<SourceLocation> SelectorLocs,
  2523. SourceLocation RBracLoc,
  2524. MultiExprArg ArgsIn,
  2525. bool isImplicit) {
  2526. // The location of the receiver.
  2527. SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
  2528. SourceRange RecRange =
  2529. SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
  2530. SourceLocation SelLoc;
  2531. if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
  2532. SelLoc = SelectorLocs.front();
  2533. else
  2534. SelLoc = Loc;
  2535. if (LBracLoc.isInvalid()) {
  2536. Diag(Loc, diag::err_missing_open_square_message_send)
  2537. << FixItHint::CreateInsertion(Loc, "[");
  2538. LBracLoc = Loc;
  2539. }
  2540. // If we have a receiver expression, perform appropriate promotions
  2541. // and determine receiver type.
  2542. if (Receiver) {
  2543. if (Receiver->hasPlaceholderType()) {
  2544. ExprResult Result;
  2545. if (Receiver->getType() == Context.UnknownAnyTy)
  2546. Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
  2547. else
  2548. Result = CheckPlaceholderExpr(Receiver);
  2549. if (Result.isInvalid()) return ExprError();
  2550. Receiver = Result.get();
  2551. }
  2552. if (Receiver->isTypeDependent()) {
  2553. // If the receiver is type-dependent, we can't type-check anything
  2554. // at this point. Build a dependent expression.
  2555. unsigned NumArgs = ArgsIn.size();
  2556. Expr **Args = ArgsIn.data();
  2557. assert(SuperLoc.isInvalid() && "Message to super with dependent type");
  2558. return ObjCMessageExpr::Create(
  2559. Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel,
  2560. SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs),
  2561. RBracLoc, isImplicit);
  2562. }
  2563. // If necessary, apply function/array conversion to the receiver.
  2564. // C99 6.7.5.3p[7,8].
  2565. ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
  2566. if (Result.isInvalid())
  2567. return ExprError();
  2568. Receiver = Result.get();
  2569. ReceiverType = Receiver->getType();
  2570. // If the receiver is an ObjC pointer, a block pointer, or an
  2571. // __attribute__((NSObject)) pointer, we don't need to do any
  2572. // special conversion in order to look up a receiver.
  2573. if (ReceiverType->isObjCRetainableType()) {
  2574. // do nothing
  2575. } else if (!getLangOpts().ObjCAutoRefCount &&
  2576. !Context.getObjCIdType().isNull() &&
  2577. (ReceiverType->isPointerType() ||
  2578. ReceiverType->isIntegerType())) {
  2579. // Implicitly convert integers and pointers to 'id' but emit a warning.
  2580. // But not in ARC.
  2581. Diag(Loc, diag::warn_bad_receiver_type)
  2582. << ReceiverType
  2583. << Receiver->getSourceRange();
  2584. if (ReceiverType->isPointerType()) {
  2585. Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
  2586. CK_CPointerToObjCPointerCast).get();
  2587. } else {
  2588. // TODO: specialized warning on null receivers?
  2589. bool IsNull = Receiver->isNullPointerConstant(Context,
  2590. Expr::NPC_ValueDependentIsNull);
  2591. CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
  2592. Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
  2593. Kind).get();
  2594. }
  2595. ReceiverType = Receiver->getType();
  2596. } else if (getLangOpts().CPlusPlus) {
  2597. // The receiver must be a complete type.
  2598. if (RequireCompleteType(Loc, Receiver->getType(),
  2599. diag::err_incomplete_receiver_type))
  2600. return ExprError();
  2601. ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
  2602. if (result.isUsable()) {
  2603. Receiver = result.get();
  2604. ReceiverType = Receiver->getType();
  2605. }
  2606. }
  2607. }
  2608. // There's a somewhat weird interaction here where we assume that we
  2609. // won't actually have a method unless we also don't need to do some
  2610. // of the more detailed type-checking on the receiver.
  2611. if (!Method) {
  2612. // Handle messages to id and __kindof types (where we use the
  2613. // global method pool).
  2614. // FIXME: The type bound is currently ignored by lookup in the
  2615. // global pool.
  2616. const ObjCObjectType *typeBound = nullptr;
  2617. bool receiverIsIdLike = ReceiverType->isObjCIdOrObjectKindOfType(Context,
  2618. typeBound);
  2619. if (receiverIsIdLike || ReceiverType->isBlockPointerType() ||
  2620. (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
  2621. Method = LookupInstanceMethodInGlobalPool(Sel,
  2622. SourceRange(LBracLoc, RBracLoc),
  2623. receiverIsIdLike);
  2624. if (!Method)
  2625. Method = LookupFactoryMethodInGlobalPool(Sel,
  2626. SourceRange(LBracLoc,RBracLoc),
  2627. receiverIsIdLike);
  2628. if (Method) {
  2629. if (ObjCMethodDecl *BestMethod =
  2630. SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod()))
  2631. Method = BestMethod;
  2632. if (!AreMultipleMethodsInGlobalPool(Sel, Method,
  2633. SourceRange(LBracLoc, RBracLoc),
  2634. receiverIsIdLike)) {
  2635. DiagnoseUseOfDecl(Method, SelLoc);
  2636. }
  2637. }
  2638. } else if (ReceiverType->isObjCClassOrClassKindOfType() ||
  2639. ReceiverType->isObjCQualifiedClassType()) {
  2640. // Handle messages to Class.
  2641. // We allow sending a message to a qualified Class ("Class<foo>"), which
  2642. // is ok as long as one of the protocols implements the selector (if not,
  2643. // warn).
  2644. if (!ReceiverType->isObjCClassOrClassKindOfType()) {
  2645. const ObjCObjectPointerType *QClassTy
  2646. = ReceiverType->getAsObjCQualifiedClassType();
  2647. // Search protocols for class methods.
  2648. Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
  2649. if (!Method) {
  2650. Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
  2651. // warn if instance method found for a Class message.
  2652. if (Method) {
  2653. Diag(SelLoc, diag::warn_instance_method_on_class_found)
  2654. << Method->getSelector() << Sel;
  2655. Diag(Method->getLocation(), diag::note_method_declared_at)
  2656. << Method->getDeclName();
  2657. }
  2658. }
  2659. } else {
  2660. if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
  2661. if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
  2662. // First check the public methods in the class interface.
  2663. Method = ClassDecl->lookupClassMethod(Sel);
  2664. if (!Method)
  2665. Method = ClassDecl->lookupPrivateClassMethod(Sel);
  2666. }
  2667. if (Method && DiagnoseUseOfDecl(Method, SelLoc))
  2668. return ExprError();
  2669. }
  2670. if (!Method) {
  2671. // If not messaging 'self', look for any factory method named 'Sel'.
  2672. if (!Receiver || !isSelfExpr(Receiver)) {
  2673. Method = LookupFactoryMethodInGlobalPool(Sel,
  2674. SourceRange(LBracLoc, RBracLoc));
  2675. if (!Method) {
  2676. // If no class (factory) method was found, check if an _instance_
  2677. // method of the same name exists in the root class only.
  2678. Method = LookupInstanceMethodInGlobalPool(Sel,
  2679. SourceRange(LBracLoc, RBracLoc));
  2680. if (Method)
  2681. if (const ObjCInterfaceDecl *ID =
  2682. dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
  2683. if (ID->getSuperClass())
  2684. Diag(SelLoc, diag::warn_root_inst_method_not_found)
  2685. << Sel << SourceRange(LBracLoc, RBracLoc);
  2686. }
  2687. }
  2688. if (Method)
  2689. if (ObjCMethodDecl *BestMethod =
  2690. SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod()))
  2691. Method = BestMethod;
  2692. }
  2693. }
  2694. }
  2695. } else {
  2696. ObjCInterfaceDecl *ClassDecl = nullptr;
  2697. // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
  2698. // long as one of the protocols implements the selector (if not, warn).
  2699. // And as long as message is not deprecated/unavailable (warn if it is).
  2700. if (const ObjCObjectPointerType *QIdTy
  2701. = ReceiverType->getAsObjCQualifiedIdType()) {
  2702. // Search protocols for instance methods.
  2703. Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
  2704. if (!Method)
  2705. Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
  2706. if (Method && DiagnoseUseOfDecl(Method, SelLoc))
  2707. return ExprError();
  2708. } else if (const ObjCObjectPointerType *OCIType
  2709. = ReceiverType->getAsObjCInterfacePointerType()) {
  2710. // We allow sending a message to a pointer to an interface (an object).
  2711. ClassDecl = OCIType->getInterfaceDecl();
  2712. // Try to complete the type. Under ARC, this is a hard error from which
  2713. // we don't try to recover.
  2714. const ObjCInterfaceDecl *forwardClass = nullptr;
  2715. if (RequireCompleteType(Loc, OCIType->getPointeeType(),
  2716. getLangOpts().ObjCAutoRefCount
  2717. ? diag::err_arc_receiver_forward_instance
  2718. : diag::warn_receiver_forward_instance,
  2719. Receiver? Receiver->getSourceRange()
  2720. : SourceRange(SuperLoc))) {
  2721. if (getLangOpts().ObjCAutoRefCount)
  2722. return ExprError();
  2723. forwardClass = OCIType->getInterfaceDecl();
  2724. Diag(Receiver ? Receiver->getLocStart()
  2725. : SuperLoc, diag::note_receiver_is_id);
  2726. Method = nullptr;
  2727. } else {
  2728. Method = ClassDecl->lookupInstanceMethod(Sel);
  2729. }
  2730. if (!Method)
  2731. // Search protocol qualifiers.
  2732. Method = LookupMethodInQualifiedType(Sel, OCIType, true);
  2733. if (!Method) {
  2734. // If we have implementations in scope, check "private" methods.
  2735. Method = ClassDecl->lookupPrivateMethod(Sel);
  2736. if (!Method && getLangOpts().ObjCAutoRefCount) {
  2737. Diag(SelLoc, diag::err_arc_may_not_respond)
  2738. << OCIType->getPointeeType() << Sel << RecRange
  2739. << SourceRange(SelectorLocs.front(), SelectorLocs.back());
  2740. return ExprError();
  2741. }
  2742. if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
  2743. // If we still haven't found a method, look in the global pool. This
  2744. // behavior isn't very desirable, however we need it for GCC
  2745. // compatibility. FIXME: should we deviate??
  2746. if (OCIType->qual_empty()) {
  2747. Method = LookupInstanceMethodInGlobalPool(Sel,
  2748. SourceRange(LBracLoc, RBracLoc));
  2749. if (Method) {
  2750. if (auto BestMethod =
  2751. SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod()))
  2752. Method = BestMethod;
  2753. AreMultipleMethodsInGlobalPool(Sel, Method,
  2754. SourceRange(LBracLoc, RBracLoc),
  2755. true);
  2756. }
  2757. if (Method && !forwardClass)
  2758. Diag(SelLoc, diag::warn_maynot_respond)
  2759. << OCIType->getInterfaceDecl()->getIdentifier()
  2760. << Sel << RecRange;
  2761. }
  2762. }
  2763. }
  2764. if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass))
  2765. return ExprError();
  2766. } else {
  2767. // Reject other random receiver types (e.g. structs).
  2768. Diag(Loc, diag::err_bad_receiver_type)
  2769. << ReceiverType << Receiver->getSourceRange();
  2770. return ExprError();
  2771. }
  2772. }
  2773. }
  2774. FunctionScopeInfo *DIFunctionScopeInfo =
  2775. (Method && Method->getMethodFamily() == OMF_init)
  2776. ? getEnclosingFunction() : nullptr;
  2777. if (DIFunctionScopeInfo &&
  2778. DIFunctionScopeInfo->ObjCIsDesignatedInit &&
  2779. (SuperLoc.isValid() || isSelfExpr(Receiver))) {
  2780. bool isDesignatedInitChain = false;
  2781. if (SuperLoc.isValid()) {
  2782. if (const ObjCObjectPointerType *
  2783. OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
  2784. if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
  2785. // Either we know this is a designated initializer or we
  2786. // conservatively assume it because we don't know for sure.
  2787. if (!ID->declaresOrInheritsDesignatedInitializers() ||
  2788. ID->isDesignatedInitializer(Sel)) {
  2789. isDesignatedInitChain = true;
  2790. DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
  2791. }
  2792. }
  2793. }
  2794. }
  2795. if (!isDesignatedInitChain) {
  2796. const ObjCMethodDecl *InitMethod = nullptr;
  2797. bool isDesignated =
  2798. getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
  2799. assert(isDesignated && InitMethod);
  2800. (void)isDesignated;
  2801. Diag(SelLoc, SuperLoc.isValid() ?
  2802. diag::warn_objc_designated_init_non_designated_init_call :
  2803. diag::warn_objc_designated_init_non_super_designated_init_call);
  2804. Diag(InitMethod->getLocation(),
  2805. diag::note_objc_designated_init_marked_here);
  2806. }
  2807. }
  2808. if (DIFunctionScopeInfo &&
  2809. DIFunctionScopeInfo->ObjCIsSecondaryInit &&
  2810. (SuperLoc.isValid() || isSelfExpr(Receiver))) {
  2811. if (SuperLoc.isValid()) {
  2812. Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
  2813. } else {
  2814. DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
  2815. }
  2816. }
  2817. // Check the message arguments.
  2818. unsigned NumArgs = ArgsIn.size();
  2819. Expr **Args = ArgsIn.data();
  2820. QualType ReturnType;
  2821. ExprValueKind VK = VK_RValue;
  2822. bool ClassMessage = (ReceiverType->isObjCClassType() ||
  2823. ReceiverType->isObjCQualifiedClassType());
  2824. if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
  2825. Sel, SelectorLocs, Method,
  2826. ClassMessage, SuperLoc.isValid(),
  2827. LBracLoc, RBracLoc, RecRange, ReturnType, VK))
  2828. return ExprError();
  2829. if (Method && !Method->getReturnType()->isVoidType() &&
  2830. RequireCompleteType(LBracLoc, Method->getReturnType(),
  2831. diag::err_illegal_message_expr_incomplete_type))
  2832. return ExprError();
  2833. // In ARC, forbid the user from sending messages to
  2834. // retain/release/autorelease/dealloc/retainCount explicitly.
  2835. if (getLangOpts().ObjCAutoRefCount) {
  2836. ObjCMethodFamily family =
  2837. (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
  2838. switch (family) {
  2839. case OMF_init:
  2840. if (Method)
  2841. checkInitMethod(Method, ReceiverType);
  2842. case OMF_None:
  2843. case OMF_alloc:
  2844. case OMF_copy:
  2845. case OMF_finalize:
  2846. case OMF_mutableCopy:
  2847. case OMF_new:
  2848. case OMF_self:
  2849. case OMF_initialize:
  2850. break;
  2851. case OMF_dealloc:
  2852. case OMF_retain:
  2853. case OMF_release:
  2854. case OMF_autorelease:
  2855. case OMF_retainCount:
  2856. Diag(SelLoc, diag::err_arc_illegal_explicit_message)
  2857. << Sel << RecRange;
  2858. break;
  2859. case OMF_performSelector:
  2860. if (Method && NumArgs >= 1) {
  2861. if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
  2862. Selector ArgSel = SelExp->getSelector();
  2863. ObjCMethodDecl *SelMethod =
  2864. LookupInstanceMethodInGlobalPool(ArgSel,
  2865. SelExp->getSourceRange());
  2866. if (!SelMethod)
  2867. SelMethod =
  2868. LookupFactoryMethodInGlobalPool(ArgSel,
  2869. SelExp->getSourceRange());
  2870. if (SelMethod) {
  2871. ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
  2872. switch (SelFamily) {
  2873. case OMF_alloc:
  2874. case OMF_copy:
  2875. case OMF_mutableCopy:
  2876. case OMF_new:
  2877. case OMF_self:
  2878. case OMF_init:
  2879. // Issue error, unless ns_returns_not_retained.
  2880. if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
  2881. // selector names a +1 method
  2882. Diag(SelLoc,
  2883. diag::err_arc_perform_selector_retains);
  2884. Diag(SelMethod->getLocation(), diag::note_method_declared_at)
  2885. << SelMethod->getDeclName();
  2886. }
  2887. break;
  2888. default:
  2889. // +0 call. OK. unless ns_returns_retained.
  2890. if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
  2891. // selector names a +1 method
  2892. Diag(SelLoc,
  2893. diag::err_arc_perform_selector_retains);
  2894. Diag(SelMethod->getLocation(), diag::note_method_declared_at)
  2895. << SelMethod->getDeclName();
  2896. }
  2897. break;
  2898. }
  2899. }
  2900. } else {
  2901. // error (may leak).
  2902. Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
  2903. Diag(Args[0]->getExprLoc(), diag::note_used_here);
  2904. }
  2905. }
  2906. break;
  2907. }
  2908. }
  2909. DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
  2910. // Construct the appropriate ObjCMessageExpr instance.
  2911. ObjCMessageExpr *Result;
  2912. if (SuperLoc.isValid())
  2913. Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
  2914. SuperLoc, /*IsInstanceSuper=*/true,
  2915. ReceiverType, Sel, SelectorLocs, Method,
  2916. makeArrayRef(Args, NumArgs), RBracLoc,
  2917. isImplicit);
  2918. else {
  2919. Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
  2920. Receiver, Sel, SelectorLocs, Method,
  2921. makeArrayRef(Args, NumArgs), RBracLoc,
  2922. isImplicit);
  2923. if (!isImplicit)
  2924. checkCocoaAPI(*this, Result);
  2925. }
  2926. if (getLangOpts().ObjCAutoRefCount) {
  2927. // In ARC, annotate delegate init calls.
  2928. if (Result->getMethodFamily() == OMF_init &&
  2929. (SuperLoc.isValid() || isSelfExpr(Receiver))) {
  2930. // Only consider init calls *directly* in init implementations,
  2931. // not within blocks.
  2932. ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
  2933. if (method && method->getMethodFamily() == OMF_init) {
  2934. // The implicit assignment to self means we also don't want to
  2935. // consume the result.
  2936. Result->setDelegateInitCall(true);
  2937. return Result;
  2938. }
  2939. }
  2940. // In ARC, check for message sends which are likely to introduce
  2941. // retain cycles.
  2942. checkRetainCycles(Result);
  2943. if (!isImplicit && Method) {
  2944. if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
  2945. bool IsWeak =
  2946. Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
  2947. if (!IsWeak && Sel.isUnarySelector())
  2948. IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
  2949. if (IsWeak &&
  2950. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
  2951. getCurFunction()->recordUseOfWeak(Result, Prop);
  2952. }
  2953. }
  2954. }
  2955. CheckObjCCircularContainer(Result);
  2956. return MaybeBindToTemporary(Result);
  2957. }
  2958. static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
  2959. if (ObjCSelectorExpr *OSE =
  2960. dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
  2961. Selector Sel = OSE->getSelector();
  2962. SourceLocation Loc = OSE->getAtLoc();
  2963. auto Pos = S.ReferencedSelectors.find(Sel);
  2964. if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
  2965. S.ReferencedSelectors.erase(Pos);
  2966. }
  2967. }
  2968. // ActOnInstanceMessage - used for both unary and keyword messages.
  2969. // ArgExprs is optional - if it is present, the number of expressions
  2970. // is obtained from Sel.getNumArgs().
  2971. ExprResult Sema::ActOnInstanceMessage(Scope *S,
  2972. Expr *Receiver,
  2973. Selector Sel,
  2974. SourceLocation LBracLoc,
  2975. ArrayRef<SourceLocation> SelectorLocs,
  2976. SourceLocation RBracLoc,
  2977. MultiExprArg Args) {
  2978. if (!Receiver)
  2979. return ExprError();
  2980. // A ParenListExpr can show up while doing error recovery with invalid code.
  2981. if (isa<ParenListExpr>(Receiver)) {
  2982. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
  2983. if (Result.isInvalid()) return ExprError();
  2984. Receiver = Result.get();
  2985. }
  2986. if (RespondsToSelectorSel.isNull()) {
  2987. IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
  2988. RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
  2989. }
  2990. if (Sel == RespondsToSelectorSel)
  2991. RemoveSelectorFromWarningCache(*this, Args[0]);
  2992. return BuildInstanceMessage(Receiver, Receiver->getType(),
  2993. /*SuperLoc=*/SourceLocation(), Sel,
  2994. /*Method=*/nullptr, LBracLoc, SelectorLocs,
  2995. RBracLoc, Args);
  2996. }
  2997. enum ARCConversionTypeClass {
  2998. /// int, void, struct A
  2999. ACTC_none,
  3000. /// id, void (^)()
  3001. ACTC_retainable,
  3002. /// id*, id***, void (^*)(),
  3003. ACTC_indirectRetainable,
  3004. /// void* might be a normal C type, or it might a CF type.
  3005. ACTC_voidPtr,
  3006. /// struct A*
  3007. ACTC_coreFoundation
  3008. };
  3009. static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
  3010. return (ACTC == ACTC_retainable ||
  3011. ACTC == ACTC_coreFoundation ||
  3012. ACTC == ACTC_voidPtr);
  3013. }
  3014. static bool isAnyCLike(ARCConversionTypeClass ACTC) {
  3015. return ACTC == ACTC_none ||
  3016. ACTC == ACTC_voidPtr ||
  3017. ACTC == ACTC_coreFoundation;
  3018. }
  3019. static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
  3020. bool isIndirect = false;
  3021. // Ignore an outermost reference type.
  3022. if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
  3023. type = ref->getPointeeType();
  3024. isIndirect = true;
  3025. }
  3026. // Drill through pointers and arrays recursively.
  3027. while (true) {
  3028. if (const PointerType *ptr = type->getAs<PointerType>()) {
  3029. type = ptr->getPointeeType();
  3030. // The first level of pointer may be the innermost pointer on a CF type.
  3031. if (!isIndirect) {
  3032. if (type->isVoidType()) return ACTC_voidPtr;
  3033. if (type->isRecordType()) return ACTC_coreFoundation;
  3034. }
  3035. } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
  3036. type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
  3037. } else {
  3038. break;
  3039. }
  3040. isIndirect = true;
  3041. }
  3042. if (isIndirect) {
  3043. if (type->isObjCARCBridgableType())
  3044. return ACTC_indirectRetainable;
  3045. return ACTC_none;
  3046. }
  3047. if (type->isObjCARCBridgableType())
  3048. return ACTC_retainable;
  3049. return ACTC_none;
  3050. }
  3051. namespace {
  3052. /// A result from the cast checker.
  3053. enum ACCResult {
  3054. /// Cannot be casted.
  3055. ACC_invalid,
  3056. /// Can be safely retained or not retained.
  3057. ACC_bottom,
  3058. /// Can be casted at +0.
  3059. ACC_plusZero,
  3060. /// Can be casted at +1.
  3061. ACC_plusOne
  3062. };
  3063. ACCResult merge(ACCResult left, ACCResult right) {
  3064. if (left == right) return left;
  3065. if (left == ACC_bottom) return right;
  3066. if (right == ACC_bottom) return left;
  3067. return ACC_invalid;
  3068. }
  3069. /// A checker which white-lists certain expressions whose conversion
  3070. /// to or from retainable type would otherwise be forbidden in ARC.
  3071. class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
  3072. typedef StmtVisitor<ARCCastChecker, ACCResult> super;
  3073. ASTContext &Context;
  3074. ARCConversionTypeClass SourceClass;
  3075. ARCConversionTypeClass TargetClass;
  3076. bool Diagnose;
  3077. static bool isCFType(QualType type) {
  3078. // Someday this can use ns_bridged. For now, it has to do this.
  3079. return type->isCARCBridgableType();
  3080. }
  3081. public:
  3082. ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
  3083. ARCConversionTypeClass target, bool diagnose)
  3084. : Context(Context), SourceClass(source), TargetClass(target),
  3085. Diagnose(diagnose) {}
  3086. using super::Visit;
  3087. ACCResult Visit(Expr *e) {
  3088. return super::Visit(e->IgnoreParens());
  3089. }
  3090. ACCResult VisitStmt(Stmt *s) {
  3091. return ACC_invalid;
  3092. }
  3093. /// Null pointer constants can be casted however you please.
  3094. ACCResult VisitExpr(Expr *e) {
  3095. if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
  3096. return ACC_bottom;
  3097. return ACC_invalid;
  3098. }
  3099. /// Objective-C string literals can be safely casted.
  3100. ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
  3101. // If we're casting to any retainable type, go ahead. Global
  3102. // strings are immune to retains, so this is bottom.
  3103. if (isAnyRetainable(TargetClass)) return ACC_bottom;
  3104. return ACC_invalid;
  3105. }
  3106. /// Look through certain implicit and explicit casts.
  3107. ACCResult VisitCastExpr(CastExpr *e) {
  3108. switch (e->getCastKind()) {
  3109. case CK_NullToPointer:
  3110. return ACC_bottom;
  3111. case CK_NoOp:
  3112. case CK_LValueToRValue:
  3113. case CK_BitCast:
  3114. case CK_CPointerToObjCPointerCast:
  3115. case CK_BlockPointerToObjCPointerCast:
  3116. case CK_AnyPointerToBlockPointerCast:
  3117. return Visit(e->getSubExpr());
  3118. default:
  3119. return ACC_invalid;
  3120. }
  3121. }
  3122. /// Look through unary extension.
  3123. ACCResult VisitUnaryExtension(UnaryOperator *e) {
  3124. return Visit(e->getSubExpr());
  3125. }
  3126. /// Ignore the LHS of a comma operator.
  3127. ACCResult VisitBinComma(BinaryOperator *e) {
  3128. return Visit(e->getRHS());
  3129. }
  3130. /// Conditional operators are okay if both sides are okay.
  3131. ACCResult VisitConditionalOperator(ConditionalOperator *e) {
  3132. ACCResult left = Visit(e->getTrueExpr());
  3133. if (left == ACC_invalid) return ACC_invalid;
  3134. return merge(left, Visit(e->getFalseExpr()));
  3135. }
  3136. /// Look through pseudo-objects.
  3137. ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
  3138. // If we're getting here, we should always have a result.
  3139. return Visit(e->getResultExpr());
  3140. }
  3141. /// Statement expressions are okay if their result expression is okay.
  3142. ACCResult VisitStmtExpr(StmtExpr *e) {
  3143. return Visit(e->getSubStmt()->body_back());
  3144. }
  3145. /// Some declaration references are okay.
  3146. ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
  3147. VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
  3148. // References to global constants are okay.
  3149. if (isAnyRetainable(TargetClass) &&
  3150. isAnyRetainable(SourceClass) &&
  3151. var &&
  3152. var->getStorageClass() == SC_Extern &&
  3153. var->getType().isConstQualified()) {
  3154. // In system headers, they can also be assumed to be immune to retains.
  3155. // These are things like 'kCFStringTransformToLatin'.
  3156. if (Context.getSourceManager().isInSystemHeader(var->getLocation()))
  3157. return ACC_bottom;
  3158. return ACC_plusZero;
  3159. }
  3160. // Nothing else.
  3161. return ACC_invalid;
  3162. }
  3163. /// Some calls are okay.
  3164. ACCResult VisitCallExpr(CallExpr *e) {
  3165. if (FunctionDecl *fn = e->getDirectCallee())
  3166. if (ACCResult result = checkCallToFunction(fn))
  3167. return result;
  3168. return super::VisitCallExpr(e);
  3169. }
  3170. ACCResult checkCallToFunction(FunctionDecl *fn) {
  3171. // Require a CF*Ref return type.
  3172. if (!isCFType(fn->getReturnType()))
  3173. return ACC_invalid;
  3174. if (!isAnyRetainable(TargetClass))
  3175. return ACC_invalid;
  3176. // Honor an explicit 'not retained' attribute.
  3177. if (fn->hasAttr<CFReturnsNotRetainedAttr>())
  3178. return ACC_plusZero;
  3179. // Honor an explicit 'retained' attribute, except that for
  3180. // now we're not going to permit implicit handling of +1 results,
  3181. // because it's a bit frightening.
  3182. if (fn->hasAttr<CFReturnsRetainedAttr>())
  3183. return Diagnose ? ACC_plusOne
  3184. : ACC_invalid; // ACC_plusOne if we start accepting this
  3185. // Recognize this specific builtin function, which is used by CFSTR.
  3186. unsigned builtinID = fn->getBuiltinID();
  3187. if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
  3188. return ACC_bottom;
  3189. // Otherwise, don't do anything implicit with an unaudited function.
  3190. if (!fn->hasAttr<CFAuditedTransferAttr>())
  3191. return ACC_invalid;
  3192. // Otherwise, it's +0 unless it follows the create convention.
  3193. if (ento::coreFoundation::followsCreateRule(fn))
  3194. return Diagnose ? ACC_plusOne
  3195. : ACC_invalid; // ACC_plusOne if we start accepting this
  3196. return ACC_plusZero;
  3197. }
  3198. ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
  3199. return checkCallToMethod(e->getMethodDecl());
  3200. }
  3201. ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
  3202. ObjCMethodDecl *method;
  3203. if (e->isExplicitProperty())
  3204. method = e->getExplicitProperty()->getGetterMethodDecl();
  3205. else
  3206. method = e->getImplicitPropertyGetter();
  3207. return checkCallToMethod(method);
  3208. }
  3209. ACCResult checkCallToMethod(ObjCMethodDecl *method) {
  3210. if (!method) return ACC_invalid;
  3211. // Check for message sends to functions returning CF types. We
  3212. // just obey the Cocoa conventions with these, even though the
  3213. // return type is CF.
  3214. if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
  3215. return ACC_invalid;
  3216. // If the method is explicitly marked not-retained, it's +0.
  3217. if (method->hasAttr<CFReturnsNotRetainedAttr>())
  3218. return ACC_plusZero;
  3219. // If the method is explicitly marked as returning retained, or its
  3220. // selector follows a +1 Cocoa convention, treat it as +1.
  3221. if (method->hasAttr<CFReturnsRetainedAttr>())
  3222. return ACC_plusOne;
  3223. switch (method->getSelector().getMethodFamily()) {
  3224. case OMF_alloc:
  3225. case OMF_copy:
  3226. case OMF_mutableCopy:
  3227. case OMF_new:
  3228. return ACC_plusOne;
  3229. default:
  3230. // Otherwise, treat it as +0.
  3231. return ACC_plusZero;
  3232. }
  3233. }
  3234. };
  3235. }
  3236. bool Sema::isKnownName(StringRef name) {
  3237. if (name.empty())
  3238. return false;
  3239. LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
  3240. Sema::LookupOrdinaryName);
  3241. return LookupName(R, TUScope, false);
  3242. }
  3243. #if 0 // HLSL Change Start - No ObjC support
  3244. static void addFixitForObjCARCConversion(Sema &S,
  3245. DiagnosticBuilder &DiagB,
  3246. Sema::CheckedConversionKind CCK,
  3247. SourceLocation afterLParen,
  3248. QualType castType,
  3249. Expr *castExpr,
  3250. Expr *realCast,
  3251. const char *bridgeKeyword,
  3252. const char *CFBridgeName) {
  3253. // We handle C-style and implicit casts here.
  3254. switch (CCK) {
  3255. case Sema::CCK_ImplicitConversion:
  3256. case Sema::CCK_CStyleCast:
  3257. case Sema::CCK_OtherCast:
  3258. break;
  3259. case Sema::CCK_FunctionalCast:
  3260. return;
  3261. }
  3262. if (CFBridgeName) {
  3263. if (CCK == Sema::CCK_OtherCast) {
  3264. if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
  3265. SourceRange range(NCE->getOperatorLoc(),
  3266. NCE->getAngleBrackets().getEnd());
  3267. SmallString<32> BridgeCall;
  3268. SourceManager &SM = S.getSourceManager();
  3269. char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
  3270. if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
  3271. BridgeCall += ' ';
  3272. BridgeCall += CFBridgeName;
  3273. DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
  3274. }
  3275. return;
  3276. }
  3277. Expr *castedE = castExpr;
  3278. if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
  3279. castedE = CCE->getSubExpr();
  3280. castedE = castedE->IgnoreImpCasts();
  3281. SourceRange range = castedE->getSourceRange();
  3282. SmallString<32> BridgeCall;
  3283. SourceManager &SM = S.getSourceManager();
  3284. char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
  3285. if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
  3286. BridgeCall += ' ';
  3287. BridgeCall += CFBridgeName;
  3288. if (isa<ParenExpr>(castedE)) {
  3289. DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
  3290. BridgeCall));
  3291. } else {
  3292. BridgeCall += '(';
  3293. DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
  3294. BridgeCall));
  3295. DiagB.AddFixItHint(FixItHint::CreateInsertion(
  3296. S.PP.getLocForEndOfToken(range.getEnd()),
  3297. ")"));
  3298. }
  3299. return;
  3300. }
  3301. if (CCK == Sema::CCK_CStyleCast) {
  3302. DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
  3303. } else if (CCK == Sema::CCK_OtherCast) {
  3304. if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
  3305. std::string castCode = "(";
  3306. castCode += bridgeKeyword;
  3307. castCode += castType.getAsString();
  3308. castCode += ")";
  3309. SourceRange Range(NCE->getOperatorLoc(),
  3310. NCE->getAngleBrackets().getEnd());
  3311. DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
  3312. }
  3313. } else {
  3314. std::string castCode = "(";
  3315. castCode += bridgeKeyword;
  3316. castCode += castType.getAsString();
  3317. castCode += ")";
  3318. Expr *castedE = castExpr->IgnoreImpCasts();
  3319. SourceRange range = castedE->getSourceRange();
  3320. if (isa<ParenExpr>(castedE)) {
  3321. DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
  3322. castCode));
  3323. } else {
  3324. castCode += "(";
  3325. DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
  3326. castCode));
  3327. DiagB.AddFixItHint(FixItHint::CreateInsertion(
  3328. S.PP.getLocForEndOfToken(range.getEnd()),
  3329. ")"));
  3330. }
  3331. }
  3332. }
  3333. #endif // HLSL change End - No ObjC support
  3334. template <typename T>
  3335. static inline T *getObjCBridgeAttr(const TypedefType *TD) {
  3336. TypedefNameDecl *TDNDecl = TD->getDecl();
  3337. QualType QT = TDNDecl->getUnderlyingType();
  3338. if (QT->isPointerType()) {
  3339. QT = QT->getPointeeType();
  3340. if (const RecordType *RT = QT->getAs<RecordType>())
  3341. if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
  3342. return RD->getAttr<T>();
  3343. }
  3344. return nullptr;
  3345. }
  3346. static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
  3347. TypedefNameDecl *&TDNDecl) {
  3348. while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
  3349. TDNDecl = TD->getDecl();
  3350. if (ObjCBridgeRelatedAttr *ObjCBAttr =
  3351. getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
  3352. return ObjCBAttr;
  3353. T = TDNDecl->getUnderlyingType();
  3354. }
  3355. return nullptr;
  3356. }
  3357. static void
  3358. diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
  3359. QualType castType, ARCConversionTypeClass castACTC,
  3360. Expr *castExpr, Expr *realCast,
  3361. ARCConversionTypeClass exprACTC,
  3362. Sema::CheckedConversionKind CCK) {
  3363. SourceLocation loc =
  3364. (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
  3365. if (S.makeUnavailableInSystemHeader(loc,
  3366. "converts between Objective-C and C pointers in -fobjc-arc"))
  3367. return;
  3368. QualType castExprType = castExpr->getType();
  3369. TypedefNameDecl *TDNDecl = nullptr;
  3370. if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
  3371. ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
  3372. (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
  3373. ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
  3374. return;
  3375. unsigned srcKind = 0;
  3376. switch (exprACTC) {
  3377. case ACTC_none:
  3378. case ACTC_coreFoundation:
  3379. case ACTC_voidPtr:
  3380. srcKind = (castExprType->isPointerType() ? 1 : 0);
  3381. break;
  3382. case ACTC_retainable:
  3383. srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
  3384. break;
  3385. case ACTC_indirectRetainable:
  3386. srcKind = 4;
  3387. break;
  3388. }
  3389. // Check whether this could be fixed with a bridge cast.
  3390. SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
  3391. SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
  3392. // Bridge from an ARC type to a CF type.
  3393. if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
  3394. S.Diag(loc, diag::err_arc_cast_requires_bridge)
  3395. << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
  3396. << 2 // of C pointer type
  3397. << castExprType
  3398. << unsigned(castType->isBlockPointerType()) // to ObjC|block type
  3399. << castType
  3400. << castRange
  3401. << castExpr->getSourceRange();
  3402. bool br = S.isKnownName("CFBridgingRelease");
  3403. ACCResult CreateRule =
  3404. ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
  3405. assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
  3406. if (CreateRule != ACC_plusOne)
  3407. {
  3408. DiagnosticBuilder DiagB =
  3409. (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
  3410. : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
  3411. addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
  3412. castType, castExpr, realCast, "__bridge ",
  3413. nullptr);
  3414. }
  3415. if (CreateRule != ACC_plusZero)
  3416. {
  3417. DiagnosticBuilder DiagB =
  3418. (CCK == Sema::CCK_OtherCast && !br) ?
  3419. S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
  3420. S.Diag(br ? castExpr->getExprLoc() : noteLoc,
  3421. diag::note_arc_bridge_transfer)
  3422. << castExprType << br;
  3423. addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
  3424. castType, castExpr, realCast, "__bridge_transfer ",
  3425. br ? "CFBridgingRelease" : nullptr);
  3426. }
  3427. return;
  3428. }
  3429. // Bridge from a CF type to an ARC type.
  3430. if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
  3431. bool br = S.isKnownName("CFBridgingRetain");
  3432. S.Diag(loc, diag::err_arc_cast_requires_bridge)
  3433. << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
  3434. << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
  3435. << castExprType
  3436. << 2 // to C pointer type
  3437. << castType
  3438. << castRange
  3439. << castExpr->getSourceRange();
  3440. ACCResult CreateRule =
  3441. ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
  3442. assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
  3443. if (CreateRule != ACC_plusOne)
  3444. {
  3445. DiagnosticBuilder DiagB =
  3446. (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
  3447. : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
  3448. addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
  3449. castType, castExpr, realCast, "__bridge ",
  3450. nullptr);
  3451. }
  3452. if (CreateRule != ACC_plusZero)
  3453. {
  3454. DiagnosticBuilder DiagB =
  3455. (CCK == Sema::CCK_OtherCast && !br) ?
  3456. S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
  3457. S.Diag(br ? castExpr->getExprLoc() : noteLoc,
  3458. diag::note_arc_bridge_retained)
  3459. << castType << br;
  3460. addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
  3461. castType, castExpr, realCast, "__bridge_retained ",
  3462. br ? "CFBridgingRetain" : nullptr);
  3463. }
  3464. return;
  3465. }
  3466. S.Diag(loc, diag::err_arc_mismatched_cast)
  3467. << (CCK != Sema::CCK_ImplicitConversion)
  3468. << srcKind << castExprType << castType
  3469. << castRange << castExpr->getSourceRange();
  3470. }
  3471. template <typename TB>
  3472. static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
  3473. bool &HadTheAttribute, bool warn) {
  3474. QualType T = castExpr->getType();
  3475. HadTheAttribute = false;
  3476. while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
  3477. TypedefNameDecl *TDNDecl = TD->getDecl();
  3478. if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
  3479. if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
  3480. HadTheAttribute = true;
  3481. if (Parm->isStr("id"))
  3482. return true;
  3483. NamedDecl *Target = nullptr;
  3484. // Check for an existing type with this name.
  3485. LookupResult R(S, DeclarationName(Parm), SourceLocation(),
  3486. Sema::LookupOrdinaryName);
  3487. if (S.LookupName(R, S.TUScope)) {
  3488. Target = R.getFoundDecl();
  3489. if (Target && isa<ObjCInterfaceDecl>(Target)) {
  3490. ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
  3491. if (const ObjCObjectPointerType *InterfacePointerType =
  3492. castType->getAsObjCInterfacePointerType()) {
  3493. ObjCInterfaceDecl *CastClass
  3494. = InterfacePointerType->getObjectType()->getInterface();
  3495. if ((CastClass == ExprClass) ||
  3496. (CastClass && CastClass->isSuperClassOf(ExprClass)))
  3497. return true;
  3498. if (warn)
  3499. S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
  3500. << T << Target->getName() << castType->getPointeeType();
  3501. return false;
  3502. } else if (castType->isObjCIdType() ||
  3503. (S.Context.ObjCObjectAdoptsQTypeProtocols(
  3504. castType, ExprClass)))
  3505. // ok to cast to 'id'.
  3506. // casting to id<p-list> is ok if bridge type adopts all of
  3507. // p-list protocols.
  3508. return true;
  3509. else {
  3510. if (warn) {
  3511. S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
  3512. << T << Target->getName() << castType;
  3513. S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
  3514. S.Diag(Target->getLocStart(), diag::note_declared_at);
  3515. }
  3516. return false;
  3517. }
  3518. }
  3519. } else if (!castType->isObjCIdType()) {
  3520. S.Diag(castExpr->getLocStart(), diag::err_objc_cf_bridged_not_interface)
  3521. << castExpr->getType() << Parm;
  3522. S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
  3523. if (Target)
  3524. S.Diag(Target->getLocStart(), diag::note_declared_at);
  3525. }
  3526. return true;
  3527. }
  3528. return false;
  3529. }
  3530. T = TDNDecl->getUnderlyingType();
  3531. }
  3532. return true;
  3533. }
  3534. template <typename TB>
  3535. static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
  3536. bool &HadTheAttribute, bool warn) {
  3537. QualType T = castType;
  3538. HadTheAttribute = false;
  3539. while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
  3540. TypedefNameDecl *TDNDecl = TD->getDecl();
  3541. if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
  3542. if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
  3543. HadTheAttribute = true;
  3544. if (Parm->isStr("id"))
  3545. return true;
  3546. NamedDecl *Target = nullptr;
  3547. // Check for an existing type with this name.
  3548. LookupResult R(S, DeclarationName(Parm), SourceLocation(),
  3549. Sema::LookupOrdinaryName);
  3550. if (S.LookupName(R, S.TUScope)) {
  3551. Target = R.getFoundDecl();
  3552. if (Target && isa<ObjCInterfaceDecl>(Target)) {
  3553. ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
  3554. if (const ObjCObjectPointerType *InterfacePointerType =
  3555. castExpr->getType()->getAsObjCInterfacePointerType()) {
  3556. ObjCInterfaceDecl *ExprClass
  3557. = InterfacePointerType->getObjectType()->getInterface();
  3558. if ((CastClass == ExprClass) ||
  3559. (ExprClass && CastClass->isSuperClassOf(ExprClass)))
  3560. return true;
  3561. if (warn) {
  3562. S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
  3563. << castExpr->getType()->getPointeeType() << T;
  3564. S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
  3565. }
  3566. return false;
  3567. } else if (castExpr->getType()->isObjCIdType() ||
  3568. (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
  3569. castExpr->getType(), CastClass)))
  3570. // ok to cast an 'id' expression to a CFtype.
  3571. // ok to cast an 'id<plist>' expression to CFtype provided plist
  3572. // adopts all of CFtype's ObjetiveC's class plist.
  3573. return true;
  3574. else {
  3575. if (warn) {
  3576. S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
  3577. << castExpr->getType() << castType;
  3578. S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
  3579. S.Diag(Target->getLocStart(), diag::note_declared_at);
  3580. }
  3581. return false;
  3582. }
  3583. }
  3584. }
  3585. S.Diag(castExpr->getLocStart(), diag::err_objc_ns_bridged_invalid_cfobject)
  3586. << castExpr->getType() << castType;
  3587. S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
  3588. if (Target)
  3589. S.Diag(Target->getLocStart(), diag::note_declared_at);
  3590. return true;
  3591. }
  3592. return false;
  3593. }
  3594. T = TDNDecl->getUnderlyingType();
  3595. }
  3596. return true;
  3597. }
  3598. void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
  3599. if (!getLangOpts().ObjC1)
  3600. return;
  3601. // warn in presence of __bridge casting to or from a toll free bridge cast.
  3602. ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
  3603. ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
  3604. if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
  3605. bool HasObjCBridgeAttr;
  3606. bool ObjCBridgeAttrWillNotWarn =
  3607. CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
  3608. false);
  3609. if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
  3610. return;
  3611. bool HasObjCBridgeMutableAttr;
  3612. bool ObjCBridgeMutableAttrWillNotWarn =
  3613. CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
  3614. HasObjCBridgeMutableAttr, false);
  3615. if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
  3616. return;
  3617. if (HasObjCBridgeAttr)
  3618. CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
  3619. true);
  3620. else if (HasObjCBridgeMutableAttr)
  3621. CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
  3622. HasObjCBridgeMutableAttr, true);
  3623. }
  3624. else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
  3625. bool HasObjCBridgeAttr;
  3626. bool ObjCBridgeAttrWillNotWarn =
  3627. CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
  3628. false);
  3629. if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
  3630. return;
  3631. bool HasObjCBridgeMutableAttr;
  3632. bool ObjCBridgeMutableAttrWillNotWarn =
  3633. CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
  3634. HasObjCBridgeMutableAttr, false);
  3635. if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
  3636. return;
  3637. if (HasObjCBridgeAttr)
  3638. CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
  3639. true);
  3640. else if (HasObjCBridgeMutableAttr)
  3641. CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
  3642. HasObjCBridgeMutableAttr, true);
  3643. }
  3644. }
  3645. void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
  3646. QualType SrcType = castExpr->getType();
  3647. if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
  3648. if (PRE->isExplicitProperty()) {
  3649. if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
  3650. SrcType = PDecl->getType();
  3651. }
  3652. else if (PRE->isImplicitProperty()) {
  3653. if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
  3654. SrcType = Getter->getReturnType();
  3655. }
  3656. }
  3657. ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
  3658. ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
  3659. if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation)
  3660. return;
  3661. CheckObjCBridgeRelatedConversions(castExpr->getLocStart(),
  3662. castType, SrcType, castExpr);
  3663. return;
  3664. }
  3665. bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
  3666. CastKind &Kind) {
  3667. if (!getLangOpts().ObjC1)
  3668. return false;
  3669. ARCConversionTypeClass exprACTC =
  3670. classifyTypeForARCConversion(castExpr->getType());
  3671. ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
  3672. if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
  3673. (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
  3674. CheckTollFreeBridgeCast(castType, castExpr);
  3675. Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
  3676. : CK_CPointerToObjCPointerCast;
  3677. return true;
  3678. }
  3679. return false;
  3680. }
  3681. bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
  3682. QualType DestType, QualType SrcType,
  3683. ObjCInterfaceDecl *&RelatedClass,
  3684. ObjCMethodDecl *&ClassMethod,
  3685. ObjCMethodDecl *&InstanceMethod,
  3686. TypedefNameDecl *&TDNDecl,
  3687. bool CfToNs) {
  3688. QualType T = CfToNs ? SrcType : DestType;
  3689. ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
  3690. if (!ObjCBAttr)
  3691. return false;
  3692. IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
  3693. IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
  3694. IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
  3695. if (!RCId)
  3696. return false;
  3697. NamedDecl *Target = nullptr;
  3698. // Check for an existing type with this name.
  3699. LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
  3700. Sema::LookupOrdinaryName);
  3701. if (!LookupName(R, TUScope)) {
  3702. Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
  3703. << SrcType << DestType;
  3704. Diag(TDNDecl->getLocStart(), diag::note_declared_at);
  3705. return false;
  3706. }
  3707. Target = R.getFoundDecl();
  3708. if (Target && isa<ObjCInterfaceDecl>(Target))
  3709. RelatedClass = cast<ObjCInterfaceDecl>(Target);
  3710. else {
  3711. Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
  3712. << SrcType << DestType;
  3713. Diag(TDNDecl->getLocStart(), diag::note_declared_at);
  3714. if (Target)
  3715. Diag(Target->getLocStart(), diag::note_declared_at);
  3716. return false;
  3717. }
  3718. // Check for an existing class method with the given selector name.
  3719. if (CfToNs && CMId) {
  3720. Selector Sel = Context.Selectors.getUnarySelector(CMId);
  3721. ClassMethod = RelatedClass->lookupMethod(Sel, false);
  3722. if (!ClassMethod) {
  3723. Diag(Loc, diag::err_objc_bridged_related_known_method)
  3724. << SrcType << DestType << Sel << false;
  3725. Diag(TDNDecl->getLocStart(), diag::note_declared_at);
  3726. return false;
  3727. }
  3728. }
  3729. // Check for an existing instance method with the given selector name.
  3730. if (!CfToNs && IMId) {
  3731. Selector Sel = Context.Selectors.getNullarySelector(IMId);
  3732. InstanceMethod = RelatedClass->lookupMethod(Sel, true);
  3733. if (!InstanceMethod) {
  3734. Diag(Loc, diag::err_objc_bridged_related_known_method)
  3735. << SrcType << DestType << Sel << true;
  3736. Diag(TDNDecl->getLocStart(), diag::note_declared_at);
  3737. return false;
  3738. }
  3739. }
  3740. return true;
  3741. }
  3742. bool
  3743. Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
  3744. QualType DestType, QualType SrcType,
  3745. Expr *&SrcExpr) {
  3746. ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
  3747. ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
  3748. bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
  3749. bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
  3750. if (!CfToNs && !NsToCf)
  3751. return false;
  3752. ObjCInterfaceDecl *RelatedClass;
  3753. ObjCMethodDecl *ClassMethod = nullptr;
  3754. ObjCMethodDecl *InstanceMethod = nullptr;
  3755. TypedefNameDecl *TDNDecl = nullptr;
  3756. if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
  3757. ClassMethod, InstanceMethod, TDNDecl, CfToNs))
  3758. return false;
  3759. if (CfToNs) {
  3760. // Implicit conversion from CF to ObjC object is needed.
  3761. if (ClassMethod) {
  3762. std::string ExpressionString = "[";
  3763. ExpressionString += RelatedClass->getNameAsString();
  3764. ExpressionString += " ";
  3765. ExpressionString += ClassMethod->getSelector().getAsString();
  3766. SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
  3767. // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
  3768. Diag(Loc, diag::err_objc_bridged_related_known_method)
  3769. << SrcType << DestType << ClassMethod->getSelector() << false
  3770. << FixItHint::CreateInsertion(SrcExpr->getLocStart(), ExpressionString)
  3771. << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
  3772. Diag(RelatedClass->getLocStart(), diag::note_declared_at);
  3773. Diag(TDNDecl->getLocStart(), diag::note_declared_at);
  3774. QualType receiverType =
  3775. Context.getObjCInterfaceType(RelatedClass);
  3776. // Argument.
  3777. Expr *args[] = { SrcExpr };
  3778. ExprResult msg = BuildClassMessageImplicit(receiverType, false,
  3779. ClassMethod->getLocation(),
  3780. ClassMethod->getSelector(), ClassMethod,
  3781. MultiExprArg(args, 1));
  3782. SrcExpr = msg.get();
  3783. return true;
  3784. }
  3785. }
  3786. else {
  3787. // Implicit conversion from ObjC type to CF object is needed.
  3788. if (InstanceMethod) {
  3789. std::string ExpressionString;
  3790. SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
  3791. if (InstanceMethod->isPropertyAccessor())
  3792. if (const ObjCPropertyDecl *PDecl = InstanceMethod->findPropertyDecl()) {
  3793. // fixit: ObjectExpr.propertyname when it is aproperty accessor.
  3794. ExpressionString = ".";
  3795. ExpressionString += PDecl->getNameAsString();
  3796. Diag(Loc, diag::err_objc_bridged_related_known_method)
  3797. << SrcType << DestType << InstanceMethod->getSelector() << true
  3798. << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
  3799. }
  3800. if (ExpressionString.empty()) {
  3801. // Provide a fixit: [ObjectExpr InstanceMethod]
  3802. ExpressionString = " ";
  3803. ExpressionString += InstanceMethod->getSelector().getAsString();
  3804. ExpressionString += "]";
  3805. Diag(Loc, diag::err_objc_bridged_related_known_method)
  3806. << SrcType << DestType << InstanceMethod->getSelector() << true
  3807. << FixItHint::CreateInsertion(SrcExpr->getLocStart(), "[")
  3808. << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
  3809. }
  3810. Diag(RelatedClass->getLocStart(), diag::note_declared_at);
  3811. Diag(TDNDecl->getLocStart(), diag::note_declared_at);
  3812. ExprResult msg =
  3813. BuildInstanceMessageImplicit(SrcExpr, SrcType,
  3814. InstanceMethod->getLocation(),
  3815. InstanceMethod->getSelector(),
  3816. InstanceMethod, None);
  3817. SrcExpr = msg.get();
  3818. return true;
  3819. }
  3820. }
  3821. return false;
  3822. }
  3823. Sema::ARCConversionResult
  3824. Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
  3825. Expr *&castExpr, CheckedConversionKind CCK,
  3826. bool DiagnoseCFAudited,
  3827. BinaryOperatorKind Opc) {
  3828. QualType castExprType = castExpr->getType();
  3829. // For the purposes of the classification, we assume reference types
  3830. // will bind to temporaries.
  3831. QualType effCastType = castType;
  3832. if (const ReferenceType *ref = castType->getAs<ReferenceType>())
  3833. effCastType = ref->getPointeeType();
  3834. ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
  3835. ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
  3836. if (exprACTC == castACTC) {
  3837. // check for viablity and report error if casting an rvalue to a
  3838. // life-time qualifier.
  3839. if ((castACTC == ACTC_retainable) &&
  3840. (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
  3841. (castType != castExprType)) {
  3842. const Type *DT = castType.getTypePtr();
  3843. QualType QDT = castType;
  3844. // We desugar some types but not others. We ignore those
  3845. // that cannot happen in a cast; i.e. auto, and those which
  3846. // should not be de-sugared; i.e typedef.
  3847. if (const ParenType *PT = dyn_cast<ParenType>(DT))
  3848. QDT = PT->desugar();
  3849. else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
  3850. QDT = TP->desugar();
  3851. else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
  3852. QDT = AT->desugar();
  3853. if (QDT != castType &&
  3854. QDT.getObjCLifetime() != Qualifiers::OCL_None) {
  3855. SourceLocation loc =
  3856. (castRange.isValid() ? castRange.getBegin()
  3857. : castExpr->getExprLoc());
  3858. Diag(loc, diag::err_arc_nolifetime_behavior);
  3859. }
  3860. }
  3861. return ACR_okay;
  3862. }
  3863. if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
  3864. // Allow all of these types to be cast to integer types (but not
  3865. // vice-versa).
  3866. if (castACTC == ACTC_none && castType->isIntegralType(Context))
  3867. return ACR_okay;
  3868. // Allow casts between pointers to lifetime types (e.g., __strong id*)
  3869. // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
  3870. // must be explicit.
  3871. if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
  3872. return ACR_okay;
  3873. if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
  3874. CCK != CCK_ImplicitConversion)
  3875. return ACR_okay;
  3876. switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
  3877. // For invalid casts, fall through.
  3878. case ACC_invalid:
  3879. break;
  3880. // Do nothing for both bottom and +0.
  3881. case ACC_bottom:
  3882. case ACC_plusZero:
  3883. return ACR_okay;
  3884. // If the result is +1, consume it here.
  3885. case ACC_plusOne:
  3886. castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
  3887. CK_ARCConsumeObject, castExpr,
  3888. nullptr, VK_RValue);
  3889. ExprNeedsCleanups = true;
  3890. return ACR_okay;
  3891. }
  3892. // If this is a non-implicit cast from id or block type to a
  3893. // CoreFoundation type, delay complaining in case the cast is used
  3894. // in an acceptable context.
  3895. if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
  3896. CCK != CCK_ImplicitConversion)
  3897. return ACR_unbridged;
  3898. // Do not issue bridge cast" diagnostic when implicit casting a cstring
  3899. // to 'NSString *'. Let caller issue a normal mismatched diagnostic with
  3900. // suitable fix-it.
  3901. if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
  3902. ConversionToObjCStringLiteralCheck(castType, castExpr))
  3903. return ACR_okay;
  3904. // Do not issue "bridge cast" diagnostic when implicit casting
  3905. // a retainable object to a CF type parameter belonging to an audited
  3906. // CF API function. Let caller issue a normal type mismatched diagnostic
  3907. // instead.
  3908. if (!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
  3909. castACTC != ACTC_coreFoundation)
  3910. if (!(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable &&
  3911. (Opc == BO_NE || Opc == BO_EQ)))
  3912. diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
  3913. castExpr, castExpr, exprACTC, CCK);
  3914. return ACR_okay;
  3915. }
  3916. /// Given that we saw an expression with the ARCUnbridgedCastTy
  3917. /// placeholder type, complain bitterly.
  3918. void Sema::diagnoseARCUnbridgedCast(Expr *e) {
  3919. // We expect the spurious ImplicitCastExpr to already have been stripped.
  3920. assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
  3921. CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
  3922. SourceRange castRange;
  3923. QualType castType;
  3924. CheckedConversionKind CCK;
  3925. if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
  3926. castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
  3927. castType = cast->getTypeAsWritten();
  3928. CCK = CCK_CStyleCast;
  3929. } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
  3930. castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
  3931. castType = cast->getTypeAsWritten();
  3932. CCK = CCK_OtherCast;
  3933. } else {
  3934. castType = cast->getType();
  3935. CCK = CCK_ImplicitConversion;
  3936. }
  3937. ARCConversionTypeClass castACTC =
  3938. classifyTypeForARCConversion(castType.getNonReferenceType());
  3939. Expr *castExpr = realCast->getSubExpr();
  3940. assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
  3941. diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
  3942. castExpr, realCast, ACTC_retainable, CCK);
  3943. }
  3944. /// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
  3945. /// type, remove the placeholder cast.
  3946. Expr *Sema::stripARCUnbridgedCast(Expr *e) {
  3947. assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
  3948. if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
  3949. Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
  3950. return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
  3951. } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
  3952. assert(uo->getOpcode() == UO_Extension);
  3953. Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
  3954. return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
  3955. sub->getValueKind(), sub->getObjectKind(),
  3956. uo->getOperatorLoc());
  3957. } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
  3958. assert(!gse->isResultDependent());
  3959. unsigned n = gse->getNumAssocs();
  3960. SmallVector<Expr*, 4> subExprs(n);
  3961. SmallVector<TypeSourceInfo*, 4> subTypes(n);
  3962. for (unsigned i = 0; i != n; ++i) {
  3963. subTypes[i] = gse->getAssocTypeSourceInfo(i);
  3964. Expr *sub = gse->getAssocExpr(i);
  3965. if (i == gse->getResultIndex())
  3966. sub = stripARCUnbridgedCast(sub);
  3967. subExprs[i] = sub;
  3968. }
  3969. return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
  3970. gse->getControllingExpr(),
  3971. subTypes, subExprs,
  3972. gse->getDefaultLoc(),
  3973. gse->getRParenLoc(),
  3974. gse->containsUnexpandedParameterPack(),
  3975. gse->getResultIndex());
  3976. } else {
  3977. assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
  3978. return cast<ImplicitCastExpr>(e)->getSubExpr();
  3979. }
  3980. }
  3981. bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
  3982. QualType exprType) {
  3983. QualType canCastType =
  3984. Context.getCanonicalType(castType).getUnqualifiedType();
  3985. QualType canExprType =
  3986. Context.getCanonicalType(exprType).getUnqualifiedType();
  3987. if (isa<ObjCObjectPointerType>(canCastType) &&
  3988. castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
  3989. canExprType->isObjCObjectPointerType()) {
  3990. if (const ObjCObjectPointerType *ObjT =
  3991. canExprType->getAs<ObjCObjectPointerType>())
  3992. if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
  3993. return !ObjI->isArcWeakrefUnavailable();
  3994. }
  3995. return true;
  3996. }
  3997. /// Look for an ObjCReclaimReturnedObject cast and destroy it.
  3998. static Expr *maybeUndoReclaimObject(Expr *e) {
  3999. // For now, we just undo operands that are *immediately* reclaim
  4000. // expressions, which prevents the vast majority of potential
  4001. // problems here. To catch them all, we'd need to rebuild arbitrary
  4002. // value-propagating subexpressions --- we can't reliably rebuild
  4003. // in-place because of expression sharing.
  4004. if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
  4005. if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
  4006. return ice->getSubExpr();
  4007. return e;
  4008. }
  4009. ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
  4010. ObjCBridgeCastKind Kind,
  4011. SourceLocation BridgeKeywordLoc,
  4012. TypeSourceInfo *TSInfo,
  4013. Expr *SubExpr) {
  4014. ExprResult SubResult = UsualUnaryConversions(SubExpr);
  4015. if (SubResult.isInvalid()) return ExprError();
  4016. SubExpr = SubResult.get();
  4017. QualType T = TSInfo->getType();
  4018. QualType FromType = SubExpr->getType();
  4019. CastKind CK;
  4020. bool MustConsume = false;
  4021. if (T->isDependentType() || SubExpr->isTypeDependent()) {
  4022. // Okay: we'll build a dependent expression type.
  4023. CK = CK_Dependent;
  4024. } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
  4025. // Casting CF -> id
  4026. CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
  4027. : CK_CPointerToObjCPointerCast);
  4028. switch (Kind) {
  4029. case OBC_Bridge:
  4030. break;
  4031. case OBC_BridgeRetained: {
  4032. bool br = isKnownName("CFBridgingRelease");
  4033. Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
  4034. << 2
  4035. << FromType
  4036. << (T->isBlockPointerType()? 1 : 0)
  4037. << T
  4038. << SubExpr->getSourceRange()
  4039. << Kind;
  4040. Diag(BridgeKeywordLoc, diag::note_arc_bridge)
  4041. << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
  4042. Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
  4043. << FromType << br
  4044. << FixItHint::CreateReplacement(BridgeKeywordLoc,
  4045. br ? "CFBridgingRelease "
  4046. : "__bridge_transfer ");
  4047. Kind = OBC_Bridge;
  4048. break;
  4049. }
  4050. case OBC_BridgeTransfer:
  4051. // We must consume the Objective-C object produced by the cast.
  4052. MustConsume = true;
  4053. break;
  4054. }
  4055. } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
  4056. // Okay: id -> CF
  4057. CK = CK_BitCast;
  4058. switch (Kind) {
  4059. case OBC_Bridge:
  4060. // Reclaiming a value that's going to be __bridge-casted to CF
  4061. // is very dangerous, so we don't do it.
  4062. SubExpr = maybeUndoReclaimObject(SubExpr);
  4063. break;
  4064. case OBC_BridgeRetained:
  4065. // Produce the object before casting it.
  4066. SubExpr = ImplicitCastExpr::Create(Context, FromType,
  4067. CK_ARCProduceObject,
  4068. SubExpr, nullptr, VK_RValue);
  4069. break;
  4070. case OBC_BridgeTransfer: {
  4071. bool br = isKnownName("CFBridgingRetain");
  4072. Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
  4073. << (FromType->isBlockPointerType()? 1 : 0)
  4074. << FromType
  4075. << 2
  4076. << T
  4077. << SubExpr->getSourceRange()
  4078. << Kind;
  4079. Diag(BridgeKeywordLoc, diag::note_arc_bridge)
  4080. << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
  4081. Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
  4082. << T << br
  4083. << FixItHint::CreateReplacement(BridgeKeywordLoc,
  4084. br ? "CFBridgingRetain " : "__bridge_retained");
  4085. Kind = OBC_Bridge;
  4086. break;
  4087. }
  4088. }
  4089. } else {
  4090. Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
  4091. << FromType << T << Kind
  4092. << SubExpr->getSourceRange()
  4093. << TSInfo->getTypeLoc().getSourceRange();
  4094. return ExprError();
  4095. }
  4096. Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
  4097. BridgeKeywordLoc,
  4098. TSInfo, SubExpr);
  4099. if (MustConsume) {
  4100. ExprNeedsCleanups = true;
  4101. Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
  4102. nullptr, VK_RValue);
  4103. }
  4104. return Result;
  4105. }
  4106. ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
  4107. SourceLocation LParenLoc,
  4108. ObjCBridgeCastKind Kind,
  4109. SourceLocation BridgeKeywordLoc,
  4110. ParsedType Type,
  4111. SourceLocation RParenLoc,
  4112. Expr *SubExpr) {
  4113. TypeSourceInfo *TSInfo = nullptr;
  4114. QualType T = GetTypeFromParser(Type, &TSInfo);
  4115. if (Kind == OBC_Bridge)
  4116. CheckTollFreeBridgeCast(T, SubExpr);
  4117. if (!TSInfo)
  4118. TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
  4119. return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
  4120. SubExpr);
  4121. }
  4122. #endif // HLSL Change