RewriteObjC.cpp 226 KB

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