RewriteObjC.cpp 225 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880
  1. //===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Hacks and fun related to the code rewriter.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Rewrite/Frontend/ASTConsumers.h"
  13. #include "clang/AST/AST.h"
  14. #include "clang/AST/ASTConsumer.h"
  15. #include "clang/AST/Attr.h"
  16. #include "clang/AST/ParentMap.h"
  17. #include "clang/Basic/CharInfo.h"
  18. #include "clang/Basic/Diagnostic.h"
  19. #include "clang/Basic/IdentifierTable.h"
  20. #include "clang/Basic/SourceManager.h"
  21. #include "clang/Config/config.h"
  22. #include "clang/Lex/Lexer.h"
  23. #include "clang/Rewrite/Core/Rewriter.h"
  24. #include "llvm/ADT/DenseSet.h"
  25. #include "llvm/ADT/SmallPtrSet.h"
  26. #include "llvm/ADT/StringExtras.h"
  27. #include "llvm/Support/MemoryBuffer.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. #include <memory>
  30. #if CLANG_ENABLE_OBJC_REWRITER
  31. using namespace clang;
  32. using llvm::utostr;
  33. namespace {
  34. class RewriteObjC : public ASTConsumer {
  35. protected:
  36. enum {
  37. BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
  38. block, ... */
  39. BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
  40. BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
  41. __block variable */
  42. BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
  43. helpers */
  44. BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
  45. support routines */
  46. BLOCK_BYREF_CURRENT_MAX = 256
  47. };
  48. enum {
  49. BLOCK_NEEDS_FREE = (1 << 24),
  50. BLOCK_HAS_COPY_DISPOSE = (1 << 25),
  51. BLOCK_HAS_CXX_OBJ = (1 << 26),
  52. BLOCK_IS_GC = (1 << 27),
  53. BLOCK_IS_GLOBAL = (1 << 28),
  54. BLOCK_HAS_DESCRIPTOR = (1 << 29)
  55. };
  56. static const int OBJC_ABI_VERSION = 7;
  57. Rewriter Rewrite;
  58. DiagnosticsEngine &Diags;
  59. const LangOptions &LangOpts;
  60. ASTContext *Context;
  61. SourceManager *SM;
  62. TranslationUnitDecl *TUDecl;
  63. FileID MainFileID;
  64. const char *MainFileStart, *MainFileEnd;
  65. Stmt *CurrentBody;
  66. ParentMap *PropParentMap; // created lazily.
  67. std::string InFileName;
  68. std::unique_ptr<raw_ostream> OutFile;
  69. std::string Preamble;
  70. TypeDecl *ProtocolTypeDecl;
  71. VarDecl *GlobalVarDecl;
  72. unsigned RewriteFailedDiag;
  73. // ObjC string constant support.
  74. unsigned NumObjCStringLiterals;
  75. VarDecl *ConstantStringClassReference;
  76. RecordDecl *NSStringRecord;
  77. // ObjC foreach break/continue generation support.
  78. int BcLabelCount;
  79. unsigned TryFinallyContainsReturnDiag;
  80. // Needed for super.
  81. ObjCMethodDecl *CurMethodDef;
  82. RecordDecl *SuperStructDecl;
  83. RecordDecl *ConstantStringDecl;
  84. FunctionDecl *MsgSendFunctionDecl;
  85. FunctionDecl *MsgSendSuperFunctionDecl;
  86. FunctionDecl *MsgSendStretFunctionDecl;
  87. FunctionDecl *MsgSendSuperStretFunctionDecl;
  88. FunctionDecl *MsgSendFpretFunctionDecl;
  89. FunctionDecl *GetClassFunctionDecl;
  90. FunctionDecl *GetMetaClassFunctionDecl;
  91. FunctionDecl *GetSuperClassFunctionDecl;
  92. FunctionDecl *SelGetUidFunctionDecl;
  93. FunctionDecl *CFStringFunctionDecl;
  94. FunctionDecl *SuperConstructorFunctionDecl;
  95. FunctionDecl *CurFunctionDef;
  96. FunctionDecl *CurFunctionDeclToDeclareForBlock;
  97. /* Misc. containers needed for meta-data rewrite. */
  98. SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
  99. SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
  100. llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
  101. llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
  102. llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
  103. llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
  104. SmallVector<Stmt *, 32> Stmts;
  105. SmallVector<int, 8> ObjCBcLabelNo;
  106. // Remember all the @protocol(<expr>) expressions.
  107. llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
  108. llvm::DenseSet<uint64_t> CopyDestroyCache;
  109. // Block expressions.
  110. SmallVector<BlockExpr *, 32> Blocks;
  111. SmallVector<int, 32> InnerDeclRefsCount;
  112. SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
  113. SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
  114. // Block related declarations.
  115. SmallVector<ValueDecl *, 8> BlockByCopyDecls;
  116. llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
  117. SmallVector<ValueDecl *, 8> BlockByRefDecls;
  118. llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
  119. llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
  120. llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
  121. llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
  122. llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
  123. // This maps an original source AST to it's rewritten form. This allows
  124. // us to avoid rewriting the same node twice (which is very uncommon).
  125. // This is needed to support some of the exotic property rewriting.
  126. llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
  127. // Needed for header files being rewritten
  128. bool IsHeader;
  129. bool SilenceRewriteMacroWarning;
  130. bool objc_impl_method;
  131. bool DisableReplaceStmt;
  132. class DisableReplaceStmtScope {
  133. RewriteObjC &R;
  134. bool SavedValue;
  135. public:
  136. DisableReplaceStmtScope(RewriteObjC &R)
  137. : R(R), SavedValue(R.DisableReplaceStmt) {
  138. R.DisableReplaceStmt = true;
  139. }
  140. ~DisableReplaceStmtScope() {
  141. R.DisableReplaceStmt = SavedValue;
  142. }
  143. };
  144. void InitializeCommon(ASTContext &context);
  145. public:
  146. // Top Level Driver code.
  147. bool HandleTopLevelDecl(DeclGroupRef D) override {
  148. for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
  149. if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
  150. if (!Class->isThisDeclarationADefinition()) {
  151. RewriteForwardClassDecl(D);
  152. break;
  153. }
  154. }
  155. if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
  156. if (!Proto->isThisDeclarationADefinition()) {
  157. RewriteForwardProtocolDecl(D);
  158. break;
  159. }
  160. }
  161. HandleTopLevelSingleDecl(*I);
  162. }
  163. return true;
  164. }
  165. void HandleTopLevelSingleDecl(Decl *D);
  166. void HandleDeclInMainFile(Decl *D);
  167. RewriteObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
  168. DiagnosticsEngine &D, const LangOptions &LOpts,
  169. bool silenceMacroWarn);
  170. ~RewriteObjC() override {}
  171. void HandleTranslationUnit(ASTContext &C) override;
  172. void ReplaceStmt(Stmt *Old, Stmt *New) {
  173. ReplaceStmtWithRange(Old, New, Old->getSourceRange());
  174. }
  175. void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
  176. assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
  177. Stmt *ReplacingStmt = ReplacedNodes[Old];
  178. if (ReplacingStmt)
  179. return; // We can't rewrite the same node twice.
  180. if (DisableReplaceStmt)
  181. return;
  182. // Measure the old text.
  183. int Size = Rewrite.getRangeSize(SrcRange);
  184. if (Size == -1) {
  185. Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
  186. << Old->getSourceRange();
  187. return;
  188. }
  189. // Get the new text.
  190. std::string SStr;
  191. llvm::raw_string_ostream S(SStr);
  192. New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
  193. const std::string &Str = S.str();
  194. // If replacement succeeded or warning disabled return with no warning.
  195. if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
  196. ReplacedNodes[Old] = New;
  197. return;
  198. }
  199. if (SilenceRewriteMacroWarning)
  200. return;
  201. Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
  202. << Old->getSourceRange();
  203. }
  204. void InsertText(SourceLocation Loc, StringRef Str,
  205. bool InsertAfter = true) {
  206. // If insertion succeeded or warning disabled return with no warning.
  207. if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
  208. SilenceRewriteMacroWarning)
  209. return;
  210. Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
  211. }
  212. void ReplaceText(SourceLocation Start, unsigned OrigLength,
  213. StringRef Str) {
  214. // If removal succeeded or warning disabled return with no warning.
  215. if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
  216. SilenceRewriteMacroWarning)
  217. return;
  218. Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
  219. }
  220. // Syntactic Rewriting.
  221. void RewriteRecordBody(RecordDecl *RD);
  222. void RewriteInclude();
  223. void RewriteForwardClassDecl(DeclGroupRef D);
  224. void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
  225. void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
  226. const std::string &typedefString);
  227. void RewriteImplementations();
  228. void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
  229. ObjCImplementationDecl *IMD,
  230. ObjCCategoryImplDecl *CID);
  231. void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
  232. void RewriteImplementationDecl(Decl *Dcl);
  233. void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
  234. ObjCMethodDecl *MDecl, std::string &ResultStr);
  235. void RewriteTypeIntoString(QualType T, std::string &ResultStr,
  236. const FunctionType *&FPRetType);
  237. void RewriteByRefString(std::string &ResultStr, const std::string &Name,
  238. ValueDecl *VD, bool def=false);
  239. void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
  240. void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
  241. void RewriteForwardProtocolDecl(DeclGroupRef D);
  242. void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
  243. void RewriteMethodDeclaration(ObjCMethodDecl *Method);
  244. void RewriteProperty(ObjCPropertyDecl *prop);
  245. void RewriteFunctionDecl(FunctionDecl *FD);
  246. void RewriteBlockPointerType(std::string& Str, QualType Type);
  247. void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
  248. void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
  249. void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
  250. void RewriteTypeOfDecl(VarDecl *VD);
  251. void RewriteObjCQualifiedInterfaceTypes(Expr *E);
  252. // Expression Rewriting.
  253. Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
  254. Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
  255. Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
  256. Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
  257. Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
  258. Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
  259. Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
  260. Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
  261. void RewriteTryReturnStmts(Stmt *S);
  262. void RewriteSyncReturnStmts(Stmt *S, std::string buf);
  263. Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
  264. Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
  265. Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
  266. Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
  267. SourceLocation OrigEnd);
  268. Stmt *RewriteBreakStmt(BreakStmt *S);
  269. Stmt *RewriteContinueStmt(ContinueStmt *S);
  270. void RewriteCastExpr(CStyleCastExpr *CE);
  271. // Block rewriting.
  272. void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
  273. // Block specific rewrite rules.
  274. void RewriteBlockPointerDecl(NamedDecl *VD);
  275. void RewriteByRefVar(VarDecl *VD);
  276. Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
  277. Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
  278. void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
  279. void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
  280. std::string &Result);
  281. void Initialize(ASTContext &context) override = 0;
  282. // Metadata Rewriting.
  283. virtual void RewriteMetaDataIntoBuffer(std::string &Result) = 0;
  284. virtual void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
  285. StringRef prefix,
  286. StringRef ClassName,
  287. std::string &Result) = 0;
  288. virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
  289. std::string &Result) = 0;
  290. virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
  291. StringRef prefix,
  292. StringRef ClassName,
  293. std::string &Result) = 0;
  294. virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
  295. std::string &Result) = 0;
  296. // Rewriting ivar access
  297. virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0;
  298. virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
  299. std::string &Result) = 0;
  300. // Misc. AST transformation routines. Sometimes they end up calling
  301. // rewriting routines on the new ASTs.
  302. CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
  303. ArrayRef<Expr *> Args,
  304. SourceLocation StartLoc=SourceLocation(),
  305. SourceLocation EndLoc=SourceLocation());
  306. CallExpr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
  307. QualType msgSendType,
  308. QualType returnType,
  309. SmallVectorImpl<QualType> &ArgTypes,
  310. SmallVectorImpl<Expr*> &MsgExprs,
  311. ObjCMethodDecl *Method);
  312. Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
  313. SourceLocation StartLoc=SourceLocation(),
  314. SourceLocation EndLoc=SourceLocation());
  315. void SynthCountByEnumWithState(std::string &buf);
  316. void SynthMsgSendFunctionDecl();
  317. void SynthMsgSendSuperFunctionDecl();
  318. void SynthMsgSendStretFunctionDecl();
  319. void SynthMsgSendFpretFunctionDecl();
  320. void SynthMsgSendSuperStretFunctionDecl();
  321. void SynthGetClassFunctionDecl();
  322. void SynthGetMetaClassFunctionDecl();
  323. void SynthGetSuperClassFunctionDecl();
  324. void SynthSelGetUidFunctionDecl();
  325. void SynthSuperConstructorFunctionDecl();
  326. std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
  327. std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
  328. StringRef funcName, std::string Tag);
  329. std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
  330. StringRef funcName, std::string Tag);
  331. std::string SynthesizeBlockImpl(BlockExpr *CE,
  332. std::string Tag, std::string Desc);
  333. std::string SynthesizeBlockDescriptor(std::string DescTag,
  334. std::string ImplTag,
  335. int i, StringRef funcName,
  336. unsigned hasCopy);
  337. Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
  338. void SynthesizeBlockLiterals(SourceLocation FunLocStart,
  339. StringRef FunName);
  340. FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
  341. Stmt *SynthBlockInitExpr(BlockExpr *Exp,
  342. const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
  343. // Misc. helper routines.
  344. QualType getProtocolType();
  345. void WarnAboutReturnGotoStmts(Stmt *S);
  346. void HasReturnStmts(Stmt *S, bool &hasReturns);
  347. void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
  348. void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
  349. void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
  350. bool IsDeclStmtInForeachHeader(DeclStmt *DS);
  351. void CollectBlockDeclRefInfo(BlockExpr *Exp);
  352. void GetBlockDeclRefExprs(Stmt *S);
  353. void GetInnerBlockDeclRefExprs(Stmt *S,
  354. SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
  355. llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
  356. // We avoid calling Type::isBlockPointerType(), since it operates on the
  357. // canonical type. We only care if the top-level type is a closure pointer.
  358. bool isTopLevelBlockPointerType(QualType T) {
  359. return isa<BlockPointerType>(T);
  360. }
  361. /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
  362. /// to a function pointer type and upon success, returns true; false
  363. /// otherwise.
  364. bool convertBlockPointerToFunctionPointer(QualType &T) {
  365. if (isTopLevelBlockPointerType(T)) {
  366. const BlockPointerType *BPT = T->getAs<BlockPointerType>();
  367. T = Context->getPointerType(BPT->getPointeeType());
  368. return true;
  369. }
  370. return false;
  371. }
  372. bool needToScanForQualifiers(QualType T);
  373. QualType getSuperStructType();
  374. QualType getConstantStringStructType();
  375. QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
  376. bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
  377. void convertToUnqualifiedObjCType(QualType &T) {
  378. if (T->isObjCQualifiedIdType())
  379. T = Context->getObjCIdType();
  380. else if (T->isObjCQualifiedClassType())
  381. T = Context->getObjCClassType();
  382. else if (T->isObjCObjectPointerType() &&
  383. T->getPointeeType()->isObjCQualifiedInterfaceType()) {
  384. if (const ObjCObjectPointerType * OBJPT =
  385. T->getAsObjCInterfacePointerType()) {
  386. const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
  387. T = QualType(IFaceT, 0);
  388. T = Context->getPointerType(T);
  389. }
  390. }
  391. }
  392. // FIXME: This predicate seems like it would be useful to add to ASTContext.
  393. bool isObjCType(QualType T) {
  394. if (!LangOpts.ObjC)
  395. return false;
  396. QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
  397. if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
  398. OCT == Context->getCanonicalType(Context->getObjCClassType()))
  399. return true;
  400. if (const PointerType *PT = OCT->getAs<PointerType>()) {
  401. if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
  402. PT->getPointeeType()->isObjCQualifiedIdType())
  403. return true;
  404. }
  405. return false;
  406. }
  407. bool PointerTypeTakesAnyBlockArguments(QualType QT);
  408. bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
  409. void GetExtentOfArgList(const char *Name, const char *&LParen,
  410. const char *&RParen);
  411. void QuoteDoublequotes(std::string &From, std::string &To) {
  412. for (unsigned i = 0; i < From.length(); i++) {
  413. if (From[i] == '"')
  414. To += "\\\"";
  415. else
  416. To += From[i];
  417. }
  418. }
  419. QualType getSimpleFunctionType(QualType result,
  420. ArrayRef<QualType> args,
  421. bool variadic = false) {
  422. if (result == Context->getObjCInstanceType())
  423. result = Context->getObjCIdType();
  424. FunctionProtoType::ExtProtoInfo fpi;
  425. fpi.Variadic = variadic;
  426. return Context->getFunctionType(result, args, fpi);
  427. }
  428. // Helper function: create a CStyleCastExpr with trivial type source info.
  429. CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
  430. CastKind Kind, Expr *E) {
  431. TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
  432. return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
  433. TInfo, SourceLocation(), SourceLocation());
  434. }
  435. StringLiteral *getStringLiteral(StringRef Str) {
  436. QualType StrType = Context->getConstantArrayType(
  437. Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
  438. 0);
  439. return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
  440. /*Pascal=*/false, StrType, SourceLocation());
  441. }
  442. };
  443. class RewriteObjCFragileABI : public RewriteObjC {
  444. public:
  445. RewriteObjCFragileABI(std::string inFile, std::unique_ptr<raw_ostream> OS,
  446. DiagnosticsEngine &D, const LangOptions &LOpts,
  447. bool silenceMacroWarn)
  448. : RewriteObjC(inFile, std::move(OS), D, LOpts, silenceMacroWarn) {}
  449. ~RewriteObjCFragileABI() override {}
  450. void Initialize(ASTContext &context) override;
  451. // Rewriting metadata
  452. template<typename MethodIterator>
  453. void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
  454. MethodIterator MethodEnd,
  455. bool IsInstanceMethod,
  456. StringRef prefix,
  457. StringRef ClassName,
  458. std::string &Result);
  459. void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
  460. StringRef prefix, StringRef ClassName,
  461. std::string &Result) override;
  462. void RewriteObjCProtocolListMetaData(
  463. const ObjCList<ObjCProtocolDecl> &Prots,
  464. StringRef prefix, StringRef ClassName, std::string &Result) override;
  465. void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
  466. std::string &Result) override;
  467. void RewriteMetaDataIntoBuffer(std::string &Result) override;
  468. void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
  469. std::string &Result) override;
  470. // Rewriting ivar
  471. void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
  472. std::string &Result) override;
  473. Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) override;
  474. };
  475. } // end anonymous namespace
  476. void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
  477. NamedDecl *D) {
  478. if (const FunctionProtoType *fproto
  479. = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
  480. for (const auto &I : fproto->param_types())
  481. if (isTopLevelBlockPointerType(I)) {
  482. // All the args are checked/rewritten. Don't call twice!
  483. RewriteBlockPointerDecl(D);
  484. break;
  485. }
  486. }
  487. }
  488. void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
  489. const PointerType *PT = funcType->getAs<PointerType>();
  490. if (PT && PointerTypeTakesAnyBlockArguments(funcType))
  491. RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
  492. }
  493. static bool IsHeaderFile(const std::string &Filename) {
  494. std::string::size_type DotPos = Filename.rfind('.');
  495. if (DotPos == std::string::npos) {
  496. // no file extension
  497. return false;
  498. }
  499. std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
  500. // C header: .h
  501. // C++ header: .hh or .H;
  502. return Ext == "h" || Ext == "hh" || Ext == "H";
  503. }
  504. RewriteObjC::RewriteObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
  505. DiagnosticsEngine &D, const LangOptions &LOpts,
  506. bool silenceMacroWarn)
  507. : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(std::move(OS)),
  508. SilenceRewriteMacroWarning(silenceMacroWarn) {
  509. IsHeader = IsHeaderFile(inFile);
  510. RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
  511. "rewriting sub-expression within a macro (may not be correct)");
  512. TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
  513. DiagnosticsEngine::Warning,
  514. "rewriter doesn't support user-specified control flow semantics "
  515. "for @try/@finally (code may not execute properly)");
  516. }
  517. std::unique_ptr<ASTConsumer>
  518. clang::CreateObjCRewriter(const std::string &InFile,
  519. std::unique_ptr<raw_ostream> OS,
  520. DiagnosticsEngine &Diags, const LangOptions &LOpts,
  521. bool SilenceRewriteMacroWarning) {
  522. return std::make_unique<RewriteObjCFragileABI>(
  523. InFile, std::move(OS), Diags, LOpts, SilenceRewriteMacroWarning);
  524. }
  525. void RewriteObjC::InitializeCommon(ASTContext &context) {
  526. Context = &context;
  527. SM = &Context->getSourceManager();
  528. TUDecl = Context->getTranslationUnitDecl();
  529. MsgSendFunctionDecl = nullptr;
  530. MsgSendSuperFunctionDecl = nullptr;
  531. MsgSendStretFunctionDecl = nullptr;
  532. MsgSendSuperStretFunctionDecl = nullptr;
  533. MsgSendFpretFunctionDecl = nullptr;
  534. GetClassFunctionDecl = nullptr;
  535. GetMetaClassFunctionDecl = nullptr;
  536. GetSuperClassFunctionDecl = nullptr;
  537. SelGetUidFunctionDecl = nullptr;
  538. CFStringFunctionDecl = nullptr;
  539. ConstantStringClassReference = nullptr;
  540. NSStringRecord = nullptr;
  541. CurMethodDef = nullptr;
  542. CurFunctionDef = nullptr;
  543. CurFunctionDeclToDeclareForBlock = nullptr;
  544. GlobalVarDecl = nullptr;
  545. SuperStructDecl = nullptr;
  546. ProtocolTypeDecl = nullptr;
  547. ConstantStringDecl = nullptr;
  548. BcLabelCount = 0;
  549. SuperConstructorFunctionDecl = nullptr;
  550. NumObjCStringLiterals = 0;
  551. PropParentMap = nullptr;
  552. CurrentBody = nullptr;
  553. DisableReplaceStmt = false;
  554. objc_impl_method = false;
  555. // Get the ID and start/end of the main file.
  556. MainFileID = SM->getMainFileID();
  557. const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
  558. MainFileStart = MainBuf->getBufferStart();
  559. MainFileEnd = MainBuf->getBufferEnd();
  560. Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
  561. }
  562. //===----------------------------------------------------------------------===//
  563. // Top Level Driver Code
  564. //===----------------------------------------------------------------------===//
  565. void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
  566. if (Diags.hasErrorOccurred())
  567. return;
  568. // Two cases: either the decl could be in the main file, or it could be in a
  569. // #included file. If the former, rewrite it now. If the later, check to see
  570. // if we rewrote the #include/#import.
  571. SourceLocation Loc = D->getLocation();
  572. Loc = SM->getExpansionLoc(Loc);
  573. // If this is for a builtin, ignore it.
  574. if (Loc.isInvalid()) return;
  575. // Look for built-in declarations that we need to refer during the rewrite.
  576. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  577. RewriteFunctionDecl(FD);
  578. } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
  579. // declared in <Foundation/NSString.h>
  580. if (FVD->getName() == "_NSConstantStringClassReference") {
  581. ConstantStringClassReference = FVD;
  582. return;
  583. }
  584. } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
  585. if (ID->isThisDeclarationADefinition())
  586. RewriteInterfaceDecl(ID);
  587. } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
  588. RewriteCategoryDecl(CD);
  589. } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
  590. if (PD->isThisDeclarationADefinition())
  591. RewriteProtocolDecl(PD);
  592. } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
  593. // Recurse into linkage specifications
  594. for (DeclContext::decl_iterator DI = LSD->decls_begin(),
  595. DIEnd = LSD->decls_end();
  596. DI != DIEnd; ) {
  597. if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
  598. if (!IFace->isThisDeclarationADefinition()) {
  599. SmallVector<Decl *, 8> DG;
  600. SourceLocation StartLoc = IFace->getBeginLoc();
  601. do {
  602. if (isa<ObjCInterfaceDecl>(*DI) &&
  603. !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
  604. StartLoc == (*DI)->getBeginLoc())
  605. DG.push_back(*DI);
  606. else
  607. break;
  608. ++DI;
  609. } while (DI != DIEnd);
  610. RewriteForwardClassDecl(DG);
  611. continue;
  612. }
  613. }
  614. if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
  615. if (!Proto->isThisDeclarationADefinition()) {
  616. SmallVector<Decl *, 8> DG;
  617. SourceLocation StartLoc = Proto->getBeginLoc();
  618. do {
  619. if (isa<ObjCProtocolDecl>(*DI) &&
  620. !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
  621. StartLoc == (*DI)->getBeginLoc())
  622. DG.push_back(*DI);
  623. else
  624. break;
  625. ++DI;
  626. } while (DI != DIEnd);
  627. RewriteForwardProtocolDecl(DG);
  628. continue;
  629. }
  630. }
  631. HandleTopLevelSingleDecl(*DI);
  632. ++DI;
  633. }
  634. }
  635. // If we have a decl in the main file, see if we should rewrite it.
  636. if (SM->isWrittenInMainFile(Loc))
  637. return HandleDeclInMainFile(D);
  638. }
  639. //===----------------------------------------------------------------------===//
  640. // Syntactic (non-AST) Rewriting Code
  641. //===----------------------------------------------------------------------===//
  642. void RewriteObjC::RewriteInclude() {
  643. SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
  644. StringRef MainBuf = SM->getBufferData(MainFileID);
  645. const char *MainBufStart = MainBuf.begin();
  646. const char *MainBufEnd = MainBuf.end();
  647. size_t ImportLen = strlen("import");
  648. // Loop over the whole file, looking for includes.
  649. for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
  650. if (*BufPtr == '#') {
  651. if (++BufPtr == MainBufEnd)
  652. return;
  653. while (*BufPtr == ' ' || *BufPtr == '\t')
  654. if (++BufPtr == MainBufEnd)
  655. return;
  656. if (!strncmp(BufPtr, "import", ImportLen)) {
  657. // replace import with include
  658. SourceLocation ImportLoc =
  659. LocStart.getLocWithOffset(BufPtr-MainBufStart);
  660. ReplaceText(ImportLoc, ImportLen, "include");
  661. BufPtr += ImportLen;
  662. }
  663. }
  664. }
  665. }
  666. static std::string getIvarAccessString(ObjCIvarDecl *OID) {
  667. const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
  668. std::string S;
  669. S = "((struct ";
  670. S += ClassDecl->getIdentifier()->getName();
  671. S += "_IMPL *)self)->";
  672. S += OID->getName();
  673. return S;
  674. }
  675. void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
  676. ObjCImplementationDecl *IMD,
  677. ObjCCategoryImplDecl *CID) {
  678. static bool objcGetPropertyDefined = false;
  679. static bool objcSetPropertyDefined = false;
  680. SourceLocation startLoc = PID->getBeginLoc();
  681. InsertText(startLoc, "// ");
  682. const char *startBuf = SM->getCharacterData(startLoc);
  683. assert((*startBuf == '@') && "bogus @synthesize location");
  684. const char *semiBuf = strchr(startBuf, ';');
  685. assert((*semiBuf == ';') && "@synthesize: can't find ';'");
  686. SourceLocation onePastSemiLoc =
  687. startLoc.getLocWithOffset(semiBuf-startBuf+1);
  688. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
  689. return; // FIXME: is this correct?
  690. // Generate the 'getter' function.
  691. ObjCPropertyDecl *PD = PID->getPropertyDecl();
  692. ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
  693. if (!OID)
  694. return;
  695. unsigned Attributes = PD->getPropertyAttributes();
  696. if (!PD->getGetterMethodDecl()->isDefined()) {
  697. bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
  698. (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
  699. ObjCPropertyDecl::OBJC_PR_copy));
  700. std::string Getr;
  701. if (GenGetProperty && !objcGetPropertyDefined) {
  702. objcGetPropertyDefined = true;
  703. // FIXME. Is this attribute correct in all cases?
  704. Getr = "\nextern \"C\" __declspec(dllimport) "
  705. "id objc_getProperty(id, SEL, long, bool);\n";
  706. }
  707. RewriteObjCMethodDecl(OID->getContainingInterface(),
  708. PD->getGetterMethodDecl(), Getr);
  709. Getr += "{ ";
  710. // Synthesize an explicit cast to gain access to the ivar.
  711. // See objc-act.c:objc_synthesize_new_getter() for details.
  712. if (GenGetProperty) {
  713. // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
  714. Getr += "typedef ";
  715. const FunctionType *FPRetType = nullptr;
  716. RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
  717. FPRetType);
  718. Getr += " _TYPE";
  719. if (FPRetType) {
  720. Getr += ")"; // close the precedence "scope" for "*".
  721. // Now, emit the argument types (if any).
  722. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
  723. Getr += "(";
  724. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  725. if (i) Getr += ", ";
  726. std::string ParamStr =
  727. FT->getParamType(i).getAsString(Context->getPrintingPolicy());
  728. Getr += ParamStr;
  729. }
  730. if (FT->isVariadic()) {
  731. if (FT->getNumParams())
  732. Getr += ", ";
  733. Getr += "...";
  734. }
  735. Getr += ")";
  736. } else
  737. Getr += "()";
  738. }
  739. Getr += ";\n";
  740. Getr += "return (_TYPE)";
  741. Getr += "objc_getProperty(self, _cmd, ";
  742. RewriteIvarOffsetComputation(OID, Getr);
  743. Getr += ", 1)";
  744. }
  745. else
  746. Getr += "return " + getIvarAccessString(OID);
  747. Getr += "; }";
  748. InsertText(onePastSemiLoc, Getr);
  749. }
  750. if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
  751. return;
  752. // Generate the 'setter' function.
  753. std::string Setr;
  754. bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
  755. ObjCPropertyDecl::OBJC_PR_copy);
  756. if (GenSetProperty && !objcSetPropertyDefined) {
  757. objcSetPropertyDefined = true;
  758. // FIXME. Is this attribute correct in all cases?
  759. Setr = "\nextern \"C\" __declspec(dllimport) "
  760. "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
  761. }
  762. RewriteObjCMethodDecl(OID->getContainingInterface(),
  763. PD->getSetterMethodDecl(), Setr);
  764. Setr += "{ ";
  765. // Synthesize an explicit cast to initialize the ivar.
  766. // See objc-act.c:objc_synthesize_new_setter() for details.
  767. if (GenSetProperty) {
  768. Setr += "objc_setProperty (self, _cmd, ";
  769. RewriteIvarOffsetComputation(OID, Setr);
  770. Setr += ", (id)";
  771. Setr += PD->getName();
  772. Setr += ", ";
  773. if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
  774. Setr += "0, ";
  775. else
  776. Setr += "1, ";
  777. if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
  778. Setr += "1)";
  779. else
  780. Setr += "0)";
  781. }
  782. else {
  783. Setr += getIvarAccessString(OID) + " = ";
  784. Setr += PD->getName();
  785. }
  786. Setr += "; }";
  787. InsertText(onePastSemiLoc, Setr);
  788. }
  789. static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
  790. std::string &typedefString) {
  791. typedefString += "#ifndef _REWRITER_typedef_";
  792. typedefString += ForwardDecl->getNameAsString();
  793. typedefString += "\n";
  794. typedefString += "#define _REWRITER_typedef_";
  795. typedefString += ForwardDecl->getNameAsString();
  796. typedefString += "\n";
  797. typedefString += "typedef struct objc_object ";
  798. typedefString += ForwardDecl->getNameAsString();
  799. typedefString += ";\n#endif\n";
  800. }
  801. void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
  802. const std::string &typedefString) {
  803. SourceLocation startLoc = ClassDecl->getBeginLoc();
  804. const char *startBuf = SM->getCharacterData(startLoc);
  805. const char *semiPtr = strchr(startBuf, ';');
  806. // Replace the @class with typedefs corresponding to the classes.
  807. ReplaceText(startLoc, semiPtr - startBuf + 1, typedefString);
  808. }
  809. void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
  810. std::string typedefString;
  811. for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
  812. ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
  813. if (I == D.begin()) {
  814. // Translate to typedef's that forward reference structs with the same name
  815. // as the class. As a convenience, we include the original declaration
  816. // as a comment.
  817. typedefString += "// @class ";
  818. typedefString += ForwardDecl->getNameAsString();
  819. typedefString += ";\n";
  820. }
  821. RewriteOneForwardClassDecl(ForwardDecl, typedefString);
  822. }
  823. DeclGroupRef::iterator I = D.begin();
  824. RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
  825. }
  826. void RewriteObjC::RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &D) {
  827. std::string typedefString;
  828. for (unsigned i = 0; i < D.size(); i++) {
  829. ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
  830. if (i == 0) {
  831. typedefString += "// @class ";
  832. typedefString += ForwardDecl->getNameAsString();
  833. typedefString += ";\n";
  834. }
  835. RewriteOneForwardClassDecl(ForwardDecl, typedefString);
  836. }
  837. RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
  838. }
  839. void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
  840. // When method is a synthesized one, such as a getter/setter there is
  841. // nothing to rewrite.
  842. if (Method->isImplicit())
  843. return;
  844. SourceLocation LocStart = Method->getBeginLoc();
  845. SourceLocation LocEnd = Method->getEndLoc();
  846. if (SM->getExpansionLineNumber(LocEnd) >
  847. SM->getExpansionLineNumber(LocStart)) {
  848. InsertText(LocStart, "#if 0\n");
  849. ReplaceText(LocEnd, 1, ";\n#endif\n");
  850. } else {
  851. InsertText(LocStart, "// ");
  852. }
  853. }
  854. void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
  855. SourceLocation Loc = prop->getAtLoc();
  856. ReplaceText(Loc, 0, "// ");
  857. // FIXME: handle properties that are declared across multiple lines.
  858. }
  859. void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
  860. SourceLocation LocStart = CatDecl->getBeginLoc();
  861. // FIXME: handle category headers that are declared across multiple lines.
  862. ReplaceText(LocStart, 0, "// ");
  863. for (auto *I : CatDecl->instance_properties())
  864. RewriteProperty(I);
  865. for (auto *I : CatDecl->instance_methods())
  866. RewriteMethodDeclaration(I);
  867. for (auto *I : CatDecl->class_methods())
  868. RewriteMethodDeclaration(I);
  869. // Lastly, comment out the @end.
  870. ReplaceText(CatDecl->getAtEndRange().getBegin(),
  871. strlen("@end"), "/* @end */");
  872. }
  873. void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
  874. SourceLocation LocStart = PDecl->getBeginLoc();
  875. assert(PDecl->isThisDeclarationADefinition());
  876. // FIXME: handle protocol headers that are declared across multiple lines.
  877. ReplaceText(LocStart, 0, "// ");
  878. for (auto *I : PDecl->instance_methods())
  879. RewriteMethodDeclaration(I);
  880. for (auto *I : PDecl->class_methods())
  881. RewriteMethodDeclaration(I);
  882. for (auto *I : PDecl->instance_properties())
  883. RewriteProperty(I);
  884. // Lastly, comment out the @end.
  885. SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
  886. ReplaceText(LocEnd, strlen("@end"), "/* @end */");
  887. // Must comment out @optional/@required
  888. const char *startBuf = SM->getCharacterData(LocStart);
  889. const char *endBuf = SM->getCharacterData(LocEnd);
  890. for (const char *p = startBuf; p < endBuf; p++) {
  891. if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
  892. SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
  893. ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
  894. }
  895. else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
  896. SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
  897. ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
  898. }
  899. }
  900. }
  901. void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
  902. SourceLocation LocStart = (*D.begin())->getBeginLoc();
  903. if (LocStart.isInvalid())
  904. llvm_unreachable("Invalid SourceLocation");
  905. // FIXME: handle forward protocol that are declared across multiple lines.
  906. ReplaceText(LocStart, 0, "// ");
  907. }
  908. void
  909. RewriteObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
  910. SourceLocation LocStart = DG[0]->getBeginLoc();
  911. if (LocStart.isInvalid())
  912. llvm_unreachable("Invalid SourceLocation");
  913. // FIXME: handle forward protocol that are declared across multiple lines.
  914. ReplaceText(LocStart, 0, "// ");
  915. }
  916. void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
  917. const FunctionType *&FPRetType) {
  918. if (T->isObjCQualifiedIdType())
  919. ResultStr += "id";
  920. else if (T->isFunctionPointerType() ||
  921. T->isBlockPointerType()) {
  922. // needs special handling, since pointer-to-functions have special
  923. // syntax (where a decaration models use).
  924. QualType retType = T;
  925. QualType PointeeTy;
  926. if (const PointerType* PT = retType->getAs<PointerType>())
  927. PointeeTy = PT->getPointeeType();
  928. else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
  929. PointeeTy = BPT->getPointeeType();
  930. if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
  931. ResultStr +=
  932. FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
  933. ResultStr += "(*";
  934. }
  935. } else
  936. ResultStr += T.getAsString(Context->getPrintingPolicy());
  937. }
  938. void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
  939. ObjCMethodDecl *OMD,
  940. std::string &ResultStr) {
  941. //fprintf(stderr,"In RewriteObjCMethodDecl\n");
  942. const FunctionType *FPRetType = nullptr;
  943. ResultStr += "\nstatic ";
  944. RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
  945. ResultStr += " ";
  946. // Unique method name
  947. std::string NameStr;
  948. if (OMD->isInstanceMethod())
  949. NameStr += "_I_";
  950. else
  951. NameStr += "_C_";
  952. NameStr += IDecl->getNameAsString();
  953. NameStr += "_";
  954. if (ObjCCategoryImplDecl *CID =
  955. dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
  956. NameStr += CID->getNameAsString();
  957. NameStr += "_";
  958. }
  959. // Append selector names, replacing ':' with '_'
  960. {
  961. std::string selString = OMD->getSelector().getAsString();
  962. int len = selString.size();
  963. for (int i = 0; i < len; i++)
  964. if (selString[i] == ':')
  965. selString[i] = '_';
  966. NameStr += selString;
  967. }
  968. // Remember this name for metadata emission
  969. MethodInternalNames[OMD] = NameStr;
  970. ResultStr += NameStr;
  971. // Rewrite arguments
  972. ResultStr += "(";
  973. // invisible arguments
  974. if (OMD->isInstanceMethod()) {
  975. QualType selfTy = Context->getObjCInterfaceType(IDecl);
  976. selfTy = Context->getPointerType(selfTy);
  977. if (!LangOpts.MicrosoftExt) {
  978. if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
  979. ResultStr += "struct ";
  980. }
  981. // When rewriting for Microsoft, explicitly omit the structure name.
  982. ResultStr += IDecl->getNameAsString();
  983. ResultStr += " *";
  984. }
  985. else
  986. ResultStr += Context->getObjCClassType().getAsString(
  987. Context->getPrintingPolicy());
  988. ResultStr += " self, ";
  989. ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
  990. ResultStr += " _cmd";
  991. // Method arguments.
  992. for (const auto *PDecl : OMD->parameters()) {
  993. ResultStr += ", ";
  994. if (PDecl->getType()->isObjCQualifiedIdType()) {
  995. ResultStr += "id ";
  996. ResultStr += PDecl->getNameAsString();
  997. } else {
  998. std::string Name = PDecl->getNameAsString();
  999. QualType QT = PDecl->getType();
  1000. // Make sure we convert "t (^)(...)" to "t (*)(...)".
  1001. (void)convertBlockPointerToFunctionPointer(QT);
  1002. QT.getAsStringInternal(Name, Context->getPrintingPolicy());
  1003. ResultStr += Name;
  1004. }
  1005. }
  1006. if (OMD->isVariadic())
  1007. ResultStr += ", ...";
  1008. ResultStr += ") ";
  1009. if (FPRetType) {
  1010. ResultStr += ")"; // close the precedence "scope" for "*".
  1011. // Now, emit the argument types (if any).
  1012. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
  1013. ResultStr += "(";
  1014. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  1015. if (i) ResultStr += ", ";
  1016. std::string ParamStr =
  1017. FT->getParamType(i).getAsString(Context->getPrintingPolicy());
  1018. ResultStr += ParamStr;
  1019. }
  1020. if (FT->isVariadic()) {
  1021. if (FT->getNumParams())
  1022. ResultStr += ", ";
  1023. ResultStr += "...";
  1024. }
  1025. ResultStr += ")";
  1026. } else {
  1027. ResultStr += "()";
  1028. }
  1029. }
  1030. }
  1031. void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
  1032. ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
  1033. ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
  1034. InsertText(IMD ? IMD->getBeginLoc() : CID->getBeginLoc(), "// ");
  1035. for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
  1036. std::string ResultStr;
  1037. RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
  1038. SourceLocation LocStart = OMD->getBeginLoc();
  1039. SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
  1040. const char *startBuf = SM->getCharacterData(LocStart);
  1041. const char *endBuf = SM->getCharacterData(LocEnd);
  1042. ReplaceText(LocStart, endBuf-startBuf, ResultStr);
  1043. }
  1044. for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
  1045. std::string ResultStr;
  1046. RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
  1047. SourceLocation LocStart = OMD->getBeginLoc();
  1048. SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
  1049. const char *startBuf = SM->getCharacterData(LocStart);
  1050. const char *endBuf = SM->getCharacterData(LocEnd);
  1051. ReplaceText(LocStart, endBuf-startBuf, ResultStr);
  1052. }
  1053. for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
  1054. RewritePropertyImplDecl(I, IMD, CID);
  1055. InsertText(IMD ? IMD->getEndLoc() : CID->getEndLoc(), "// ");
  1056. }
  1057. void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
  1058. std::string ResultStr;
  1059. if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
  1060. // we haven't seen a forward decl - generate a typedef.
  1061. ResultStr = "#ifndef _REWRITER_typedef_";
  1062. ResultStr += ClassDecl->getNameAsString();
  1063. ResultStr += "\n";
  1064. ResultStr += "#define _REWRITER_typedef_";
  1065. ResultStr += ClassDecl->getNameAsString();
  1066. ResultStr += "\n";
  1067. ResultStr += "typedef struct objc_object ";
  1068. ResultStr += ClassDecl->getNameAsString();
  1069. ResultStr += ";\n#endif\n";
  1070. // Mark this typedef as having been generated.
  1071. ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
  1072. }
  1073. RewriteObjCInternalStruct(ClassDecl, ResultStr);
  1074. for (auto *I : ClassDecl->instance_properties())
  1075. RewriteProperty(I);
  1076. for (auto *I : ClassDecl->instance_methods())
  1077. RewriteMethodDeclaration(I);
  1078. for (auto *I : ClassDecl->class_methods())
  1079. RewriteMethodDeclaration(I);
  1080. // Lastly, comment out the @end.
  1081. ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
  1082. "/* @end */");
  1083. }
  1084. Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
  1085. SourceRange OldRange = PseudoOp->getSourceRange();
  1086. // We just magically know some things about the structure of this
  1087. // expression.
  1088. ObjCMessageExpr *OldMsg =
  1089. cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
  1090. PseudoOp->getNumSemanticExprs() - 1));
  1091. // Because the rewriter doesn't allow us to rewrite rewritten code,
  1092. // we need to suppress rewriting the sub-statements.
  1093. Expr *Base, *RHS;
  1094. {
  1095. DisableReplaceStmtScope S(*this);
  1096. // Rebuild the base expression if we have one.
  1097. Base = nullptr;
  1098. if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
  1099. Base = OldMsg->getInstanceReceiver();
  1100. Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
  1101. Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
  1102. }
  1103. // Rebuild the RHS.
  1104. RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
  1105. RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
  1106. RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
  1107. }
  1108. // TODO: avoid this copy.
  1109. SmallVector<SourceLocation, 1> SelLocs;
  1110. OldMsg->getSelectorLocs(SelLocs);
  1111. ObjCMessageExpr *NewMsg = nullptr;
  1112. switch (OldMsg->getReceiverKind()) {
  1113. case ObjCMessageExpr::Class:
  1114. NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
  1115. OldMsg->getValueKind(),
  1116. OldMsg->getLeftLoc(),
  1117. OldMsg->getClassReceiverTypeInfo(),
  1118. OldMsg->getSelector(),
  1119. SelLocs,
  1120. OldMsg->getMethodDecl(),
  1121. RHS,
  1122. OldMsg->getRightLoc(),
  1123. OldMsg->isImplicit());
  1124. break;
  1125. case ObjCMessageExpr::Instance:
  1126. NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
  1127. OldMsg->getValueKind(),
  1128. OldMsg->getLeftLoc(),
  1129. Base,
  1130. OldMsg->getSelector(),
  1131. SelLocs,
  1132. OldMsg->getMethodDecl(),
  1133. RHS,
  1134. OldMsg->getRightLoc(),
  1135. OldMsg->isImplicit());
  1136. break;
  1137. case ObjCMessageExpr::SuperClass:
  1138. case ObjCMessageExpr::SuperInstance:
  1139. NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
  1140. OldMsg->getValueKind(),
  1141. OldMsg->getLeftLoc(),
  1142. OldMsg->getSuperLoc(),
  1143. OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
  1144. OldMsg->getSuperType(),
  1145. OldMsg->getSelector(),
  1146. SelLocs,
  1147. OldMsg->getMethodDecl(),
  1148. RHS,
  1149. OldMsg->getRightLoc(),
  1150. OldMsg->isImplicit());
  1151. break;
  1152. }
  1153. Stmt *Replacement = SynthMessageExpr(NewMsg);
  1154. ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
  1155. return Replacement;
  1156. }
  1157. Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
  1158. SourceRange OldRange = PseudoOp->getSourceRange();
  1159. // We just magically know some things about the structure of this
  1160. // expression.
  1161. ObjCMessageExpr *OldMsg =
  1162. cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
  1163. // Because the rewriter doesn't allow us to rewrite rewritten code,
  1164. // we need to suppress rewriting the sub-statements.
  1165. Expr *Base = nullptr;
  1166. {
  1167. DisableReplaceStmtScope S(*this);
  1168. // Rebuild the base expression if we have one.
  1169. if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
  1170. Base = OldMsg->getInstanceReceiver();
  1171. Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
  1172. Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
  1173. }
  1174. }
  1175. // Intentionally empty.
  1176. SmallVector<SourceLocation, 1> SelLocs;
  1177. SmallVector<Expr*, 1> Args;
  1178. ObjCMessageExpr *NewMsg = nullptr;
  1179. switch (OldMsg->getReceiverKind()) {
  1180. case ObjCMessageExpr::Class:
  1181. NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
  1182. OldMsg->getValueKind(),
  1183. OldMsg->getLeftLoc(),
  1184. OldMsg->getClassReceiverTypeInfo(),
  1185. OldMsg->getSelector(),
  1186. SelLocs,
  1187. OldMsg->getMethodDecl(),
  1188. Args,
  1189. OldMsg->getRightLoc(),
  1190. OldMsg->isImplicit());
  1191. break;
  1192. case ObjCMessageExpr::Instance:
  1193. NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
  1194. OldMsg->getValueKind(),
  1195. OldMsg->getLeftLoc(),
  1196. Base,
  1197. OldMsg->getSelector(),
  1198. SelLocs,
  1199. OldMsg->getMethodDecl(),
  1200. Args,
  1201. OldMsg->getRightLoc(),
  1202. OldMsg->isImplicit());
  1203. break;
  1204. case ObjCMessageExpr::SuperClass:
  1205. case ObjCMessageExpr::SuperInstance:
  1206. NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
  1207. OldMsg->getValueKind(),
  1208. OldMsg->getLeftLoc(),
  1209. OldMsg->getSuperLoc(),
  1210. OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
  1211. OldMsg->getSuperType(),
  1212. OldMsg->getSelector(),
  1213. SelLocs,
  1214. OldMsg->getMethodDecl(),
  1215. Args,
  1216. OldMsg->getRightLoc(),
  1217. OldMsg->isImplicit());
  1218. break;
  1219. }
  1220. Stmt *Replacement = SynthMessageExpr(NewMsg);
  1221. ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
  1222. return Replacement;
  1223. }
  1224. /// SynthCountByEnumWithState - To print:
  1225. /// ((unsigned int (*)
  1226. /// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
  1227. /// (void *)objc_msgSend)((id)l_collection,
  1228. /// sel_registerName(
  1229. /// "countByEnumeratingWithState:objects:count:"),
  1230. /// &enumState,
  1231. /// (id *)__rw_items, (unsigned int)16)
  1232. ///
  1233. void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
  1234. buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
  1235. "id *, unsigned int))(void *)objc_msgSend)";
  1236. buf += "\n\t\t";
  1237. buf += "((id)l_collection,\n\t\t";
  1238. buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
  1239. buf += "\n\t\t";
  1240. buf += "&enumState, "
  1241. "(id *)__rw_items, (unsigned int)16)";
  1242. }
  1243. /// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
  1244. /// statement to exit to its outer synthesized loop.
  1245. ///
  1246. Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
  1247. if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
  1248. return S;
  1249. // replace break with goto __break_label
  1250. std::string buf;
  1251. SourceLocation startLoc = S->getBeginLoc();
  1252. buf = "goto __break_label_";
  1253. buf += utostr(ObjCBcLabelNo.back());
  1254. ReplaceText(startLoc, strlen("break"), buf);
  1255. return nullptr;
  1256. }
  1257. /// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
  1258. /// statement to continue with its inner synthesized loop.
  1259. ///
  1260. Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
  1261. if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
  1262. return S;
  1263. // replace continue with goto __continue_label
  1264. std::string buf;
  1265. SourceLocation startLoc = S->getBeginLoc();
  1266. buf = "goto __continue_label_";
  1267. buf += utostr(ObjCBcLabelNo.back());
  1268. ReplaceText(startLoc, strlen("continue"), buf);
  1269. return nullptr;
  1270. }
  1271. /// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
  1272. /// It rewrites:
  1273. /// for ( type elem in collection) { stmts; }
  1274. /// Into:
  1275. /// {
  1276. /// type elem;
  1277. /// struct __objcFastEnumerationState enumState = { 0 };
  1278. /// id __rw_items[16];
  1279. /// id l_collection = (id)collection;
  1280. /// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
  1281. /// objects:__rw_items count:16];
  1282. /// if (limit) {
  1283. /// unsigned long startMutations = *enumState.mutationsPtr;
  1284. /// do {
  1285. /// unsigned long counter = 0;
  1286. /// do {
  1287. /// if (startMutations != *enumState.mutationsPtr)
  1288. /// objc_enumerationMutation(l_collection);
  1289. /// elem = (type)enumState.itemsPtr[counter++];
  1290. /// stmts;
  1291. /// __continue_label: ;
  1292. /// } while (counter < limit);
  1293. /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
  1294. /// objects:__rw_items count:16]);
  1295. /// elem = nil;
  1296. /// __break_label: ;
  1297. /// }
  1298. /// else
  1299. /// elem = nil;
  1300. /// }
  1301. ///
  1302. Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
  1303. SourceLocation OrigEnd) {
  1304. assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
  1305. assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
  1306. "ObjCForCollectionStmt Statement stack mismatch");
  1307. assert(!ObjCBcLabelNo.empty() &&
  1308. "ObjCForCollectionStmt - Label No stack empty");
  1309. SourceLocation startLoc = S->getBeginLoc();
  1310. const char *startBuf = SM->getCharacterData(startLoc);
  1311. StringRef elementName;
  1312. std::string elementTypeAsString;
  1313. std::string buf;
  1314. buf = "\n{\n\t";
  1315. if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
  1316. // type elem;
  1317. NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
  1318. QualType ElementType = cast<ValueDecl>(D)->getType();
  1319. if (ElementType->isObjCQualifiedIdType() ||
  1320. ElementType->isObjCQualifiedInterfaceType())
  1321. // Simply use 'id' for all qualified types.
  1322. elementTypeAsString = "id";
  1323. else
  1324. elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
  1325. buf += elementTypeAsString;
  1326. buf += " ";
  1327. elementName = D->getName();
  1328. buf += elementName;
  1329. buf += ";\n\t";
  1330. }
  1331. else {
  1332. DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
  1333. elementName = DR->getDecl()->getName();
  1334. ValueDecl *VD = DR->getDecl();
  1335. if (VD->getType()->isObjCQualifiedIdType() ||
  1336. VD->getType()->isObjCQualifiedInterfaceType())
  1337. // Simply use 'id' for all qualified types.
  1338. elementTypeAsString = "id";
  1339. else
  1340. elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
  1341. }
  1342. // struct __objcFastEnumerationState enumState = { 0 };
  1343. buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
  1344. // id __rw_items[16];
  1345. buf += "id __rw_items[16];\n\t";
  1346. // id l_collection = (id)
  1347. buf += "id l_collection = (id)";
  1348. // Find start location of 'collection' the hard way!
  1349. const char *startCollectionBuf = startBuf;
  1350. startCollectionBuf += 3; // skip 'for'
  1351. startCollectionBuf = strchr(startCollectionBuf, '(');
  1352. startCollectionBuf++; // skip '('
  1353. // find 'in' and skip it.
  1354. while (*startCollectionBuf != ' ' ||
  1355. *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
  1356. (*(startCollectionBuf+3) != ' ' &&
  1357. *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
  1358. startCollectionBuf++;
  1359. startCollectionBuf += 3;
  1360. // Replace: "for (type element in" with string constructed thus far.
  1361. ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
  1362. // Replace ')' in for '(' type elem in collection ')' with ';'
  1363. SourceLocation rightParenLoc = S->getRParenLoc();
  1364. const char *rparenBuf = SM->getCharacterData(rightParenLoc);
  1365. SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
  1366. buf = ";\n\t";
  1367. // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
  1368. // objects:__rw_items count:16];
  1369. // which is synthesized into:
  1370. // unsigned int limit =
  1371. // ((unsigned int (*)
  1372. // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
  1373. // (void *)objc_msgSend)((id)l_collection,
  1374. // sel_registerName(
  1375. // "countByEnumeratingWithState:objects:count:"),
  1376. // (struct __objcFastEnumerationState *)&state,
  1377. // (id *)__rw_items, (unsigned int)16);
  1378. buf += "unsigned long limit =\n\t\t";
  1379. SynthCountByEnumWithState(buf);
  1380. buf += ";\n\t";
  1381. /// if (limit) {
  1382. /// unsigned long startMutations = *enumState.mutationsPtr;
  1383. /// do {
  1384. /// unsigned long counter = 0;
  1385. /// do {
  1386. /// if (startMutations != *enumState.mutationsPtr)
  1387. /// objc_enumerationMutation(l_collection);
  1388. /// elem = (type)enumState.itemsPtr[counter++];
  1389. buf += "if (limit) {\n\t";
  1390. buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
  1391. buf += "do {\n\t\t";
  1392. buf += "unsigned long counter = 0;\n\t\t";
  1393. buf += "do {\n\t\t\t";
  1394. buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
  1395. buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
  1396. buf += elementName;
  1397. buf += " = (";
  1398. buf += elementTypeAsString;
  1399. buf += ")enumState.itemsPtr[counter++];";
  1400. // Replace ')' in for '(' type elem in collection ')' with all of these.
  1401. ReplaceText(lparenLoc, 1, buf);
  1402. /// __continue_label: ;
  1403. /// } while (counter < limit);
  1404. /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
  1405. /// objects:__rw_items count:16]);
  1406. /// elem = nil;
  1407. /// __break_label: ;
  1408. /// }
  1409. /// else
  1410. /// elem = nil;
  1411. /// }
  1412. ///
  1413. buf = ";\n\t";
  1414. buf += "__continue_label_";
  1415. buf += utostr(ObjCBcLabelNo.back());
  1416. buf += ": ;";
  1417. buf += "\n\t\t";
  1418. buf += "} while (counter < limit);\n\t";
  1419. buf += "} while (limit = ";
  1420. SynthCountByEnumWithState(buf);
  1421. buf += ");\n\t";
  1422. buf += elementName;
  1423. buf += " = ((";
  1424. buf += elementTypeAsString;
  1425. buf += ")0);\n\t";
  1426. buf += "__break_label_";
  1427. buf += utostr(ObjCBcLabelNo.back());
  1428. buf += ": ;\n\t";
  1429. buf += "}\n\t";
  1430. buf += "else\n\t\t";
  1431. buf += elementName;
  1432. buf += " = ((";
  1433. buf += elementTypeAsString;
  1434. buf += ")0);\n\t";
  1435. buf += "}\n";
  1436. // Insert all these *after* the statement body.
  1437. // FIXME: If this should support Obj-C++, support CXXTryStmt
  1438. if (isa<CompoundStmt>(S->getBody())) {
  1439. SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
  1440. InsertText(endBodyLoc, buf);
  1441. } else {
  1442. /* Need to treat single statements specially. For example:
  1443. *
  1444. * for (A *a in b) if (stuff()) break;
  1445. * for (A *a in b) xxxyy;
  1446. *
  1447. * The following code simply scans ahead to the semi to find the actual end.
  1448. */
  1449. const char *stmtBuf = SM->getCharacterData(OrigEnd);
  1450. const char *semiBuf = strchr(stmtBuf, ';');
  1451. assert(semiBuf && "Can't find ';'");
  1452. SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
  1453. InsertText(endBodyLoc, buf);
  1454. }
  1455. Stmts.pop_back();
  1456. ObjCBcLabelNo.pop_back();
  1457. return nullptr;
  1458. }
  1459. /// RewriteObjCSynchronizedStmt -
  1460. /// This routine rewrites @synchronized(expr) stmt;
  1461. /// into:
  1462. /// objc_sync_enter(expr);
  1463. /// @try stmt @finally { objc_sync_exit(expr); }
  1464. ///
  1465. Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
  1466. // Get the start location and compute the semi location.
  1467. SourceLocation startLoc = S->getBeginLoc();
  1468. const char *startBuf = SM->getCharacterData(startLoc);
  1469. assert((*startBuf == '@') && "bogus @synchronized location");
  1470. std::string buf;
  1471. buf = "objc_sync_enter((id)";
  1472. const char *lparenBuf = startBuf;
  1473. while (*lparenBuf != '(') lparenBuf++;
  1474. ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
  1475. // We can't use S->getSynchExpr()->getEndLoc() to find the end location, since
  1476. // the sync expression is typically a message expression that's already
  1477. // been rewritten! (which implies the SourceLocation's are invalid).
  1478. SourceLocation endLoc = S->getSynchBody()->getBeginLoc();
  1479. const char *endBuf = SM->getCharacterData(endLoc);
  1480. while (*endBuf != ')') endBuf--;
  1481. SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
  1482. buf = ");\n";
  1483. // declare a new scope with two variables, _stack and _rethrow.
  1484. buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
  1485. buf += "int buf[18/*32-bit i386*/];\n";
  1486. buf += "char *pointers[4];} _stack;\n";
  1487. buf += "id volatile _rethrow = 0;\n";
  1488. buf += "objc_exception_try_enter(&_stack);\n";
  1489. buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
  1490. ReplaceText(rparenLoc, 1, buf);
  1491. startLoc = S->getSynchBody()->getEndLoc();
  1492. startBuf = SM->getCharacterData(startLoc);
  1493. assert((*startBuf == '}') && "bogus @synchronized block");
  1494. SourceLocation lastCurlyLoc = startLoc;
  1495. buf = "}\nelse {\n";
  1496. buf += " _rethrow = objc_exception_extract(&_stack);\n";
  1497. buf += "}\n";
  1498. buf += "{ /* implicit finally clause */\n";
  1499. buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
  1500. std::string syncBuf;
  1501. syncBuf += " objc_sync_exit(";
  1502. Expr *syncExpr = S->getSynchExpr();
  1503. CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
  1504. ? CK_BitCast :
  1505. syncExpr->getType()->isBlockPointerType()
  1506. ? CK_BlockPointerToObjCPointerCast
  1507. : CK_CPointerToObjCPointerCast;
  1508. syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
  1509. CK, syncExpr);
  1510. std::string syncExprBufS;
  1511. llvm::raw_string_ostream syncExprBuf(syncExprBufS);
  1512. assert(syncExpr != nullptr && "Expected non-null Expr");
  1513. syncExpr->printPretty(syncExprBuf, nullptr, PrintingPolicy(LangOpts));
  1514. syncBuf += syncExprBuf.str();
  1515. syncBuf += ");";
  1516. buf += syncBuf;
  1517. buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
  1518. buf += "}\n";
  1519. buf += "}";
  1520. ReplaceText(lastCurlyLoc, 1, buf);
  1521. bool hasReturns = false;
  1522. HasReturnStmts(S->getSynchBody(), hasReturns);
  1523. if (hasReturns)
  1524. RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
  1525. return nullptr;
  1526. }
  1527. void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
  1528. {
  1529. // Perform a bottom up traversal of all children.
  1530. for (Stmt *SubStmt : S->children())
  1531. if (SubStmt)
  1532. WarnAboutReturnGotoStmts(SubStmt);
  1533. if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
  1534. Diags.Report(Context->getFullLoc(S->getBeginLoc()),
  1535. TryFinallyContainsReturnDiag);
  1536. }
  1537. }
  1538. void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
  1539. {
  1540. // Perform a bottom up traversal of all children.
  1541. for (Stmt *SubStmt : S->children())
  1542. if (SubStmt)
  1543. HasReturnStmts(SubStmt, hasReturns);
  1544. if (isa<ReturnStmt>(S))
  1545. hasReturns = true;
  1546. }
  1547. void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
  1548. // Perform a bottom up traversal of all children.
  1549. for (Stmt *SubStmt : S->children())
  1550. if (SubStmt) {
  1551. RewriteTryReturnStmts(SubStmt);
  1552. }
  1553. if (isa<ReturnStmt>(S)) {
  1554. SourceLocation startLoc = S->getBeginLoc();
  1555. const char *startBuf = SM->getCharacterData(startLoc);
  1556. const char *semiBuf = strchr(startBuf, ';');
  1557. assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
  1558. SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
  1559. std::string buf;
  1560. buf = "{ objc_exception_try_exit(&_stack); return";
  1561. ReplaceText(startLoc, 6, buf);
  1562. InsertText(onePastSemiLoc, "}");
  1563. }
  1564. }
  1565. void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
  1566. // Perform a bottom up traversal of all children.
  1567. for (Stmt *SubStmt : S->children())
  1568. if (SubStmt) {
  1569. RewriteSyncReturnStmts(SubStmt, syncExitBuf);
  1570. }
  1571. if (isa<ReturnStmt>(S)) {
  1572. SourceLocation startLoc = S->getBeginLoc();
  1573. const char *startBuf = SM->getCharacterData(startLoc);
  1574. const char *semiBuf = strchr(startBuf, ';');
  1575. assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
  1576. SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
  1577. std::string buf;
  1578. buf = "{ objc_exception_try_exit(&_stack);";
  1579. buf += syncExitBuf;
  1580. buf += " return";
  1581. ReplaceText(startLoc, 6, buf);
  1582. InsertText(onePastSemiLoc, "}");
  1583. }
  1584. }
  1585. Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
  1586. // Get the start location and compute the semi location.
  1587. SourceLocation startLoc = S->getBeginLoc();
  1588. const char *startBuf = SM->getCharacterData(startLoc);
  1589. assert((*startBuf == '@') && "bogus @try location");
  1590. std::string buf;
  1591. // declare a new scope with two variables, _stack and _rethrow.
  1592. buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
  1593. buf += "int buf[18/*32-bit i386*/];\n";
  1594. buf += "char *pointers[4];} _stack;\n";
  1595. buf += "id volatile _rethrow = 0;\n";
  1596. buf += "objc_exception_try_enter(&_stack);\n";
  1597. buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
  1598. ReplaceText(startLoc, 4, buf);
  1599. startLoc = S->getTryBody()->getEndLoc();
  1600. startBuf = SM->getCharacterData(startLoc);
  1601. assert((*startBuf == '}') && "bogus @try block");
  1602. SourceLocation lastCurlyLoc = startLoc;
  1603. if (S->getNumCatchStmts()) {
  1604. startLoc = startLoc.getLocWithOffset(1);
  1605. buf = " /* @catch begin */ else {\n";
  1606. buf += " id _caught = objc_exception_extract(&_stack);\n";
  1607. buf += " objc_exception_try_enter (&_stack);\n";
  1608. buf += " if (_setjmp(_stack.buf))\n";
  1609. buf += " _rethrow = objc_exception_extract(&_stack);\n";
  1610. buf += " else { /* @catch continue */";
  1611. InsertText(startLoc, buf);
  1612. } else { /* no catch list */
  1613. buf = "}\nelse {\n";
  1614. buf += " _rethrow = objc_exception_extract(&_stack);\n";
  1615. buf += "}";
  1616. ReplaceText(lastCurlyLoc, 1, buf);
  1617. }
  1618. Stmt *lastCatchBody = nullptr;
  1619. for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
  1620. ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
  1621. VarDecl *catchDecl = Catch->getCatchParamDecl();
  1622. if (I == 0)
  1623. buf = "if ("; // we are generating code for the first catch clause
  1624. else
  1625. buf = "else if (";
  1626. startLoc = Catch->getBeginLoc();
  1627. startBuf = SM->getCharacterData(startLoc);
  1628. assert((*startBuf == '@') && "bogus @catch location");
  1629. const char *lParenLoc = strchr(startBuf, '(');
  1630. if (Catch->hasEllipsis()) {
  1631. // Now rewrite the body...
  1632. lastCatchBody = Catch->getCatchBody();
  1633. SourceLocation bodyLoc = lastCatchBody->getBeginLoc();
  1634. const char *bodyBuf = SM->getCharacterData(bodyLoc);
  1635. assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
  1636. "bogus @catch paren location");
  1637. assert((*bodyBuf == '{') && "bogus @catch body location");
  1638. buf += "1) { id _tmp = _caught;";
  1639. Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
  1640. } else if (catchDecl) {
  1641. QualType t = catchDecl->getType();
  1642. if (t == Context->getObjCIdType()) {
  1643. buf += "1) { ";
  1644. ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
  1645. } else if (const ObjCObjectPointerType *Ptr =
  1646. t->getAs<ObjCObjectPointerType>()) {
  1647. // Should be a pointer to a class.
  1648. ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
  1649. if (IDecl) {
  1650. buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
  1651. buf += IDecl->getNameAsString();
  1652. buf += "\"), (struct objc_object *)_caught)) { ";
  1653. ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
  1654. }
  1655. }
  1656. // Now rewrite the body...
  1657. lastCatchBody = Catch->getCatchBody();
  1658. SourceLocation rParenLoc = Catch->getRParenLoc();
  1659. SourceLocation bodyLoc = lastCatchBody->getBeginLoc();
  1660. const char *bodyBuf = SM->getCharacterData(bodyLoc);
  1661. const char *rParenBuf = SM->getCharacterData(rParenLoc);
  1662. assert((*rParenBuf == ')') && "bogus @catch paren location");
  1663. assert((*bodyBuf == '{') && "bogus @catch body location");
  1664. // Here we replace ") {" with "= _caught;" (which initializes and
  1665. // declares the @catch parameter).
  1666. ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
  1667. } else {
  1668. llvm_unreachable("@catch rewrite bug");
  1669. }
  1670. }
  1671. // Complete the catch list...
  1672. if (lastCatchBody) {
  1673. SourceLocation bodyLoc = lastCatchBody->getEndLoc();
  1674. assert(*SM->getCharacterData(bodyLoc) == '}' &&
  1675. "bogus @catch body location");
  1676. // Insert the last (implicit) else clause *before* the right curly brace.
  1677. bodyLoc = bodyLoc.getLocWithOffset(-1);
  1678. buf = "} /* last catch end */\n";
  1679. buf += "else {\n";
  1680. buf += " _rethrow = _caught;\n";
  1681. buf += " objc_exception_try_exit(&_stack);\n";
  1682. buf += "} } /* @catch end */\n";
  1683. if (!S->getFinallyStmt())
  1684. buf += "}\n";
  1685. InsertText(bodyLoc, buf);
  1686. // Set lastCurlyLoc
  1687. lastCurlyLoc = lastCatchBody->getEndLoc();
  1688. }
  1689. if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
  1690. startLoc = finalStmt->getBeginLoc();
  1691. startBuf = SM->getCharacterData(startLoc);
  1692. assert((*startBuf == '@') && "bogus @finally start");
  1693. ReplaceText(startLoc, 8, "/* @finally */");
  1694. Stmt *body = finalStmt->getFinallyBody();
  1695. SourceLocation startLoc = body->getBeginLoc();
  1696. SourceLocation endLoc = body->getEndLoc();
  1697. assert(*SM->getCharacterData(startLoc) == '{' &&
  1698. "bogus @finally body location");
  1699. assert(*SM->getCharacterData(endLoc) == '}' &&
  1700. "bogus @finally body location");
  1701. startLoc = startLoc.getLocWithOffset(1);
  1702. InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
  1703. endLoc = endLoc.getLocWithOffset(-1);
  1704. InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
  1705. // Set lastCurlyLoc
  1706. lastCurlyLoc = body->getEndLoc();
  1707. // Now check for any return/continue/go statements within the @try.
  1708. WarnAboutReturnGotoStmts(S->getTryBody());
  1709. } else { /* no finally clause - make sure we synthesize an implicit one */
  1710. buf = "{ /* implicit finally clause */\n";
  1711. buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
  1712. buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
  1713. buf += "}";
  1714. ReplaceText(lastCurlyLoc, 1, buf);
  1715. // Now check for any return/continue/go statements within the @try.
  1716. // The implicit finally clause won't called if the @try contains any
  1717. // jump statements.
  1718. bool hasReturns = false;
  1719. HasReturnStmts(S->getTryBody(), hasReturns);
  1720. if (hasReturns)
  1721. RewriteTryReturnStmts(S->getTryBody());
  1722. }
  1723. // Now emit the final closing curly brace...
  1724. lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
  1725. InsertText(lastCurlyLoc, " } /* @try scope end */\n");
  1726. return nullptr;
  1727. }
  1728. // This can't be done with ReplaceStmt(S, ThrowExpr), since
  1729. // the throw expression is typically a message expression that's already
  1730. // been rewritten! (which implies the SourceLocation's are invalid).
  1731. Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
  1732. // Get the start location and compute the semi location.
  1733. SourceLocation startLoc = S->getBeginLoc();
  1734. const char *startBuf = SM->getCharacterData(startLoc);
  1735. assert((*startBuf == '@') && "bogus @throw location");
  1736. std::string buf;
  1737. /* void objc_exception_throw(id) __attribute__((noreturn)); */
  1738. if (S->getThrowExpr())
  1739. buf = "objc_exception_throw(";
  1740. else // add an implicit argument
  1741. buf = "objc_exception_throw(_caught";
  1742. // handle "@ throw" correctly.
  1743. const char *wBuf = strchr(startBuf, 'w');
  1744. assert((*wBuf == 'w') && "@throw: can't find 'w'");
  1745. ReplaceText(startLoc, wBuf-startBuf+1, buf);
  1746. const char *semiBuf = strchr(startBuf, ';');
  1747. assert((*semiBuf == ';') && "@throw: can't find ';'");
  1748. SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
  1749. ReplaceText(semiLoc, 1, ");");
  1750. return nullptr;
  1751. }
  1752. Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
  1753. // Create a new string expression.
  1754. std::string StrEncoding;
  1755. Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
  1756. Expr *Replacement = getStringLiteral(StrEncoding);
  1757. ReplaceStmt(Exp, Replacement);
  1758. // Replace this subexpr in the parent.
  1759. // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
  1760. return Replacement;
  1761. }
  1762. Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
  1763. if (!SelGetUidFunctionDecl)
  1764. SynthSelGetUidFunctionDecl();
  1765. assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
  1766. // Create a call to sel_registerName("selName").
  1767. SmallVector<Expr*, 8> SelExprs;
  1768. SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
  1769. CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
  1770. SelExprs);
  1771. ReplaceStmt(Exp, SelExp);
  1772. // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
  1773. return SelExp;
  1774. }
  1775. CallExpr *
  1776. RewriteObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
  1777. ArrayRef<Expr *> Args,
  1778. SourceLocation StartLoc,
  1779. SourceLocation EndLoc) {
  1780. // Get the type, we will need to reference it in a couple spots.
  1781. QualType msgSendType = FD->getType();
  1782. // Create a reference to the objc_msgSend() declaration.
  1783. DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, FD, false, msgSendType,
  1784. VK_LValue, SourceLocation());
  1785. // Now, we cast the reference to a pointer to the objc_msgSend type.
  1786. QualType pToFunc = Context->getPointerType(msgSendType);
  1787. ImplicitCastExpr *ICE =
  1788. ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
  1789. DRE, nullptr, VK_RValue);
  1790. const FunctionType *FT = msgSendType->getAs<FunctionType>();
  1791. CallExpr *Exp = CallExpr::Create(
  1792. *Context, ICE, Args, FT->getCallResultType(*Context), VK_RValue, EndLoc);
  1793. return Exp;
  1794. }
  1795. static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
  1796. const char *&startRef, const char *&endRef) {
  1797. while (startBuf < endBuf) {
  1798. if (*startBuf == '<')
  1799. startRef = startBuf; // mark the start.
  1800. if (*startBuf == '>') {
  1801. if (startRef && *startRef == '<') {
  1802. endRef = startBuf; // mark the end.
  1803. return true;
  1804. }
  1805. return false;
  1806. }
  1807. startBuf++;
  1808. }
  1809. return false;
  1810. }
  1811. static void scanToNextArgument(const char *&argRef) {
  1812. int angle = 0;
  1813. while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
  1814. if (*argRef == '<')
  1815. angle++;
  1816. else if (*argRef == '>')
  1817. angle--;
  1818. argRef++;
  1819. }
  1820. assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
  1821. }
  1822. bool RewriteObjC::needToScanForQualifiers(QualType T) {
  1823. if (T->isObjCQualifiedIdType())
  1824. return true;
  1825. if (const PointerType *PT = T->getAs<PointerType>()) {
  1826. if (PT->getPointeeType()->isObjCQualifiedIdType())
  1827. return true;
  1828. }
  1829. if (T->isObjCObjectPointerType()) {
  1830. T = T->getPointeeType();
  1831. return T->isObjCQualifiedInterfaceType();
  1832. }
  1833. if (T->isArrayType()) {
  1834. QualType ElemTy = Context->getBaseElementType(T);
  1835. return needToScanForQualifiers(ElemTy);
  1836. }
  1837. return false;
  1838. }
  1839. void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
  1840. QualType Type = E->getType();
  1841. if (needToScanForQualifiers(Type)) {
  1842. SourceLocation Loc, EndLoc;
  1843. if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
  1844. Loc = ECE->getLParenLoc();
  1845. EndLoc = ECE->getRParenLoc();
  1846. } else {
  1847. Loc = E->getBeginLoc();
  1848. EndLoc = E->getEndLoc();
  1849. }
  1850. // This will defend against trying to rewrite synthesized expressions.
  1851. if (Loc.isInvalid() || EndLoc.isInvalid())
  1852. return;
  1853. const char *startBuf = SM->getCharacterData(Loc);
  1854. const char *endBuf = SM->getCharacterData(EndLoc);
  1855. const char *startRef = nullptr, *endRef = nullptr;
  1856. if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
  1857. // Get the locations of the startRef, endRef.
  1858. SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
  1859. SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
  1860. // Comment out the protocol references.
  1861. InsertText(LessLoc, "/*");
  1862. InsertText(GreaterLoc, "*/");
  1863. }
  1864. }
  1865. }
  1866. void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
  1867. SourceLocation Loc;
  1868. QualType Type;
  1869. const FunctionProtoType *proto = nullptr;
  1870. if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
  1871. Loc = VD->getLocation();
  1872. Type = VD->getType();
  1873. }
  1874. else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
  1875. Loc = FD->getLocation();
  1876. // Check for ObjC 'id' and class types that have been adorned with protocol
  1877. // information (id<p>, C<p>*). The protocol references need to be rewritten!
  1878. const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
  1879. assert(funcType && "missing function type");
  1880. proto = dyn_cast<FunctionProtoType>(funcType);
  1881. if (!proto)
  1882. return;
  1883. Type = proto->getReturnType();
  1884. }
  1885. else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
  1886. Loc = FD->getLocation();
  1887. Type = FD->getType();
  1888. }
  1889. else
  1890. return;
  1891. if (needToScanForQualifiers(Type)) {
  1892. // Since types are unique, we need to scan the buffer.
  1893. const char *endBuf = SM->getCharacterData(Loc);
  1894. const char *startBuf = endBuf;
  1895. while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
  1896. startBuf--; // scan backward (from the decl location) for return type.
  1897. const char *startRef = nullptr, *endRef = nullptr;
  1898. if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
  1899. // Get the locations of the startRef, endRef.
  1900. SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
  1901. SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
  1902. // Comment out the protocol references.
  1903. InsertText(LessLoc, "/*");
  1904. InsertText(GreaterLoc, "*/");
  1905. }
  1906. }
  1907. if (!proto)
  1908. return; // most likely, was a variable
  1909. // Now check arguments.
  1910. const char *startBuf = SM->getCharacterData(Loc);
  1911. const char *startFuncBuf = startBuf;
  1912. for (unsigned i = 0; i < proto->getNumParams(); i++) {
  1913. if (needToScanForQualifiers(proto->getParamType(i))) {
  1914. // Since types are unique, we need to scan the buffer.
  1915. const char *endBuf = startBuf;
  1916. // scan forward (from the decl location) for argument types.
  1917. scanToNextArgument(endBuf);
  1918. const char *startRef = nullptr, *endRef = nullptr;
  1919. if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
  1920. // Get the locations of the startRef, endRef.
  1921. SourceLocation LessLoc =
  1922. Loc.getLocWithOffset(startRef-startFuncBuf);
  1923. SourceLocation GreaterLoc =
  1924. Loc.getLocWithOffset(endRef-startFuncBuf+1);
  1925. // Comment out the protocol references.
  1926. InsertText(LessLoc, "/*");
  1927. InsertText(GreaterLoc, "*/");
  1928. }
  1929. startBuf = ++endBuf;
  1930. }
  1931. else {
  1932. // If the function name is derived from a macro expansion, then the
  1933. // argument buffer will not follow the name. Need to speak with Chris.
  1934. while (*startBuf && *startBuf != ')' && *startBuf != ',')
  1935. startBuf++; // scan forward (from the decl location) for argument types.
  1936. startBuf++;
  1937. }
  1938. }
  1939. }
  1940. void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
  1941. QualType QT = ND->getType();
  1942. const Type* TypePtr = QT->getAs<Type>();
  1943. if (!isa<TypeOfExprType>(TypePtr))
  1944. return;
  1945. while (isa<TypeOfExprType>(TypePtr)) {
  1946. const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
  1947. QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
  1948. TypePtr = QT->getAs<Type>();
  1949. }
  1950. // FIXME. This will not work for multiple declarators; as in:
  1951. // __typeof__(a) b,c,d;
  1952. std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
  1953. SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
  1954. const char *startBuf = SM->getCharacterData(DeclLoc);
  1955. if (ND->getInit()) {
  1956. std::string Name(ND->getNameAsString());
  1957. TypeAsString += " " + Name + " = ";
  1958. Expr *E = ND->getInit();
  1959. SourceLocation startLoc;
  1960. if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
  1961. startLoc = ECE->getLParenLoc();
  1962. else
  1963. startLoc = E->getBeginLoc();
  1964. startLoc = SM->getExpansionLoc(startLoc);
  1965. const char *endBuf = SM->getCharacterData(startLoc);
  1966. ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
  1967. }
  1968. else {
  1969. SourceLocation X = ND->getEndLoc();
  1970. X = SM->getExpansionLoc(X);
  1971. const char *endBuf = SM->getCharacterData(X);
  1972. ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
  1973. }
  1974. }
  1975. // SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
  1976. void RewriteObjC::SynthSelGetUidFunctionDecl() {
  1977. IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
  1978. SmallVector<QualType, 16> ArgTys;
  1979. ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
  1980. QualType getFuncType =
  1981. getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
  1982. SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
  1983. SourceLocation(),
  1984. SourceLocation(),
  1985. SelGetUidIdent, getFuncType,
  1986. nullptr, SC_Extern);
  1987. }
  1988. void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
  1989. // declared in <objc/objc.h>
  1990. if (FD->getIdentifier() &&
  1991. FD->getName() == "sel_registerName") {
  1992. SelGetUidFunctionDecl = FD;
  1993. return;
  1994. }
  1995. RewriteObjCQualifiedInterfaceTypes(FD);
  1996. }
  1997. void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
  1998. std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
  1999. const char *argPtr = TypeString.c_str();
  2000. if (!strchr(argPtr, '^')) {
  2001. Str += TypeString;
  2002. return;
  2003. }
  2004. while (*argPtr) {
  2005. Str += (*argPtr == '^' ? '*' : *argPtr);
  2006. argPtr++;
  2007. }
  2008. }
  2009. // FIXME. Consolidate this routine with RewriteBlockPointerType.
  2010. void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
  2011. ValueDecl *VD) {
  2012. QualType Type = VD->getType();
  2013. std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
  2014. const char *argPtr = TypeString.c_str();
  2015. int paren = 0;
  2016. while (*argPtr) {
  2017. switch (*argPtr) {
  2018. case '(':
  2019. Str += *argPtr;
  2020. paren++;
  2021. break;
  2022. case ')':
  2023. Str += *argPtr;
  2024. paren--;
  2025. break;
  2026. case '^':
  2027. Str += '*';
  2028. if (paren == 1)
  2029. Str += VD->getNameAsString();
  2030. break;
  2031. default:
  2032. Str += *argPtr;
  2033. break;
  2034. }
  2035. argPtr++;
  2036. }
  2037. }
  2038. void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
  2039. SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
  2040. const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
  2041. const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
  2042. if (!proto)
  2043. return;
  2044. QualType Type = proto->getReturnType();
  2045. std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
  2046. FdStr += " ";
  2047. FdStr += FD->getName();
  2048. FdStr += "(";
  2049. unsigned numArgs = proto->getNumParams();
  2050. for (unsigned i = 0; i < numArgs; i++) {
  2051. QualType ArgType = proto->getParamType(i);
  2052. RewriteBlockPointerType(FdStr, ArgType);
  2053. if (i+1 < numArgs)
  2054. FdStr += ", ";
  2055. }
  2056. FdStr += ");\n";
  2057. InsertText(FunLocStart, FdStr);
  2058. CurFunctionDeclToDeclareForBlock = nullptr;
  2059. }
  2060. // SynthSuperConstructorFunctionDecl - id objc_super(id obj, id super);
  2061. void RewriteObjC::SynthSuperConstructorFunctionDecl() {
  2062. if (SuperConstructorFunctionDecl)
  2063. return;
  2064. IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
  2065. SmallVector<QualType, 16> ArgTys;
  2066. QualType argT = Context->getObjCIdType();
  2067. assert(!argT.isNull() && "Can't find 'id' type");
  2068. ArgTys.push_back(argT);
  2069. ArgTys.push_back(argT);
  2070. QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
  2071. ArgTys);
  2072. SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
  2073. SourceLocation(),
  2074. SourceLocation(),
  2075. msgSendIdent, msgSendType,
  2076. nullptr, SC_Extern);
  2077. }
  2078. // SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
  2079. void RewriteObjC::SynthMsgSendFunctionDecl() {
  2080. IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
  2081. SmallVector<QualType, 16> ArgTys;
  2082. QualType argT = Context->getObjCIdType();
  2083. assert(!argT.isNull() && "Can't find 'id' type");
  2084. ArgTys.push_back(argT);
  2085. argT = Context->getObjCSelType();
  2086. assert(!argT.isNull() && "Can't find 'SEL' type");
  2087. ArgTys.push_back(argT);
  2088. QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
  2089. ArgTys, /*variadic=*/true);
  2090. MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
  2091. SourceLocation(),
  2092. SourceLocation(),
  2093. msgSendIdent, msgSendType,
  2094. nullptr, SC_Extern);
  2095. }
  2096. // SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
  2097. void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
  2098. IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
  2099. SmallVector<QualType, 16> ArgTys;
  2100. RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
  2101. SourceLocation(), SourceLocation(),
  2102. &Context->Idents.get("objc_super"));
  2103. QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
  2104. assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
  2105. ArgTys.push_back(argT);
  2106. argT = Context->getObjCSelType();
  2107. assert(!argT.isNull() && "Can't find 'SEL' type");
  2108. ArgTys.push_back(argT);
  2109. QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
  2110. ArgTys, /*variadic=*/true);
  2111. MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
  2112. SourceLocation(),
  2113. SourceLocation(),
  2114. msgSendIdent, msgSendType,
  2115. nullptr, SC_Extern);
  2116. }
  2117. // SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
  2118. void RewriteObjC::SynthMsgSendStretFunctionDecl() {
  2119. IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
  2120. SmallVector<QualType, 16> ArgTys;
  2121. QualType argT = Context->getObjCIdType();
  2122. assert(!argT.isNull() && "Can't find 'id' type");
  2123. ArgTys.push_back(argT);
  2124. argT = Context->getObjCSelType();
  2125. assert(!argT.isNull() && "Can't find 'SEL' type");
  2126. ArgTys.push_back(argT);
  2127. QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
  2128. ArgTys, /*variadic=*/true);
  2129. MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
  2130. SourceLocation(),
  2131. SourceLocation(),
  2132. msgSendIdent, msgSendType,
  2133. nullptr, SC_Extern);
  2134. }
  2135. // SynthMsgSendSuperStretFunctionDecl -
  2136. // id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
  2137. void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
  2138. IdentifierInfo *msgSendIdent =
  2139. &Context->Idents.get("objc_msgSendSuper_stret");
  2140. SmallVector<QualType, 16> ArgTys;
  2141. RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
  2142. SourceLocation(), SourceLocation(),
  2143. &Context->Idents.get("objc_super"));
  2144. QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
  2145. assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
  2146. ArgTys.push_back(argT);
  2147. argT = Context->getObjCSelType();
  2148. assert(!argT.isNull() && "Can't find 'SEL' type");
  2149. ArgTys.push_back(argT);
  2150. QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
  2151. ArgTys, /*variadic=*/true);
  2152. MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
  2153. SourceLocation(),
  2154. SourceLocation(),
  2155. msgSendIdent,
  2156. msgSendType, nullptr,
  2157. SC_Extern);
  2158. }
  2159. // SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
  2160. void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
  2161. IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
  2162. SmallVector<QualType, 16> ArgTys;
  2163. QualType argT = Context->getObjCIdType();
  2164. assert(!argT.isNull() && "Can't find 'id' type");
  2165. ArgTys.push_back(argT);
  2166. argT = Context->getObjCSelType();
  2167. assert(!argT.isNull() && "Can't find 'SEL' type");
  2168. ArgTys.push_back(argT);
  2169. QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
  2170. ArgTys, /*variadic=*/true);
  2171. MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
  2172. SourceLocation(),
  2173. SourceLocation(),
  2174. msgSendIdent, msgSendType,
  2175. nullptr, SC_Extern);
  2176. }
  2177. // SynthGetClassFunctionDecl - id objc_getClass(const char *name);
  2178. void RewriteObjC::SynthGetClassFunctionDecl() {
  2179. IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
  2180. SmallVector<QualType, 16> ArgTys;
  2181. ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
  2182. QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
  2183. ArgTys);
  2184. GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
  2185. SourceLocation(),
  2186. SourceLocation(),
  2187. getClassIdent, getClassType,
  2188. nullptr, SC_Extern);
  2189. }
  2190. // SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
  2191. void RewriteObjC::SynthGetSuperClassFunctionDecl() {
  2192. IdentifierInfo *getSuperClassIdent =
  2193. &Context->Idents.get("class_getSuperclass");
  2194. SmallVector<QualType, 16> ArgTys;
  2195. ArgTys.push_back(Context->getObjCClassType());
  2196. QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
  2197. ArgTys);
  2198. GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
  2199. SourceLocation(),
  2200. SourceLocation(),
  2201. getSuperClassIdent,
  2202. getClassType, nullptr,
  2203. SC_Extern);
  2204. }
  2205. // SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
  2206. void RewriteObjC::SynthGetMetaClassFunctionDecl() {
  2207. IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
  2208. SmallVector<QualType, 16> ArgTys;
  2209. ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
  2210. QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
  2211. ArgTys);
  2212. GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
  2213. SourceLocation(),
  2214. SourceLocation(),
  2215. getClassIdent, getClassType,
  2216. nullptr, SC_Extern);
  2217. }
  2218. Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
  2219. assert(Exp != nullptr && "Expected non-null ObjCStringLiteral");
  2220. QualType strType = getConstantStringStructType();
  2221. std::string S = "__NSConstantStringImpl_";
  2222. std::string tmpName = InFileName;
  2223. unsigned i;
  2224. for (i=0; i < tmpName.length(); i++) {
  2225. char c = tmpName.at(i);
  2226. // replace any non-alphanumeric characters with '_'.
  2227. if (!isAlphanumeric(c))
  2228. tmpName[i] = '_';
  2229. }
  2230. S += tmpName;
  2231. S += "_";
  2232. S += utostr(NumObjCStringLiterals++);
  2233. Preamble += "static __NSConstantStringImpl " + S;
  2234. Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
  2235. Preamble += "0x000007c8,"; // utf8_str
  2236. // The pretty printer for StringLiteral handles escape characters properly.
  2237. std::string prettyBufS;
  2238. llvm::raw_string_ostream prettyBuf(prettyBufS);
  2239. Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
  2240. Preamble += prettyBuf.str();
  2241. Preamble += ",";
  2242. Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
  2243. VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
  2244. SourceLocation(), &Context->Idents.get(S),
  2245. strType, nullptr, SC_Static);
  2246. DeclRefExpr *DRE = new (Context)
  2247. DeclRefExpr(*Context, NewVD, false, strType, VK_LValue, SourceLocation());
  2248. Expr *Unop = new (Context)
  2249. UnaryOperator(DRE, UO_AddrOf, Context->getPointerType(DRE->getType()),
  2250. VK_RValue, OK_Ordinary, SourceLocation(), false);
  2251. // cast to NSConstantString *
  2252. CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
  2253. CK_CPointerToObjCPointerCast, Unop);
  2254. ReplaceStmt(Exp, cast);
  2255. // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
  2256. return cast;
  2257. }
  2258. // struct objc_super { struct objc_object *receiver; struct objc_class *super; };
  2259. QualType RewriteObjC::getSuperStructType() {
  2260. if (!SuperStructDecl) {
  2261. SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
  2262. SourceLocation(), SourceLocation(),
  2263. &Context->Idents.get("objc_super"));
  2264. QualType FieldTypes[2];
  2265. // struct objc_object *receiver;
  2266. FieldTypes[0] = Context->getObjCIdType();
  2267. // struct objc_class *super;
  2268. FieldTypes[1] = Context->getObjCClassType();
  2269. // Create fields
  2270. for (unsigned i = 0; i < 2; ++i) {
  2271. SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
  2272. SourceLocation(),
  2273. SourceLocation(), nullptr,
  2274. FieldTypes[i], nullptr,
  2275. /*BitWidth=*/nullptr,
  2276. /*Mutable=*/false,
  2277. ICIS_NoInit));
  2278. }
  2279. SuperStructDecl->completeDefinition();
  2280. }
  2281. return Context->getTagDeclType(SuperStructDecl);
  2282. }
  2283. QualType RewriteObjC::getConstantStringStructType() {
  2284. if (!ConstantStringDecl) {
  2285. ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
  2286. SourceLocation(), SourceLocation(),
  2287. &Context->Idents.get("__NSConstantStringImpl"));
  2288. QualType FieldTypes[4];
  2289. // struct objc_object *receiver;
  2290. FieldTypes[0] = Context->getObjCIdType();
  2291. // int flags;
  2292. FieldTypes[1] = Context->IntTy;
  2293. // char *str;
  2294. FieldTypes[2] = Context->getPointerType(Context->CharTy);
  2295. // long length;
  2296. FieldTypes[3] = Context->LongTy;
  2297. // Create fields
  2298. for (unsigned i = 0; i < 4; ++i) {
  2299. ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
  2300. ConstantStringDecl,
  2301. SourceLocation(),
  2302. SourceLocation(), nullptr,
  2303. FieldTypes[i], nullptr,
  2304. /*BitWidth=*/nullptr,
  2305. /*Mutable=*/true,
  2306. ICIS_NoInit));
  2307. }
  2308. ConstantStringDecl->completeDefinition();
  2309. }
  2310. return Context->getTagDeclType(ConstantStringDecl);
  2311. }
  2312. CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
  2313. QualType msgSendType,
  2314. QualType returnType,
  2315. SmallVectorImpl<QualType> &ArgTypes,
  2316. SmallVectorImpl<Expr*> &MsgExprs,
  2317. ObjCMethodDecl *Method) {
  2318. // Create a reference to the objc_msgSend_stret() declaration.
  2319. DeclRefExpr *STDRE =
  2320. new (Context) DeclRefExpr(*Context, MsgSendStretFlavor, false,
  2321. msgSendType, VK_LValue, SourceLocation());
  2322. // Need to cast objc_msgSend_stret to "void *" (see above comment).
  2323. CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
  2324. Context->getPointerType(Context->VoidTy),
  2325. CK_BitCast, STDRE);
  2326. // Now do the "normal" pointer to function cast.
  2327. QualType castType = getSimpleFunctionType(returnType, ArgTypes,
  2328. Method ? Method->isVariadic()
  2329. : false);
  2330. castType = Context->getPointerType(castType);
  2331. cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
  2332. cast);
  2333. // Don't forget the parens to enforce the proper binding.
  2334. ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
  2335. const FunctionType *FT = msgSendType->getAs<FunctionType>();
  2336. CallExpr *STCE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
  2337. VK_RValue, SourceLocation());
  2338. return STCE;
  2339. }
  2340. Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
  2341. SourceLocation StartLoc,
  2342. SourceLocation EndLoc) {
  2343. if (!SelGetUidFunctionDecl)
  2344. SynthSelGetUidFunctionDecl();
  2345. if (!MsgSendFunctionDecl)
  2346. SynthMsgSendFunctionDecl();
  2347. if (!MsgSendSuperFunctionDecl)
  2348. SynthMsgSendSuperFunctionDecl();
  2349. if (!MsgSendStretFunctionDecl)
  2350. SynthMsgSendStretFunctionDecl();
  2351. if (!MsgSendSuperStretFunctionDecl)
  2352. SynthMsgSendSuperStretFunctionDecl();
  2353. if (!MsgSendFpretFunctionDecl)
  2354. SynthMsgSendFpretFunctionDecl();
  2355. if (!GetClassFunctionDecl)
  2356. SynthGetClassFunctionDecl();
  2357. if (!GetSuperClassFunctionDecl)
  2358. SynthGetSuperClassFunctionDecl();
  2359. if (!GetMetaClassFunctionDecl)
  2360. SynthGetMetaClassFunctionDecl();
  2361. // default to objc_msgSend().
  2362. FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
  2363. // May need to use objc_msgSend_stret() as well.
  2364. FunctionDecl *MsgSendStretFlavor = nullptr;
  2365. if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
  2366. QualType resultType = mDecl->getReturnType();
  2367. if (resultType->isRecordType())
  2368. MsgSendStretFlavor = MsgSendStretFunctionDecl;
  2369. else if (resultType->isRealFloatingType())
  2370. MsgSendFlavor = MsgSendFpretFunctionDecl;
  2371. }
  2372. // Synthesize a call to objc_msgSend().
  2373. SmallVector<Expr*, 8> MsgExprs;
  2374. switch (Exp->getReceiverKind()) {
  2375. case ObjCMessageExpr::SuperClass: {
  2376. MsgSendFlavor = MsgSendSuperFunctionDecl;
  2377. if (MsgSendStretFlavor)
  2378. MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
  2379. assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
  2380. ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
  2381. SmallVector<Expr*, 4> InitExprs;
  2382. // set the receiver to self, the first argument to all methods.
  2383. InitExprs.push_back(
  2384. NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
  2385. CK_BitCast,
  2386. new (Context) DeclRefExpr(*Context,
  2387. CurMethodDef->getSelfDecl(),
  2388. false,
  2389. Context->getObjCIdType(),
  2390. VK_RValue,
  2391. SourceLocation()))
  2392. ); // set the 'receiver'.
  2393. // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
  2394. SmallVector<Expr*, 8> ClsExprs;
  2395. ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
  2396. CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
  2397. ClsExprs, StartLoc, EndLoc);
  2398. // (Class)objc_getClass("CurrentClass")
  2399. CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
  2400. Context->getObjCClassType(),
  2401. CK_BitCast, Cls);
  2402. ClsExprs.clear();
  2403. ClsExprs.push_back(ArgExpr);
  2404. Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
  2405. StartLoc, EndLoc);
  2406. // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
  2407. // To turn off a warning, type-cast to 'id'
  2408. InitExprs.push_back( // set 'super class', using class_getSuperclass().
  2409. NoTypeInfoCStyleCastExpr(Context,
  2410. Context->getObjCIdType(),
  2411. CK_BitCast, Cls));
  2412. // struct objc_super
  2413. QualType superType = getSuperStructType();
  2414. Expr *SuperRep;
  2415. if (LangOpts.MicrosoftExt) {
  2416. SynthSuperConstructorFunctionDecl();
  2417. // Simulate a constructor call...
  2418. DeclRefExpr *DRE = new (Context)
  2419. DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
  2420. VK_LValue, SourceLocation());
  2421. SuperRep = CallExpr::Create(*Context, DRE, InitExprs, superType,
  2422. VK_LValue, SourceLocation());
  2423. // The code for super is a little tricky to prevent collision with
  2424. // the structure definition in the header. The rewriter has it's own
  2425. // internal definition (__rw_objc_super) that is uses. This is why
  2426. // we need the cast below. For example:
  2427. // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
  2428. //
  2429. SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
  2430. Context->getPointerType(SuperRep->getType()),
  2431. VK_RValue, OK_Ordinary,
  2432. SourceLocation(), false);
  2433. SuperRep = NoTypeInfoCStyleCastExpr(Context,
  2434. Context->getPointerType(superType),
  2435. CK_BitCast, SuperRep);
  2436. } else {
  2437. // (struct objc_super) { <exprs from above> }
  2438. InitListExpr *ILE =
  2439. new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
  2440. SourceLocation());
  2441. TypeSourceInfo *superTInfo
  2442. = Context->getTrivialTypeSourceInfo(superType);
  2443. SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
  2444. superType, VK_LValue,
  2445. ILE, false);
  2446. // struct objc_super *
  2447. SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
  2448. Context->getPointerType(SuperRep->getType()),
  2449. VK_RValue, OK_Ordinary,
  2450. SourceLocation(), false);
  2451. }
  2452. MsgExprs.push_back(SuperRep);
  2453. break;
  2454. }
  2455. case ObjCMessageExpr::Class: {
  2456. SmallVector<Expr*, 8> ClsExprs;
  2457. ObjCInterfaceDecl *Class
  2458. = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
  2459. IdentifierInfo *clsName = Class->getIdentifier();
  2460. ClsExprs.push_back(getStringLiteral(clsName->getName()));
  2461. CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
  2462. StartLoc, EndLoc);
  2463. MsgExprs.push_back(Cls);
  2464. break;
  2465. }
  2466. case ObjCMessageExpr::SuperInstance:{
  2467. MsgSendFlavor = MsgSendSuperFunctionDecl;
  2468. if (MsgSendStretFlavor)
  2469. MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
  2470. assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
  2471. ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
  2472. SmallVector<Expr*, 4> InitExprs;
  2473. InitExprs.push_back(
  2474. NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
  2475. CK_BitCast,
  2476. new (Context) DeclRefExpr(*Context,
  2477. CurMethodDef->getSelfDecl(),
  2478. false,
  2479. Context->getObjCIdType(),
  2480. VK_RValue, SourceLocation()))
  2481. ); // set the 'receiver'.
  2482. // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
  2483. SmallVector<Expr*, 8> ClsExprs;
  2484. ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
  2485. CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
  2486. StartLoc, EndLoc);
  2487. // (Class)objc_getClass("CurrentClass")
  2488. CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
  2489. Context->getObjCClassType(),
  2490. CK_BitCast, Cls);
  2491. ClsExprs.clear();
  2492. ClsExprs.push_back(ArgExpr);
  2493. Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
  2494. StartLoc, EndLoc);
  2495. // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
  2496. // To turn off a warning, type-cast to 'id'
  2497. InitExprs.push_back(
  2498. // set 'super class', using class_getSuperclass().
  2499. NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
  2500. CK_BitCast, Cls));
  2501. // struct objc_super
  2502. QualType superType = getSuperStructType();
  2503. Expr *SuperRep;
  2504. if (LangOpts.MicrosoftExt) {
  2505. SynthSuperConstructorFunctionDecl();
  2506. // Simulate a constructor call...
  2507. DeclRefExpr *DRE = new (Context)
  2508. DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
  2509. VK_LValue, SourceLocation());
  2510. SuperRep = CallExpr::Create(*Context, DRE, InitExprs, superType,
  2511. VK_LValue, SourceLocation());
  2512. // The code for super is a little tricky to prevent collision with
  2513. // the structure definition in the header. The rewriter has it's own
  2514. // internal definition (__rw_objc_super) that is uses. This is why
  2515. // we need the cast below. For example:
  2516. // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
  2517. //
  2518. SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
  2519. Context->getPointerType(SuperRep->getType()),
  2520. VK_RValue, OK_Ordinary,
  2521. SourceLocation(), false);
  2522. SuperRep = NoTypeInfoCStyleCastExpr(Context,
  2523. Context->getPointerType(superType),
  2524. CK_BitCast, SuperRep);
  2525. } else {
  2526. // (struct objc_super) { <exprs from above> }
  2527. InitListExpr *ILE =
  2528. new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
  2529. SourceLocation());
  2530. TypeSourceInfo *superTInfo
  2531. = Context->getTrivialTypeSourceInfo(superType);
  2532. SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
  2533. superType, VK_RValue, ILE,
  2534. false);
  2535. }
  2536. MsgExprs.push_back(SuperRep);
  2537. break;
  2538. }
  2539. case ObjCMessageExpr::Instance: {
  2540. // Remove all type-casts because it may contain objc-style types; e.g.
  2541. // Foo<Proto> *.
  2542. Expr *recExpr = Exp->getInstanceReceiver();
  2543. while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
  2544. recExpr = CE->getSubExpr();
  2545. CastKind CK = recExpr->getType()->isObjCObjectPointerType()
  2546. ? CK_BitCast : recExpr->getType()->isBlockPointerType()
  2547. ? CK_BlockPointerToObjCPointerCast
  2548. : CK_CPointerToObjCPointerCast;
  2549. recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
  2550. CK, recExpr);
  2551. MsgExprs.push_back(recExpr);
  2552. break;
  2553. }
  2554. }
  2555. // Create a call to sel_registerName("selName"), it will be the 2nd argument.
  2556. SmallVector<Expr*, 8> SelExprs;
  2557. SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
  2558. CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
  2559. SelExprs, StartLoc, EndLoc);
  2560. MsgExprs.push_back(SelExp);
  2561. // Now push any user supplied arguments.
  2562. for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
  2563. Expr *userExpr = Exp->getArg(i);
  2564. // Make all implicit casts explicit...ICE comes in handy:-)
  2565. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
  2566. // Reuse the ICE type, it is exactly what the doctor ordered.
  2567. QualType type = ICE->getType();
  2568. if (needToScanForQualifiers(type))
  2569. type = Context->getObjCIdType();
  2570. // Make sure we convert "type (^)(...)" to "type (*)(...)".
  2571. (void)convertBlockPointerToFunctionPointer(type);
  2572. const Expr *SubExpr = ICE->IgnoreParenImpCasts();
  2573. CastKind CK;
  2574. if (SubExpr->getType()->isIntegralType(*Context) &&
  2575. type->isBooleanType()) {
  2576. CK = CK_IntegralToBoolean;
  2577. } else if (type->isObjCObjectPointerType()) {
  2578. if (SubExpr->getType()->isBlockPointerType()) {
  2579. CK = CK_BlockPointerToObjCPointerCast;
  2580. } else if (SubExpr->getType()->isPointerType()) {
  2581. CK = CK_CPointerToObjCPointerCast;
  2582. } else {
  2583. CK = CK_BitCast;
  2584. }
  2585. } else {
  2586. CK = CK_BitCast;
  2587. }
  2588. userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
  2589. }
  2590. // Make id<P...> cast into an 'id' cast.
  2591. else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
  2592. if (CE->getType()->isObjCQualifiedIdType()) {
  2593. while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
  2594. userExpr = CE->getSubExpr();
  2595. CastKind CK;
  2596. if (userExpr->getType()->isIntegralType(*Context)) {
  2597. CK = CK_IntegralToPointer;
  2598. } else if (userExpr->getType()->isBlockPointerType()) {
  2599. CK = CK_BlockPointerToObjCPointerCast;
  2600. } else if (userExpr->getType()->isPointerType()) {
  2601. CK = CK_CPointerToObjCPointerCast;
  2602. } else {
  2603. CK = CK_BitCast;
  2604. }
  2605. userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
  2606. CK, userExpr);
  2607. }
  2608. }
  2609. MsgExprs.push_back(userExpr);
  2610. // We've transferred the ownership to MsgExprs. For now, we *don't* null
  2611. // out the argument in the original expression (since we aren't deleting
  2612. // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
  2613. //Exp->setArg(i, 0);
  2614. }
  2615. // Generate the funky cast.
  2616. CastExpr *cast;
  2617. SmallVector<QualType, 8> ArgTypes;
  2618. QualType returnType;
  2619. // Push 'id' and 'SEL', the 2 implicit arguments.
  2620. if (MsgSendFlavor == MsgSendSuperFunctionDecl)
  2621. ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
  2622. else
  2623. ArgTypes.push_back(Context->getObjCIdType());
  2624. ArgTypes.push_back(Context->getObjCSelType());
  2625. if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
  2626. // Push any user argument types.
  2627. for (const auto *PI : OMD->parameters()) {
  2628. QualType t = PI->getType()->isObjCQualifiedIdType()
  2629. ? Context->getObjCIdType()
  2630. : PI->getType();
  2631. // Make sure we convert "t (^)(...)" to "t (*)(...)".
  2632. (void)convertBlockPointerToFunctionPointer(t);
  2633. ArgTypes.push_back(t);
  2634. }
  2635. returnType = Exp->getType();
  2636. convertToUnqualifiedObjCType(returnType);
  2637. (void)convertBlockPointerToFunctionPointer(returnType);
  2638. } else {
  2639. returnType = Context->getObjCIdType();
  2640. }
  2641. // Get the type, we will need to reference it in a couple spots.
  2642. QualType msgSendType = MsgSendFlavor->getType();
  2643. // Create a reference to the objc_msgSend() declaration.
  2644. DeclRefExpr *DRE = new (Context) DeclRefExpr(
  2645. *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
  2646. // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
  2647. // If we don't do this cast, we get the following bizarre warning/note:
  2648. // xx.m:13: warning: function called through a non-compatible type
  2649. // xx.m:13: note: if this code is reached, the program will abort
  2650. cast = NoTypeInfoCStyleCastExpr(Context,
  2651. Context->getPointerType(Context->VoidTy),
  2652. CK_BitCast, DRE);
  2653. // Now do the "normal" pointer to function cast.
  2654. // If we don't have a method decl, force a variadic cast.
  2655. const ObjCMethodDecl *MD = Exp->getMethodDecl();
  2656. QualType castType =
  2657. getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
  2658. castType = Context->getPointerType(castType);
  2659. cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
  2660. cast);
  2661. // Don't forget the parens to enforce the proper binding.
  2662. ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
  2663. const FunctionType *FT = msgSendType->getAs<FunctionType>();
  2664. CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
  2665. VK_RValue, EndLoc);
  2666. Stmt *ReplacingStmt = CE;
  2667. if (MsgSendStretFlavor) {
  2668. // We have the method which returns a struct/union. Must also generate
  2669. // call to objc_msgSend_stret and hang both varieties on a conditional
  2670. // expression which dictate which one to envoke depending on size of
  2671. // method's return type.
  2672. CallExpr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
  2673. msgSendType, returnType,
  2674. ArgTypes, MsgExprs,
  2675. Exp->getMethodDecl());
  2676. // Build sizeof(returnType)
  2677. UnaryExprOrTypeTraitExpr *sizeofExpr =
  2678. new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
  2679. Context->getTrivialTypeSourceInfo(returnType),
  2680. Context->getSizeType(), SourceLocation(),
  2681. SourceLocation());
  2682. // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
  2683. // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
  2684. // For X86 it is more complicated and some kind of target specific routine
  2685. // is needed to decide what to do.
  2686. unsigned IntSize =
  2687. static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
  2688. IntegerLiteral *limit = IntegerLiteral::Create(*Context,
  2689. llvm::APInt(IntSize, 8),
  2690. Context->IntTy,
  2691. SourceLocation());
  2692. BinaryOperator *lessThanExpr =
  2693. new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
  2694. VK_RValue, OK_Ordinary, SourceLocation(),
  2695. FPOptions());
  2696. // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
  2697. ConditionalOperator *CondExpr =
  2698. new (Context) ConditionalOperator(lessThanExpr,
  2699. SourceLocation(), CE,
  2700. SourceLocation(), STCE,
  2701. returnType, VK_RValue, OK_Ordinary);
  2702. ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
  2703. CondExpr);
  2704. }
  2705. // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
  2706. return ReplacingStmt;
  2707. }
  2708. Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
  2709. Stmt *ReplacingStmt =
  2710. SynthMessageExpr(Exp, Exp->getBeginLoc(), Exp->getEndLoc());
  2711. // Now do the actual rewrite.
  2712. ReplaceStmt(Exp, ReplacingStmt);
  2713. // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
  2714. return ReplacingStmt;
  2715. }
  2716. // typedef struct objc_object Protocol;
  2717. QualType RewriteObjC::getProtocolType() {
  2718. if (!ProtocolTypeDecl) {
  2719. TypeSourceInfo *TInfo
  2720. = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
  2721. ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
  2722. SourceLocation(), SourceLocation(),
  2723. &Context->Idents.get("Protocol"),
  2724. TInfo);
  2725. }
  2726. return Context->getTypeDeclType(ProtocolTypeDecl);
  2727. }
  2728. /// RewriteObjCProtocolExpr - Rewrite a protocol expression into
  2729. /// a synthesized/forward data reference (to the protocol's metadata).
  2730. /// The forward references (and metadata) are generated in
  2731. /// RewriteObjC::HandleTranslationUnit().
  2732. Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
  2733. std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
  2734. IdentifierInfo *ID = &Context->Idents.get(Name);
  2735. VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
  2736. SourceLocation(), ID, getProtocolType(),
  2737. nullptr, SC_Extern);
  2738. DeclRefExpr *DRE = new (Context) DeclRefExpr(
  2739. *Context, VD, false, getProtocolType(), VK_LValue, SourceLocation());
  2740. Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
  2741. Context->getPointerType(DRE->getType()),
  2742. VK_RValue, OK_Ordinary, SourceLocation(), false);
  2743. CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
  2744. CK_BitCast,
  2745. DerefExpr);
  2746. ReplaceStmt(Exp, castExpr);
  2747. ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
  2748. // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
  2749. return castExpr;
  2750. }
  2751. bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
  2752. const char *endBuf) {
  2753. while (startBuf < endBuf) {
  2754. if (*startBuf == '#') {
  2755. // Skip whitespace.
  2756. for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
  2757. ;
  2758. if (!strncmp(startBuf, "if", strlen("if")) ||
  2759. !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
  2760. !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
  2761. !strncmp(startBuf, "define", strlen("define")) ||
  2762. !strncmp(startBuf, "undef", strlen("undef")) ||
  2763. !strncmp(startBuf, "else", strlen("else")) ||
  2764. !strncmp(startBuf, "elif", strlen("elif")) ||
  2765. !strncmp(startBuf, "endif", strlen("endif")) ||
  2766. !strncmp(startBuf, "pragma", strlen("pragma")) ||
  2767. !strncmp(startBuf, "include", strlen("include")) ||
  2768. !strncmp(startBuf, "import", strlen("import")) ||
  2769. !strncmp(startBuf, "include_next", strlen("include_next")))
  2770. return true;
  2771. }
  2772. startBuf++;
  2773. }
  2774. return false;
  2775. }
  2776. /// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
  2777. /// an objective-c class with ivars.
  2778. void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
  2779. std::string &Result) {
  2780. assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
  2781. assert(CDecl->getName() != "" &&
  2782. "Name missing in SynthesizeObjCInternalStruct");
  2783. // Do not synthesize more than once.
  2784. if (ObjCSynthesizedStructs.count(CDecl))
  2785. return;
  2786. ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
  2787. int NumIvars = CDecl->ivar_size();
  2788. SourceLocation LocStart = CDecl->getBeginLoc();
  2789. SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
  2790. const char *startBuf = SM->getCharacterData(LocStart);
  2791. const char *endBuf = SM->getCharacterData(LocEnd);
  2792. // If no ivars and no root or if its root, directly or indirectly,
  2793. // have no ivars (thus not synthesized) then no need to synthesize this class.
  2794. if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
  2795. (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
  2796. endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
  2797. ReplaceText(LocStart, endBuf-startBuf, Result);
  2798. return;
  2799. }
  2800. // FIXME: This has potential of causing problem. If
  2801. // SynthesizeObjCInternalStruct is ever called recursively.
  2802. Result += "\nstruct ";
  2803. Result += CDecl->getNameAsString();
  2804. if (LangOpts.MicrosoftExt)
  2805. Result += "_IMPL";
  2806. if (NumIvars > 0) {
  2807. const char *cursor = strchr(startBuf, '{');
  2808. assert((cursor && endBuf)
  2809. && "SynthesizeObjCInternalStruct - malformed @interface");
  2810. // If the buffer contains preprocessor directives, we do more fine-grained
  2811. // rewrites. This is intended to fix code that looks like (which occurs in
  2812. // NSURL.h, for example):
  2813. //
  2814. // #ifdef XYZ
  2815. // @interface Foo : NSObject
  2816. // #else
  2817. // @interface FooBar : NSObject
  2818. // #endif
  2819. // {
  2820. // int i;
  2821. // }
  2822. // @end
  2823. //
  2824. // This clause is segregated to avoid breaking the common case.
  2825. if (BufferContainsPPDirectives(startBuf, cursor)) {
  2826. SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
  2827. CDecl->getAtStartLoc();
  2828. const char *endHeader = SM->getCharacterData(L);
  2829. endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
  2830. if (CDecl->protocol_begin() != CDecl->protocol_end()) {
  2831. // advance to the end of the referenced protocols.
  2832. while (endHeader < cursor && *endHeader != '>') endHeader++;
  2833. endHeader++;
  2834. }
  2835. // rewrite the original header
  2836. ReplaceText(LocStart, endHeader-startBuf, Result);
  2837. } else {
  2838. // rewrite the original header *without* disturbing the '{'
  2839. ReplaceText(LocStart, cursor-startBuf, Result);
  2840. }
  2841. if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
  2842. Result = "\n struct ";
  2843. Result += RCDecl->getNameAsString();
  2844. Result += "_IMPL ";
  2845. Result += RCDecl->getNameAsString();
  2846. Result += "_IVARS;\n";
  2847. // insert the super class structure definition.
  2848. SourceLocation OnePastCurly =
  2849. LocStart.getLocWithOffset(cursor-startBuf+1);
  2850. InsertText(OnePastCurly, Result);
  2851. }
  2852. cursor++; // past '{'
  2853. // Now comment out any visibility specifiers.
  2854. while (cursor < endBuf) {
  2855. if (*cursor == '@') {
  2856. SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
  2857. // Skip whitespace.
  2858. for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
  2859. /*scan*/;
  2860. // FIXME: presence of @public, etc. inside comment results in
  2861. // this transformation as well, which is still correct c-code.
  2862. if (!strncmp(cursor, "public", strlen("public")) ||
  2863. !strncmp(cursor, "private", strlen("private")) ||
  2864. !strncmp(cursor, "package", strlen("package")) ||
  2865. !strncmp(cursor, "protected", strlen("protected")))
  2866. InsertText(atLoc, "// ");
  2867. }
  2868. // FIXME: If there are cases where '<' is used in ivar declaration part
  2869. // of user code, then scan the ivar list and use needToScanForQualifiers
  2870. // for type checking.
  2871. else if (*cursor == '<') {
  2872. SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
  2873. InsertText(atLoc, "/* ");
  2874. cursor = strchr(cursor, '>');
  2875. cursor++;
  2876. atLoc = LocStart.getLocWithOffset(cursor-startBuf);
  2877. InsertText(atLoc, " */");
  2878. } else if (*cursor == '^') { // rewrite block specifier.
  2879. SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
  2880. ReplaceText(caretLoc, 1, "*");
  2881. }
  2882. cursor++;
  2883. }
  2884. // Don't forget to add a ';'!!
  2885. InsertText(LocEnd.getLocWithOffset(1), ";");
  2886. } else { // we don't have any instance variables - insert super struct.
  2887. endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
  2888. Result += " {\n struct ";
  2889. Result += RCDecl->getNameAsString();
  2890. Result += "_IMPL ";
  2891. Result += RCDecl->getNameAsString();
  2892. Result += "_IVARS;\n};\n";
  2893. ReplaceText(LocStart, endBuf-startBuf, Result);
  2894. }
  2895. // Mark this struct as having been generated.
  2896. if (!ObjCSynthesizedStructs.insert(CDecl).second)
  2897. llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
  2898. }
  2899. //===----------------------------------------------------------------------===//
  2900. // Meta Data Emission
  2901. //===----------------------------------------------------------------------===//
  2902. /// RewriteImplementations - This routine rewrites all method implementations
  2903. /// and emits meta-data.
  2904. void RewriteObjC::RewriteImplementations() {
  2905. int ClsDefCount = ClassImplementation.size();
  2906. int CatDefCount = CategoryImplementation.size();
  2907. // Rewrite implemented methods
  2908. for (int i = 0; i < ClsDefCount; i++)
  2909. RewriteImplementationDecl(ClassImplementation[i]);
  2910. for (int i = 0; i < CatDefCount; i++)
  2911. RewriteImplementationDecl(CategoryImplementation[i]);
  2912. }
  2913. void RewriteObjC::RewriteByRefString(std::string &ResultStr,
  2914. const std::string &Name,
  2915. ValueDecl *VD, bool def) {
  2916. assert(BlockByRefDeclNo.count(VD) &&
  2917. "RewriteByRefString: ByRef decl missing");
  2918. if (def)
  2919. ResultStr += "struct ";
  2920. ResultStr += "__Block_byref_" + Name +
  2921. "_" + utostr(BlockByRefDeclNo[VD]) ;
  2922. }
  2923. static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
  2924. if (VarDecl *Var = dyn_cast<VarDecl>(VD))
  2925. return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
  2926. return false;
  2927. }
  2928. std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
  2929. StringRef funcName,
  2930. std::string Tag) {
  2931. const FunctionType *AFT = CE->getFunctionType();
  2932. QualType RT = AFT->getReturnType();
  2933. std::string StructRef = "struct " + Tag;
  2934. std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
  2935. funcName.str() + "_" + "block_func_" + utostr(i);
  2936. BlockDecl *BD = CE->getBlockDecl();
  2937. if (isa<FunctionNoProtoType>(AFT)) {
  2938. // No user-supplied arguments. Still need to pass in a pointer to the
  2939. // block (to reference imported block decl refs).
  2940. S += "(" + StructRef + " *__cself)";
  2941. } else if (BD->param_empty()) {
  2942. S += "(" + StructRef + " *__cself)";
  2943. } else {
  2944. const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
  2945. assert(FT && "SynthesizeBlockFunc: No function proto");
  2946. S += '(';
  2947. // first add the implicit argument.
  2948. S += StructRef + " *__cself, ";
  2949. std::string ParamStr;
  2950. for (BlockDecl::param_iterator AI = BD->param_begin(),
  2951. E = BD->param_end(); AI != E; ++AI) {
  2952. if (AI != BD->param_begin()) S += ", ";
  2953. ParamStr = (*AI)->getNameAsString();
  2954. QualType QT = (*AI)->getType();
  2955. (void)convertBlockPointerToFunctionPointer(QT);
  2956. QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
  2957. S += ParamStr;
  2958. }
  2959. if (FT->isVariadic()) {
  2960. if (!BD->param_empty()) S += ", ";
  2961. S += "...";
  2962. }
  2963. S += ')';
  2964. }
  2965. S += " {\n";
  2966. // Create local declarations to avoid rewriting all closure decl ref exprs.
  2967. // First, emit a declaration for all "by ref" decls.
  2968. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
  2969. E = BlockByRefDecls.end(); I != E; ++I) {
  2970. S += " ";
  2971. std::string Name = (*I)->getNameAsString();
  2972. std::string TypeString;
  2973. RewriteByRefString(TypeString, Name, (*I));
  2974. TypeString += " *";
  2975. Name = TypeString + Name;
  2976. S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
  2977. }
  2978. // Next, emit a declaration for all "by copy" declarations.
  2979. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
  2980. E = BlockByCopyDecls.end(); I != E; ++I) {
  2981. S += " ";
  2982. // Handle nested closure invocation. For example:
  2983. //
  2984. // void (^myImportedClosure)(void);
  2985. // myImportedClosure = ^(void) { setGlobalInt(x + y); };
  2986. //
  2987. // void (^anotherClosure)(void);
  2988. // anotherClosure = ^(void) {
  2989. // myImportedClosure(); // import and invoke the closure
  2990. // };
  2991. //
  2992. if (isTopLevelBlockPointerType((*I)->getType())) {
  2993. RewriteBlockPointerTypeVariable(S, (*I));
  2994. S += " = (";
  2995. RewriteBlockPointerType(S, (*I)->getType());
  2996. S += ")";
  2997. S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
  2998. }
  2999. else {
  3000. std::string Name = (*I)->getNameAsString();
  3001. QualType QT = (*I)->getType();
  3002. if (HasLocalVariableExternalStorage(*I))
  3003. QT = Context->getPointerType(QT);
  3004. QT.getAsStringInternal(Name, Context->getPrintingPolicy());
  3005. S += Name + " = __cself->" +
  3006. (*I)->getNameAsString() + "; // bound by copy\n";
  3007. }
  3008. }
  3009. std::string RewrittenStr = RewrittenBlockExprs[CE];
  3010. const char *cstr = RewrittenStr.c_str();
  3011. while (*cstr++ != '{') ;
  3012. S += cstr;
  3013. S += "\n";
  3014. return S;
  3015. }
  3016. std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
  3017. StringRef funcName,
  3018. std::string Tag) {
  3019. std::string StructRef = "struct " + Tag;
  3020. std::string S = "static void __";
  3021. S += funcName;
  3022. S += "_block_copy_" + utostr(i);
  3023. S += "(" + StructRef;
  3024. S += "*dst, " + StructRef;
  3025. S += "*src) {";
  3026. for (ValueDecl *VD : ImportedBlockDecls) {
  3027. S += "_Block_object_assign((void*)&dst->";
  3028. S += VD->getNameAsString();
  3029. S += ", (void*)src->";
  3030. S += VD->getNameAsString();
  3031. if (BlockByRefDeclsPtrSet.count(VD))
  3032. S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
  3033. else if (VD->getType()->isBlockPointerType())
  3034. S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
  3035. else
  3036. S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
  3037. }
  3038. S += "}\n";
  3039. S += "\nstatic void __";
  3040. S += funcName;
  3041. S += "_block_dispose_" + utostr(i);
  3042. S += "(" + StructRef;
  3043. S += "*src) {";
  3044. for (ValueDecl *VD : ImportedBlockDecls) {
  3045. S += "_Block_object_dispose((void*)src->";
  3046. S += VD->getNameAsString();
  3047. if (BlockByRefDeclsPtrSet.count(VD))
  3048. S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
  3049. else if (VD->getType()->isBlockPointerType())
  3050. S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
  3051. else
  3052. S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
  3053. }
  3054. S += "}\n";
  3055. return S;
  3056. }
  3057. std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
  3058. std::string Desc) {
  3059. std::string S = "\nstruct " + Tag;
  3060. std::string Constructor = " " + Tag;
  3061. S += " {\n struct __block_impl impl;\n";
  3062. S += " struct " + Desc;
  3063. S += "* Desc;\n";
  3064. Constructor += "(void *fp, "; // Invoke function pointer.
  3065. Constructor += "struct " + Desc; // Descriptor pointer.
  3066. Constructor += " *desc";
  3067. if (BlockDeclRefs.size()) {
  3068. // Output all "by copy" declarations.
  3069. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
  3070. E = BlockByCopyDecls.end(); I != E; ++I) {
  3071. S += " ";
  3072. std::string FieldName = (*I)->getNameAsString();
  3073. std::string ArgName = "_" + FieldName;
  3074. // Handle nested closure invocation. For example:
  3075. //
  3076. // void (^myImportedBlock)(void);
  3077. // myImportedBlock = ^(void) { setGlobalInt(x + y); };
  3078. //
  3079. // void (^anotherBlock)(void);
  3080. // anotherBlock = ^(void) {
  3081. // myImportedBlock(); // import and invoke the closure
  3082. // };
  3083. //
  3084. if (isTopLevelBlockPointerType((*I)->getType())) {
  3085. S += "struct __block_impl *";
  3086. Constructor += ", void *" + ArgName;
  3087. } else {
  3088. QualType QT = (*I)->getType();
  3089. if (HasLocalVariableExternalStorage(*I))
  3090. QT = Context->getPointerType(QT);
  3091. QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
  3092. QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
  3093. Constructor += ", " + ArgName;
  3094. }
  3095. S += FieldName + ";\n";
  3096. }
  3097. // Output all "by ref" declarations.
  3098. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
  3099. E = BlockByRefDecls.end(); I != E; ++I) {
  3100. S += " ";
  3101. std::string FieldName = (*I)->getNameAsString();
  3102. std::string ArgName = "_" + FieldName;
  3103. {
  3104. std::string TypeString;
  3105. RewriteByRefString(TypeString, FieldName, (*I));
  3106. TypeString += " *";
  3107. FieldName = TypeString + FieldName;
  3108. ArgName = TypeString + ArgName;
  3109. Constructor += ", " + ArgName;
  3110. }
  3111. S += FieldName + "; // by ref\n";
  3112. }
  3113. // Finish writing the constructor.
  3114. Constructor += ", int flags=0)";
  3115. // Initialize all "by copy" arguments.
  3116. bool firsTime = true;
  3117. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
  3118. E = BlockByCopyDecls.end(); I != E; ++I) {
  3119. std::string Name = (*I)->getNameAsString();
  3120. if (firsTime) {
  3121. Constructor += " : ";
  3122. firsTime = false;
  3123. }
  3124. else
  3125. Constructor += ", ";
  3126. if (isTopLevelBlockPointerType((*I)->getType()))
  3127. Constructor += Name + "((struct __block_impl *)_" + Name + ")";
  3128. else
  3129. Constructor += Name + "(_" + Name + ")";
  3130. }
  3131. // Initialize all "by ref" arguments.
  3132. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
  3133. E = BlockByRefDecls.end(); I != E; ++I) {
  3134. std::string Name = (*I)->getNameAsString();
  3135. if (firsTime) {
  3136. Constructor += " : ";
  3137. firsTime = false;
  3138. }
  3139. else
  3140. Constructor += ", ";
  3141. Constructor += Name + "(_" + Name + "->__forwarding)";
  3142. }
  3143. Constructor += " {\n";
  3144. if (GlobalVarDecl)
  3145. Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
  3146. else
  3147. Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
  3148. Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
  3149. Constructor += " Desc = desc;\n";
  3150. } else {
  3151. // Finish writing the constructor.
  3152. Constructor += ", int flags=0) {\n";
  3153. if (GlobalVarDecl)
  3154. Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
  3155. else
  3156. Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
  3157. Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
  3158. Constructor += " Desc = desc;\n";
  3159. }
  3160. Constructor += " ";
  3161. Constructor += "}\n";
  3162. S += Constructor;
  3163. S += "};\n";
  3164. return S;
  3165. }
  3166. std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
  3167. std::string ImplTag, int i,
  3168. StringRef FunName,
  3169. unsigned hasCopy) {
  3170. std::string S = "\nstatic struct " + DescTag;
  3171. S += " {\n unsigned long reserved;\n";
  3172. S += " unsigned long Block_size;\n";
  3173. if (hasCopy) {
  3174. S += " void (*copy)(struct ";
  3175. S += ImplTag; S += "*, struct ";
  3176. S += ImplTag; S += "*);\n";
  3177. S += " void (*dispose)(struct ";
  3178. S += ImplTag; S += "*);\n";
  3179. }
  3180. S += "} ";
  3181. S += DescTag + "_DATA = { 0, sizeof(struct ";
  3182. S += ImplTag + ")";
  3183. if (hasCopy) {
  3184. S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
  3185. S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
  3186. }
  3187. S += "};\n";
  3188. return S;
  3189. }
  3190. void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
  3191. StringRef FunName) {
  3192. // Insert declaration for the function in which block literal is used.
  3193. if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
  3194. RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
  3195. bool RewriteSC = (GlobalVarDecl &&
  3196. !Blocks.empty() &&
  3197. GlobalVarDecl->getStorageClass() == SC_Static &&
  3198. GlobalVarDecl->getType().getCVRQualifiers());
  3199. if (RewriteSC) {
  3200. std::string SC(" void __");
  3201. SC += GlobalVarDecl->getNameAsString();
  3202. SC += "() {}";
  3203. InsertText(FunLocStart, SC);
  3204. }
  3205. // Insert closures that were part of the function.
  3206. for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
  3207. CollectBlockDeclRefInfo(Blocks[i]);
  3208. // Need to copy-in the inner copied-in variables not actually used in this
  3209. // block.
  3210. for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
  3211. DeclRefExpr *Exp = InnerDeclRefs[count++];
  3212. ValueDecl *VD = Exp->getDecl();
  3213. BlockDeclRefs.push_back(Exp);
  3214. if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
  3215. BlockByCopyDeclsPtrSet.insert(VD);
  3216. BlockByCopyDecls.push_back(VD);
  3217. }
  3218. if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
  3219. BlockByRefDeclsPtrSet.insert(VD);
  3220. BlockByRefDecls.push_back(VD);
  3221. }
  3222. // imported objects in the inner blocks not used in the outer
  3223. // blocks must be copied/disposed in the outer block as well.
  3224. if (VD->hasAttr<BlocksAttr>() ||
  3225. VD->getType()->isObjCObjectPointerType() ||
  3226. VD->getType()->isBlockPointerType())
  3227. ImportedBlockDecls.insert(VD);
  3228. }
  3229. std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
  3230. std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
  3231. std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
  3232. InsertText(FunLocStart, CI);
  3233. std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
  3234. InsertText(FunLocStart, CF);
  3235. if (ImportedBlockDecls.size()) {
  3236. std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
  3237. InsertText(FunLocStart, HF);
  3238. }
  3239. std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
  3240. ImportedBlockDecls.size() > 0);
  3241. InsertText(FunLocStart, BD);
  3242. BlockDeclRefs.clear();
  3243. BlockByRefDecls.clear();
  3244. BlockByRefDeclsPtrSet.clear();
  3245. BlockByCopyDecls.clear();
  3246. BlockByCopyDeclsPtrSet.clear();
  3247. ImportedBlockDecls.clear();
  3248. }
  3249. if (RewriteSC) {
  3250. // Must insert any 'const/volatile/static here. Since it has been
  3251. // removed as result of rewriting of block literals.
  3252. std::string SC;
  3253. if (GlobalVarDecl->getStorageClass() == SC_Static)
  3254. SC = "static ";
  3255. if (GlobalVarDecl->getType().isConstQualified())
  3256. SC += "const ";
  3257. if (GlobalVarDecl->getType().isVolatileQualified())
  3258. SC += "volatile ";
  3259. if (GlobalVarDecl->getType().isRestrictQualified())
  3260. SC += "restrict ";
  3261. InsertText(FunLocStart, SC);
  3262. }
  3263. Blocks.clear();
  3264. InnerDeclRefsCount.clear();
  3265. InnerDeclRefs.clear();
  3266. RewrittenBlockExprs.clear();
  3267. }
  3268. void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
  3269. SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
  3270. StringRef FuncName = FD->getName();
  3271. SynthesizeBlockLiterals(FunLocStart, FuncName);
  3272. }
  3273. static void BuildUniqueMethodName(std::string &Name,
  3274. ObjCMethodDecl *MD) {
  3275. ObjCInterfaceDecl *IFace = MD->getClassInterface();
  3276. Name = IFace->getName();
  3277. Name += "__" + MD->getSelector().getAsString();
  3278. // Convert colons to underscores.
  3279. std::string::size_type loc = 0;
  3280. while ((loc = Name.find(':', loc)) != std::string::npos)
  3281. Name.replace(loc, 1, "_");
  3282. }
  3283. void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
  3284. // fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
  3285. // SourceLocation FunLocStart = MD->getBeginLoc();
  3286. SourceLocation FunLocStart = MD->getBeginLoc();
  3287. std::string FuncName;
  3288. BuildUniqueMethodName(FuncName, MD);
  3289. SynthesizeBlockLiterals(FunLocStart, FuncName);
  3290. }
  3291. void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
  3292. for (Stmt *SubStmt : S->children())
  3293. if (SubStmt) {
  3294. if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
  3295. GetBlockDeclRefExprs(CBE->getBody());
  3296. else
  3297. GetBlockDeclRefExprs(SubStmt);
  3298. }
  3299. // Handle specific things.
  3300. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
  3301. if (DRE->refersToEnclosingVariableOrCapture() ||
  3302. HasLocalVariableExternalStorage(DRE->getDecl()))
  3303. // FIXME: Handle enums.
  3304. BlockDeclRefs.push_back(DRE);
  3305. }
  3306. void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
  3307. SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
  3308. llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
  3309. for (Stmt *SubStmt : S->children())
  3310. if (SubStmt) {
  3311. if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
  3312. InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
  3313. GetInnerBlockDeclRefExprs(CBE->getBody(),
  3314. InnerBlockDeclRefs,
  3315. InnerContexts);
  3316. }
  3317. else
  3318. GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
  3319. }
  3320. // Handle specific things.
  3321. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
  3322. if (DRE->refersToEnclosingVariableOrCapture() ||
  3323. HasLocalVariableExternalStorage(DRE->getDecl())) {
  3324. if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
  3325. InnerBlockDeclRefs.push_back(DRE);
  3326. if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
  3327. if (Var->isFunctionOrMethodVarDecl())
  3328. ImportedLocalExternalDecls.insert(Var);
  3329. }
  3330. }
  3331. }
  3332. /// convertFunctionTypeOfBlocks - This routine converts a function type
  3333. /// whose result type may be a block pointer or whose argument type(s)
  3334. /// might be block pointers to an equivalent function type replacing
  3335. /// all block pointers to function pointers.
  3336. QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
  3337. const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
  3338. // FTP will be null for closures that don't take arguments.
  3339. // Generate a funky cast.
  3340. SmallVector<QualType, 8> ArgTypes;
  3341. QualType Res = FT->getReturnType();
  3342. bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
  3343. if (FTP) {
  3344. for (auto &I : FTP->param_types()) {
  3345. QualType t = I;
  3346. // Make sure we convert "t (^)(...)" to "t (*)(...)".
  3347. if (convertBlockPointerToFunctionPointer(t))
  3348. HasBlockType = true;
  3349. ArgTypes.push_back(t);
  3350. }
  3351. }
  3352. QualType FuncType;
  3353. // FIXME. Does this work if block takes no argument but has a return type
  3354. // which is of block type?
  3355. if (HasBlockType)
  3356. FuncType = getSimpleFunctionType(Res, ArgTypes);
  3357. else FuncType = QualType(FT, 0);
  3358. return FuncType;
  3359. }
  3360. Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
  3361. // Navigate to relevant type information.
  3362. const BlockPointerType *CPT = nullptr;
  3363. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
  3364. CPT = DRE->getType()->getAs<BlockPointerType>();
  3365. } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
  3366. CPT = MExpr->getType()->getAs<BlockPointerType>();
  3367. }
  3368. else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
  3369. return SynthesizeBlockCall(Exp, PRE->getSubExpr());
  3370. }
  3371. else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
  3372. CPT = IEXPR->getType()->getAs<BlockPointerType>();
  3373. else if (const ConditionalOperator *CEXPR =
  3374. dyn_cast<ConditionalOperator>(BlockExp)) {
  3375. Expr *LHSExp = CEXPR->getLHS();
  3376. Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
  3377. Expr *RHSExp = CEXPR->getRHS();
  3378. Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
  3379. Expr *CONDExp = CEXPR->getCond();
  3380. ConditionalOperator *CondExpr =
  3381. new (Context) ConditionalOperator(CONDExp,
  3382. SourceLocation(), cast<Expr>(LHSStmt),
  3383. SourceLocation(), cast<Expr>(RHSStmt),
  3384. Exp->getType(), VK_RValue, OK_Ordinary);
  3385. return CondExpr;
  3386. } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
  3387. CPT = IRE->getType()->getAs<BlockPointerType>();
  3388. } else if (const PseudoObjectExpr *POE
  3389. = dyn_cast<PseudoObjectExpr>(BlockExp)) {
  3390. CPT = POE->getType()->castAs<BlockPointerType>();
  3391. } else {
  3392. assert(false && "RewriteBlockClass: Bad type");
  3393. }
  3394. assert(CPT && "RewriteBlockClass: Bad type");
  3395. const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
  3396. assert(FT && "RewriteBlockClass: Bad type");
  3397. const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
  3398. // FTP will be null for closures that don't take arguments.
  3399. RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
  3400. SourceLocation(), SourceLocation(),
  3401. &Context->Idents.get("__block_impl"));
  3402. QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
  3403. // Generate a funky cast.
  3404. SmallVector<QualType, 8> ArgTypes;
  3405. // Push the block argument type.
  3406. ArgTypes.push_back(PtrBlock);
  3407. if (FTP) {
  3408. for (auto &I : FTP->param_types()) {
  3409. QualType t = I;
  3410. // Make sure we convert "t (^)(...)" to "t (*)(...)".
  3411. if (!convertBlockPointerToFunctionPointer(t))
  3412. convertToUnqualifiedObjCType(t);
  3413. ArgTypes.push_back(t);
  3414. }
  3415. }
  3416. // Now do the pointer to function cast.
  3417. QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
  3418. PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
  3419. CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
  3420. CK_BitCast,
  3421. const_cast<Expr*>(BlockExp));
  3422. // Don't forget the parens to enforce the proper binding.
  3423. ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
  3424. BlkCast);
  3425. //PE->dump();
  3426. FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
  3427. SourceLocation(),
  3428. &Context->Idents.get("FuncPtr"),
  3429. Context->VoidPtrTy, nullptr,
  3430. /*BitWidth=*/nullptr, /*Mutable=*/true,
  3431. ICIS_NoInit);
  3432. MemberExpr *ME = MemberExpr::CreateImplicit(
  3433. *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
  3434. CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
  3435. CK_BitCast, ME);
  3436. PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
  3437. SmallVector<Expr*, 8> BlkExprs;
  3438. // Add the implicit argument.
  3439. BlkExprs.push_back(BlkCast);
  3440. // Add the user arguments.
  3441. for (CallExpr::arg_iterator I = Exp->arg_begin(),
  3442. E = Exp->arg_end(); I != E; ++I) {
  3443. BlkExprs.push_back(*I);
  3444. }
  3445. CallExpr *CE = CallExpr::Create(*Context, PE, BlkExprs, Exp->getType(),
  3446. VK_RValue, SourceLocation());
  3447. return CE;
  3448. }
  3449. // We need to return the rewritten expression to handle cases where the
  3450. // BlockDeclRefExpr is embedded in another expression being rewritten.
  3451. // For example:
  3452. //
  3453. // int main() {
  3454. // __block Foo *f;
  3455. // __block int i;
  3456. //
  3457. // void (^myblock)() = ^() {
  3458. // [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
  3459. // i = 77;
  3460. // };
  3461. //}
  3462. Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
  3463. // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
  3464. // for each DeclRefExp where BYREFVAR is name of the variable.
  3465. ValueDecl *VD = DeclRefExp->getDecl();
  3466. bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
  3467. HasLocalVariableExternalStorage(DeclRefExp->getDecl());
  3468. FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
  3469. SourceLocation(),
  3470. &Context->Idents.get("__forwarding"),
  3471. Context->VoidPtrTy, nullptr,
  3472. /*BitWidth=*/nullptr, /*Mutable=*/true,
  3473. ICIS_NoInit);
  3474. MemberExpr *ME =
  3475. MemberExpr::CreateImplicit(*Context, DeclRefExp, isArrow, FD,
  3476. FD->getType(), VK_LValue, OK_Ordinary);
  3477. StringRef Name = VD->getName();
  3478. FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
  3479. &Context->Idents.get(Name),
  3480. Context->VoidPtrTy, nullptr,
  3481. /*BitWidth=*/nullptr, /*Mutable=*/true,
  3482. ICIS_NoInit);
  3483. ME = MemberExpr::CreateImplicit(*Context, ME, true, FD, DeclRefExp->getType(),
  3484. VK_LValue, OK_Ordinary);
  3485. // Need parens to enforce precedence.
  3486. ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
  3487. DeclRefExp->getExprLoc(),
  3488. ME);
  3489. ReplaceStmt(DeclRefExp, PE);
  3490. return PE;
  3491. }
  3492. // Rewrites the imported local variable V with external storage
  3493. // (static, extern, etc.) as *V
  3494. //
  3495. Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
  3496. ValueDecl *VD = DRE->getDecl();
  3497. if (VarDecl *Var = dyn_cast<VarDecl>(VD))
  3498. if (!ImportedLocalExternalDecls.count(Var))
  3499. return DRE;
  3500. Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
  3501. VK_LValue, OK_Ordinary,
  3502. DRE->getLocation(), false);
  3503. // Need parens to enforce precedence.
  3504. ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
  3505. Exp);
  3506. ReplaceStmt(DRE, PE);
  3507. return PE;
  3508. }
  3509. void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
  3510. SourceLocation LocStart = CE->getLParenLoc();
  3511. SourceLocation LocEnd = CE->getRParenLoc();
  3512. // Need to avoid trying to rewrite synthesized casts.
  3513. if (LocStart.isInvalid())
  3514. return;
  3515. // Need to avoid trying to rewrite casts contained in macros.
  3516. if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
  3517. return;
  3518. const char *startBuf = SM->getCharacterData(LocStart);
  3519. const char *endBuf = SM->getCharacterData(LocEnd);
  3520. QualType QT = CE->getType();
  3521. const Type* TypePtr = QT->getAs<Type>();
  3522. if (isa<TypeOfExprType>(TypePtr)) {
  3523. const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
  3524. QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
  3525. std::string TypeAsString = "(";
  3526. RewriteBlockPointerType(TypeAsString, QT);
  3527. TypeAsString += ")";
  3528. ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
  3529. return;
  3530. }
  3531. // advance the location to startArgList.
  3532. const char *argPtr = startBuf;
  3533. while (*argPtr++ && (argPtr < endBuf)) {
  3534. switch (*argPtr) {
  3535. case '^':
  3536. // Replace the '^' with '*'.
  3537. LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
  3538. ReplaceText(LocStart, 1, "*");
  3539. break;
  3540. }
  3541. }
  3542. }
  3543. void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
  3544. SourceLocation DeclLoc = FD->getLocation();
  3545. unsigned parenCount = 0;
  3546. // We have 1 or more arguments that have closure pointers.
  3547. const char *startBuf = SM->getCharacterData(DeclLoc);
  3548. const char *startArgList = strchr(startBuf, '(');
  3549. assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
  3550. parenCount++;
  3551. // advance the location to startArgList.
  3552. DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
  3553. assert((DeclLoc.isValid()) && "Invalid DeclLoc");
  3554. const char *argPtr = startArgList;
  3555. while (*argPtr++ && parenCount) {
  3556. switch (*argPtr) {
  3557. case '^':
  3558. // Replace the '^' with '*'.
  3559. DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
  3560. ReplaceText(DeclLoc, 1, "*");
  3561. break;
  3562. case '(':
  3563. parenCount++;
  3564. break;
  3565. case ')':
  3566. parenCount--;
  3567. break;
  3568. }
  3569. }
  3570. }
  3571. bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
  3572. const FunctionProtoType *FTP;
  3573. const PointerType *PT = QT->getAs<PointerType>();
  3574. if (PT) {
  3575. FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
  3576. } else {
  3577. const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
  3578. assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
  3579. FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
  3580. }
  3581. if (FTP) {
  3582. for (const auto &I : FTP->param_types())
  3583. if (isTopLevelBlockPointerType(I))
  3584. return true;
  3585. }
  3586. return false;
  3587. }
  3588. bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
  3589. const FunctionProtoType *FTP;
  3590. const PointerType *PT = QT->getAs<PointerType>();
  3591. if (PT) {
  3592. FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
  3593. } else {
  3594. const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
  3595. assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
  3596. FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
  3597. }
  3598. if (FTP) {
  3599. for (const auto &I : FTP->param_types()) {
  3600. if (I->isObjCQualifiedIdType())
  3601. return true;
  3602. if (I->isObjCObjectPointerType() &&
  3603. I->getPointeeType()->isObjCQualifiedInterfaceType())
  3604. return true;
  3605. }
  3606. }
  3607. return false;
  3608. }
  3609. void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
  3610. const char *&RParen) {
  3611. const char *argPtr = strchr(Name, '(');
  3612. assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
  3613. LParen = argPtr; // output the start.
  3614. argPtr++; // skip past the left paren.
  3615. unsigned parenCount = 1;
  3616. while (*argPtr && parenCount) {
  3617. switch (*argPtr) {
  3618. case '(': parenCount++; break;
  3619. case ')': parenCount--; break;
  3620. default: break;
  3621. }
  3622. if (parenCount) argPtr++;
  3623. }
  3624. assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
  3625. RParen = argPtr; // output the end
  3626. }
  3627. void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
  3628. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  3629. RewriteBlockPointerFunctionArgs(FD);
  3630. return;
  3631. }
  3632. // Handle Variables and Typedefs.
  3633. SourceLocation DeclLoc = ND->getLocation();
  3634. QualType DeclT;
  3635. if (VarDecl *VD = dyn_cast<VarDecl>(ND))
  3636. DeclT = VD->getType();
  3637. else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
  3638. DeclT = TDD->getUnderlyingType();
  3639. else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
  3640. DeclT = FD->getType();
  3641. else
  3642. llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
  3643. const char *startBuf = SM->getCharacterData(DeclLoc);
  3644. const char *endBuf = startBuf;
  3645. // scan backward (from the decl location) for the end of the previous decl.
  3646. while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
  3647. startBuf--;
  3648. SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
  3649. std::string buf;
  3650. unsigned OrigLength=0;
  3651. // *startBuf != '^' if we are dealing with a pointer to function that
  3652. // may take block argument types (which will be handled below).
  3653. if (*startBuf == '^') {
  3654. // Replace the '^' with '*', computing a negative offset.
  3655. buf = '*';
  3656. startBuf++;
  3657. OrigLength++;
  3658. }
  3659. while (*startBuf != ')') {
  3660. buf += *startBuf;
  3661. startBuf++;
  3662. OrigLength++;
  3663. }
  3664. buf += ')';
  3665. OrigLength++;
  3666. if (PointerTypeTakesAnyBlockArguments(DeclT) ||
  3667. PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
  3668. // Replace the '^' with '*' for arguments.
  3669. // Replace id<P> with id/*<>*/
  3670. DeclLoc = ND->getLocation();
  3671. startBuf = SM->getCharacterData(DeclLoc);
  3672. const char *argListBegin, *argListEnd;
  3673. GetExtentOfArgList(startBuf, argListBegin, argListEnd);
  3674. while (argListBegin < argListEnd) {
  3675. if (*argListBegin == '^')
  3676. buf += '*';
  3677. else if (*argListBegin == '<') {
  3678. buf += "/*";
  3679. buf += *argListBegin++;
  3680. OrigLength++;
  3681. while (*argListBegin != '>') {
  3682. buf += *argListBegin++;
  3683. OrigLength++;
  3684. }
  3685. buf += *argListBegin;
  3686. buf += "*/";
  3687. }
  3688. else
  3689. buf += *argListBegin;
  3690. argListBegin++;
  3691. OrigLength++;
  3692. }
  3693. buf += ')';
  3694. OrigLength++;
  3695. }
  3696. ReplaceText(Start, OrigLength, buf);
  3697. }
  3698. /// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
  3699. /// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
  3700. /// struct Block_byref_id_object *src) {
  3701. /// _Block_object_assign (&_dest->object, _src->object,
  3702. /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
  3703. /// [|BLOCK_FIELD_IS_WEAK]) // object
  3704. /// _Block_object_assign(&_dest->object, _src->object,
  3705. /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
  3706. /// [|BLOCK_FIELD_IS_WEAK]) // block
  3707. /// }
  3708. /// And:
  3709. /// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
  3710. /// _Block_object_dispose(_src->object,
  3711. /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
  3712. /// [|BLOCK_FIELD_IS_WEAK]) // object
  3713. /// _Block_object_dispose(_src->object,
  3714. /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
  3715. /// [|BLOCK_FIELD_IS_WEAK]) // block
  3716. /// }
  3717. std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
  3718. int flag) {
  3719. std::string S;
  3720. if (CopyDestroyCache.count(flag))
  3721. return S;
  3722. CopyDestroyCache.insert(flag);
  3723. S = "static void __Block_byref_id_object_copy_";
  3724. S += utostr(flag);
  3725. S += "(void *dst, void *src) {\n";
  3726. // offset into the object pointer is computed as:
  3727. // void * + void* + int + int + void* + void *
  3728. unsigned IntSize =
  3729. static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
  3730. unsigned VoidPtrSize =
  3731. static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
  3732. unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
  3733. S += " _Block_object_assign((char*)dst + ";
  3734. S += utostr(offset);
  3735. S += ", *(void * *) ((char*)src + ";
  3736. S += utostr(offset);
  3737. S += "), ";
  3738. S += utostr(flag);
  3739. S += ");\n}\n";
  3740. S += "static void __Block_byref_id_object_dispose_";
  3741. S += utostr(flag);
  3742. S += "(void *src) {\n";
  3743. S += " _Block_object_dispose(*(void * *) ((char*)src + ";
  3744. S += utostr(offset);
  3745. S += "), ";
  3746. S += utostr(flag);
  3747. S += ");\n}\n";
  3748. return S;
  3749. }
  3750. /// RewriteByRefVar - For each __block typex ND variable this routine transforms
  3751. /// the declaration into:
  3752. /// struct __Block_byref_ND {
  3753. /// void *__isa; // NULL for everything except __weak pointers
  3754. /// struct __Block_byref_ND *__forwarding;
  3755. /// int32_t __flags;
  3756. /// int32_t __size;
  3757. /// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
  3758. /// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
  3759. /// typex ND;
  3760. /// };
  3761. ///
  3762. /// It then replaces declaration of ND variable with:
  3763. /// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
  3764. /// __size=sizeof(struct __Block_byref_ND),
  3765. /// ND=initializer-if-any};
  3766. ///
  3767. ///
  3768. void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
  3769. // Insert declaration for the function in which block literal is
  3770. // used.
  3771. if (CurFunctionDeclToDeclareForBlock)
  3772. RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
  3773. int flag = 0;
  3774. int isa = 0;
  3775. SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
  3776. if (DeclLoc.isInvalid())
  3777. // If type location is missing, it is because of missing type (a warning).
  3778. // Use variable's location which is good for this case.
  3779. DeclLoc = ND->getLocation();
  3780. const char *startBuf = SM->getCharacterData(DeclLoc);
  3781. SourceLocation X = ND->getEndLoc();
  3782. X = SM->getExpansionLoc(X);
  3783. const char *endBuf = SM->getCharacterData(X);
  3784. std::string Name(ND->getNameAsString());
  3785. std::string ByrefType;
  3786. RewriteByRefString(ByrefType, Name, ND, true);
  3787. ByrefType += " {\n";
  3788. ByrefType += " void *__isa;\n";
  3789. RewriteByRefString(ByrefType, Name, ND);
  3790. ByrefType += " *__forwarding;\n";
  3791. ByrefType += " int __flags;\n";
  3792. ByrefType += " int __size;\n";
  3793. // Add void *__Block_byref_id_object_copy;
  3794. // void *__Block_byref_id_object_dispose; if needed.
  3795. QualType Ty = ND->getType();
  3796. bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
  3797. if (HasCopyAndDispose) {
  3798. ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
  3799. ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
  3800. }
  3801. QualType T = Ty;
  3802. (void)convertBlockPointerToFunctionPointer(T);
  3803. T.getAsStringInternal(Name, Context->getPrintingPolicy());
  3804. ByrefType += " " + Name + ";\n";
  3805. ByrefType += "};\n";
  3806. // Insert this type in global scope. It is needed by helper function.
  3807. SourceLocation FunLocStart;
  3808. if (CurFunctionDef)
  3809. FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
  3810. else {
  3811. assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
  3812. FunLocStart = CurMethodDef->getBeginLoc();
  3813. }
  3814. InsertText(FunLocStart, ByrefType);
  3815. if (Ty.isObjCGCWeak()) {
  3816. flag |= BLOCK_FIELD_IS_WEAK;
  3817. isa = 1;
  3818. }
  3819. if (HasCopyAndDispose) {
  3820. flag = BLOCK_BYREF_CALLER;
  3821. QualType Ty = ND->getType();
  3822. // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
  3823. if (Ty->isBlockPointerType())
  3824. flag |= BLOCK_FIELD_IS_BLOCK;
  3825. else
  3826. flag |= BLOCK_FIELD_IS_OBJECT;
  3827. std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
  3828. if (!HF.empty())
  3829. InsertText(FunLocStart, HF);
  3830. }
  3831. // struct __Block_byref_ND ND =
  3832. // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
  3833. // initializer-if-any};
  3834. bool hasInit = (ND->getInit() != nullptr);
  3835. unsigned flags = 0;
  3836. if (HasCopyAndDispose)
  3837. flags |= BLOCK_HAS_COPY_DISPOSE;
  3838. Name = ND->getNameAsString();
  3839. ByrefType.clear();
  3840. RewriteByRefString(ByrefType, Name, ND);
  3841. std::string ForwardingCastType("(");
  3842. ForwardingCastType += ByrefType + " *)";
  3843. if (!hasInit) {
  3844. ByrefType += " " + Name + " = {(void*)";
  3845. ByrefType += utostr(isa);
  3846. ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
  3847. ByrefType += utostr(flags);
  3848. ByrefType += ", ";
  3849. ByrefType += "sizeof(";
  3850. RewriteByRefString(ByrefType, Name, ND);
  3851. ByrefType += ")";
  3852. if (HasCopyAndDispose) {
  3853. ByrefType += ", __Block_byref_id_object_copy_";
  3854. ByrefType += utostr(flag);
  3855. ByrefType += ", __Block_byref_id_object_dispose_";
  3856. ByrefType += utostr(flag);
  3857. }
  3858. ByrefType += "};\n";
  3859. unsigned nameSize = Name.size();
  3860. // for block or function pointer declaration. Name is already
  3861. // part of the declaration.
  3862. if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
  3863. nameSize = 1;
  3864. ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
  3865. }
  3866. else {
  3867. SourceLocation startLoc;
  3868. Expr *E = ND->getInit();
  3869. if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
  3870. startLoc = ECE->getLParenLoc();
  3871. else
  3872. startLoc = E->getBeginLoc();
  3873. startLoc = SM->getExpansionLoc(startLoc);
  3874. endBuf = SM->getCharacterData(startLoc);
  3875. ByrefType += " " + Name;
  3876. ByrefType += " = {(void*)";
  3877. ByrefType += utostr(isa);
  3878. ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
  3879. ByrefType += utostr(flags);
  3880. ByrefType += ", ";
  3881. ByrefType += "sizeof(";
  3882. RewriteByRefString(ByrefType, Name, ND);
  3883. ByrefType += "), ";
  3884. if (HasCopyAndDispose) {
  3885. ByrefType += "__Block_byref_id_object_copy_";
  3886. ByrefType += utostr(flag);
  3887. ByrefType += ", __Block_byref_id_object_dispose_";
  3888. ByrefType += utostr(flag);
  3889. ByrefType += ", ";
  3890. }
  3891. ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
  3892. // Complete the newly synthesized compound expression by inserting a right
  3893. // curly brace before the end of the declaration.
  3894. // FIXME: This approach avoids rewriting the initializer expression. It
  3895. // also assumes there is only one declarator. For example, the following
  3896. // isn't currently supported by this routine (in general):
  3897. //
  3898. // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
  3899. //
  3900. const char *startInitializerBuf = SM->getCharacterData(startLoc);
  3901. const char *semiBuf = strchr(startInitializerBuf, ';');
  3902. assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
  3903. SourceLocation semiLoc =
  3904. startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
  3905. InsertText(semiLoc, "}");
  3906. }
  3907. }
  3908. void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
  3909. // Add initializers for any closure decl refs.
  3910. GetBlockDeclRefExprs(Exp->getBody());
  3911. if (BlockDeclRefs.size()) {
  3912. // Unique all "by copy" declarations.
  3913. for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
  3914. if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
  3915. if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
  3916. BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
  3917. BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
  3918. }
  3919. }
  3920. // Unique all "by ref" declarations.
  3921. for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
  3922. if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
  3923. if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
  3924. BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
  3925. BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
  3926. }
  3927. }
  3928. // Find any imported blocks...they will need special attention.
  3929. for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
  3930. if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
  3931. BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
  3932. BlockDeclRefs[i]->getType()->isBlockPointerType())
  3933. ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
  3934. }
  3935. }
  3936. FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
  3937. IdentifierInfo *ID = &Context->Idents.get(name);
  3938. QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
  3939. return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
  3940. SourceLocation(), ID, FType, nullptr, SC_Extern,
  3941. false, false);
  3942. }
  3943. Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
  3944. const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
  3945. const BlockDecl *block = Exp->getBlockDecl();
  3946. Blocks.push_back(Exp);
  3947. CollectBlockDeclRefInfo(Exp);
  3948. // Add inner imported variables now used in current block.
  3949. int countOfInnerDecls = 0;
  3950. if (!InnerBlockDeclRefs.empty()) {
  3951. for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
  3952. DeclRefExpr *Exp = InnerBlockDeclRefs[i];
  3953. ValueDecl *VD = Exp->getDecl();
  3954. if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
  3955. // We need to save the copied-in variables in nested
  3956. // blocks because it is needed at the end for some of the API generations.
  3957. // See SynthesizeBlockLiterals routine.
  3958. InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
  3959. BlockDeclRefs.push_back(Exp);
  3960. BlockByCopyDeclsPtrSet.insert(VD);
  3961. BlockByCopyDecls.push_back(VD);
  3962. }
  3963. if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
  3964. InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
  3965. BlockDeclRefs.push_back(Exp);
  3966. BlockByRefDeclsPtrSet.insert(VD);
  3967. BlockByRefDecls.push_back(VD);
  3968. }
  3969. }
  3970. // Find any imported blocks...they will need special attention.
  3971. for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
  3972. if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
  3973. InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
  3974. InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
  3975. ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
  3976. }
  3977. InnerDeclRefsCount.push_back(countOfInnerDecls);
  3978. std::string FuncName;
  3979. if (CurFunctionDef)
  3980. FuncName = CurFunctionDef->getNameAsString();
  3981. else if (CurMethodDef)
  3982. BuildUniqueMethodName(FuncName, CurMethodDef);
  3983. else if (GlobalVarDecl)
  3984. FuncName = std::string(GlobalVarDecl->getNameAsString());
  3985. std::string BlockNumber = utostr(Blocks.size()-1);
  3986. std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
  3987. std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
  3988. // Get a pointer to the function type so we can cast appropriately.
  3989. QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
  3990. QualType FType = Context->getPointerType(BFT);
  3991. FunctionDecl *FD;
  3992. Expr *NewRep;
  3993. // Simulate a constructor call...
  3994. FD = SynthBlockInitFunctionDecl(Tag);
  3995. DeclRefExpr *DRE = new (Context)
  3996. DeclRefExpr(*Context, FD, false, FType, VK_RValue, SourceLocation());
  3997. SmallVector<Expr*, 4> InitExprs;
  3998. // Initialize the block function.
  3999. FD = SynthBlockInitFunctionDecl(Func);
  4000. DeclRefExpr *Arg = new (Context) DeclRefExpr(
  4001. *Context, FD, false, FD->getType(), VK_LValue, SourceLocation());
  4002. CastExpr *castExpr =
  4003. NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy, CK_BitCast, Arg);
  4004. InitExprs.push_back(castExpr);
  4005. // Initialize the block descriptor.
  4006. std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
  4007. VarDecl *NewVD = VarDecl::Create(
  4008. *Context, TUDecl, SourceLocation(), SourceLocation(),
  4009. &Context->Idents.get(DescData), Context->VoidPtrTy, nullptr, SC_Static);
  4010. UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
  4011. new (Context) DeclRefExpr(*Context, NewVD, false, Context->VoidPtrTy,
  4012. VK_LValue, SourceLocation()),
  4013. UO_AddrOf, Context->getPointerType(Context->VoidPtrTy), VK_RValue,
  4014. OK_Ordinary, SourceLocation(), false);
  4015. InitExprs.push_back(DescRefExpr);
  4016. // Add initializers for any closure decl refs.
  4017. if (BlockDeclRefs.size()) {
  4018. Expr *Exp;
  4019. // Output all "by copy" declarations.
  4020. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
  4021. E = BlockByCopyDecls.end(); I != E; ++I) {
  4022. if (isObjCType((*I)->getType())) {
  4023. // FIXME: Conform to ABI ([[obj retain] autorelease]).
  4024. FD = SynthBlockInitFunctionDecl((*I)->getName());
  4025. Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
  4026. VK_LValue, SourceLocation());
  4027. if (HasLocalVariableExternalStorage(*I)) {
  4028. QualType QT = (*I)->getType();
  4029. QT = Context->getPointerType(QT);
  4030. Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
  4031. OK_Ordinary, SourceLocation(),
  4032. false);
  4033. }
  4034. } else if (isTopLevelBlockPointerType((*I)->getType())) {
  4035. FD = SynthBlockInitFunctionDecl((*I)->getName());
  4036. Arg = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
  4037. VK_LValue, SourceLocation());
  4038. Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy, CK_BitCast,
  4039. Arg);
  4040. } else {
  4041. FD = SynthBlockInitFunctionDecl((*I)->getName());
  4042. Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
  4043. VK_LValue, SourceLocation());
  4044. if (HasLocalVariableExternalStorage(*I)) {
  4045. QualType QT = (*I)->getType();
  4046. QT = Context->getPointerType(QT);
  4047. Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
  4048. OK_Ordinary, SourceLocation(),
  4049. false);
  4050. }
  4051. }
  4052. InitExprs.push_back(Exp);
  4053. }
  4054. // Output all "by ref" declarations.
  4055. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
  4056. E = BlockByRefDecls.end(); I != E; ++I) {
  4057. ValueDecl *ND = (*I);
  4058. std::string Name(ND->getNameAsString());
  4059. std::string RecName;
  4060. RewriteByRefString(RecName, Name, ND, true);
  4061. IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
  4062. + sizeof("struct"));
  4063. RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
  4064. SourceLocation(), SourceLocation(),
  4065. II);
  4066. assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
  4067. QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
  4068. FD = SynthBlockInitFunctionDecl((*I)->getName());
  4069. Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
  4070. VK_LValue, SourceLocation());
  4071. bool isNestedCapturedVar = false;
  4072. if (block)
  4073. for (const auto &CI : block->captures()) {
  4074. const VarDecl *variable = CI.getVariable();
  4075. if (variable == ND && CI.isNested()) {
  4076. assert (CI.isByRef() &&
  4077. "SynthBlockInitExpr - captured block variable is not byref");
  4078. isNestedCapturedVar = true;
  4079. break;
  4080. }
  4081. }
  4082. // captured nested byref variable has its address passed. Do not take
  4083. // its address again.
  4084. if (!isNestedCapturedVar)
  4085. Exp = new (Context) UnaryOperator(
  4086. Exp, UO_AddrOf, Context->getPointerType(Exp->getType()), VK_RValue,
  4087. OK_Ordinary, SourceLocation(), false);
  4088. Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
  4089. InitExprs.push_back(Exp);
  4090. }
  4091. }
  4092. if (ImportedBlockDecls.size()) {
  4093. // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
  4094. int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
  4095. unsigned IntSize =
  4096. static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
  4097. Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
  4098. Context->IntTy, SourceLocation());
  4099. InitExprs.push_back(FlagExp);
  4100. }
  4101. NewRep = CallExpr::Create(*Context, DRE, InitExprs, FType, VK_LValue,
  4102. SourceLocation());
  4103. NewRep = new (Context) UnaryOperator(
  4104. NewRep, UO_AddrOf, Context->getPointerType(NewRep->getType()), VK_RValue,
  4105. OK_Ordinary, SourceLocation(), false);
  4106. NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
  4107. NewRep);
  4108. BlockDeclRefs.clear();
  4109. BlockByRefDecls.clear();
  4110. BlockByRefDeclsPtrSet.clear();
  4111. BlockByCopyDecls.clear();
  4112. BlockByCopyDeclsPtrSet.clear();
  4113. ImportedBlockDecls.clear();
  4114. return NewRep;
  4115. }
  4116. bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
  4117. if (const ObjCForCollectionStmt * CS =
  4118. dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
  4119. return CS->getElement() == DS;
  4120. return false;
  4121. }
  4122. //===----------------------------------------------------------------------===//
  4123. // Function Body / Expression rewriting
  4124. //===----------------------------------------------------------------------===//
  4125. Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
  4126. if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
  4127. isa<DoStmt>(S) || isa<ForStmt>(S))
  4128. Stmts.push_back(S);
  4129. else if (isa<ObjCForCollectionStmt>(S)) {
  4130. Stmts.push_back(S);
  4131. ObjCBcLabelNo.push_back(++BcLabelCount);
  4132. }
  4133. // Pseudo-object operations and ivar references need special
  4134. // treatment because we're going to recursively rewrite them.
  4135. if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
  4136. if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
  4137. return RewritePropertyOrImplicitSetter(PseudoOp);
  4138. } else {
  4139. return RewritePropertyOrImplicitGetter(PseudoOp);
  4140. }
  4141. } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
  4142. return RewriteObjCIvarRefExpr(IvarRefExpr);
  4143. }
  4144. SourceRange OrigStmtRange = S->getSourceRange();
  4145. // Perform a bottom up rewrite of all children.
  4146. for (Stmt *&childStmt : S->children())
  4147. if (childStmt) {
  4148. Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
  4149. if (newStmt) {
  4150. childStmt = newStmt;
  4151. }
  4152. }
  4153. if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
  4154. SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
  4155. llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
  4156. InnerContexts.insert(BE->getBlockDecl());
  4157. ImportedLocalExternalDecls.clear();
  4158. GetInnerBlockDeclRefExprs(BE->getBody(),
  4159. InnerBlockDeclRefs, InnerContexts);
  4160. // Rewrite the block body in place.
  4161. Stmt *SaveCurrentBody = CurrentBody;
  4162. CurrentBody = BE->getBody();
  4163. PropParentMap = nullptr;
  4164. // block literal on rhs of a property-dot-sytax assignment
  4165. // must be replaced by its synthesize ast so getRewrittenText
  4166. // works as expected. In this case, what actually ends up on RHS
  4167. // is the blockTranscribed which is the helper function for the
  4168. // block literal; as in: self.c = ^() {[ace ARR];};
  4169. bool saveDisableReplaceStmt = DisableReplaceStmt;
  4170. DisableReplaceStmt = false;
  4171. RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
  4172. DisableReplaceStmt = saveDisableReplaceStmt;
  4173. CurrentBody = SaveCurrentBody;
  4174. PropParentMap = nullptr;
  4175. ImportedLocalExternalDecls.clear();
  4176. // Now we snarf the rewritten text and stash it away for later use.
  4177. std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
  4178. RewrittenBlockExprs[BE] = Str;
  4179. Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
  4180. //blockTranscribed->dump();
  4181. ReplaceStmt(S, blockTranscribed);
  4182. return blockTranscribed;
  4183. }
  4184. // Handle specific things.
  4185. if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
  4186. return RewriteAtEncode(AtEncode);
  4187. if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
  4188. return RewriteAtSelector(AtSelector);
  4189. if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
  4190. return RewriteObjCStringLiteral(AtString);
  4191. if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
  4192. #if 0
  4193. // Before we rewrite it, put the original message expression in a comment.
  4194. SourceLocation startLoc = MessExpr->getBeginLoc();
  4195. SourceLocation endLoc = MessExpr->getEndLoc();
  4196. const char *startBuf = SM->getCharacterData(startLoc);
  4197. const char *endBuf = SM->getCharacterData(endLoc);
  4198. std::string messString;
  4199. messString += "// ";
  4200. messString.append(startBuf, endBuf-startBuf+1);
  4201. messString += "\n";
  4202. // FIXME: Missing definition of
  4203. // InsertText(clang::SourceLocation, char const*, unsigned int).
  4204. // InsertText(startLoc, messString);
  4205. // Tried this, but it didn't work either...
  4206. // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
  4207. #endif
  4208. return RewriteMessageExpr(MessExpr);
  4209. }
  4210. if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
  4211. return RewriteObjCTryStmt(StmtTry);
  4212. if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
  4213. return RewriteObjCSynchronizedStmt(StmtTry);
  4214. if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
  4215. return RewriteObjCThrowStmt(StmtThrow);
  4216. if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
  4217. return RewriteObjCProtocolExpr(ProtocolExp);
  4218. if (ObjCForCollectionStmt *StmtForCollection =
  4219. dyn_cast<ObjCForCollectionStmt>(S))
  4220. return RewriteObjCForCollectionStmt(StmtForCollection,
  4221. OrigStmtRange.getEnd());
  4222. if (BreakStmt *StmtBreakStmt =
  4223. dyn_cast<BreakStmt>(S))
  4224. return RewriteBreakStmt(StmtBreakStmt);
  4225. if (ContinueStmt *StmtContinueStmt =
  4226. dyn_cast<ContinueStmt>(S))
  4227. return RewriteContinueStmt(StmtContinueStmt);
  4228. // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
  4229. // and cast exprs.
  4230. if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
  4231. // FIXME: What we're doing here is modifying the type-specifier that
  4232. // precedes the first Decl. In the future the DeclGroup should have
  4233. // a separate type-specifier that we can rewrite.
  4234. // NOTE: We need to avoid rewriting the DeclStmt if it is within
  4235. // the context of an ObjCForCollectionStmt. For example:
  4236. // NSArray *someArray;
  4237. // for (id <FooProtocol> index in someArray) ;
  4238. // This is because RewriteObjCForCollectionStmt() does textual rewriting
  4239. // and it depends on the original text locations/positions.
  4240. if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
  4241. RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
  4242. // Blocks rewrite rules.
  4243. for (auto *SD : DS->decls()) {
  4244. if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
  4245. if (isTopLevelBlockPointerType(ND->getType()))
  4246. RewriteBlockPointerDecl(ND);
  4247. else if (ND->getType()->isFunctionPointerType())
  4248. CheckFunctionPointerDecl(ND->getType(), ND);
  4249. if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
  4250. if (VD->hasAttr<BlocksAttr>()) {
  4251. static unsigned uniqueByrefDeclCount = 0;
  4252. assert(!BlockByRefDeclNo.count(ND) &&
  4253. "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
  4254. BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
  4255. RewriteByRefVar(VD);
  4256. }
  4257. else
  4258. RewriteTypeOfDecl(VD);
  4259. }
  4260. }
  4261. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
  4262. if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
  4263. RewriteBlockPointerDecl(TD);
  4264. else if (TD->getUnderlyingType()->isFunctionPointerType())
  4265. CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
  4266. }
  4267. }
  4268. }
  4269. if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
  4270. RewriteObjCQualifiedInterfaceTypes(CE);
  4271. if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
  4272. isa<DoStmt>(S) || isa<ForStmt>(S)) {
  4273. assert(!Stmts.empty() && "Statement stack is empty");
  4274. assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
  4275. isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
  4276. && "Statement stack mismatch");
  4277. Stmts.pop_back();
  4278. }
  4279. // Handle blocks rewriting.
  4280. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
  4281. ValueDecl *VD = DRE->getDecl();
  4282. if (VD->hasAttr<BlocksAttr>())
  4283. return RewriteBlockDeclRefExpr(DRE);
  4284. if (HasLocalVariableExternalStorage(VD))
  4285. return RewriteLocalVariableExternalStorage(DRE);
  4286. }
  4287. if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
  4288. if (CE->getCallee()->getType()->isBlockPointerType()) {
  4289. Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
  4290. ReplaceStmt(S, BlockCall);
  4291. return BlockCall;
  4292. }
  4293. }
  4294. if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
  4295. RewriteCastExpr(CE);
  4296. }
  4297. #if 0
  4298. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
  4299. CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
  4300. ICE->getSubExpr(),
  4301. SourceLocation());
  4302. // Get the new text.
  4303. std::string SStr;
  4304. llvm::raw_string_ostream Buf(SStr);
  4305. Replacement->printPretty(Buf);
  4306. const std::string &Str = Buf.str();
  4307. printf("CAST = %s\n", &Str[0]);
  4308. InsertText(ICE->getSubExpr()->getBeginLoc(), Str);
  4309. delete S;
  4310. return Replacement;
  4311. }
  4312. #endif
  4313. // Return this stmt unmodified.
  4314. return S;
  4315. }
  4316. void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
  4317. for (auto *FD : RD->fields()) {
  4318. if (isTopLevelBlockPointerType(FD->getType()))
  4319. RewriteBlockPointerDecl(FD);
  4320. if (FD->getType()->isObjCQualifiedIdType() ||
  4321. FD->getType()->isObjCQualifiedInterfaceType())
  4322. RewriteObjCQualifiedInterfaceTypes(FD);
  4323. }
  4324. }
  4325. /// HandleDeclInMainFile - This is called for each top-level decl defined in the
  4326. /// main file of the input.
  4327. void RewriteObjC::HandleDeclInMainFile(Decl *D) {
  4328. switch (D->getKind()) {
  4329. case Decl::Function: {
  4330. FunctionDecl *FD = cast<FunctionDecl>(D);
  4331. if (FD->isOverloadedOperator())
  4332. return;
  4333. // Since function prototypes don't have ParmDecl's, we check the function
  4334. // prototype. This enables us to rewrite function declarations and
  4335. // definitions using the same code.
  4336. RewriteBlocksInFunctionProtoType(FD->getType(), FD);
  4337. if (!FD->isThisDeclarationADefinition())
  4338. break;
  4339. // FIXME: If this should support Obj-C++, support CXXTryStmt
  4340. if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
  4341. CurFunctionDef = FD;
  4342. CurFunctionDeclToDeclareForBlock = FD;
  4343. CurrentBody = Body;
  4344. Body =
  4345. cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
  4346. FD->setBody(Body);
  4347. CurrentBody = nullptr;
  4348. if (PropParentMap) {
  4349. delete PropParentMap;
  4350. PropParentMap = nullptr;
  4351. }
  4352. // This synthesizes and inserts the block "impl" struct, invoke function,
  4353. // and any copy/dispose helper functions.
  4354. InsertBlockLiteralsWithinFunction(FD);
  4355. CurFunctionDef = nullptr;
  4356. CurFunctionDeclToDeclareForBlock = nullptr;
  4357. }
  4358. break;
  4359. }
  4360. case Decl::ObjCMethod: {
  4361. ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
  4362. if (CompoundStmt *Body = MD->getCompoundBody()) {
  4363. CurMethodDef = MD;
  4364. CurrentBody = Body;
  4365. Body =
  4366. cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
  4367. MD->setBody(Body);
  4368. CurrentBody = nullptr;
  4369. if (PropParentMap) {
  4370. delete PropParentMap;
  4371. PropParentMap = nullptr;
  4372. }
  4373. InsertBlockLiteralsWithinMethod(MD);
  4374. CurMethodDef = nullptr;
  4375. }
  4376. break;
  4377. }
  4378. case Decl::ObjCImplementation: {
  4379. ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
  4380. ClassImplementation.push_back(CI);
  4381. break;
  4382. }
  4383. case Decl::ObjCCategoryImpl: {
  4384. ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
  4385. CategoryImplementation.push_back(CI);
  4386. break;
  4387. }
  4388. case Decl::Var: {
  4389. VarDecl *VD = cast<VarDecl>(D);
  4390. RewriteObjCQualifiedInterfaceTypes(VD);
  4391. if (isTopLevelBlockPointerType(VD->getType()))
  4392. RewriteBlockPointerDecl(VD);
  4393. else if (VD->getType()->isFunctionPointerType()) {
  4394. CheckFunctionPointerDecl(VD->getType(), VD);
  4395. if (VD->getInit()) {
  4396. if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
  4397. RewriteCastExpr(CE);
  4398. }
  4399. }
  4400. } else if (VD->getType()->isRecordType()) {
  4401. RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
  4402. if (RD->isCompleteDefinition())
  4403. RewriteRecordBody(RD);
  4404. }
  4405. if (VD->getInit()) {
  4406. GlobalVarDecl = VD;
  4407. CurrentBody = VD->getInit();
  4408. RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
  4409. CurrentBody = nullptr;
  4410. if (PropParentMap) {
  4411. delete PropParentMap;
  4412. PropParentMap = nullptr;
  4413. }
  4414. SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
  4415. GlobalVarDecl = nullptr;
  4416. // This is needed for blocks.
  4417. if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
  4418. RewriteCastExpr(CE);
  4419. }
  4420. }
  4421. break;
  4422. }
  4423. case Decl::TypeAlias:
  4424. case Decl::Typedef: {
  4425. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
  4426. if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
  4427. RewriteBlockPointerDecl(TD);
  4428. else if (TD->getUnderlyingType()->isFunctionPointerType())
  4429. CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
  4430. }
  4431. break;
  4432. }
  4433. case Decl::CXXRecord:
  4434. case Decl::Record: {
  4435. RecordDecl *RD = cast<RecordDecl>(D);
  4436. if (RD->isCompleteDefinition())
  4437. RewriteRecordBody(RD);
  4438. break;
  4439. }
  4440. default:
  4441. break;
  4442. }
  4443. // Nothing yet.
  4444. }
  4445. void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
  4446. if (Diags.hasErrorOccurred())
  4447. return;
  4448. RewriteInclude();
  4449. // Here's a great place to add any extra declarations that may be needed.
  4450. // Write out meta data for each @protocol(<expr>).
  4451. for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls)
  4452. RewriteObjCProtocolMetaData(ProtDecl, "", "", Preamble);
  4453. InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
  4454. if (ClassImplementation.size() || CategoryImplementation.size())
  4455. RewriteImplementations();
  4456. // Get the buffer corresponding to MainFileID. If we haven't changed it, then
  4457. // we are done.
  4458. if (const RewriteBuffer *RewriteBuf =
  4459. Rewrite.getRewriteBufferFor(MainFileID)) {
  4460. //printf("Changed:\n");
  4461. *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
  4462. } else {
  4463. llvm::errs() << "No changes\n";
  4464. }
  4465. if (ClassImplementation.size() || CategoryImplementation.size() ||
  4466. ProtocolExprDecls.size()) {
  4467. // Rewrite Objective-c meta data*
  4468. std::string ResultStr;
  4469. RewriteMetaDataIntoBuffer(ResultStr);
  4470. // Emit metadata.
  4471. *OutFile << ResultStr;
  4472. }
  4473. OutFile->flush();
  4474. }
  4475. void RewriteObjCFragileABI::Initialize(ASTContext &context) {
  4476. InitializeCommon(context);
  4477. // declaring objc_selector outside the parameter list removes a silly
  4478. // scope related warning...
  4479. if (IsHeader)
  4480. Preamble = "#pragma once\n";
  4481. Preamble += "struct objc_selector; struct objc_class;\n";
  4482. Preamble += "struct __rw_objc_super { struct objc_object *object; ";
  4483. Preamble += "struct objc_object *superClass; ";
  4484. if (LangOpts.MicrosoftExt) {
  4485. // Add a constructor for creating temporary objects.
  4486. Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
  4487. ": ";
  4488. Preamble += "object(o), superClass(s) {} ";
  4489. }
  4490. Preamble += "};\n";
  4491. Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
  4492. Preamble += "typedef struct objc_object Protocol;\n";
  4493. Preamble += "#define _REWRITER_typedef_Protocol\n";
  4494. Preamble += "#endif\n";
  4495. if (LangOpts.MicrosoftExt) {
  4496. Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
  4497. Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
  4498. } else
  4499. Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
  4500. Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
  4501. Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
  4502. Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
  4503. Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
  4504. Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
  4505. Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
  4506. Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
  4507. Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
  4508. Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
  4509. Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
  4510. Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
  4511. Preamble += "(const char *);\n";
  4512. Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
  4513. Preamble += "(struct objc_class *);\n";
  4514. Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
  4515. Preamble += "(const char *);\n";
  4516. Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
  4517. Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
  4518. Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
  4519. Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
  4520. Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
  4521. Preamble += "(struct objc_class *, struct objc_object *);\n";
  4522. // @synchronized hooks.
  4523. Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter(struct objc_object *);\n";
  4524. Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit(struct objc_object *);\n";
  4525. Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
  4526. Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
  4527. Preamble += "struct __objcFastEnumerationState {\n\t";
  4528. Preamble += "unsigned long state;\n\t";
  4529. Preamble += "void **itemsPtr;\n\t";
  4530. Preamble += "unsigned long *mutationsPtr;\n\t";
  4531. Preamble += "unsigned long extra[5];\n};\n";
  4532. Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
  4533. Preamble += "#define __FASTENUMERATIONSTATE\n";
  4534. Preamble += "#endif\n";
  4535. Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
  4536. Preamble += "struct __NSConstantStringImpl {\n";
  4537. Preamble += " int *isa;\n";
  4538. Preamble += " int flags;\n";
  4539. Preamble += " char *str;\n";
  4540. Preamble += " long length;\n";
  4541. Preamble += "};\n";
  4542. Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
  4543. Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
  4544. Preamble += "#else\n";
  4545. Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
  4546. Preamble += "#endif\n";
  4547. Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
  4548. Preamble += "#endif\n";
  4549. // Blocks preamble.
  4550. Preamble += "#ifndef BLOCK_IMPL\n";
  4551. Preamble += "#define BLOCK_IMPL\n";
  4552. Preamble += "struct __block_impl {\n";
  4553. Preamble += " void *isa;\n";
  4554. Preamble += " int Flags;\n";
  4555. Preamble += " int Reserved;\n";
  4556. Preamble += " void *FuncPtr;\n";
  4557. Preamble += "};\n";
  4558. Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
  4559. Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
  4560. Preamble += "extern \"C\" __declspec(dllexport) "
  4561. "void _Block_object_assign(void *, const void *, const int);\n";
  4562. Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
  4563. Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
  4564. Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
  4565. Preamble += "#else\n";
  4566. Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
  4567. Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
  4568. Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
  4569. Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
  4570. Preamble += "#endif\n";
  4571. Preamble += "#endif\n";
  4572. if (LangOpts.MicrosoftExt) {
  4573. Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
  4574. Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
  4575. Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
  4576. Preamble += "#define __attribute__(X)\n";
  4577. Preamble += "#endif\n";
  4578. Preamble += "#define __weak\n";
  4579. }
  4580. else {
  4581. Preamble += "#define __block\n";
  4582. Preamble += "#define __weak\n";
  4583. }
  4584. // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
  4585. // as this avoids warning in any 64bit/32bit compilation model.
  4586. Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
  4587. }
  4588. /// RewriteIvarOffsetComputation - This routine synthesizes computation of
  4589. /// ivar offset.
  4590. void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
  4591. std::string &Result) {
  4592. if (ivar->isBitField()) {
  4593. // FIXME: The hack below doesn't work for bitfields. For now, we simply
  4594. // place all bitfields at offset 0.
  4595. Result += "0";
  4596. } else {
  4597. Result += "__OFFSETOFIVAR__(struct ";
  4598. Result += ivar->getContainingInterface()->getNameAsString();
  4599. if (LangOpts.MicrosoftExt)
  4600. Result += "_IMPL";
  4601. Result += ", ";
  4602. Result += ivar->getNameAsString();
  4603. Result += ")";
  4604. }
  4605. }
  4606. /// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
  4607. void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
  4608. ObjCProtocolDecl *PDecl, StringRef prefix,
  4609. StringRef ClassName, std::string &Result) {
  4610. static bool objc_protocol_methods = false;
  4611. // Output struct protocol_methods holder of method selector and type.
  4612. if (!objc_protocol_methods && PDecl->hasDefinition()) {
  4613. /* struct protocol_methods {
  4614. SEL _cmd;
  4615. char *method_types;
  4616. }
  4617. */
  4618. Result += "\nstruct _protocol_methods {\n";
  4619. Result += "\tstruct objc_selector *_cmd;\n";
  4620. Result += "\tchar *method_types;\n";
  4621. Result += "};\n";
  4622. objc_protocol_methods = true;
  4623. }
  4624. // Do not synthesize the protocol more than once.
  4625. if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
  4626. return;
  4627. if (ObjCProtocolDecl *Def = PDecl->getDefinition())
  4628. PDecl = Def;
  4629. if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
  4630. unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
  4631. PDecl->instmeth_end());
  4632. /* struct _objc_protocol_method_list {
  4633. int protocol_method_count;
  4634. struct protocol_methods protocols[];
  4635. }
  4636. */
  4637. Result += "\nstatic struct {\n";
  4638. Result += "\tint protocol_method_count;\n";
  4639. Result += "\tstruct _protocol_methods protocol_methods[";
  4640. Result += utostr(NumMethods);
  4641. Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
  4642. Result += PDecl->getNameAsString();
  4643. Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
  4644. "{\n\t" + utostr(NumMethods) + "\n";
  4645. // Output instance methods declared in this protocol.
  4646. for (ObjCProtocolDecl::instmeth_iterator
  4647. I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
  4648. I != E; ++I) {
  4649. if (I == PDecl->instmeth_begin())
  4650. Result += "\t ,{{(struct objc_selector *)\"";
  4651. else
  4652. Result += "\t ,{(struct objc_selector *)\"";
  4653. Result += (*I)->getSelector().getAsString();
  4654. std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(*I);
  4655. Result += "\", \"";
  4656. Result += MethodTypeString;
  4657. Result += "\"}\n";
  4658. }
  4659. Result += "\t }\n};\n";
  4660. }
  4661. // Output class methods declared in this protocol.
  4662. unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
  4663. PDecl->classmeth_end());
  4664. if (NumMethods > 0) {
  4665. /* struct _objc_protocol_method_list {
  4666. int protocol_method_count;
  4667. struct protocol_methods protocols[];
  4668. }
  4669. */
  4670. Result += "\nstatic struct {\n";
  4671. Result += "\tint protocol_method_count;\n";
  4672. Result += "\tstruct _protocol_methods protocol_methods[";
  4673. Result += utostr(NumMethods);
  4674. Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
  4675. Result += PDecl->getNameAsString();
  4676. Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
  4677. "{\n\t";
  4678. Result += utostr(NumMethods);
  4679. Result += "\n";
  4680. // Output instance methods declared in this protocol.
  4681. for (ObjCProtocolDecl::classmeth_iterator
  4682. I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
  4683. I != E; ++I) {
  4684. if (I == PDecl->classmeth_begin())
  4685. Result += "\t ,{{(struct objc_selector *)\"";
  4686. else
  4687. Result += "\t ,{(struct objc_selector *)\"";
  4688. Result += (*I)->getSelector().getAsString();
  4689. std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(*I);
  4690. Result += "\", \"";
  4691. Result += MethodTypeString;
  4692. Result += "\"}\n";
  4693. }
  4694. Result += "\t }\n};\n";
  4695. }
  4696. // Output:
  4697. /* struct _objc_protocol {
  4698. // Objective-C 1.0 extensions
  4699. struct _objc_protocol_extension *isa;
  4700. char *protocol_name;
  4701. struct _objc_protocol **protocol_list;
  4702. struct _objc_protocol_method_list *instance_methods;
  4703. struct _objc_protocol_method_list *class_methods;
  4704. };
  4705. */
  4706. static bool objc_protocol = false;
  4707. if (!objc_protocol) {
  4708. Result += "\nstruct _objc_protocol {\n";
  4709. Result += "\tstruct _objc_protocol_extension *isa;\n";
  4710. Result += "\tchar *protocol_name;\n";
  4711. Result += "\tstruct _objc_protocol **protocol_list;\n";
  4712. Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
  4713. Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
  4714. Result += "};\n";
  4715. objc_protocol = true;
  4716. }
  4717. Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
  4718. Result += PDecl->getNameAsString();
  4719. Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
  4720. "{\n\t0, \"";
  4721. Result += PDecl->getNameAsString();
  4722. Result += "\", 0, ";
  4723. if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
  4724. Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
  4725. Result += PDecl->getNameAsString();
  4726. Result += ", ";
  4727. }
  4728. else
  4729. Result += "0, ";
  4730. if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
  4731. Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
  4732. Result += PDecl->getNameAsString();
  4733. Result += "\n";
  4734. }
  4735. else
  4736. Result += "0\n";
  4737. Result += "};\n";
  4738. // Mark this protocol as having been generated.
  4739. if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
  4740. llvm_unreachable("protocol already synthesized");
  4741. }
  4742. void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
  4743. const ObjCList<ObjCProtocolDecl> &Protocols,
  4744. StringRef prefix, StringRef ClassName,
  4745. std::string &Result) {
  4746. if (Protocols.empty()) return;
  4747. for (unsigned i = 0; i != Protocols.size(); i++)
  4748. RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
  4749. // Output the top lovel protocol meta-data for the class.
  4750. /* struct _objc_protocol_list {
  4751. struct _objc_protocol_list *next;
  4752. int protocol_count;
  4753. struct _objc_protocol *class_protocols[];
  4754. }
  4755. */
  4756. Result += "\nstatic struct {\n";
  4757. Result += "\tstruct _objc_protocol_list *next;\n";
  4758. Result += "\tint protocol_count;\n";
  4759. Result += "\tstruct _objc_protocol *class_protocols[";
  4760. Result += utostr(Protocols.size());
  4761. Result += "];\n} _OBJC_";
  4762. Result += prefix;
  4763. Result += "_PROTOCOLS_";
  4764. Result += ClassName;
  4765. Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
  4766. "{\n\t0, ";
  4767. Result += utostr(Protocols.size());
  4768. Result += "\n";
  4769. Result += "\t,{&_OBJC_PROTOCOL_";
  4770. Result += Protocols[0]->getNameAsString();
  4771. Result += " \n";
  4772. for (unsigned i = 1; i != Protocols.size(); i++) {
  4773. Result += "\t ,&_OBJC_PROTOCOL_";
  4774. Result += Protocols[i]->getNameAsString();
  4775. Result += "\n";
  4776. }
  4777. Result += "\t }\n};\n";
  4778. }
  4779. void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
  4780. std::string &Result) {
  4781. ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
  4782. // Explicitly declared @interface's are already synthesized.
  4783. if (CDecl->isImplicitInterfaceDecl()) {
  4784. // FIXME: Implementation of a class with no @interface (legacy) does not
  4785. // produce correct synthesis as yet.
  4786. RewriteObjCInternalStruct(CDecl, Result);
  4787. }
  4788. // Build _objc_ivar_list metadata for classes ivars if needed
  4789. unsigned NumIvars = !IDecl->ivar_empty()
  4790. ? IDecl->ivar_size()
  4791. : (CDecl ? CDecl->ivar_size() : 0);
  4792. if (NumIvars > 0) {
  4793. static bool objc_ivar = false;
  4794. if (!objc_ivar) {
  4795. /* struct _objc_ivar {
  4796. char *ivar_name;
  4797. char *ivar_type;
  4798. int ivar_offset;
  4799. };
  4800. */
  4801. Result += "\nstruct _objc_ivar {\n";
  4802. Result += "\tchar *ivar_name;\n";
  4803. Result += "\tchar *ivar_type;\n";
  4804. Result += "\tint ivar_offset;\n";
  4805. Result += "};\n";
  4806. objc_ivar = true;
  4807. }
  4808. /* struct {
  4809. int ivar_count;
  4810. struct _objc_ivar ivar_list[nIvars];
  4811. };
  4812. */
  4813. Result += "\nstatic struct {\n";
  4814. Result += "\tint ivar_count;\n";
  4815. Result += "\tstruct _objc_ivar ivar_list[";
  4816. Result += utostr(NumIvars);
  4817. Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
  4818. Result += IDecl->getNameAsString();
  4819. Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
  4820. "{\n\t";
  4821. Result += utostr(NumIvars);
  4822. Result += "\n";
  4823. ObjCInterfaceDecl::ivar_iterator IVI, IVE;
  4824. SmallVector<ObjCIvarDecl *, 8> IVars;
  4825. if (!IDecl->ivar_empty()) {
  4826. for (auto *IV : IDecl->ivars())
  4827. IVars.push_back(IV);
  4828. IVI = IDecl->ivar_begin();
  4829. IVE = IDecl->ivar_end();
  4830. } else {
  4831. IVI = CDecl->ivar_begin();
  4832. IVE = CDecl->ivar_end();
  4833. }
  4834. Result += "\t,{{\"";
  4835. Result += IVI->getNameAsString();
  4836. Result += "\", \"";
  4837. std::string TmpString, StrEncoding;
  4838. Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
  4839. QuoteDoublequotes(TmpString, StrEncoding);
  4840. Result += StrEncoding;
  4841. Result += "\", ";
  4842. RewriteIvarOffsetComputation(*IVI, Result);
  4843. Result += "}\n";
  4844. for (++IVI; IVI != IVE; ++IVI) {
  4845. Result += "\t ,{\"";
  4846. Result += IVI->getNameAsString();
  4847. Result += "\", \"";
  4848. std::string TmpString, StrEncoding;
  4849. Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
  4850. QuoteDoublequotes(TmpString, StrEncoding);
  4851. Result += StrEncoding;
  4852. Result += "\", ";
  4853. RewriteIvarOffsetComputation(*IVI, Result);
  4854. Result += "}\n";
  4855. }
  4856. Result += "\t }\n};\n";
  4857. }
  4858. // Build _objc_method_list for class's instance methods if needed
  4859. SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
  4860. // If any of our property implementations have associated getters or
  4861. // setters, produce metadata for them as well.
  4862. for (const auto *Prop : IDecl->property_impls()) {
  4863. if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
  4864. continue;
  4865. if (!Prop->getPropertyIvarDecl())
  4866. continue;
  4867. ObjCPropertyDecl *PD = Prop->getPropertyDecl();
  4868. if (!PD)
  4869. continue;
  4870. if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
  4871. if (!Getter->isDefined())
  4872. InstanceMethods.push_back(Getter);
  4873. if (PD->isReadOnly())
  4874. continue;
  4875. if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
  4876. if (!Setter->isDefined())
  4877. InstanceMethods.push_back(Setter);
  4878. }
  4879. RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
  4880. true, "", IDecl->getName(), Result);
  4881. // Build _objc_method_list for class's class methods if needed
  4882. RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
  4883. false, "", IDecl->getName(), Result);
  4884. // Protocols referenced in class declaration?
  4885. RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
  4886. "CLASS", CDecl->getName(), Result);
  4887. // Declaration of class/meta-class metadata
  4888. /* struct _objc_class {
  4889. struct _objc_class *isa; // or const char *root_class_name when metadata
  4890. const char *super_class_name;
  4891. char *name;
  4892. long version;
  4893. long info;
  4894. long instance_size;
  4895. struct _objc_ivar_list *ivars;
  4896. struct _objc_method_list *methods;
  4897. struct objc_cache *cache;
  4898. struct objc_protocol_list *protocols;
  4899. const char *ivar_layout;
  4900. struct _objc_class_ext *ext;
  4901. };
  4902. */
  4903. static bool objc_class = false;
  4904. if (!objc_class) {
  4905. Result += "\nstruct _objc_class {\n";
  4906. Result += "\tstruct _objc_class *isa;\n";
  4907. Result += "\tconst char *super_class_name;\n";
  4908. Result += "\tchar *name;\n";
  4909. Result += "\tlong version;\n";
  4910. Result += "\tlong info;\n";
  4911. Result += "\tlong instance_size;\n";
  4912. Result += "\tstruct _objc_ivar_list *ivars;\n";
  4913. Result += "\tstruct _objc_method_list *methods;\n";
  4914. Result += "\tstruct objc_cache *cache;\n";
  4915. Result += "\tstruct _objc_protocol_list *protocols;\n";
  4916. Result += "\tconst char *ivar_layout;\n";
  4917. Result += "\tstruct _objc_class_ext *ext;\n";
  4918. Result += "};\n";
  4919. objc_class = true;
  4920. }
  4921. // Meta-class metadata generation.
  4922. ObjCInterfaceDecl *RootClass = nullptr;
  4923. ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
  4924. while (SuperClass) {
  4925. RootClass = SuperClass;
  4926. SuperClass = SuperClass->getSuperClass();
  4927. }
  4928. SuperClass = CDecl->getSuperClass();
  4929. Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
  4930. Result += CDecl->getNameAsString();
  4931. Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
  4932. "{\n\t(struct _objc_class *)\"";
  4933. Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
  4934. Result += "\"";
  4935. if (SuperClass) {
  4936. Result += ", \"";
  4937. Result += SuperClass->getNameAsString();
  4938. Result += "\", \"";
  4939. Result += CDecl->getNameAsString();
  4940. Result += "\"";
  4941. }
  4942. else {
  4943. Result += ", 0, \"";
  4944. Result += CDecl->getNameAsString();
  4945. Result += "\"";
  4946. }
  4947. // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
  4948. // 'info' field is initialized to CLS_META(2) for metaclass
  4949. Result += ", 0,2, sizeof(struct _objc_class), 0";
  4950. if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
  4951. Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
  4952. Result += IDecl->getNameAsString();
  4953. Result += "\n";
  4954. }
  4955. else
  4956. Result += ", 0\n";
  4957. if (CDecl->protocol_begin() != CDecl->protocol_end()) {
  4958. Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
  4959. Result += CDecl->getNameAsString();
  4960. Result += ",0,0\n";
  4961. }
  4962. else
  4963. Result += "\t,0,0,0,0\n";
  4964. Result += "};\n";
  4965. // class metadata generation.
  4966. Result += "\nstatic struct _objc_class _OBJC_CLASS_";
  4967. Result += CDecl->getNameAsString();
  4968. Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
  4969. "{\n\t&_OBJC_METACLASS_";
  4970. Result += CDecl->getNameAsString();
  4971. if (SuperClass) {
  4972. Result += ", \"";
  4973. Result += SuperClass->getNameAsString();
  4974. Result += "\", \"";
  4975. Result += CDecl->getNameAsString();
  4976. Result += "\"";
  4977. }
  4978. else {
  4979. Result += ", 0, \"";
  4980. Result += CDecl->getNameAsString();
  4981. Result += "\"";
  4982. }
  4983. // 'info' field is initialized to CLS_CLASS(1) for class
  4984. Result += ", 0,1";
  4985. if (!ObjCSynthesizedStructs.count(CDecl))
  4986. Result += ",0";
  4987. else {
  4988. // class has size. Must synthesize its size.
  4989. Result += ",sizeof(struct ";
  4990. Result += CDecl->getNameAsString();
  4991. if (LangOpts.MicrosoftExt)
  4992. Result += "_IMPL";
  4993. Result += ")";
  4994. }
  4995. if (NumIvars > 0) {
  4996. Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
  4997. Result += CDecl->getNameAsString();
  4998. Result += "\n\t";
  4999. }
  5000. else
  5001. Result += ",0";
  5002. if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
  5003. Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
  5004. Result += CDecl->getNameAsString();
  5005. Result += ", 0\n\t";
  5006. }
  5007. else
  5008. Result += ",0,0";
  5009. if (CDecl->protocol_begin() != CDecl->protocol_end()) {
  5010. Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
  5011. Result += CDecl->getNameAsString();
  5012. Result += ", 0,0\n";
  5013. }
  5014. else
  5015. Result += ",0,0,0\n";
  5016. Result += "};\n";
  5017. }
  5018. void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
  5019. int ClsDefCount = ClassImplementation.size();
  5020. int CatDefCount = CategoryImplementation.size();
  5021. // For each implemented class, write out all its meta data.
  5022. for (int i = 0; i < ClsDefCount; i++)
  5023. RewriteObjCClassMetaData(ClassImplementation[i], Result);
  5024. // For each implemented category, write out all its meta data.
  5025. for (int i = 0; i < CatDefCount; i++)
  5026. RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
  5027. // Write objc_symtab metadata
  5028. /*
  5029. struct _objc_symtab
  5030. {
  5031. long sel_ref_cnt;
  5032. SEL *refs;
  5033. short cls_def_cnt;
  5034. short cat_def_cnt;
  5035. void *defs[cls_def_cnt + cat_def_cnt];
  5036. };
  5037. */
  5038. Result += "\nstruct _objc_symtab {\n";
  5039. Result += "\tlong sel_ref_cnt;\n";
  5040. Result += "\tSEL *refs;\n";
  5041. Result += "\tshort cls_def_cnt;\n";
  5042. Result += "\tshort cat_def_cnt;\n";
  5043. Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
  5044. Result += "};\n\n";
  5045. Result += "static struct _objc_symtab "
  5046. "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
  5047. Result += "\t0, 0, " + utostr(ClsDefCount)
  5048. + ", " + utostr(CatDefCount) + "\n";
  5049. for (int i = 0; i < ClsDefCount; i++) {
  5050. Result += "\t,&_OBJC_CLASS_";
  5051. Result += ClassImplementation[i]->getNameAsString();
  5052. Result += "\n";
  5053. }
  5054. for (int i = 0; i < CatDefCount; i++) {
  5055. Result += "\t,&_OBJC_CATEGORY_";
  5056. Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
  5057. Result += "_";
  5058. Result += CategoryImplementation[i]->getNameAsString();
  5059. Result += "\n";
  5060. }
  5061. Result += "};\n\n";
  5062. // Write objc_module metadata
  5063. /*
  5064. struct _objc_module {
  5065. long version;
  5066. long size;
  5067. const char *name;
  5068. struct _objc_symtab *symtab;
  5069. }
  5070. */
  5071. Result += "\nstruct _objc_module {\n";
  5072. Result += "\tlong version;\n";
  5073. Result += "\tlong size;\n";
  5074. Result += "\tconst char *name;\n";
  5075. Result += "\tstruct _objc_symtab *symtab;\n";
  5076. Result += "};\n\n";
  5077. Result += "static struct _objc_module "
  5078. "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
  5079. Result += "\t" + utostr(OBJC_ABI_VERSION) +
  5080. ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
  5081. Result += "};\n\n";
  5082. if (LangOpts.MicrosoftExt) {
  5083. if (ProtocolExprDecls.size()) {
  5084. Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
  5085. Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
  5086. for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
  5087. Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
  5088. Result += ProtDecl->getNameAsString();
  5089. Result += " = &_OBJC_PROTOCOL_";
  5090. Result += ProtDecl->getNameAsString();
  5091. Result += ";\n";
  5092. }
  5093. Result += "#pragma data_seg(pop)\n\n";
  5094. }
  5095. Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
  5096. Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
  5097. Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
  5098. Result += "&_OBJC_MODULES;\n";
  5099. Result += "#pragma data_seg(pop)\n\n";
  5100. }
  5101. }
  5102. /// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
  5103. /// implementation.
  5104. void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
  5105. std::string &Result) {
  5106. ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
  5107. // Find category declaration for this implementation.
  5108. ObjCCategoryDecl *CDecl
  5109. = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
  5110. std::string FullCategoryName = ClassDecl->getNameAsString();
  5111. FullCategoryName += '_';
  5112. FullCategoryName += IDecl->getNameAsString();
  5113. // Build _objc_method_list for class's instance methods if needed
  5114. SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
  5115. // If any of our property implementations have associated getters or
  5116. // setters, produce metadata for them as well.
  5117. for (const auto *Prop : IDecl->property_impls()) {
  5118. if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
  5119. continue;
  5120. if (!Prop->getPropertyIvarDecl())
  5121. continue;
  5122. ObjCPropertyDecl *PD = Prop->getPropertyDecl();
  5123. if (!PD)
  5124. continue;
  5125. if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
  5126. InstanceMethods.push_back(Getter);
  5127. if (PD->isReadOnly())
  5128. continue;
  5129. if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
  5130. InstanceMethods.push_back(Setter);
  5131. }
  5132. RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
  5133. true, "CATEGORY_", FullCategoryName, Result);
  5134. // Build _objc_method_list for class's class methods if needed
  5135. RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
  5136. false, "CATEGORY_", FullCategoryName, Result);
  5137. // Protocols referenced in class declaration?
  5138. // Null CDecl is case of a category implementation with no category interface
  5139. if (CDecl)
  5140. RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
  5141. FullCategoryName, Result);
  5142. /* struct _objc_category {
  5143. char *category_name;
  5144. char *class_name;
  5145. struct _objc_method_list *instance_methods;
  5146. struct _objc_method_list *class_methods;
  5147. struct _objc_protocol_list *protocols;
  5148. // Objective-C 1.0 extensions
  5149. uint32_t size; // sizeof (struct _objc_category)
  5150. struct _objc_property_list *instance_properties; // category's own
  5151. // @property decl.
  5152. };
  5153. */
  5154. static bool objc_category = false;
  5155. if (!objc_category) {
  5156. Result += "\nstruct _objc_category {\n";
  5157. Result += "\tchar *category_name;\n";
  5158. Result += "\tchar *class_name;\n";
  5159. Result += "\tstruct _objc_method_list *instance_methods;\n";
  5160. Result += "\tstruct _objc_method_list *class_methods;\n";
  5161. Result += "\tstruct _objc_protocol_list *protocols;\n";
  5162. Result += "\tunsigned int size;\n";
  5163. Result += "\tstruct _objc_property_list *instance_properties;\n";
  5164. Result += "};\n";
  5165. objc_category = true;
  5166. }
  5167. Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
  5168. Result += FullCategoryName;
  5169. Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
  5170. Result += IDecl->getNameAsString();
  5171. Result += "\"\n\t, \"";
  5172. Result += ClassDecl->getNameAsString();
  5173. Result += "\"\n";
  5174. if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
  5175. Result += "\t, (struct _objc_method_list *)"
  5176. "&_OBJC_CATEGORY_INSTANCE_METHODS_";
  5177. Result += FullCategoryName;
  5178. Result += "\n";
  5179. }
  5180. else
  5181. Result += "\t, 0\n";
  5182. if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
  5183. Result += "\t, (struct _objc_method_list *)"
  5184. "&_OBJC_CATEGORY_CLASS_METHODS_";
  5185. Result += FullCategoryName;
  5186. Result += "\n";
  5187. }
  5188. else
  5189. Result += "\t, 0\n";
  5190. if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
  5191. Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
  5192. Result += FullCategoryName;
  5193. Result += "\n";
  5194. }
  5195. else
  5196. Result += "\t, 0\n";
  5197. Result += "\t, sizeof(struct _objc_category), 0\n};\n";
  5198. }
  5199. // RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
  5200. /// class methods.
  5201. template<typename MethodIterator>
  5202. void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
  5203. MethodIterator MethodEnd,
  5204. bool IsInstanceMethod,
  5205. StringRef prefix,
  5206. StringRef ClassName,
  5207. std::string &Result) {
  5208. if (MethodBegin == MethodEnd) return;
  5209. if (!objc_impl_method) {
  5210. /* struct _objc_method {
  5211. SEL _cmd;
  5212. char *method_types;
  5213. void *_imp;
  5214. }
  5215. */
  5216. Result += "\nstruct _objc_method {\n";
  5217. Result += "\tSEL _cmd;\n";
  5218. Result += "\tchar *method_types;\n";
  5219. Result += "\tvoid *_imp;\n";
  5220. Result += "};\n";
  5221. objc_impl_method = true;
  5222. }
  5223. // Build _objc_method_list for class's methods if needed
  5224. /* struct {
  5225. struct _objc_method_list *next_method;
  5226. int method_count;
  5227. struct _objc_method method_list[];
  5228. }
  5229. */
  5230. unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
  5231. Result += "\nstatic struct {\n";
  5232. Result += "\tstruct _objc_method_list *next_method;\n";
  5233. Result += "\tint method_count;\n";
  5234. Result += "\tstruct _objc_method method_list[";
  5235. Result += utostr(NumMethods);
  5236. Result += "];\n} _OBJC_";
  5237. Result += prefix;
  5238. Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
  5239. Result += "_METHODS_";
  5240. Result += ClassName;
  5241. Result += " __attribute__ ((used, section (\"__OBJC, __";
  5242. Result += IsInstanceMethod ? "inst" : "cls";
  5243. Result += "_meth\")))= ";
  5244. Result += "{\n\t0, " + utostr(NumMethods) + "\n";
  5245. Result += "\t,{{(SEL)\"";
  5246. Result += (*MethodBegin)->getSelector().getAsString();
  5247. std::string MethodTypeString =
  5248. Context->getObjCEncodingForMethodDecl(*MethodBegin);
  5249. Result += "\", \"";
  5250. Result += MethodTypeString;
  5251. Result += "\", (void *)";
  5252. Result += MethodInternalNames[*MethodBegin];
  5253. Result += "}\n";
  5254. for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
  5255. Result += "\t ,{(SEL)\"";
  5256. Result += (*MethodBegin)->getSelector().getAsString();
  5257. std::string MethodTypeString =
  5258. Context->getObjCEncodingForMethodDecl(*MethodBegin);
  5259. Result += "\", \"";
  5260. Result += MethodTypeString;
  5261. Result += "\", (void *)";
  5262. Result += MethodInternalNames[*MethodBegin];
  5263. Result += "}\n";
  5264. }
  5265. Result += "\t }\n};\n";
  5266. }
  5267. Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
  5268. SourceRange OldRange = IV->getSourceRange();
  5269. Expr *BaseExpr = IV->getBase();
  5270. // Rewrite the base, but without actually doing replaces.
  5271. {
  5272. DisableReplaceStmtScope S(*this);
  5273. BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
  5274. IV->setBase(BaseExpr);
  5275. }
  5276. ObjCIvarDecl *D = IV->getDecl();
  5277. Expr *Replacement = IV;
  5278. if (CurMethodDef) {
  5279. if (BaseExpr->getType()->isObjCObjectPointerType()) {
  5280. const ObjCInterfaceType *iFaceDecl =
  5281. dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
  5282. assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
  5283. // lookup which class implements the instance variable.
  5284. ObjCInterfaceDecl *clsDeclared = nullptr;
  5285. iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
  5286. clsDeclared);
  5287. assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
  5288. // Synthesize an explicit cast to gain access to the ivar.
  5289. std::string RecName = clsDeclared->getIdentifier()->getName();
  5290. RecName += "_IMPL";
  5291. IdentifierInfo *II = &Context->Idents.get(RecName);
  5292. RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
  5293. SourceLocation(), SourceLocation(),
  5294. II);
  5295. assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
  5296. QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
  5297. CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
  5298. CK_BitCast,
  5299. IV->getBase());
  5300. // Don't forget the parens to enforce the proper binding.
  5301. ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
  5302. OldRange.getEnd(),
  5303. castExpr);
  5304. if (IV->isFreeIvar() &&
  5305. declaresSameEntity(CurMethodDef->getClassInterface(),
  5306. iFaceDecl->getDecl())) {
  5307. MemberExpr *ME = MemberExpr::CreateImplicit(
  5308. *Context, PE, true, D, D->getType(), VK_LValue, OK_Ordinary);
  5309. Replacement = ME;
  5310. } else {
  5311. IV->setBase(PE);
  5312. }
  5313. }
  5314. } else { // we are outside a method.
  5315. assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
  5316. // Explicit ivar refs need to have a cast inserted.
  5317. // FIXME: consider sharing some of this code with the code above.
  5318. if (BaseExpr->getType()->isObjCObjectPointerType()) {
  5319. const ObjCInterfaceType *iFaceDecl =
  5320. dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
  5321. // lookup which class implements the instance variable.
  5322. ObjCInterfaceDecl *clsDeclared = nullptr;
  5323. iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
  5324. clsDeclared);
  5325. assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
  5326. // Synthesize an explicit cast to gain access to the ivar.
  5327. std::string RecName = clsDeclared->getIdentifier()->getName();
  5328. RecName += "_IMPL";
  5329. IdentifierInfo *II = &Context->Idents.get(RecName);
  5330. RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
  5331. SourceLocation(), SourceLocation(),
  5332. II);
  5333. assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
  5334. QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
  5335. CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
  5336. CK_BitCast,
  5337. IV->getBase());
  5338. // Don't forget the parens to enforce the proper binding.
  5339. ParenExpr *PE = new (Context) ParenExpr(
  5340. IV->getBase()->getBeginLoc(), IV->getBase()->getEndLoc(), castExpr);
  5341. // Cannot delete IV->getBase(), since PE points to it.
  5342. // Replace the old base with the cast. This is important when doing
  5343. // embedded rewrites. For example, [newInv->_container addObject:0].
  5344. IV->setBase(PE);
  5345. }
  5346. }
  5347. ReplaceStmtWithRange(IV, Replacement, OldRange);
  5348. return Replacement;
  5349. }
  5350. #endif // CLANG_ENABLE_OBJC_REWRITER