RewriteObjC.cpp 228 KB

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