RewriteModernObjC.cpp 288 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569
  1. //===-- RewriteModernObjC.cpp - Playground for the code rewriter ----------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Hacks and fun related to the code rewriter.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Rewrite/Frontend/ASTConsumers.h"
  13. #include "clang/AST/AST.h"
  14. #include "clang/AST/ASTConsumer.h"
  15. #include "clang/AST/Attr.h"
  16. #include "clang/AST/ParentMap.h"
  17. #include "clang/Basic/CharInfo.h"
  18. #include "clang/Basic/Diagnostic.h"
  19. #include "clang/Basic/IdentifierTable.h"
  20. #include "clang/Basic/SourceManager.h"
  21. #include "clang/Basic/TargetInfo.h"
  22. #include "clang/Config/config.h"
  23. #include "clang/Lex/Lexer.h"
  24. #include "clang/Rewrite/Core/Rewriter.h"
  25. #include "llvm/ADT/DenseSet.h"
  26. #include "llvm/ADT/SmallPtrSet.h"
  27. #include "llvm/ADT/StringExtras.h"
  28. #include "llvm/Support/MemoryBuffer.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. #include <memory>
  31. #if CLANG_ENABLE_OBJC_REWRITER
  32. using namespace clang;
  33. using llvm::utostr;
  34. namespace {
  35. class RewriteModernObjC : public ASTConsumer {
  36. protected:
  37. enum {
  38. BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
  39. block, ... */
  40. BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
  41. BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
  42. __block variable */
  43. BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
  44. helpers */
  45. BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
  46. support routines */
  47. BLOCK_BYREF_CURRENT_MAX = 256
  48. };
  49. enum {
  50. BLOCK_NEEDS_FREE = (1 << 24),
  51. BLOCK_HAS_COPY_DISPOSE = (1 << 25),
  52. BLOCK_HAS_CXX_OBJ = (1 << 26),
  53. BLOCK_IS_GC = (1 << 27),
  54. BLOCK_IS_GLOBAL = (1 << 28),
  55. BLOCK_HAS_DESCRIPTOR = (1 << 29)
  56. };
  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. Expr *GlobalConstructionExp;
  73. unsigned RewriteFailedDiag;
  74. unsigned GlobalBlockRewriteFailedDiag;
  75. // ObjC string constant support.
  76. unsigned NumObjCStringLiterals;
  77. VarDecl *ConstantStringClassReference;
  78. RecordDecl *NSStringRecord;
  79. // ObjC foreach break/continue generation support.
  80. int BcLabelCount;
  81. unsigned TryFinallyContainsReturnDiag;
  82. // Needed for super.
  83. ObjCMethodDecl *CurMethodDef;
  84. RecordDecl *SuperStructDecl;
  85. RecordDecl *ConstantStringDecl;
  86. FunctionDecl *MsgSendFunctionDecl;
  87. FunctionDecl *MsgSendSuperFunctionDecl;
  88. FunctionDecl *MsgSendStretFunctionDecl;
  89. FunctionDecl *MsgSendSuperStretFunctionDecl;
  90. FunctionDecl *MsgSendFpretFunctionDecl;
  91. FunctionDecl *GetClassFunctionDecl;
  92. FunctionDecl *GetMetaClassFunctionDecl;
  93. FunctionDecl *GetSuperClassFunctionDecl;
  94. FunctionDecl *SelGetUidFunctionDecl;
  95. FunctionDecl *CFStringFunctionDecl;
  96. FunctionDecl *SuperConstructorFunctionDecl;
  97. FunctionDecl *CurFunctionDef;
  98. /* Misc. containers needed for meta-data rewrite. */
  99. SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
  100. SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
  101. llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
  102. llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
  103. llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
  104. llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
  105. SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
  106. /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
  107. SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
  108. /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
  109. SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
  110. SmallVector<Stmt *, 32> Stmts;
  111. SmallVector<int, 8> ObjCBcLabelNo;
  112. // Remember all the @protocol(<expr>) expressions.
  113. llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
  114. llvm::DenseSet<uint64_t> CopyDestroyCache;
  115. // Block expressions.
  116. SmallVector<BlockExpr *, 32> Blocks;
  117. SmallVector<int, 32> InnerDeclRefsCount;
  118. SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
  119. SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
  120. // Block related declarations.
  121. SmallVector<ValueDecl *, 8> BlockByCopyDecls;
  122. llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
  123. SmallVector<ValueDecl *, 8> BlockByRefDecls;
  124. llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
  125. llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
  126. llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
  127. llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
  128. llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
  129. llvm::DenseMap<ObjCInterfaceDecl *,
  130. llvm::SmallSetVector<ObjCIvarDecl *, 8> > ReferencedIvars;
  131. // ivar bitfield grouping containers
  132. llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups;
  133. llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber;
  134. // This container maps an <class, group number for ivar> tuple to the type
  135. // of the struct where the bitfield belongs.
  136. llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType;
  137. SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen;
  138. // This maps an original source AST to it's rewritten form. This allows
  139. // us to avoid rewriting the same node twice (which is very uncommon).
  140. // This is needed to support some of the exotic property rewriting.
  141. llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
  142. // Needed for header files being rewritten
  143. bool IsHeader;
  144. bool SilenceRewriteMacroWarning;
  145. bool GenerateLineInfo;
  146. bool objc_impl_method;
  147. bool DisableReplaceStmt;
  148. class DisableReplaceStmtScope {
  149. RewriteModernObjC &R;
  150. bool SavedValue;
  151. public:
  152. DisableReplaceStmtScope(RewriteModernObjC &R)
  153. : R(R), SavedValue(R.DisableReplaceStmt) {
  154. R.DisableReplaceStmt = true;
  155. }
  156. ~DisableReplaceStmtScope() {
  157. R.DisableReplaceStmt = SavedValue;
  158. }
  159. };
  160. void InitializeCommon(ASTContext &context);
  161. public:
  162. llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
  163. // Top Level Driver code.
  164. bool HandleTopLevelDecl(DeclGroupRef D) override {
  165. for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
  166. if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
  167. if (!Class->isThisDeclarationADefinition()) {
  168. RewriteForwardClassDecl(D);
  169. break;
  170. } else {
  171. // Keep track of all interface declarations seen.
  172. ObjCInterfacesSeen.push_back(Class);
  173. break;
  174. }
  175. }
  176. if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
  177. if (!Proto->isThisDeclarationADefinition()) {
  178. RewriteForwardProtocolDecl(D);
  179. break;
  180. }
  181. }
  182. if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I)) {
  183. // Under modern abi, we cannot translate body of the function
  184. // yet until all class extensions and its implementation is seen.
  185. // This is because they may introduce new bitfields which must go
  186. // into their grouping struct.
  187. if (FDecl->isThisDeclarationADefinition() &&
  188. // Not c functions defined inside an objc container.
  189. !FDecl->isTopLevelDeclInObjCContainer()) {
  190. FunctionDefinitionsSeen.push_back(FDecl);
  191. break;
  192. }
  193. }
  194. HandleTopLevelSingleDecl(*I);
  195. }
  196. return true;
  197. }
  198. void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
  199. for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
  200. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(*I)) {
  201. if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
  202. RewriteBlockPointerDecl(TD);
  203. else if (TD->getUnderlyingType()->isFunctionPointerType())
  204. CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
  205. else
  206. RewriteObjCQualifiedInterfaceTypes(TD);
  207. }
  208. }
  209. }
  210. void HandleTopLevelSingleDecl(Decl *D);
  211. void HandleDeclInMainFile(Decl *D);
  212. RewriteModernObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
  213. DiagnosticsEngine &D, const LangOptions &LOpts,
  214. bool silenceMacroWarn, bool LineInfo);
  215. ~RewriteModernObjC() override {}
  216. void HandleTranslationUnit(ASTContext &C) override;
  217. void ReplaceStmt(Stmt *Old, Stmt *New) {
  218. ReplaceStmtWithRange(Old, New, Old->getSourceRange());
  219. }
  220. void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
  221. assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
  222. Stmt *ReplacingStmt = ReplacedNodes[Old];
  223. if (ReplacingStmt)
  224. return; // We can't rewrite the same node twice.
  225. if (DisableReplaceStmt)
  226. return;
  227. // Measure the old text.
  228. int Size = Rewrite.getRangeSize(SrcRange);
  229. if (Size == -1) {
  230. Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
  231. << Old->getSourceRange();
  232. return;
  233. }
  234. // Get the new text.
  235. std::string SStr;
  236. llvm::raw_string_ostream S(SStr);
  237. New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
  238. const std::string &Str = S.str();
  239. // If replacement succeeded or warning disabled return with no warning.
  240. if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
  241. ReplacedNodes[Old] = New;
  242. return;
  243. }
  244. if (SilenceRewriteMacroWarning)
  245. return;
  246. Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
  247. << Old->getSourceRange();
  248. }
  249. void InsertText(SourceLocation Loc, StringRef Str,
  250. bool InsertAfter = true) {
  251. // If insertion succeeded or warning disabled return with no warning.
  252. if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
  253. SilenceRewriteMacroWarning)
  254. return;
  255. Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
  256. }
  257. void ReplaceText(SourceLocation Start, unsigned OrigLength,
  258. StringRef Str) {
  259. // If removal succeeded or warning disabled return with no warning.
  260. if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
  261. SilenceRewriteMacroWarning)
  262. return;
  263. Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
  264. }
  265. // Syntactic Rewriting.
  266. void RewriteRecordBody(RecordDecl *RD);
  267. void RewriteInclude();
  268. void RewriteLineDirective(const Decl *D);
  269. void ConvertSourceLocationToLineDirective(SourceLocation Loc,
  270. std::string &LineString);
  271. void RewriteForwardClassDecl(DeclGroupRef D);
  272. void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
  273. void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
  274. const std::string &typedefString);
  275. void RewriteImplementations();
  276. void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
  277. ObjCImplementationDecl *IMD,
  278. ObjCCategoryImplDecl *CID);
  279. void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
  280. void RewriteImplementationDecl(Decl *Dcl);
  281. void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
  282. ObjCMethodDecl *MDecl, std::string &ResultStr);
  283. void RewriteTypeIntoString(QualType T, std::string &ResultStr,
  284. const FunctionType *&FPRetType);
  285. void RewriteByRefString(std::string &ResultStr, const std::string &Name,
  286. ValueDecl *VD, bool def=false);
  287. void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
  288. void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
  289. void RewriteForwardProtocolDecl(DeclGroupRef D);
  290. void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
  291. void RewriteMethodDeclaration(ObjCMethodDecl *Method);
  292. void RewriteProperty(ObjCPropertyDecl *prop);
  293. void RewriteFunctionDecl(FunctionDecl *FD);
  294. void RewriteBlockPointerType(std::string& Str, QualType Type);
  295. void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
  296. void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
  297. void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
  298. void RewriteTypeOfDecl(VarDecl *VD);
  299. void RewriteObjCQualifiedInterfaceTypes(Expr *E);
  300. std::string getIvarAccessString(ObjCIvarDecl *D);
  301. // Expression Rewriting.
  302. Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
  303. Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
  304. Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
  305. Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
  306. Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
  307. Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
  308. Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
  309. Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
  310. Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
  311. Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
  312. Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
  313. Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
  314. Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
  315. Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
  316. Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
  317. Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
  318. Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
  319. SourceLocation OrigEnd);
  320. Stmt *RewriteBreakStmt(BreakStmt *S);
  321. Stmt *RewriteContinueStmt(ContinueStmt *S);
  322. void RewriteCastExpr(CStyleCastExpr *CE);
  323. void RewriteImplicitCastObjCExpr(CastExpr *IE);
  324. // Computes ivar bitfield group no.
  325. unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
  326. // Names field decl. for ivar bitfield group.
  327. void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
  328. // Names struct type for ivar bitfield group.
  329. void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
  330. // Names symbol for ivar bitfield group field offset.
  331. void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
  332. // Given an ivar bitfield, it builds (or finds) its group record type.
  333. QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
  334. QualType SynthesizeBitfieldGroupStructType(
  335. ObjCIvarDecl *IV,
  336. SmallVectorImpl<ObjCIvarDecl *> &IVars);
  337. // Block rewriting.
  338. void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
  339. // Block specific rewrite rules.
  340. void RewriteBlockPointerDecl(NamedDecl *VD);
  341. void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
  342. Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
  343. Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
  344. void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
  345. void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
  346. std::string &Result);
  347. void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
  348. bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
  349. bool &IsNamedDefinition);
  350. void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
  351. std::string &Result);
  352. bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
  353. void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
  354. std::string &Result);
  355. void Initialize(ASTContext &context) override;
  356. // Misc. AST transformation routines. Sometimes they end up calling
  357. // rewriting routines on the new ASTs.
  358. CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
  359. ArrayRef<Expr *> Args,
  360. SourceLocation StartLoc=SourceLocation(),
  361. SourceLocation EndLoc=SourceLocation());
  362. Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
  363. QualType returnType,
  364. SmallVectorImpl<QualType> &ArgTypes,
  365. SmallVectorImpl<Expr*> &MsgExprs,
  366. ObjCMethodDecl *Method);
  367. Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
  368. SourceLocation StartLoc=SourceLocation(),
  369. SourceLocation EndLoc=SourceLocation());
  370. void SynthCountByEnumWithState(std::string &buf);
  371. void SynthMsgSendFunctionDecl();
  372. void SynthMsgSendSuperFunctionDecl();
  373. void SynthMsgSendStretFunctionDecl();
  374. void SynthMsgSendFpretFunctionDecl();
  375. void SynthMsgSendSuperStretFunctionDecl();
  376. void SynthGetClassFunctionDecl();
  377. void SynthGetMetaClassFunctionDecl();
  378. void SynthGetSuperClassFunctionDecl();
  379. void SynthSelGetUidFunctionDecl();
  380. void SynthSuperConstructorFunctionDecl();
  381. // Rewriting metadata
  382. template<typename MethodIterator>
  383. void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
  384. MethodIterator MethodEnd,
  385. bool IsInstanceMethod,
  386. StringRef prefix,
  387. StringRef ClassName,
  388. std::string &Result);
  389. void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
  390. std::string &Result);
  391. void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
  392. std::string &Result);
  393. void RewriteClassSetupInitHook(std::string &Result);
  394. void RewriteMetaDataIntoBuffer(std::string &Result);
  395. void WriteImageInfo(std::string &Result);
  396. void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
  397. std::string &Result);
  398. void RewriteCategorySetupInitHook(std::string &Result);
  399. // Rewriting ivar
  400. void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
  401. std::string &Result);
  402. Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
  403. std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
  404. std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
  405. StringRef funcName, std::string Tag);
  406. std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
  407. StringRef funcName, std::string Tag);
  408. std::string SynthesizeBlockImpl(BlockExpr *CE,
  409. std::string Tag, std::string Desc);
  410. std::string SynthesizeBlockDescriptor(std::string DescTag,
  411. std::string ImplTag,
  412. int i, StringRef funcName,
  413. unsigned hasCopy);
  414. Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
  415. void SynthesizeBlockLiterals(SourceLocation FunLocStart,
  416. StringRef FunName);
  417. FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
  418. Stmt *SynthBlockInitExpr(BlockExpr *Exp,
  419. const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
  420. // Misc. helper routines.
  421. QualType getProtocolType();
  422. void WarnAboutReturnGotoStmts(Stmt *S);
  423. void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
  424. void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
  425. void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
  426. bool IsDeclStmtInForeachHeader(DeclStmt *DS);
  427. void CollectBlockDeclRefInfo(BlockExpr *Exp);
  428. void GetBlockDeclRefExprs(Stmt *S);
  429. void GetInnerBlockDeclRefExprs(Stmt *S,
  430. SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
  431. llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
  432. // We avoid calling Type::isBlockPointerType(), since it operates on the
  433. // canonical type. We only care if the top-level type is a closure pointer.
  434. bool isTopLevelBlockPointerType(QualType T) {
  435. return isa<BlockPointerType>(T);
  436. }
  437. /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
  438. /// to a function pointer type and upon success, returns true; false
  439. /// otherwise.
  440. bool convertBlockPointerToFunctionPointer(QualType &T) {
  441. if (isTopLevelBlockPointerType(T)) {
  442. const auto *BPT = T->castAs<BlockPointerType>();
  443. T = Context->getPointerType(BPT->getPointeeType());
  444. return true;
  445. }
  446. return false;
  447. }
  448. bool convertObjCTypeToCStyleType(QualType &T);
  449. bool needToScanForQualifiers(QualType T);
  450. QualType getSuperStructType();
  451. QualType getConstantStringStructType();
  452. QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
  453. void convertToUnqualifiedObjCType(QualType &T) {
  454. if (T->isObjCQualifiedIdType()) {
  455. bool isConst = T.isConstQualified();
  456. T = isConst ? Context->getObjCIdType().withConst()
  457. : Context->getObjCIdType();
  458. }
  459. else if (T->isObjCQualifiedClassType())
  460. T = Context->getObjCClassType();
  461. else if (T->isObjCObjectPointerType() &&
  462. T->getPointeeType()->isObjCQualifiedInterfaceType()) {
  463. if (const ObjCObjectPointerType * OBJPT =
  464. T->getAsObjCInterfacePointerType()) {
  465. const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
  466. T = QualType(IFaceT, 0);
  467. T = Context->getPointerType(T);
  468. }
  469. }
  470. }
  471. // FIXME: This predicate seems like it would be useful to add to ASTContext.
  472. bool isObjCType(QualType T) {
  473. if (!LangOpts.ObjC)
  474. return false;
  475. QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
  476. if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
  477. OCT == Context->getCanonicalType(Context->getObjCClassType()))
  478. return true;
  479. if (const PointerType *PT = OCT->getAs<PointerType>()) {
  480. if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
  481. PT->getPointeeType()->isObjCQualifiedIdType())
  482. return true;
  483. }
  484. return false;
  485. }
  486. bool PointerTypeTakesAnyBlockArguments(QualType QT);
  487. bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
  488. void GetExtentOfArgList(const char *Name, const char *&LParen,
  489. const char *&RParen);
  490. void QuoteDoublequotes(std::string &From, std::string &To) {
  491. for (unsigned i = 0; i < From.length(); i++) {
  492. if (From[i] == '"')
  493. To += "\\\"";
  494. else
  495. To += From[i];
  496. }
  497. }
  498. QualType getSimpleFunctionType(QualType result,
  499. ArrayRef<QualType> args,
  500. bool variadic = false) {
  501. if (result == Context->getObjCInstanceType())
  502. result = Context->getObjCIdType();
  503. FunctionProtoType::ExtProtoInfo fpi;
  504. fpi.Variadic = variadic;
  505. return Context->getFunctionType(result, args, fpi);
  506. }
  507. // Helper function: create a CStyleCastExpr with trivial type source info.
  508. CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
  509. CastKind Kind, Expr *E) {
  510. TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
  511. return CStyleCastExpr::Create(*Ctx, Ty, VK_PRValue, Kind, E, nullptr,
  512. FPOptionsOverride(), TInfo,
  513. SourceLocation(), SourceLocation());
  514. }
  515. bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
  516. IdentifierInfo* II = &Context->Idents.get("load");
  517. Selector LoadSel = Context->Selectors.getSelector(0, &II);
  518. return OD->getClassMethod(LoadSel) != nullptr;
  519. }
  520. StringLiteral *getStringLiteral(StringRef Str) {
  521. QualType StrType = Context->getConstantArrayType(
  522. Context->CharTy, llvm::APInt(32, Str.size() + 1), nullptr,
  523. ArrayType::Normal, 0);
  524. return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
  525. /*Pascal=*/false, StrType, SourceLocation());
  526. }
  527. };
  528. } // end anonymous namespace
  529. void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
  530. NamedDecl *D) {
  531. if (const FunctionProtoType *fproto
  532. = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
  533. for (const auto &I : fproto->param_types())
  534. if (isTopLevelBlockPointerType(I)) {
  535. // All the args are checked/rewritten. Don't call twice!
  536. RewriteBlockPointerDecl(D);
  537. break;
  538. }
  539. }
  540. }
  541. void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
  542. const PointerType *PT = funcType->getAs<PointerType>();
  543. if (PT && PointerTypeTakesAnyBlockArguments(funcType))
  544. RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
  545. }
  546. static bool IsHeaderFile(const std::string &Filename) {
  547. std::string::size_type DotPos = Filename.rfind('.');
  548. if (DotPos == std::string::npos) {
  549. // no file extension
  550. return false;
  551. }
  552. std::string Ext = Filename.substr(DotPos + 1);
  553. // C header: .h
  554. // C++ header: .hh or .H;
  555. return Ext == "h" || Ext == "hh" || Ext == "H";
  556. }
  557. RewriteModernObjC::RewriteModernObjC(std::string inFile,
  558. std::unique_ptr<raw_ostream> OS,
  559. DiagnosticsEngine &D,
  560. const LangOptions &LOpts,
  561. bool silenceMacroWarn, bool LineInfo)
  562. : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(std::move(OS)),
  563. SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
  564. IsHeader = IsHeaderFile(inFile);
  565. RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
  566. "rewriting sub-expression within a macro (may not be correct)");
  567. // FIXME. This should be an error. But if block is not called, it is OK. And it
  568. // may break including some headers.
  569. GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
  570. "rewriting block literal declared in global scope is not implemented");
  571. TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
  572. DiagnosticsEngine::Warning,
  573. "rewriter doesn't support user-specified control flow semantics "
  574. "for @try/@finally (code may not execute properly)");
  575. }
  576. std::unique_ptr<ASTConsumer> clang::CreateModernObjCRewriter(
  577. const std::string &InFile, std::unique_ptr<raw_ostream> OS,
  578. DiagnosticsEngine &Diags, const LangOptions &LOpts,
  579. bool SilenceRewriteMacroWarning, bool LineInfo) {
  580. return std::make_unique<RewriteModernObjC>(InFile, std::move(OS), Diags,
  581. LOpts, SilenceRewriteMacroWarning,
  582. LineInfo);
  583. }
  584. void RewriteModernObjC::InitializeCommon(ASTContext &context) {
  585. Context = &context;
  586. SM = &Context->getSourceManager();
  587. TUDecl = Context->getTranslationUnitDecl();
  588. MsgSendFunctionDecl = nullptr;
  589. MsgSendSuperFunctionDecl = nullptr;
  590. MsgSendStretFunctionDecl = nullptr;
  591. MsgSendSuperStretFunctionDecl = nullptr;
  592. MsgSendFpretFunctionDecl = nullptr;
  593. GetClassFunctionDecl = nullptr;
  594. GetMetaClassFunctionDecl = nullptr;
  595. GetSuperClassFunctionDecl = nullptr;
  596. SelGetUidFunctionDecl = nullptr;
  597. CFStringFunctionDecl = nullptr;
  598. ConstantStringClassReference = nullptr;
  599. NSStringRecord = nullptr;
  600. CurMethodDef = nullptr;
  601. CurFunctionDef = nullptr;
  602. GlobalVarDecl = nullptr;
  603. GlobalConstructionExp = nullptr;
  604. SuperStructDecl = nullptr;
  605. ProtocolTypeDecl = nullptr;
  606. ConstantStringDecl = nullptr;
  607. BcLabelCount = 0;
  608. SuperConstructorFunctionDecl = nullptr;
  609. NumObjCStringLiterals = 0;
  610. PropParentMap = nullptr;
  611. CurrentBody = nullptr;
  612. DisableReplaceStmt = false;
  613. objc_impl_method = false;
  614. // Get the ID and start/end of the main file.
  615. MainFileID = SM->getMainFileID();
  616. llvm::MemoryBufferRef MainBuf = SM->getBufferOrFake(MainFileID);
  617. MainFileStart = MainBuf.getBufferStart();
  618. MainFileEnd = MainBuf.getBufferEnd();
  619. Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
  620. }
  621. //===----------------------------------------------------------------------===//
  622. // Top Level Driver Code
  623. //===----------------------------------------------------------------------===//
  624. void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
  625. if (Diags.hasErrorOccurred())
  626. return;
  627. // Two cases: either the decl could be in the main file, or it could be in a
  628. // #included file. If the former, rewrite it now. If the later, check to see
  629. // if we rewrote the #include/#import.
  630. SourceLocation Loc = D->getLocation();
  631. Loc = SM->getExpansionLoc(Loc);
  632. // If this is for a builtin, ignore it.
  633. if (Loc.isInvalid()) return;
  634. // Look for built-in declarations that we need to refer during the rewrite.
  635. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  636. RewriteFunctionDecl(FD);
  637. } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
  638. // declared in <Foundation/NSString.h>
  639. if (FVD->getName() == "_NSConstantStringClassReference") {
  640. ConstantStringClassReference = FVD;
  641. return;
  642. }
  643. } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
  644. RewriteCategoryDecl(CD);
  645. } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
  646. if (PD->isThisDeclarationADefinition())
  647. RewriteProtocolDecl(PD);
  648. } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
  649. // Recurse into linkage specifications
  650. for (DeclContext::decl_iterator DI = LSD->decls_begin(),
  651. DIEnd = LSD->decls_end();
  652. DI != DIEnd; ) {
  653. if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
  654. if (!IFace->isThisDeclarationADefinition()) {
  655. SmallVector<Decl *, 8> DG;
  656. SourceLocation StartLoc = IFace->getBeginLoc();
  657. do {
  658. if (isa<ObjCInterfaceDecl>(*DI) &&
  659. !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
  660. StartLoc == (*DI)->getBeginLoc())
  661. DG.push_back(*DI);
  662. else
  663. break;
  664. ++DI;
  665. } while (DI != DIEnd);
  666. RewriteForwardClassDecl(DG);
  667. continue;
  668. }
  669. else {
  670. // Keep track of all interface declarations seen.
  671. ObjCInterfacesSeen.push_back(IFace);
  672. ++DI;
  673. continue;
  674. }
  675. }
  676. if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
  677. if (!Proto->isThisDeclarationADefinition()) {
  678. SmallVector<Decl *, 8> DG;
  679. SourceLocation StartLoc = Proto->getBeginLoc();
  680. do {
  681. if (isa<ObjCProtocolDecl>(*DI) &&
  682. !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
  683. StartLoc == (*DI)->getBeginLoc())
  684. DG.push_back(*DI);
  685. else
  686. break;
  687. ++DI;
  688. } while (DI != DIEnd);
  689. RewriteForwardProtocolDecl(DG);
  690. continue;
  691. }
  692. }
  693. HandleTopLevelSingleDecl(*DI);
  694. ++DI;
  695. }
  696. }
  697. // If we have a decl in the main file, see if we should rewrite it.
  698. if (SM->isWrittenInMainFile(Loc))
  699. return HandleDeclInMainFile(D);
  700. }
  701. //===----------------------------------------------------------------------===//
  702. // Syntactic (non-AST) Rewriting Code
  703. //===----------------------------------------------------------------------===//
  704. void RewriteModernObjC::RewriteInclude() {
  705. SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
  706. StringRef MainBuf = SM->getBufferData(MainFileID);
  707. const char *MainBufStart = MainBuf.begin();
  708. const char *MainBufEnd = MainBuf.end();
  709. size_t ImportLen = strlen("import");
  710. // Loop over the whole file, looking for includes.
  711. for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
  712. if (*BufPtr == '#') {
  713. if (++BufPtr == MainBufEnd)
  714. return;
  715. while (*BufPtr == ' ' || *BufPtr == '\t')
  716. if (++BufPtr == MainBufEnd)
  717. return;
  718. if (!strncmp(BufPtr, "import", ImportLen)) {
  719. // replace import with include
  720. SourceLocation ImportLoc =
  721. LocStart.getLocWithOffset(BufPtr-MainBufStart);
  722. ReplaceText(ImportLoc, ImportLen, "include");
  723. BufPtr += ImportLen;
  724. }
  725. }
  726. }
  727. }
  728. static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
  729. ObjCIvarDecl *IvarDecl, std::string &Result) {
  730. Result += "OBJC_IVAR_$_";
  731. Result += IDecl->getName();
  732. Result += "$";
  733. Result += IvarDecl->getName();
  734. }
  735. std::string
  736. RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
  737. const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
  738. // Build name of symbol holding ivar offset.
  739. std::string IvarOffsetName;
  740. if (D->isBitField())
  741. ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
  742. else
  743. WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
  744. std::string S = "(*(";
  745. QualType IvarT = D->getType();
  746. if (D->isBitField())
  747. IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
  748. if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
  749. RecordDecl *RD = IvarT->castAs<RecordType>()->getDecl();
  750. RD = RD->getDefinition();
  751. if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
  752. // decltype(((Foo_IMPL*)0)->bar) *
  753. auto *CDecl = cast<ObjCContainerDecl>(D->getDeclContext());
  754. // ivar in class extensions requires special treatment.
  755. if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
  756. CDecl = CatDecl->getClassInterface();
  757. std::string RecName = std::string(CDecl->getName());
  758. RecName += "_IMPL";
  759. RecordDecl *RD =
  760. RecordDecl::Create(*Context, TTK_Struct, TUDecl, SourceLocation(),
  761. SourceLocation(), &Context->Idents.get(RecName));
  762. QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
  763. unsigned UnsignedIntSize =
  764. static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
  765. Expr *Zero = IntegerLiteral::Create(*Context,
  766. llvm::APInt(UnsignedIntSize, 0),
  767. Context->UnsignedIntTy, SourceLocation());
  768. Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
  769. ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
  770. Zero);
  771. FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
  772. SourceLocation(),
  773. &Context->Idents.get(D->getNameAsString()),
  774. IvarT, nullptr,
  775. /*BitWidth=*/nullptr, /*Mutable=*/true,
  776. ICIS_NoInit);
  777. MemberExpr *ME = MemberExpr::CreateImplicit(
  778. *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
  779. IvarT = Context->getDecltypeType(ME, ME->getType());
  780. }
  781. }
  782. convertObjCTypeToCStyleType(IvarT);
  783. QualType castT = Context->getPointerType(IvarT);
  784. std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
  785. S += TypeString;
  786. S += ")";
  787. // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
  788. S += "((char *)self + ";
  789. S += IvarOffsetName;
  790. S += "))";
  791. if (D->isBitField()) {
  792. S += ".";
  793. S += D->getNameAsString();
  794. }
  795. ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
  796. return S;
  797. }
  798. /// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
  799. /// been found in the class implementation. In this case, it must be synthesized.
  800. static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
  801. ObjCPropertyDecl *PD,
  802. bool getter) {
  803. auto *OMD = IMP->getInstanceMethod(getter ? PD->getGetterName()
  804. : PD->getSetterName());
  805. return !OMD || OMD->isSynthesizedAccessorStub();
  806. }
  807. void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
  808. ObjCImplementationDecl *IMD,
  809. ObjCCategoryImplDecl *CID) {
  810. static bool objcGetPropertyDefined = false;
  811. static bool objcSetPropertyDefined = false;
  812. SourceLocation startGetterSetterLoc;
  813. if (PID->getBeginLoc().isValid()) {
  814. SourceLocation startLoc = PID->getBeginLoc();
  815. InsertText(startLoc, "// ");
  816. const char *startBuf = SM->getCharacterData(startLoc);
  817. assert((*startBuf == '@') && "bogus @synthesize location");
  818. const char *semiBuf = strchr(startBuf, ';');
  819. assert((*semiBuf == ';') && "@synthesize: can't find ';'");
  820. startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
  821. } else
  822. startGetterSetterLoc = IMD ? IMD->getEndLoc() : CID->getEndLoc();
  823. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
  824. return; // FIXME: is this correct?
  825. // Generate the 'getter' function.
  826. ObjCPropertyDecl *PD = PID->getPropertyDecl();
  827. ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
  828. assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
  829. unsigned Attributes = PD->getPropertyAttributes();
  830. if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
  831. bool GenGetProperty =
  832. !(Attributes & ObjCPropertyAttribute::kind_nonatomic) &&
  833. (Attributes & (ObjCPropertyAttribute::kind_retain |
  834. ObjCPropertyAttribute::kind_copy));
  835. std::string Getr;
  836. if (GenGetProperty && !objcGetPropertyDefined) {
  837. objcGetPropertyDefined = true;
  838. // FIXME. Is this attribute correct in all cases?
  839. Getr = "\nextern \"C\" __declspec(dllimport) "
  840. "id objc_getProperty(id, SEL, long, bool);\n";
  841. }
  842. RewriteObjCMethodDecl(OID->getContainingInterface(),
  843. PID->getGetterMethodDecl(), Getr);
  844. Getr += "{ ";
  845. // Synthesize an explicit cast to gain access to the ivar.
  846. // See objc-act.c:objc_synthesize_new_getter() for details.
  847. if (GenGetProperty) {
  848. // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
  849. Getr += "typedef ";
  850. const FunctionType *FPRetType = nullptr;
  851. RewriteTypeIntoString(PID->getGetterMethodDecl()->getReturnType(), Getr,
  852. FPRetType);
  853. Getr += " _TYPE";
  854. if (FPRetType) {
  855. Getr += ")"; // close the precedence "scope" for "*".
  856. // Now, emit the argument types (if any).
  857. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
  858. Getr += "(";
  859. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  860. if (i) Getr += ", ";
  861. std::string ParamStr =
  862. FT->getParamType(i).getAsString(Context->getPrintingPolicy());
  863. Getr += ParamStr;
  864. }
  865. if (FT->isVariadic()) {
  866. if (FT->getNumParams())
  867. Getr += ", ";
  868. Getr += "...";
  869. }
  870. Getr += ")";
  871. } else
  872. Getr += "()";
  873. }
  874. Getr += ";\n";
  875. Getr += "return (_TYPE)";
  876. Getr += "objc_getProperty(self, _cmd, ";
  877. RewriteIvarOffsetComputation(OID, Getr);
  878. Getr += ", 1)";
  879. }
  880. else
  881. Getr += "return " + getIvarAccessString(OID);
  882. Getr += "; }";
  883. InsertText(startGetterSetterLoc, Getr);
  884. }
  885. if (PD->isReadOnly() ||
  886. !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
  887. return;
  888. // Generate the 'setter' function.
  889. std::string Setr;
  890. bool GenSetProperty = Attributes & (ObjCPropertyAttribute::kind_retain |
  891. ObjCPropertyAttribute::kind_copy);
  892. if (GenSetProperty && !objcSetPropertyDefined) {
  893. objcSetPropertyDefined = true;
  894. // FIXME. Is this attribute correct in all cases?
  895. Setr = "\nextern \"C\" __declspec(dllimport) "
  896. "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
  897. }
  898. RewriteObjCMethodDecl(OID->getContainingInterface(),
  899. PID->getSetterMethodDecl(), Setr);
  900. Setr += "{ ";
  901. // Synthesize an explicit cast to initialize the ivar.
  902. // See objc-act.c:objc_synthesize_new_setter() for details.
  903. if (GenSetProperty) {
  904. Setr += "objc_setProperty (self, _cmd, ";
  905. RewriteIvarOffsetComputation(OID, Setr);
  906. Setr += ", (id)";
  907. Setr += PD->getName();
  908. Setr += ", ";
  909. if (Attributes & ObjCPropertyAttribute::kind_nonatomic)
  910. Setr += "0, ";
  911. else
  912. Setr += "1, ";
  913. if (Attributes & ObjCPropertyAttribute::kind_copy)
  914. Setr += "1)";
  915. else
  916. Setr += "0)";
  917. }
  918. else {
  919. Setr += getIvarAccessString(OID) + " = ";
  920. Setr += PD->getName();
  921. }
  922. Setr += "; }\n";
  923. InsertText(startGetterSetterLoc, Setr);
  924. }
  925. static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
  926. std::string &typedefString) {
  927. typedefString += "\n#ifndef _REWRITER_typedef_";
  928. typedefString += ForwardDecl->getNameAsString();
  929. typedefString += "\n";
  930. typedefString += "#define _REWRITER_typedef_";
  931. typedefString += ForwardDecl->getNameAsString();
  932. typedefString += "\n";
  933. typedefString += "typedef struct objc_object ";
  934. typedefString += ForwardDecl->getNameAsString();
  935. // typedef struct { } _objc_exc_Classname;
  936. typedefString += ";\ntypedef struct {} _objc_exc_";
  937. typedefString += ForwardDecl->getNameAsString();
  938. typedefString += ";\n#endif\n";
  939. }
  940. void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
  941. const std::string &typedefString) {
  942. SourceLocation startLoc = ClassDecl->getBeginLoc();
  943. const char *startBuf = SM->getCharacterData(startLoc);
  944. const char *semiPtr = strchr(startBuf, ';');
  945. // Replace the @class with typedefs corresponding to the classes.
  946. ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
  947. }
  948. void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
  949. std::string typedefString;
  950. for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
  951. if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
  952. if (I == D.begin()) {
  953. // Translate to typedef's that forward reference structs with the same name
  954. // as the class. As a convenience, we include the original declaration
  955. // as a comment.
  956. typedefString += "// @class ";
  957. typedefString += ForwardDecl->getNameAsString();
  958. typedefString += ";";
  959. }
  960. RewriteOneForwardClassDecl(ForwardDecl, typedefString);
  961. }
  962. else
  963. HandleTopLevelSingleDecl(*I);
  964. }
  965. DeclGroupRef::iterator I = D.begin();
  966. RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
  967. }
  968. void RewriteModernObjC::RewriteForwardClassDecl(
  969. const SmallVectorImpl<Decl *> &D) {
  970. std::string typedefString;
  971. for (unsigned i = 0; i < D.size(); i++) {
  972. ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
  973. if (i == 0) {
  974. typedefString += "// @class ";
  975. typedefString += ForwardDecl->getNameAsString();
  976. typedefString += ";";
  977. }
  978. RewriteOneForwardClassDecl(ForwardDecl, typedefString);
  979. }
  980. RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
  981. }
  982. void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
  983. // When method is a synthesized one, such as a getter/setter there is
  984. // nothing to rewrite.
  985. if (Method->isImplicit())
  986. return;
  987. SourceLocation LocStart = Method->getBeginLoc();
  988. SourceLocation LocEnd = Method->getEndLoc();
  989. if (SM->getExpansionLineNumber(LocEnd) >
  990. SM->getExpansionLineNumber(LocStart)) {
  991. InsertText(LocStart, "#if 0\n");
  992. ReplaceText(LocEnd, 1, ";\n#endif\n");
  993. } else {
  994. InsertText(LocStart, "// ");
  995. }
  996. }
  997. void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
  998. SourceLocation Loc = prop->getAtLoc();
  999. ReplaceText(Loc, 0, "// ");
  1000. // FIXME: handle properties that are declared across multiple lines.
  1001. }
  1002. void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
  1003. SourceLocation LocStart = CatDecl->getBeginLoc();
  1004. // FIXME: handle category headers that are declared across multiple lines.
  1005. if (CatDecl->getIvarRBraceLoc().isValid()) {
  1006. ReplaceText(LocStart, 1, "/** ");
  1007. ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
  1008. }
  1009. else {
  1010. ReplaceText(LocStart, 0, "// ");
  1011. }
  1012. for (auto *I : CatDecl->instance_properties())
  1013. RewriteProperty(I);
  1014. for (auto *I : CatDecl->instance_methods())
  1015. RewriteMethodDeclaration(I);
  1016. for (auto *I : CatDecl->class_methods())
  1017. RewriteMethodDeclaration(I);
  1018. // Lastly, comment out the @end.
  1019. ReplaceText(CatDecl->getAtEndRange().getBegin(),
  1020. strlen("@end"), "/* @end */\n");
  1021. }
  1022. void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
  1023. SourceLocation LocStart = PDecl->getBeginLoc();
  1024. assert(PDecl->isThisDeclarationADefinition());
  1025. // FIXME: handle protocol headers that are declared across multiple lines.
  1026. ReplaceText(LocStart, 0, "// ");
  1027. for (auto *I : PDecl->instance_methods())
  1028. RewriteMethodDeclaration(I);
  1029. for (auto *I : PDecl->class_methods())
  1030. RewriteMethodDeclaration(I);
  1031. for (auto *I : PDecl->instance_properties())
  1032. RewriteProperty(I);
  1033. // Lastly, comment out the @end.
  1034. SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
  1035. ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
  1036. // Must comment out @optional/@required
  1037. const char *startBuf = SM->getCharacterData(LocStart);
  1038. const char *endBuf = SM->getCharacterData(LocEnd);
  1039. for (const char *p = startBuf; p < endBuf; p++) {
  1040. if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
  1041. SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
  1042. ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
  1043. }
  1044. else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
  1045. SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
  1046. ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
  1047. }
  1048. }
  1049. }
  1050. void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
  1051. SourceLocation LocStart = (*D.begin())->getBeginLoc();
  1052. if (LocStart.isInvalid())
  1053. llvm_unreachable("Invalid SourceLocation");
  1054. // FIXME: handle forward protocol that are declared across multiple lines.
  1055. ReplaceText(LocStart, 0, "// ");
  1056. }
  1057. void
  1058. RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
  1059. SourceLocation LocStart = DG[0]->getBeginLoc();
  1060. if (LocStart.isInvalid())
  1061. llvm_unreachable("Invalid SourceLocation");
  1062. // FIXME: handle forward protocol that are declared across multiple lines.
  1063. ReplaceText(LocStart, 0, "// ");
  1064. }
  1065. void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
  1066. const FunctionType *&FPRetType) {
  1067. if (T->isObjCQualifiedIdType())
  1068. ResultStr += "id";
  1069. else if (T->isFunctionPointerType() ||
  1070. T->isBlockPointerType()) {
  1071. // needs special handling, since pointer-to-functions have special
  1072. // syntax (where a decaration models use).
  1073. QualType retType = T;
  1074. QualType PointeeTy;
  1075. if (const PointerType* PT = retType->getAs<PointerType>())
  1076. PointeeTy = PT->getPointeeType();
  1077. else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
  1078. PointeeTy = BPT->getPointeeType();
  1079. if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
  1080. ResultStr +=
  1081. FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
  1082. ResultStr += "(*";
  1083. }
  1084. } else
  1085. ResultStr += T.getAsString(Context->getPrintingPolicy());
  1086. }
  1087. void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
  1088. ObjCMethodDecl *OMD,
  1089. std::string &ResultStr) {
  1090. //fprintf(stderr,"In RewriteObjCMethodDecl\n");
  1091. const FunctionType *FPRetType = nullptr;
  1092. ResultStr += "\nstatic ";
  1093. RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
  1094. ResultStr += " ";
  1095. // Unique method name
  1096. std::string NameStr;
  1097. if (OMD->isInstanceMethod())
  1098. NameStr += "_I_";
  1099. else
  1100. NameStr += "_C_";
  1101. NameStr += IDecl->getNameAsString();
  1102. NameStr += "_";
  1103. if (ObjCCategoryImplDecl *CID =
  1104. dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
  1105. NameStr += CID->getNameAsString();
  1106. NameStr += "_";
  1107. }
  1108. // Append selector names, replacing ':' with '_'
  1109. {
  1110. std::string selString = OMD->getSelector().getAsString();
  1111. int len = selString.size();
  1112. for (int i = 0; i < len; i++)
  1113. if (selString[i] == ':')
  1114. selString[i] = '_';
  1115. NameStr += selString;
  1116. }
  1117. // Remember this name for metadata emission
  1118. MethodInternalNames[OMD] = NameStr;
  1119. ResultStr += NameStr;
  1120. // Rewrite arguments
  1121. ResultStr += "(";
  1122. // invisible arguments
  1123. if (OMD->isInstanceMethod()) {
  1124. QualType selfTy = Context->getObjCInterfaceType(IDecl);
  1125. selfTy = Context->getPointerType(selfTy);
  1126. if (!LangOpts.MicrosoftExt) {
  1127. if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
  1128. ResultStr += "struct ";
  1129. }
  1130. // When rewriting for Microsoft, explicitly omit the structure name.
  1131. ResultStr += IDecl->getNameAsString();
  1132. ResultStr += " *";
  1133. }
  1134. else
  1135. ResultStr += Context->getObjCClassType().getAsString(
  1136. Context->getPrintingPolicy());
  1137. ResultStr += " self, ";
  1138. ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
  1139. ResultStr += " _cmd";
  1140. // Method arguments.
  1141. for (const auto *PDecl : OMD->parameters()) {
  1142. ResultStr += ", ";
  1143. if (PDecl->getType()->isObjCQualifiedIdType()) {
  1144. ResultStr += "id ";
  1145. ResultStr += PDecl->getNameAsString();
  1146. } else {
  1147. std::string Name = PDecl->getNameAsString();
  1148. QualType QT = PDecl->getType();
  1149. // Make sure we convert "t (^)(...)" to "t (*)(...)".
  1150. (void)convertBlockPointerToFunctionPointer(QT);
  1151. QT.getAsStringInternal(Name, Context->getPrintingPolicy());
  1152. ResultStr += Name;
  1153. }
  1154. }
  1155. if (OMD->isVariadic())
  1156. ResultStr += ", ...";
  1157. ResultStr += ") ";
  1158. if (FPRetType) {
  1159. ResultStr += ")"; // close the precedence "scope" for "*".
  1160. // Now, emit the argument types (if any).
  1161. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
  1162. ResultStr += "(";
  1163. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  1164. if (i) ResultStr += ", ";
  1165. std::string ParamStr =
  1166. FT->getParamType(i).getAsString(Context->getPrintingPolicy());
  1167. ResultStr += ParamStr;
  1168. }
  1169. if (FT->isVariadic()) {
  1170. if (FT->getNumParams())
  1171. ResultStr += ", ";
  1172. ResultStr += "...";
  1173. }
  1174. ResultStr += ")";
  1175. } else {
  1176. ResultStr += "()";
  1177. }
  1178. }
  1179. }
  1180. void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
  1181. ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
  1182. ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
  1183. assert((IMD || CID) && "Unknown implementation type");
  1184. if (IMD) {
  1185. if (IMD->getIvarRBraceLoc().isValid()) {
  1186. ReplaceText(IMD->getBeginLoc(), 1, "/** ");
  1187. ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
  1188. }
  1189. else {
  1190. InsertText(IMD->getBeginLoc(), "// ");
  1191. }
  1192. }
  1193. else
  1194. InsertText(CID->getBeginLoc(), "// ");
  1195. for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
  1196. if (!OMD->getBody())
  1197. continue;
  1198. std::string ResultStr;
  1199. RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
  1200. SourceLocation LocStart = OMD->getBeginLoc();
  1201. SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
  1202. const char *startBuf = SM->getCharacterData(LocStart);
  1203. const char *endBuf = SM->getCharacterData(LocEnd);
  1204. ReplaceText(LocStart, endBuf-startBuf, ResultStr);
  1205. }
  1206. for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
  1207. if (!OMD->getBody())
  1208. continue;
  1209. std::string ResultStr;
  1210. RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
  1211. SourceLocation LocStart = OMD->getBeginLoc();
  1212. SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
  1213. const char *startBuf = SM->getCharacterData(LocStart);
  1214. const char *endBuf = SM->getCharacterData(LocEnd);
  1215. ReplaceText(LocStart, endBuf-startBuf, ResultStr);
  1216. }
  1217. for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
  1218. RewritePropertyImplDecl(I, IMD, CID);
  1219. InsertText(IMD ? IMD->getEndLoc() : CID->getEndLoc(), "// ");
  1220. }
  1221. void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
  1222. // Do not synthesize more than once.
  1223. if (ObjCSynthesizedStructs.count(ClassDecl))
  1224. return;
  1225. // Make sure super class's are written before current class is written.
  1226. ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
  1227. while (SuperClass) {
  1228. RewriteInterfaceDecl(SuperClass);
  1229. SuperClass = SuperClass->getSuperClass();
  1230. }
  1231. std::string ResultStr;
  1232. if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
  1233. // we haven't seen a forward decl - generate a typedef.
  1234. RewriteOneForwardClassDecl(ClassDecl, ResultStr);
  1235. RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
  1236. RewriteObjCInternalStruct(ClassDecl, ResultStr);
  1237. // Mark this typedef as having been written into its c++ equivalent.
  1238. ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
  1239. for (auto *I : ClassDecl->instance_properties())
  1240. RewriteProperty(I);
  1241. for (auto *I : ClassDecl->instance_methods())
  1242. RewriteMethodDeclaration(I);
  1243. for (auto *I : ClassDecl->class_methods())
  1244. RewriteMethodDeclaration(I);
  1245. // Lastly, comment out the @end.
  1246. ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
  1247. "/* @end */\n");
  1248. }
  1249. }
  1250. Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
  1251. SourceRange OldRange = PseudoOp->getSourceRange();
  1252. // We just magically know some things about the structure of this
  1253. // expression.
  1254. ObjCMessageExpr *OldMsg =
  1255. cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
  1256. PseudoOp->getNumSemanticExprs() - 1));
  1257. // Because the rewriter doesn't allow us to rewrite rewritten code,
  1258. // we need to suppress rewriting the sub-statements.
  1259. Expr *Base;
  1260. SmallVector<Expr*, 2> Args;
  1261. {
  1262. DisableReplaceStmtScope S(*this);
  1263. // Rebuild the base expression if we have one.
  1264. Base = nullptr;
  1265. if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
  1266. Base = OldMsg->getInstanceReceiver();
  1267. Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
  1268. Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
  1269. }
  1270. unsigned numArgs = OldMsg->getNumArgs();
  1271. for (unsigned i = 0; i < numArgs; i++) {
  1272. Expr *Arg = OldMsg->getArg(i);
  1273. if (isa<OpaqueValueExpr>(Arg))
  1274. Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
  1275. Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
  1276. Args.push_back(Arg);
  1277. }
  1278. }
  1279. // TODO: avoid this copy.
  1280. SmallVector<SourceLocation, 1> SelLocs;
  1281. OldMsg->getSelectorLocs(SelLocs);
  1282. ObjCMessageExpr *NewMsg = nullptr;
  1283. switch (OldMsg->getReceiverKind()) {
  1284. case ObjCMessageExpr::Class:
  1285. NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
  1286. OldMsg->getValueKind(),
  1287. OldMsg->getLeftLoc(),
  1288. OldMsg->getClassReceiverTypeInfo(),
  1289. OldMsg->getSelector(),
  1290. SelLocs,
  1291. OldMsg->getMethodDecl(),
  1292. Args,
  1293. OldMsg->getRightLoc(),
  1294. OldMsg->isImplicit());
  1295. break;
  1296. case ObjCMessageExpr::Instance:
  1297. NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
  1298. OldMsg->getValueKind(),
  1299. OldMsg->getLeftLoc(),
  1300. Base,
  1301. OldMsg->getSelector(),
  1302. SelLocs,
  1303. OldMsg->getMethodDecl(),
  1304. Args,
  1305. OldMsg->getRightLoc(),
  1306. OldMsg->isImplicit());
  1307. break;
  1308. case ObjCMessageExpr::SuperClass:
  1309. case ObjCMessageExpr::SuperInstance:
  1310. NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
  1311. OldMsg->getValueKind(),
  1312. OldMsg->getLeftLoc(),
  1313. OldMsg->getSuperLoc(),
  1314. OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
  1315. OldMsg->getSuperType(),
  1316. OldMsg->getSelector(),
  1317. SelLocs,
  1318. OldMsg->getMethodDecl(),
  1319. Args,
  1320. OldMsg->getRightLoc(),
  1321. OldMsg->isImplicit());
  1322. break;
  1323. }
  1324. Stmt *Replacement = SynthMessageExpr(NewMsg);
  1325. ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
  1326. return Replacement;
  1327. }
  1328. Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
  1329. SourceRange OldRange = PseudoOp->getSourceRange();
  1330. // We just magically know some things about the structure of this
  1331. // expression.
  1332. ObjCMessageExpr *OldMsg =
  1333. cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
  1334. // Because the rewriter doesn't allow us to rewrite rewritten code,
  1335. // we need to suppress rewriting the sub-statements.
  1336. Expr *Base = nullptr;
  1337. SmallVector<Expr*, 1> Args;
  1338. {
  1339. DisableReplaceStmtScope S(*this);
  1340. // Rebuild the base expression if we have one.
  1341. if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
  1342. Base = OldMsg->getInstanceReceiver();
  1343. Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
  1344. Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
  1345. }
  1346. unsigned numArgs = OldMsg->getNumArgs();
  1347. for (unsigned i = 0; i < numArgs; i++) {
  1348. Expr *Arg = OldMsg->getArg(i);
  1349. if (isa<OpaqueValueExpr>(Arg))
  1350. Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
  1351. Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
  1352. Args.push_back(Arg);
  1353. }
  1354. }
  1355. // Intentionally empty.
  1356. SmallVector<SourceLocation, 1> SelLocs;
  1357. ObjCMessageExpr *NewMsg = nullptr;
  1358. switch (OldMsg->getReceiverKind()) {
  1359. case ObjCMessageExpr::Class:
  1360. NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
  1361. OldMsg->getValueKind(),
  1362. OldMsg->getLeftLoc(),
  1363. OldMsg->getClassReceiverTypeInfo(),
  1364. OldMsg->getSelector(),
  1365. SelLocs,
  1366. OldMsg->getMethodDecl(),
  1367. Args,
  1368. OldMsg->getRightLoc(),
  1369. OldMsg->isImplicit());
  1370. break;
  1371. case ObjCMessageExpr::Instance:
  1372. NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
  1373. OldMsg->getValueKind(),
  1374. OldMsg->getLeftLoc(),
  1375. Base,
  1376. OldMsg->getSelector(),
  1377. SelLocs,
  1378. OldMsg->getMethodDecl(),
  1379. Args,
  1380. OldMsg->getRightLoc(),
  1381. OldMsg->isImplicit());
  1382. break;
  1383. case ObjCMessageExpr::SuperClass:
  1384. case ObjCMessageExpr::SuperInstance:
  1385. NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
  1386. OldMsg->getValueKind(),
  1387. OldMsg->getLeftLoc(),
  1388. OldMsg->getSuperLoc(),
  1389. OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
  1390. OldMsg->getSuperType(),
  1391. OldMsg->getSelector(),
  1392. SelLocs,
  1393. OldMsg->getMethodDecl(),
  1394. Args,
  1395. OldMsg->getRightLoc(),
  1396. OldMsg->isImplicit());
  1397. break;
  1398. }
  1399. Stmt *Replacement = SynthMessageExpr(NewMsg);
  1400. ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
  1401. return Replacement;
  1402. }
  1403. /// SynthCountByEnumWithState - To print:
  1404. /// ((NSUInteger (*)
  1405. /// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
  1406. /// (void *)objc_msgSend)((id)l_collection,
  1407. /// sel_registerName(
  1408. /// "countByEnumeratingWithState:objects:count:"),
  1409. /// &enumState,
  1410. /// (id *)__rw_items, (NSUInteger)16)
  1411. ///
  1412. void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
  1413. buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
  1414. "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
  1415. buf += "\n\t\t";
  1416. buf += "((id)l_collection,\n\t\t";
  1417. buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
  1418. buf += "\n\t\t";
  1419. buf += "&enumState, "
  1420. "(id *)__rw_items, (_WIN_NSUInteger)16)";
  1421. }
  1422. /// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
  1423. /// statement to exit to its outer synthesized loop.
  1424. ///
  1425. Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
  1426. if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
  1427. return S;
  1428. // replace break with goto __break_label
  1429. std::string buf;
  1430. SourceLocation startLoc = S->getBeginLoc();
  1431. buf = "goto __break_label_";
  1432. buf += utostr(ObjCBcLabelNo.back());
  1433. ReplaceText(startLoc, strlen("break"), buf);
  1434. return nullptr;
  1435. }
  1436. void RewriteModernObjC::ConvertSourceLocationToLineDirective(
  1437. SourceLocation Loc,
  1438. std::string &LineString) {
  1439. if (Loc.isFileID() && GenerateLineInfo) {
  1440. LineString += "\n#line ";
  1441. PresumedLoc PLoc = SM->getPresumedLoc(Loc);
  1442. LineString += utostr(PLoc.getLine());
  1443. LineString += " \"";
  1444. LineString += Lexer::Stringify(PLoc.getFilename());
  1445. LineString += "\"\n";
  1446. }
  1447. }
  1448. /// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
  1449. /// statement to continue with its inner synthesized loop.
  1450. ///
  1451. Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
  1452. if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
  1453. return S;
  1454. // replace continue with goto __continue_label
  1455. std::string buf;
  1456. SourceLocation startLoc = S->getBeginLoc();
  1457. buf = "goto __continue_label_";
  1458. buf += utostr(ObjCBcLabelNo.back());
  1459. ReplaceText(startLoc, strlen("continue"), buf);
  1460. return nullptr;
  1461. }
  1462. /// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
  1463. /// It rewrites:
  1464. /// for ( type elem in collection) { stmts; }
  1465. /// Into:
  1466. /// {
  1467. /// type elem;
  1468. /// struct __objcFastEnumerationState enumState = { 0 };
  1469. /// id __rw_items[16];
  1470. /// id l_collection = (id)collection;
  1471. /// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
  1472. /// objects:__rw_items count:16];
  1473. /// if (limit) {
  1474. /// unsigned long startMutations = *enumState.mutationsPtr;
  1475. /// do {
  1476. /// unsigned long counter = 0;
  1477. /// do {
  1478. /// if (startMutations != *enumState.mutationsPtr)
  1479. /// objc_enumerationMutation(l_collection);
  1480. /// elem = (type)enumState.itemsPtr[counter++];
  1481. /// stmts;
  1482. /// __continue_label: ;
  1483. /// } while (counter < limit);
  1484. /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
  1485. /// objects:__rw_items count:16]));
  1486. /// elem = nil;
  1487. /// __break_label: ;
  1488. /// }
  1489. /// else
  1490. /// elem = nil;
  1491. /// }
  1492. ///
  1493. Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
  1494. SourceLocation OrigEnd) {
  1495. assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
  1496. assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
  1497. "ObjCForCollectionStmt Statement stack mismatch");
  1498. assert(!ObjCBcLabelNo.empty() &&
  1499. "ObjCForCollectionStmt - Label No stack empty");
  1500. SourceLocation startLoc = S->getBeginLoc();
  1501. const char *startBuf = SM->getCharacterData(startLoc);
  1502. StringRef elementName;
  1503. std::string elementTypeAsString;
  1504. std::string buf;
  1505. // line directive first.
  1506. SourceLocation ForEachLoc = S->getForLoc();
  1507. ConvertSourceLocationToLineDirective(ForEachLoc, buf);
  1508. buf += "{\n\t";
  1509. if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
  1510. // type elem;
  1511. NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
  1512. QualType ElementType = cast<ValueDecl>(D)->getType();
  1513. if (ElementType->isObjCQualifiedIdType() ||
  1514. ElementType->isObjCQualifiedInterfaceType())
  1515. // Simply use 'id' for all qualified types.
  1516. elementTypeAsString = "id";
  1517. else
  1518. elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
  1519. buf += elementTypeAsString;
  1520. buf += " ";
  1521. elementName = D->getName();
  1522. buf += elementName;
  1523. buf += ";\n\t";
  1524. }
  1525. else {
  1526. DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
  1527. elementName = DR->getDecl()->getName();
  1528. ValueDecl *VD = DR->getDecl();
  1529. if (VD->getType()->isObjCQualifiedIdType() ||
  1530. VD->getType()->isObjCQualifiedInterfaceType())
  1531. // Simply use 'id' for all qualified types.
  1532. elementTypeAsString = "id";
  1533. else
  1534. elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
  1535. }
  1536. // struct __objcFastEnumerationState enumState = { 0 };
  1537. buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
  1538. // id __rw_items[16];
  1539. buf += "id __rw_items[16];\n\t";
  1540. // id l_collection = (id)
  1541. buf += "id l_collection = (id)";
  1542. // Find start location of 'collection' the hard way!
  1543. const char *startCollectionBuf = startBuf;
  1544. startCollectionBuf += 3; // skip 'for'
  1545. startCollectionBuf = strchr(startCollectionBuf, '(');
  1546. startCollectionBuf++; // skip '('
  1547. // find 'in' and skip it.
  1548. while (*startCollectionBuf != ' ' ||
  1549. *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
  1550. (*(startCollectionBuf+3) != ' ' &&
  1551. *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
  1552. startCollectionBuf++;
  1553. startCollectionBuf += 3;
  1554. // Replace: "for (type element in" with string constructed thus far.
  1555. ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
  1556. // Replace ')' in for '(' type elem in collection ')' with ';'
  1557. SourceLocation rightParenLoc = S->getRParenLoc();
  1558. const char *rparenBuf = SM->getCharacterData(rightParenLoc);
  1559. SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
  1560. buf = ";\n\t";
  1561. // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
  1562. // objects:__rw_items count:16];
  1563. // which is synthesized into:
  1564. // NSUInteger limit =
  1565. // ((NSUInteger (*)
  1566. // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
  1567. // (void *)objc_msgSend)((id)l_collection,
  1568. // sel_registerName(
  1569. // "countByEnumeratingWithState:objects:count:"),
  1570. // (struct __objcFastEnumerationState *)&state,
  1571. // (id *)__rw_items, (NSUInteger)16);
  1572. buf += "_WIN_NSUInteger limit =\n\t\t";
  1573. SynthCountByEnumWithState(buf);
  1574. buf += ";\n\t";
  1575. /// if (limit) {
  1576. /// unsigned long startMutations = *enumState.mutationsPtr;
  1577. /// do {
  1578. /// unsigned long counter = 0;
  1579. /// do {
  1580. /// if (startMutations != *enumState.mutationsPtr)
  1581. /// objc_enumerationMutation(l_collection);
  1582. /// elem = (type)enumState.itemsPtr[counter++];
  1583. buf += "if (limit) {\n\t";
  1584. buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
  1585. buf += "do {\n\t\t";
  1586. buf += "unsigned long counter = 0;\n\t\t";
  1587. buf += "do {\n\t\t\t";
  1588. buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
  1589. buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
  1590. buf += elementName;
  1591. buf += " = (";
  1592. buf += elementTypeAsString;
  1593. buf += ")enumState.itemsPtr[counter++];";
  1594. // Replace ')' in for '(' type elem in collection ')' with all of these.
  1595. ReplaceText(lparenLoc, 1, buf);
  1596. /// __continue_label: ;
  1597. /// } while (counter < limit);
  1598. /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
  1599. /// objects:__rw_items count:16]));
  1600. /// elem = nil;
  1601. /// __break_label: ;
  1602. /// }
  1603. /// else
  1604. /// elem = nil;
  1605. /// }
  1606. ///
  1607. buf = ";\n\t";
  1608. buf += "__continue_label_";
  1609. buf += utostr(ObjCBcLabelNo.back());
  1610. buf += ": ;";
  1611. buf += "\n\t\t";
  1612. buf += "} while (counter < limit);\n\t";
  1613. buf += "} while ((limit = ";
  1614. SynthCountByEnumWithState(buf);
  1615. buf += "));\n\t";
  1616. buf += elementName;
  1617. buf += " = ((";
  1618. buf += elementTypeAsString;
  1619. buf += ")0);\n\t";
  1620. buf += "__break_label_";
  1621. buf += utostr(ObjCBcLabelNo.back());
  1622. buf += ": ;\n\t";
  1623. buf += "}\n\t";
  1624. buf += "else\n\t\t";
  1625. buf += elementName;
  1626. buf += " = ((";
  1627. buf += elementTypeAsString;
  1628. buf += ")0);\n\t";
  1629. buf += "}\n";
  1630. // Insert all these *after* the statement body.
  1631. // FIXME: If this should support Obj-C++, support CXXTryStmt
  1632. if (isa<CompoundStmt>(S->getBody())) {
  1633. SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
  1634. InsertText(endBodyLoc, buf);
  1635. } else {
  1636. /* Need to treat single statements specially. For example:
  1637. *
  1638. * for (A *a in b) if (stuff()) break;
  1639. * for (A *a in b) xxxyy;
  1640. *
  1641. * The following code simply scans ahead to the semi to find the actual end.
  1642. */
  1643. const char *stmtBuf = SM->getCharacterData(OrigEnd);
  1644. const char *semiBuf = strchr(stmtBuf, ';');
  1645. assert(semiBuf && "Can't find ';'");
  1646. SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
  1647. InsertText(endBodyLoc, buf);
  1648. }
  1649. Stmts.pop_back();
  1650. ObjCBcLabelNo.pop_back();
  1651. return nullptr;
  1652. }
  1653. static void Write_RethrowObject(std::string &buf) {
  1654. buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
  1655. buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
  1656. buf += "\tid rethrow;\n";
  1657. buf += "\t} _fin_force_rethow(_rethrow);";
  1658. }
  1659. /// RewriteObjCSynchronizedStmt -
  1660. /// This routine rewrites @synchronized(expr) stmt;
  1661. /// into:
  1662. /// objc_sync_enter(expr);
  1663. /// @try stmt @finally { objc_sync_exit(expr); }
  1664. ///
  1665. Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
  1666. // Get the start location and compute the semi location.
  1667. SourceLocation startLoc = S->getBeginLoc();
  1668. const char *startBuf = SM->getCharacterData(startLoc);
  1669. assert((*startBuf == '@') && "bogus @synchronized location");
  1670. std::string buf;
  1671. SourceLocation SynchLoc = S->getAtSynchronizedLoc();
  1672. ConvertSourceLocationToLineDirective(SynchLoc, buf);
  1673. buf += "{ id _rethrow = 0; id _sync_obj = (id)";
  1674. const char *lparenBuf = startBuf;
  1675. while (*lparenBuf != '(') lparenBuf++;
  1676. ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
  1677. buf = "; objc_sync_enter(_sync_obj);\n";
  1678. buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
  1679. buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
  1680. buf += "\n\tid sync_exit;";
  1681. buf += "\n\t} _sync_exit(_sync_obj);\n";
  1682. // We can't use S->getSynchExpr()->getEndLoc() to find the end location, since
  1683. // the sync expression is typically a message expression that's already
  1684. // been rewritten! (which implies the SourceLocation's are invalid).
  1685. SourceLocation RParenExprLoc = S->getSynchBody()->getBeginLoc();
  1686. const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
  1687. while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
  1688. RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
  1689. SourceLocation LBranceLoc = S->getSynchBody()->getBeginLoc();
  1690. const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
  1691. assert (*LBraceLocBuf == '{');
  1692. ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
  1693. SourceLocation startRBraceLoc = S->getSynchBody()->getEndLoc();
  1694. assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
  1695. "bogus @synchronized block");
  1696. buf = "} catch (id e) {_rethrow = e;}\n";
  1697. Write_RethrowObject(buf);
  1698. buf += "}\n";
  1699. buf += "}\n";
  1700. ReplaceText(startRBraceLoc, 1, buf);
  1701. return nullptr;
  1702. }
  1703. void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
  1704. {
  1705. // Perform a bottom up traversal of all children.
  1706. for (Stmt *SubStmt : S->children())
  1707. if (SubStmt)
  1708. WarnAboutReturnGotoStmts(SubStmt);
  1709. if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
  1710. Diags.Report(Context->getFullLoc(S->getBeginLoc()),
  1711. TryFinallyContainsReturnDiag);
  1712. }
  1713. }
  1714. Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
  1715. SourceLocation startLoc = S->getAtLoc();
  1716. ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
  1717. ReplaceText(S->getSubStmt()->getBeginLoc(), 1,
  1718. "{ __AtAutoreleasePool __autoreleasepool; ");
  1719. return nullptr;
  1720. }
  1721. Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
  1722. ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
  1723. bool noCatch = S->getNumCatchStmts() == 0;
  1724. std::string buf;
  1725. SourceLocation TryLocation = S->getAtTryLoc();
  1726. ConvertSourceLocationToLineDirective(TryLocation, buf);
  1727. if (finalStmt) {
  1728. if (noCatch)
  1729. buf += "{ id volatile _rethrow = 0;\n";
  1730. else {
  1731. buf += "{ id volatile _rethrow = 0;\ntry {\n";
  1732. }
  1733. }
  1734. // Get the start location and compute the semi location.
  1735. SourceLocation startLoc = S->getBeginLoc();
  1736. const char *startBuf = SM->getCharacterData(startLoc);
  1737. assert((*startBuf == '@') && "bogus @try location");
  1738. if (finalStmt)
  1739. ReplaceText(startLoc, 1, buf);
  1740. else
  1741. // @try -> try
  1742. ReplaceText(startLoc, 1, "");
  1743. for (ObjCAtCatchStmt *Catch : S->catch_stmts()) {
  1744. VarDecl *catchDecl = Catch->getCatchParamDecl();
  1745. startLoc = Catch->getBeginLoc();
  1746. bool AtRemoved = false;
  1747. if (catchDecl) {
  1748. QualType t = catchDecl->getType();
  1749. if (const ObjCObjectPointerType *Ptr =
  1750. t->getAs<ObjCObjectPointerType>()) {
  1751. // Should be a pointer to a class.
  1752. ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
  1753. if (IDecl) {
  1754. std::string Result;
  1755. ConvertSourceLocationToLineDirective(Catch->getBeginLoc(), Result);
  1756. startBuf = SM->getCharacterData(startLoc);
  1757. assert((*startBuf == '@') && "bogus @catch location");
  1758. SourceLocation rParenLoc = Catch->getRParenLoc();
  1759. const char *rParenBuf = SM->getCharacterData(rParenLoc);
  1760. // _objc_exc_Foo *_e as argument to catch.
  1761. Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
  1762. Result += " *_"; Result += catchDecl->getNameAsString();
  1763. Result += ")";
  1764. ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
  1765. // Foo *e = (Foo *)_e;
  1766. Result.clear();
  1767. Result = "{ ";
  1768. Result += IDecl->getNameAsString();
  1769. Result += " *"; Result += catchDecl->getNameAsString();
  1770. Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
  1771. Result += "_"; Result += catchDecl->getNameAsString();
  1772. Result += "; ";
  1773. SourceLocation lBraceLoc = Catch->getCatchBody()->getBeginLoc();
  1774. ReplaceText(lBraceLoc, 1, Result);
  1775. AtRemoved = true;
  1776. }
  1777. }
  1778. }
  1779. if (!AtRemoved)
  1780. // @catch -> catch
  1781. ReplaceText(startLoc, 1, "");
  1782. }
  1783. if (finalStmt) {
  1784. buf.clear();
  1785. SourceLocation FinallyLoc = finalStmt->getBeginLoc();
  1786. if (noCatch) {
  1787. ConvertSourceLocationToLineDirective(FinallyLoc, buf);
  1788. buf += "catch (id e) {_rethrow = e;}\n";
  1789. }
  1790. else {
  1791. buf += "}\n";
  1792. ConvertSourceLocationToLineDirective(FinallyLoc, buf);
  1793. buf += "catch (id e) {_rethrow = e;}\n";
  1794. }
  1795. SourceLocation startFinalLoc = finalStmt->getBeginLoc();
  1796. ReplaceText(startFinalLoc, 8, buf);
  1797. Stmt *body = finalStmt->getFinallyBody();
  1798. SourceLocation startFinalBodyLoc = body->getBeginLoc();
  1799. buf.clear();
  1800. Write_RethrowObject(buf);
  1801. ReplaceText(startFinalBodyLoc, 1, buf);
  1802. SourceLocation endFinalBodyLoc = body->getEndLoc();
  1803. ReplaceText(endFinalBodyLoc, 1, "}\n}");
  1804. // Now check for any return/continue/go statements within the @try.
  1805. WarnAboutReturnGotoStmts(S->getTryBody());
  1806. }
  1807. return nullptr;
  1808. }
  1809. // This can't be done with ReplaceStmt(S, ThrowExpr), since
  1810. // the throw expression is typically a message expression that's already
  1811. // been rewritten! (which implies the SourceLocation's are invalid).
  1812. Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
  1813. // Get the start location and compute the semi location.
  1814. SourceLocation startLoc = S->getBeginLoc();
  1815. const char *startBuf = SM->getCharacterData(startLoc);
  1816. assert((*startBuf == '@') && "bogus @throw location");
  1817. std::string buf;
  1818. /* void objc_exception_throw(id) __attribute__((noreturn)); */
  1819. if (S->getThrowExpr())
  1820. buf = "objc_exception_throw(";
  1821. else
  1822. buf = "throw";
  1823. // handle "@ throw" correctly.
  1824. const char *wBuf = strchr(startBuf, 'w');
  1825. assert((*wBuf == 'w') && "@throw: can't find 'w'");
  1826. ReplaceText(startLoc, wBuf-startBuf+1, buf);
  1827. SourceLocation endLoc = S->getEndLoc();
  1828. const char *endBuf = SM->getCharacterData(endLoc);
  1829. const char *semiBuf = strchr(endBuf, ';');
  1830. assert((*semiBuf == ';') && "@throw: can't find ';'");
  1831. SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
  1832. if (S->getThrowExpr())
  1833. ReplaceText(semiLoc, 1, ");");
  1834. return nullptr;
  1835. }
  1836. Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
  1837. // Create a new string expression.
  1838. std::string StrEncoding;
  1839. Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
  1840. Expr *Replacement = getStringLiteral(StrEncoding);
  1841. ReplaceStmt(Exp, Replacement);
  1842. // Replace this subexpr in the parent.
  1843. // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
  1844. return Replacement;
  1845. }
  1846. Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
  1847. if (!SelGetUidFunctionDecl)
  1848. SynthSelGetUidFunctionDecl();
  1849. assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
  1850. // Create a call to sel_registerName("selName").
  1851. SmallVector<Expr*, 8> SelExprs;
  1852. SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
  1853. CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
  1854. SelExprs);
  1855. ReplaceStmt(Exp, SelExp);
  1856. // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
  1857. return SelExp;
  1858. }
  1859. CallExpr *
  1860. RewriteModernObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
  1861. ArrayRef<Expr *> Args,
  1862. SourceLocation StartLoc,
  1863. SourceLocation EndLoc) {
  1864. // Get the type, we will need to reference it in a couple spots.
  1865. QualType msgSendType = FD->getType();
  1866. // Create a reference to the objc_msgSend() declaration.
  1867. DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, FD, false, msgSendType,
  1868. VK_LValue, SourceLocation());
  1869. // Now, we cast the reference to a pointer to the objc_msgSend type.
  1870. QualType pToFunc = Context->getPointerType(msgSendType);
  1871. ImplicitCastExpr *ICE =
  1872. ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
  1873. DRE, nullptr, VK_PRValue, FPOptionsOverride());
  1874. const auto *FT = msgSendType->castAs<FunctionType>();
  1875. CallExpr *Exp =
  1876. CallExpr::Create(*Context, ICE, Args, FT->getCallResultType(*Context),
  1877. VK_PRValue, EndLoc, FPOptionsOverride());
  1878. return Exp;
  1879. }
  1880. static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
  1881. const char *&startRef, const char *&endRef) {
  1882. while (startBuf < endBuf) {
  1883. if (*startBuf == '<')
  1884. startRef = startBuf; // mark the start.
  1885. if (*startBuf == '>') {
  1886. if (startRef && *startRef == '<') {
  1887. endRef = startBuf; // mark the end.
  1888. return true;
  1889. }
  1890. return false;
  1891. }
  1892. startBuf++;
  1893. }
  1894. return false;
  1895. }
  1896. static void scanToNextArgument(const char *&argRef) {
  1897. int angle = 0;
  1898. while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
  1899. if (*argRef == '<')
  1900. angle++;
  1901. else if (*argRef == '>')
  1902. angle--;
  1903. argRef++;
  1904. }
  1905. assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
  1906. }
  1907. bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
  1908. if (T->isObjCQualifiedIdType())
  1909. return true;
  1910. if (const PointerType *PT = T->getAs<PointerType>()) {
  1911. if (PT->getPointeeType()->isObjCQualifiedIdType())
  1912. return true;
  1913. }
  1914. if (T->isObjCObjectPointerType()) {
  1915. T = T->getPointeeType();
  1916. return T->isObjCQualifiedInterfaceType();
  1917. }
  1918. if (T->isArrayType()) {
  1919. QualType ElemTy = Context->getBaseElementType(T);
  1920. return needToScanForQualifiers(ElemTy);
  1921. }
  1922. return false;
  1923. }
  1924. void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
  1925. QualType Type = E->getType();
  1926. if (needToScanForQualifiers(Type)) {
  1927. SourceLocation Loc, EndLoc;
  1928. if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
  1929. Loc = ECE->getLParenLoc();
  1930. EndLoc = ECE->getRParenLoc();
  1931. } else {
  1932. Loc = E->getBeginLoc();
  1933. EndLoc = E->getEndLoc();
  1934. }
  1935. // This will defend against trying to rewrite synthesized expressions.
  1936. if (Loc.isInvalid() || EndLoc.isInvalid())
  1937. return;
  1938. const char *startBuf = SM->getCharacterData(Loc);
  1939. const char *endBuf = SM->getCharacterData(EndLoc);
  1940. const char *startRef = nullptr, *endRef = nullptr;
  1941. if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
  1942. // Get the locations of the startRef, endRef.
  1943. SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
  1944. SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
  1945. // Comment out the protocol references.
  1946. InsertText(LessLoc, "/*");
  1947. InsertText(GreaterLoc, "*/");
  1948. }
  1949. }
  1950. }
  1951. void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
  1952. SourceLocation Loc;
  1953. QualType Type;
  1954. const FunctionProtoType *proto = nullptr;
  1955. if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
  1956. Loc = VD->getLocation();
  1957. Type = VD->getType();
  1958. }
  1959. else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
  1960. Loc = FD->getLocation();
  1961. // Check for ObjC 'id' and class types that have been adorned with protocol
  1962. // information (id<p>, C<p>*). The protocol references need to be rewritten!
  1963. const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
  1964. assert(funcType && "missing function type");
  1965. proto = dyn_cast<FunctionProtoType>(funcType);
  1966. if (!proto)
  1967. return;
  1968. Type = proto->getReturnType();
  1969. }
  1970. else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
  1971. Loc = FD->getLocation();
  1972. Type = FD->getType();
  1973. }
  1974. else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
  1975. Loc = TD->getLocation();
  1976. Type = TD->getUnderlyingType();
  1977. }
  1978. else
  1979. return;
  1980. if (needToScanForQualifiers(Type)) {
  1981. // Since types are unique, we need to scan the buffer.
  1982. const char *endBuf = SM->getCharacterData(Loc);
  1983. const char *startBuf = endBuf;
  1984. while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
  1985. startBuf--; // scan backward (from the decl location) for return type.
  1986. const char *startRef = nullptr, *endRef = nullptr;
  1987. if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
  1988. // Get the locations of the startRef, endRef.
  1989. SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
  1990. SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
  1991. // Comment out the protocol references.
  1992. InsertText(LessLoc, "/*");
  1993. InsertText(GreaterLoc, "*/");
  1994. }
  1995. }
  1996. if (!proto)
  1997. return; // most likely, was a variable
  1998. // Now check arguments.
  1999. const char *startBuf = SM->getCharacterData(Loc);
  2000. const char *startFuncBuf = startBuf;
  2001. for (unsigned i = 0; i < proto->getNumParams(); i++) {
  2002. if (needToScanForQualifiers(proto->getParamType(i))) {
  2003. // Since types are unique, we need to scan the buffer.
  2004. const char *endBuf = startBuf;
  2005. // scan forward (from the decl location) for argument types.
  2006. scanToNextArgument(endBuf);
  2007. const char *startRef = nullptr, *endRef = nullptr;
  2008. if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
  2009. // Get the locations of the startRef, endRef.
  2010. SourceLocation LessLoc =
  2011. Loc.getLocWithOffset(startRef-startFuncBuf);
  2012. SourceLocation GreaterLoc =
  2013. Loc.getLocWithOffset(endRef-startFuncBuf+1);
  2014. // Comment out the protocol references.
  2015. InsertText(LessLoc, "/*");
  2016. InsertText(GreaterLoc, "*/");
  2017. }
  2018. startBuf = ++endBuf;
  2019. }
  2020. else {
  2021. // If the function name is derived from a macro expansion, then the
  2022. // argument buffer will not follow the name. Need to speak with Chris.
  2023. while (*startBuf && *startBuf != ')' && *startBuf != ',')
  2024. startBuf++; // scan forward (from the decl location) for argument types.
  2025. startBuf++;
  2026. }
  2027. }
  2028. }
  2029. void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
  2030. QualType QT = ND->getType();
  2031. const Type* TypePtr = QT->getAs<Type>();
  2032. if (!isa<TypeOfExprType>(TypePtr))
  2033. return;
  2034. while (isa<TypeOfExprType>(TypePtr)) {
  2035. const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
  2036. QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
  2037. TypePtr = QT->getAs<Type>();
  2038. }
  2039. // FIXME. This will not work for multiple declarators; as in:
  2040. // __typeof__(a) b,c,d;
  2041. std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
  2042. SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
  2043. const char *startBuf = SM->getCharacterData(DeclLoc);
  2044. if (ND->getInit()) {
  2045. std::string Name(ND->getNameAsString());
  2046. TypeAsString += " " + Name + " = ";
  2047. Expr *E = ND->getInit();
  2048. SourceLocation startLoc;
  2049. if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
  2050. startLoc = ECE->getLParenLoc();
  2051. else
  2052. startLoc = E->getBeginLoc();
  2053. startLoc = SM->getExpansionLoc(startLoc);
  2054. const char *endBuf = SM->getCharacterData(startLoc);
  2055. ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
  2056. }
  2057. else {
  2058. SourceLocation X = ND->getEndLoc();
  2059. X = SM->getExpansionLoc(X);
  2060. const char *endBuf = SM->getCharacterData(X);
  2061. ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
  2062. }
  2063. }
  2064. // SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
  2065. void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
  2066. IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
  2067. SmallVector<QualType, 16> ArgTys;
  2068. ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
  2069. QualType getFuncType =
  2070. getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
  2071. SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
  2072. SourceLocation(),
  2073. SourceLocation(),
  2074. SelGetUidIdent, getFuncType,
  2075. nullptr, SC_Extern);
  2076. }
  2077. void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
  2078. // declared in <objc/objc.h>
  2079. if (FD->getIdentifier() &&
  2080. FD->getName() == "sel_registerName") {
  2081. SelGetUidFunctionDecl = FD;
  2082. return;
  2083. }
  2084. RewriteObjCQualifiedInterfaceTypes(FD);
  2085. }
  2086. void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
  2087. std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
  2088. const char *argPtr = TypeString.c_str();
  2089. if (!strchr(argPtr, '^')) {
  2090. Str += TypeString;
  2091. return;
  2092. }
  2093. while (*argPtr) {
  2094. Str += (*argPtr == '^' ? '*' : *argPtr);
  2095. argPtr++;
  2096. }
  2097. }
  2098. // FIXME. Consolidate this routine with RewriteBlockPointerType.
  2099. void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
  2100. ValueDecl *VD) {
  2101. QualType Type = VD->getType();
  2102. std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
  2103. const char *argPtr = TypeString.c_str();
  2104. int paren = 0;
  2105. while (*argPtr) {
  2106. switch (*argPtr) {
  2107. case '(':
  2108. Str += *argPtr;
  2109. paren++;
  2110. break;
  2111. case ')':
  2112. Str += *argPtr;
  2113. paren--;
  2114. break;
  2115. case '^':
  2116. Str += '*';
  2117. if (paren == 1)
  2118. Str += VD->getNameAsString();
  2119. break;
  2120. default:
  2121. Str += *argPtr;
  2122. break;
  2123. }
  2124. argPtr++;
  2125. }
  2126. }
  2127. void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
  2128. SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
  2129. const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
  2130. const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
  2131. if (!proto)
  2132. return;
  2133. QualType Type = proto->getReturnType();
  2134. std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
  2135. FdStr += " ";
  2136. FdStr += FD->getName();
  2137. FdStr += "(";
  2138. unsigned numArgs = proto->getNumParams();
  2139. for (unsigned i = 0; i < numArgs; i++) {
  2140. QualType ArgType = proto->getParamType(i);
  2141. RewriteBlockPointerType(FdStr, ArgType);
  2142. if (i+1 < numArgs)
  2143. FdStr += ", ";
  2144. }
  2145. if (FD->isVariadic()) {
  2146. FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
  2147. }
  2148. else
  2149. FdStr += ");\n";
  2150. InsertText(FunLocStart, FdStr);
  2151. }
  2152. // SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
  2153. void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
  2154. if (SuperConstructorFunctionDecl)
  2155. return;
  2156. IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
  2157. SmallVector<QualType, 16> ArgTys;
  2158. QualType argT = Context->getObjCIdType();
  2159. assert(!argT.isNull() && "Can't find 'id' type");
  2160. ArgTys.push_back(argT);
  2161. ArgTys.push_back(argT);
  2162. QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
  2163. ArgTys);
  2164. SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
  2165. SourceLocation(),
  2166. SourceLocation(),
  2167. msgSendIdent, msgSendType,
  2168. nullptr, SC_Extern);
  2169. }
  2170. // SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
  2171. void RewriteModernObjC::SynthMsgSendFunctionDecl() {
  2172. IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
  2173. SmallVector<QualType, 16> ArgTys;
  2174. QualType argT = Context->getObjCIdType();
  2175. assert(!argT.isNull() && "Can't find 'id' type");
  2176. ArgTys.push_back(argT);
  2177. argT = Context->getObjCSelType();
  2178. assert(!argT.isNull() && "Can't find 'SEL' type");
  2179. ArgTys.push_back(argT);
  2180. QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
  2181. ArgTys, /*variadic=*/true);
  2182. MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
  2183. SourceLocation(),
  2184. SourceLocation(),
  2185. msgSendIdent, msgSendType, nullptr,
  2186. SC_Extern);
  2187. }
  2188. // SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
  2189. void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
  2190. IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
  2191. SmallVector<QualType, 2> ArgTys;
  2192. ArgTys.push_back(Context->VoidTy);
  2193. QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
  2194. ArgTys, /*variadic=*/true);
  2195. MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
  2196. SourceLocation(),
  2197. SourceLocation(),
  2198. msgSendIdent, msgSendType,
  2199. nullptr, SC_Extern);
  2200. }
  2201. // SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
  2202. void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
  2203. IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
  2204. SmallVector<QualType, 16> ArgTys;
  2205. QualType argT = Context->getObjCIdType();
  2206. assert(!argT.isNull() && "Can't find 'id' type");
  2207. ArgTys.push_back(argT);
  2208. argT = Context->getObjCSelType();
  2209. assert(!argT.isNull() && "Can't find 'SEL' type");
  2210. ArgTys.push_back(argT);
  2211. QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
  2212. ArgTys, /*variadic=*/true);
  2213. MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
  2214. SourceLocation(),
  2215. SourceLocation(),
  2216. msgSendIdent, msgSendType,
  2217. nullptr, SC_Extern);
  2218. }
  2219. // SynthMsgSendSuperStretFunctionDecl -
  2220. // id objc_msgSendSuper_stret(void);
  2221. void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
  2222. IdentifierInfo *msgSendIdent =
  2223. &Context->Idents.get("objc_msgSendSuper_stret");
  2224. SmallVector<QualType, 2> ArgTys;
  2225. ArgTys.push_back(Context->VoidTy);
  2226. QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
  2227. ArgTys, /*variadic=*/true);
  2228. MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
  2229. SourceLocation(),
  2230. SourceLocation(),
  2231. msgSendIdent,
  2232. msgSendType, nullptr,
  2233. SC_Extern);
  2234. }
  2235. // SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
  2236. void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
  2237. IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
  2238. SmallVector<QualType, 16> ArgTys;
  2239. QualType argT = Context->getObjCIdType();
  2240. assert(!argT.isNull() && "Can't find 'id' type");
  2241. ArgTys.push_back(argT);
  2242. argT = Context->getObjCSelType();
  2243. assert(!argT.isNull() && "Can't find 'SEL' type");
  2244. ArgTys.push_back(argT);
  2245. QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
  2246. ArgTys, /*variadic=*/true);
  2247. MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
  2248. SourceLocation(),
  2249. SourceLocation(),
  2250. msgSendIdent, msgSendType,
  2251. nullptr, SC_Extern);
  2252. }
  2253. // SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
  2254. void RewriteModernObjC::SynthGetClassFunctionDecl() {
  2255. IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
  2256. SmallVector<QualType, 16> ArgTys;
  2257. ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
  2258. QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
  2259. ArgTys);
  2260. GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
  2261. SourceLocation(),
  2262. SourceLocation(),
  2263. getClassIdent, getClassType,
  2264. nullptr, SC_Extern);
  2265. }
  2266. // SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
  2267. void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
  2268. IdentifierInfo *getSuperClassIdent =
  2269. &Context->Idents.get("class_getSuperclass");
  2270. SmallVector<QualType, 16> ArgTys;
  2271. ArgTys.push_back(Context->getObjCClassType());
  2272. QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
  2273. ArgTys);
  2274. GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
  2275. SourceLocation(),
  2276. SourceLocation(),
  2277. getSuperClassIdent,
  2278. getClassType, nullptr,
  2279. SC_Extern);
  2280. }
  2281. // SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
  2282. void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
  2283. IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
  2284. SmallVector<QualType, 16> ArgTys;
  2285. ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
  2286. QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
  2287. ArgTys);
  2288. GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
  2289. SourceLocation(),
  2290. SourceLocation(),
  2291. getClassIdent, getClassType,
  2292. nullptr, SC_Extern);
  2293. }
  2294. Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
  2295. assert (Exp != nullptr && "Expected non-null ObjCStringLiteral");
  2296. QualType strType = getConstantStringStructType();
  2297. std::string S = "__NSConstantStringImpl_";
  2298. std::string tmpName = InFileName;
  2299. unsigned i;
  2300. for (i=0; i < tmpName.length(); i++) {
  2301. char c = tmpName.at(i);
  2302. // replace any non-alphanumeric characters with '_'.
  2303. if (!isAlphanumeric(c))
  2304. tmpName[i] = '_';
  2305. }
  2306. S += tmpName;
  2307. S += "_";
  2308. S += utostr(NumObjCStringLiterals++);
  2309. Preamble += "static __NSConstantStringImpl " + S;
  2310. Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
  2311. Preamble += "0x000007c8,"; // utf8_str
  2312. // The pretty printer for StringLiteral handles escape characters properly.
  2313. std::string prettyBufS;
  2314. llvm::raw_string_ostream prettyBuf(prettyBufS);
  2315. Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
  2316. Preamble += prettyBuf.str();
  2317. Preamble += ",";
  2318. Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
  2319. VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
  2320. SourceLocation(), &Context->Idents.get(S),
  2321. strType, nullptr, SC_Static);
  2322. DeclRefExpr *DRE = new (Context)
  2323. DeclRefExpr(*Context, NewVD, false, strType, VK_LValue, SourceLocation());
  2324. Expr *Unop = UnaryOperator::Create(
  2325. const_cast<ASTContext &>(*Context), DRE, UO_AddrOf,
  2326. Context->getPointerType(DRE->getType()), VK_PRValue, OK_Ordinary,
  2327. SourceLocation(), false, FPOptionsOverride());
  2328. // cast to NSConstantString *
  2329. CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
  2330. CK_CPointerToObjCPointerCast, Unop);
  2331. ReplaceStmt(Exp, cast);
  2332. // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
  2333. return cast;
  2334. }
  2335. Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
  2336. unsigned IntSize =
  2337. static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
  2338. Expr *FlagExp = IntegerLiteral::Create(*Context,
  2339. llvm::APInt(IntSize, Exp->getValue()),
  2340. Context->IntTy, Exp->getLocation());
  2341. CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
  2342. CK_BitCast, FlagExp);
  2343. ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
  2344. cast);
  2345. ReplaceStmt(Exp, PE);
  2346. return PE;
  2347. }
  2348. Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
  2349. // synthesize declaration of helper functions needed in this routine.
  2350. if (!SelGetUidFunctionDecl)
  2351. SynthSelGetUidFunctionDecl();
  2352. // use objc_msgSend() for all.
  2353. if (!MsgSendFunctionDecl)
  2354. SynthMsgSendFunctionDecl();
  2355. if (!GetClassFunctionDecl)
  2356. SynthGetClassFunctionDecl();
  2357. FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
  2358. SourceLocation StartLoc = Exp->getBeginLoc();
  2359. SourceLocation EndLoc = Exp->getEndLoc();
  2360. // Synthesize a call to objc_msgSend().
  2361. SmallVector<Expr*, 4> MsgExprs;
  2362. SmallVector<Expr*, 4> ClsExprs;
  2363. // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
  2364. ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
  2365. ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
  2366. IdentifierInfo *clsName = BoxingClass->getIdentifier();
  2367. ClsExprs.push_back(getStringLiteral(clsName->getName()));
  2368. CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
  2369. StartLoc, EndLoc);
  2370. MsgExprs.push_back(Cls);
  2371. // Create a call to sel_registerName("<BoxingMethod>:"), etc.
  2372. // it will be the 2nd argument.
  2373. SmallVector<Expr*, 4> SelExprs;
  2374. SelExprs.push_back(
  2375. getStringLiteral(BoxingMethod->getSelector().getAsString()));
  2376. CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
  2377. SelExprs, StartLoc, EndLoc);
  2378. MsgExprs.push_back(SelExp);
  2379. // User provided sub-expression is the 3rd, and last, argument.
  2380. Expr *subExpr = Exp->getSubExpr();
  2381. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
  2382. QualType type = ICE->getType();
  2383. const Expr *SubExpr = ICE->IgnoreParenImpCasts();
  2384. CastKind CK = CK_BitCast;
  2385. if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
  2386. CK = CK_IntegralToBoolean;
  2387. subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
  2388. }
  2389. MsgExprs.push_back(subExpr);
  2390. SmallVector<QualType, 4> ArgTypes;
  2391. ArgTypes.push_back(Context->getObjCClassType());
  2392. ArgTypes.push_back(Context->getObjCSelType());
  2393. for (const auto PI : BoxingMethod->parameters())
  2394. ArgTypes.push_back(PI->getType());
  2395. QualType returnType = Exp->getType();
  2396. // Get the type, we will need to reference it in a couple spots.
  2397. QualType msgSendType = MsgSendFlavor->getType();
  2398. // Create a reference to the objc_msgSend() declaration.
  2399. DeclRefExpr *DRE = new (Context) DeclRefExpr(
  2400. *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
  2401. CastExpr *cast = NoTypeInfoCStyleCastExpr(
  2402. Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
  2403. // Now do the "normal" pointer to function cast.
  2404. QualType castType =
  2405. getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
  2406. castType = Context->getPointerType(castType);
  2407. cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
  2408. cast);
  2409. // Don't forget the parens to enforce the proper binding.
  2410. ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
  2411. auto *FT = msgSendType->castAs<FunctionType>();
  2412. CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
  2413. VK_PRValue, EndLoc, FPOptionsOverride());
  2414. ReplaceStmt(Exp, CE);
  2415. return CE;
  2416. }
  2417. Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
  2418. // synthesize declaration of helper functions needed in this routine.
  2419. if (!SelGetUidFunctionDecl)
  2420. SynthSelGetUidFunctionDecl();
  2421. // use objc_msgSend() for all.
  2422. if (!MsgSendFunctionDecl)
  2423. SynthMsgSendFunctionDecl();
  2424. if (!GetClassFunctionDecl)
  2425. SynthGetClassFunctionDecl();
  2426. FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
  2427. SourceLocation StartLoc = Exp->getBeginLoc();
  2428. SourceLocation EndLoc = Exp->getEndLoc();
  2429. // Build the expression: __NSContainer_literal(int, ...).arr
  2430. QualType IntQT = Context->IntTy;
  2431. QualType NSArrayFType =
  2432. getSimpleFunctionType(Context->VoidTy, IntQT, true);
  2433. std::string NSArrayFName("__NSContainer_literal");
  2434. FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
  2435. DeclRefExpr *NSArrayDRE = new (Context) DeclRefExpr(
  2436. *Context, NSArrayFD, false, NSArrayFType, VK_PRValue, SourceLocation());
  2437. SmallVector<Expr*, 16> InitExprs;
  2438. unsigned NumElements = Exp->getNumElements();
  2439. unsigned UnsignedIntSize =
  2440. static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
  2441. Expr *count = IntegerLiteral::Create(*Context,
  2442. llvm::APInt(UnsignedIntSize, NumElements),
  2443. Context->UnsignedIntTy, SourceLocation());
  2444. InitExprs.push_back(count);
  2445. for (unsigned i = 0; i < NumElements; i++)
  2446. InitExprs.push_back(Exp->getElement(i));
  2447. Expr *NSArrayCallExpr =
  2448. CallExpr::Create(*Context, NSArrayDRE, InitExprs, NSArrayFType, VK_LValue,
  2449. SourceLocation(), FPOptionsOverride());
  2450. FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
  2451. SourceLocation(),
  2452. &Context->Idents.get("arr"),
  2453. Context->getPointerType(Context->VoidPtrTy),
  2454. nullptr, /*BitWidth=*/nullptr,
  2455. /*Mutable=*/true, ICIS_NoInit);
  2456. MemberExpr *ArrayLiteralME =
  2457. MemberExpr::CreateImplicit(*Context, NSArrayCallExpr, false, ARRFD,
  2458. ARRFD->getType(), VK_LValue, OK_Ordinary);
  2459. QualType ConstIdT = Context->getObjCIdType().withConst();
  2460. CStyleCastExpr * ArrayLiteralObjects =
  2461. NoTypeInfoCStyleCastExpr(Context,
  2462. Context->getPointerType(ConstIdT),
  2463. CK_BitCast,
  2464. ArrayLiteralME);
  2465. // Synthesize a call to objc_msgSend().
  2466. SmallVector<Expr*, 32> MsgExprs;
  2467. SmallVector<Expr*, 4> ClsExprs;
  2468. QualType expType = Exp->getType();
  2469. // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
  2470. ObjCInterfaceDecl *Class =
  2471. expType->getPointeeType()->castAs<ObjCObjectType>()->getInterface();
  2472. IdentifierInfo *clsName = Class->getIdentifier();
  2473. ClsExprs.push_back(getStringLiteral(clsName->getName()));
  2474. CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
  2475. StartLoc, EndLoc);
  2476. MsgExprs.push_back(Cls);
  2477. // Create a call to sel_registerName("arrayWithObjects:count:").
  2478. // it will be the 2nd argument.
  2479. SmallVector<Expr*, 4> SelExprs;
  2480. ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
  2481. SelExprs.push_back(
  2482. getStringLiteral(ArrayMethod->getSelector().getAsString()));
  2483. CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
  2484. SelExprs, StartLoc, EndLoc);
  2485. MsgExprs.push_back(SelExp);
  2486. // (const id [])objects
  2487. MsgExprs.push_back(ArrayLiteralObjects);
  2488. // (NSUInteger)cnt
  2489. Expr *cnt = IntegerLiteral::Create(*Context,
  2490. llvm::APInt(UnsignedIntSize, NumElements),
  2491. Context->UnsignedIntTy, SourceLocation());
  2492. MsgExprs.push_back(cnt);
  2493. SmallVector<QualType, 4> ArgTypes;
  2494. ArgTypes.push_back(Context->getObjCClassType());
  2495. ArgTypes.push_back(Context->getObjCSelType());
  2496. for (const auto *PI : ArrayMethod->parameters())
  2497. ArgTypes.push_back(PI->getType());
  2498. QualType returnType = Exp->getType();
  2499. // Get the type, we will need to reference it in a couple spots.
  2500. QualType msgSendType = MsgSendFlavor->getType();
  2501. // Create a reference to the objc_msgSend() declaration.
  2502. DeclRefExpr *DRE = new (Context) DeclRefExpr(
  2503. *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
  2504. CastExpr *cast = NoTypeInfoCStyleCastExpr(
  2505. Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
  2506. // Now do the "normal" pointer to function cast.
  2507. QualType castType =
  2508. getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
  2509. castType = Context->getPointerType(castType);
  2510. cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
  2511. cast);
  2512. // Don't forget the parens to enforce the proper binding.
  2513. ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
  2514. const FunctionType *FT = msgSendType->castAs<FunctionType>();
  2515. CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
  2516. VK_PRValue, EndLoc, FPOptionsOverride());
  2517. ReplaceStmt(Exp, CE);
  2518. return CE;
  2519. }
  2520. Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
  2521. // synthesize declaration of helper functions needed in this routine.
  2522. if (!SelGetUidFunctionDecl)
  2523. SynthSelGetUidFunctionDecl();
  2524. // use objc_msgSend() for all.
  2525. if (!MsgSendFunctionDecl)
  2526. SynthMsgSendFunctionDecl();
  2527. if (!GetClassFunctionDecl)
  2528. SynthGetClassFunctionDecl();
  2529. FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
  2530. SourceLocation StartLoc = Exp->getBeginLoc();
  2531. SourceLocation EndLoc = Exp->getEndLoc();
  2532. // Build the expression: __NSContainer_literal(int, ...).arr
  2533. QualType IntQT = Context->IntTy;
  2534. QualType NSDictFType =
  2535. getSimpleFunctionType(Context->VoidTy, IntQT, true);
  2536. std::string NSDictFName("__NSContainer_literal");
  2537. FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
  2538. DeclRefExpr *NSDictDRE = new (Context) DeclRefExpr(
  2539. *Context, NSDictFD, false, NSDictFType, VK_PRValue, SourceLocation());
  2540. SmallVector<Expr*, 16> KeyExprs;
  2541. SmallVector<Expr*, 16> ValueExprs;
  2542. unsigned NumElements = Exp->getNumElements();
  2543. unsigned UnsignedIntSize =
  2544. static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
  2545. Expr *count = IntegerLiteral::Create(*Context,
  2546. llvm::APInt(UnsignedIntSize, NumElements),
  2547. Context->UnsignedIntTy, SourceLocation());
  2548. KeyExprs.push_back(count);
  2549. ValueExprs.push_back(count);
  2550. for (unsigned i = 0; i < NumElements; i++) {
  2551. ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
  2552. KeyExprs.push_back(Element.Key);
  2553. ValueExprs.push_back(Element.Value);
  2554. }
  2555. // (const id [])objects
  2556. Expr *NSValueCallExpr =
  2557. CallExpr::Create(*Context, NSDictDRE, ValueExprs, NSDictFType, VK_LValue,
  2558. SourceLocation(), FPOptionsOverride());
  2559. FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
  2560. SourceLocation(),
  2561. &Context->Idents.get("arr"),
  2562. Context->getPointerType(Context->VoidPtrTy),
  2563. nullptr, /*BitWidth=*/nullptr,
  2564. /*Mutable=*/true, ICIS_NoInit);
  2565. MemberExpr *DictLiteralValueME =
  2566. MemberExpr::CreateImplicit(*Context, NSValueCallExpr, false, ARRFD,
  2567. ARRFD->getType(), VK_LValue, OK_Ordinary);
  2568. QualType ConstIdT = Context->getObjCIdType().withConst();
  2569. CStyleCastExpr * DictValueObjects =
  2570. NoTypeInfoCStyleCastExpr(Context,
  2571. Context->getPointerType(ConstIdT),
  2572. CK_BitCast,
  2573. DictLiteralValueME);
  2574. // (const id <NSCopying> [])keys
  2575. Expr *NSKeyCallExpr =
  2576. CallExpr::Create(*Context, NSDictDRE, KeyExprs, NSDictFType, VK_LValue,
  2577. SourceLocation(), FPOptionsOverride());
  2578. MemberExpr *DictLiteralKeyME =
  2579. MemberExpr::CreateImplicit(*Context, NSKeyCallExpr, false, ARRFD,
  2580. ARRFD->getType(), VK_LValue, OK_Ordinary);
  2581. CStyleCastExpr * DictKeyObjects =
  2582. NoTypeInfoCStyleCastExpr(Context,
  2583. Context->getPointerType(ConstIdT),
  2584. CK_BitCast,
  2585. DictLiteralKeyME);
  2586. // Synthesize a call to objc_msgSend().
  2587. SmallVector<Expr*, 32> MsgExprs;
  2588. SmallVector<Expr*, 4> ClsExprs;
  2589. QualType expType = Exp->getType();
  2590. // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
  2591. ObjCInterfaceDecl *Class =
  2592. expType->getPointeeType()->castAs<ObjCObjectType>()->getInterface();
  2593. IdentifierInfo *clsName = Class->getIdentifier();
  2594. ClsExprs.push_back(getStringLiteral(clsName->getName()));
  2595. CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
  2596. StartLoc, EndLoc);
  2597. MsgExprs.push_back(Cls);
  2598. // Create a call to sel_registerName("arrayWithObjects:count:").
  2599. // it will be the 2nd argument.
  2600. SmallVector<Expr*, 4> SelExprs;
  2601. ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
  2602. SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
  2603. CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
  2604. SelExprs, StartLoc, EndLoc);
  2605. MsgExprs.push_back(SelExp);
  2606. // (const id [])objects
  2607. MsgExprs.push_back(DictValueObjects);
  2608. // (const id <NSCopying> [])keys
  2609. MsgExprs.push_back(DictKeyObjects);
  2610. // (NSUInteger)cnt
  2611. Expr *cnt = IntegerLiteral::Create(*Context,
  2612. llvm::APInt(UnsignedIntSize, NumElements),
  2613. Context->UnsignedIntTy, SourceLocation());
  2614. MsgExprs.push_back(cnt);
  2615. SmallVector<QualType, 8> ArgTypes;
  2616. ArgTypes.push_back(Context->getObjCClassType());
  2617. ArgTypes.push_back(Context->getObjCSelType());
  2618. for (const auto *PI : DictMethod->parameters()) {
  2619. QualType T = PI->getType();
  2620. if (const PointerType* PT = T->getAs<PointerType>()) {
  2621. QualType PointeeTy = PT->getPointeeType();
  2622. convertToUnqualifiedObjCType(PointeeTy);
  2623. T = Context->getPointerType(PointeeTy);
  2624. }
  2625. ArgTypes.push_back(T);
  2626. }
  2627. QualType returnType = Exp->getType();
  2628. // Get the type, we will need to reference it in a couple spots.
  2629. QualType msgSendType = MsgSendFlavor->getType();
  2630. // Create a reference to the objc_msgSend() declaration.
  2631. DeclRefExpr *DRE = new (Context) DeclRefExpr(
  2632. *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
  2633. CastExpr *cast = NoTypeInfoCStyleCastExpr(
  2634. Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
  2635. // Now do the "normal" pointer to function cast.
  2636. QualType castType =
  2637. getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
  2638. castType = Context->getPointerType(castType);
  2639. cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
  2640. cast);
  2641. // Don't forget the parens to enforce the proper binding.
  2642. ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
  2643. const FunctionType *FT = msgSendType->castAs<FunctionType>();
  2644. CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
  2645. VK_PRValue, EndLoc, FPOptionsOverride());
  2646. ReplaceStmt(Exp, CE);
  2647. return CE;
  2648. }
  2649. // struct __rw_objc_super {
  2650. // struct objc_object *object; struct objc_object *superClass;
  2651. // };
  2652. QualType RewriteModernObjC::getSuperStructType() {
  2653. if (!SuperStructDecl) {
  2654. SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
  2655. SourceLocation(), SourceLocation(),
  2656. &Context->Idents.get("__rw_objc_super"));
  2657. QualType FieldTypes[2];
  2658. // struct objc_object *object;
  2659. FieldTypes[0] = Context->getObjCIdType();
  2660. // struct objc_object *superClass;
  2661. FieldTypes[1] = Context->getObjCIdType();
  2662. // Create fields
  2663. for (unsigned i = 0; i < 2; ++i) {
  2664. SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
  2665. SourceLocation(),
  2666. SourceLocation(), nullptr,
  2667. FieldTypes[i], nullptr,
  2668. /*BitWidth=*/nullptr,
  2669. /*Mutable=*/false,
  2670. ICIS_NoInit));
  2671. }
  2672. SuperStructDecl->completeDefinition();
  2673. }
  2674. return Context->getTagDeclType(SuperStructDecl);
  2675. }
  2676. QualType RewriteModernObjC::getConstantStringStructType() {
  2677. if (!ConstantStringDecl) {
  2678. ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
  2679. SourceLocation(), SourceLocation(),
  2680. &Context->Idents.get("__NSConstantStringImpl"));
  2681. QualType FieldTypes[4];
  2682. // struct objc_object *receiver;
  2683. FieldTypes[0] = Context->getObjCIdType();
  2684. // int flags;
  2685. FieldTypes[1] = Context->IntTy;
  2686. // char *str;
  2687. FieldTypes[2] = Context->getPointerType(Context->CharTy);
  2688. // long length;
  2689. FieldTypes[3] = Context->LongTy;
  2690. // Create fields
  2691. for (unsigned i = 0; i < 4; ++i) {
  2692. ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
  2693. ConstantStringDecl,
  2694. SourceLocation(),
  2695. SourceLocation(), nullptr,
  2696. FieldTypes[i], nullptr,
  2697. /*BitWidth=*/nullptr,
  2698. /*Mutable=*/true,
  2699. ICIS_NoInit));
  2700. }
  2701. ConstantStringDecl->completeDefinition();
  2702. }
  2703. return Context->getTagDeclType(ConstantStringDecl);
  2704. }
  2705. /// getFunctionSourceLocation - returns start location of a function
  2706. /// definition. Complication arises when function has declared as
  2707. /// extern "C" or extern "C" {...}
  2708. static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
  2709. FunctionDecl *FD) {
  2710. if (FD->isExternC() && !FD->isMain()) {
  2711. const DeclContext *DC = FD->getDeclContext();
  2712. if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
  2713. // if it is extern "C" {...}, return function decl's own location.
  2714. if (!LSD->getRBraceLoc().isValid())
  2715. return LSD->getExternLoc();
  2716. }
  2717. if (FD->getStorageClass() != SC_None)
  2718. R.RewriteBlockLiteralFunctionDecl(FD);
  2719. return FD->getTypeSpecStartLoc();
  2720. }
  2721. void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
  2722. SourceLocation Location = D->getLocation();
  2723. if (Location.isFileID() && GenerateLineInfo) {
  2724. std::string LineString("\n#line ");
  2725. PresumedLoc PLoc = SM->getPresumedLoc(Location);
  2726. LineString += utostr(PLoc.getLine());
  2727. LineString += " \"";
  2728. LineString += Lexer::Stringify(PLoc.getFilename());
  2729. if (isa<ObjCMethodDecl>(D))
  2730. LineString += "\"";
  2731. else LineString += "\"\n";
  2732. Location = D->getBeginLoc();
  2733. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  2734. if (FD->isExternC() && !FD->isMain()) {
  2735. const DeclContext *DC = FD->getDeclContext();
  2736. if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
  2737. // if it is extern "C" {...}, return function decl's own location.
  2738. if (!LSD->getRBraceLoc().isValid())
  2739. Location = LSD->getExternLoc();
  2740. }
  2741. }
  2742. InsertText(Location, LineString);
  2743. }
  2744. }
  2745. /// SynthMsgSendStretCallExpr - This routine translates message expression
  2746. /// into a call to objc_msgSend_stret() entry point. Tricky part is that
  2747. /// nil check on receiver must be performed before calling objc_msgSend_stret.
  2748. /// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
  2749. /// msgSendType - function type of objc_msgSend_stret(...)
  2750. /// returnType - Result type of the method being synthesized.
  2751. /// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
  2752. /// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
  2753. /// starting with receiver.
  2754. /// Method - Method being rewritten.
  2755. Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
  2756. QualType returnType,
  2757. SmallVectorImpl<QualType> &ArgTypes,
  2758. SmallVectorImpl<Expr*> &MsgExprs,
  2759. ObjCMethodDecl *Method) {
  2760. // Now do the "normal" pointer to function cast.
  2761. QualType FuncType = getSimpleFunctionType(
  2762. returnType, ArgTypes, Method ? Method->isVariadic() : false);
  2763. QualType castType = Context->getPointerType(FuncType);
  2764. // build type for containing the objc_msgSend_stret object.
  2765. static unsigned stretCount=0;
  2766. std::string name = "__Stret"; name += utostr(stretCount);
  2767. std::string str =
  2768. "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
  2769. str += "namespace {\n";
  2770. str += "struct "; str += name;
  2771. str += " {\n\t";
  2772. str += name;
  2773. str += "(id receiver, SEL sel";
  2774. for (unsigned i = 2; i < ArgTypes.size(); i++) {
  2775. std::string ArgName = "arg"; ArgName += utostr(i);
  2776. ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
  2777. str += ", "; str += ArgName;
  2778. }
  2779. // could be vararg.
  2780. for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
  2781. std::string ArgName = "arg"; ArgName += utostr(i);
  2782. MsgExprs[i]->getType().getAsStringInternal(ArgName,
  2783. Context->getPrintingPolicy());
  2784. str += ", "; str += ArgName;
  2785. }
  2786. str += ") {\n";
  2787. str += "\t unsigned size = sizeof(";
  2788. str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
  2789. str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
  2790. str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
  2791. str += ")(void *)objc_msgSend)(receiver, sel";
  2792. for (unsigned i = 2; i < ArgTypes.size(); i++) {
  2793. str += ", arg"; str += utostr(i);
  2794. }
  2795. // could be vararg.
  2796. for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
  2797. str += ", arg"; str += utostr(i);
  2798. }
  2799. str+= ");\n";
  2800. str += "\t else if (receiver == 0)\n";
  2801. str += "\t memset((void*)&s, 0, sizeof(s));\n";
  2802. str += "\t else\n";
  2803. str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
  2804. str += ")(void *)objc_msgSend_stret)(receiver, sel";
  2805. for (unsigned i = 2; i < ArgTypes.size(); i++) {
  2806. str += ", arg"; str += utostr(i);
  2807. }
  2808. // could be vararg.
  2809. for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
  2810. str += ", arg"; str += utostr(i);
  2811. }
  2812. str += ");\n";
  2813. str += "\t}\n";
  2814. str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
  2815. str += " s;\n";
  2816. str += "};\n};\n\n";
  2817. SourceLocation FunLocStart;
  2818. if (CurFunctionDef)
  2819. FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
  2820. else {
  2821. assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
  2822. FunLocStart = CurMethodDef->getBeginLoc();
  2823. }
  2824. InsertText(FunLocStart, str);
  2825. ++stretCount;
  2826. // AST for __Stretn(receiver, args).s;
  2827. IdentifierInfo *ID = &Context->Idents.get(name);
  2828. FunctionDecl *FD =
  2829. FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(),
  2830. ID, FuncType, nullptr, SC_Extern, false, false);
  2831. DeclRefExpr *DRE = new (Context)
  2832. DeclRefExpr(*Context, FD, false, castType, VK_PRValue, SourceLocation());
  2833. CallExpr *STCE =
  2834. CallExpr::Create(*Context, DRE, MsgExprs, castType, VK_LValue,
  2835. SourceLocation(), FPOptionsOverride());
  2836. FieldDecl *FieldD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
  2837. SourceLocation(),
  2838. &Context->Idents.get("s"),
  2839. returnType, nullptr,
  2840. /*BitWidth=*/nullptr,
  2841. /*Mutable=*/true, ICIS_NoInit);
  2842. MemberExpr *ME = MemberExpr::CreateImplicit(
  2843. *Context, STCE, false, FieldD, FieldD->getType(), VK_LValue, OK_Ordinary);
  2844. return ME;
  2845. }
  2846. Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
  2847. SourceLocation StartLoc,
  2848. SourceLocation EndLoc) {
  2849. if (!SelGetUidFunctionDecl)
  2850. SynthSelGetUidFunctionDecl();
  2851. if (!MsgSendFunctionDecl)
  2852. SynthMsgSendFunctionDecl();
  2853. if (!MsgSendSuperFunctionDecl)
  2854. SynthMsgSendSuperFunctionDecl();
  2855. if (!MsgSendStretFunctionDecl)
  2856. SynthMsgSendStretFunctionDecl();
  2857. if (!MsgSendSuperStretFunctionDecl)
  2858. SynthMsgSendSuperStretFunctionDecl();
  2859. if (!MsgSendFpretFunctionDecl)
  2860. SynthMsgSendFpretFunctionDecl();
  2861. if (!GetClassFunctionDecl)
  2862. SynthGetClassFunctionDecl();
  2863. if (!GetSuperClassFunctionDecl)
  2864. SynthGetSuperClassFunctionDecl();
  2865. if (!GetMetaClassFunctionDecl)
  2866. SynthGetMetaClassFunctionDecl();
  2867. // default to objc_msgSend().
  2868. FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
  2869. // May need to use objc_msgSend_stret() as well.
  2870. FunctionDecl *MsgSendStretFlavor = nullptr;
  2871. if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
  2872. QualType resultType = mDecl->getReturnType();
  2873. if (resultType->isRecordType())
  2874. MsgSendStretFlavor = MsgSendStretFunctionDecl;
  2875. else if (resultType->isRealFloatingType())
  2876. MsgSendFlavor = MsgSendFpretFunctionDecl;
  2877. }
  2878. // Synthesize a call to objc_msgSend().
  2879. SmallVector<Expr*, 8> MsgExprs;
  2880. switch (Exp->getReceiverKind()) {
  2881. case ObjCMessageExpr::SuperClass: {
  2882. MsgSendFlavor = MsgSendSuperFunctionDecl;
  2883. if (MsgSendStretFlavor)
  2884. MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
  2885. assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
  2886. ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
  2887. SmallVector<Expr*, 4> InitExprs;
  2888. // set the receiver to self, the first argument to all methods.
  2889. InitExprs.push_back(NoTypeInfoCStyleCastExpr(
  2890. Context, Context->getObjCIdType(), CK_BitCast,
  2891. new (Context) DeclRefExpr(*Context, CurMethodDef->getSelfDecl(), false,
  2892. Context->getObjCIdType(), VK_PRValue,
  2893. SourceLocation()))); // set the 'receiver'.
  2894. // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
  2895. SmallVector<Expr*, 8> ClsExprs;
  2896. ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
  2897. // (Class)objc_getClass("CurrentClass")
  2898. CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
  2899. ClsExprs, StartLoc, EndLoc);
  2900. ClsExprs.clear();
  2901. ClsExprs.push_back(Cls);
  2902. Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
  2903. StartLoc, EndLoc);
  2904. // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
  2905. // To turn off a warning, type-cast to 'id'
  2906. InitExprs.push_back( // set 'super class', using class_getSuperclass().
  2907. NoTypeInfoCStyleCastExpr(Context,
  2908. Context->getObjCIdType(),
  2909. CK_BitCast, Cls));
  2910. // struct __rw_objc_super
  2911. QualType superType = getSuperStructType();
  2912. Expr *SuperRep;
  2913. if (LangOpts.MicrosoftExt) {
  2914. SynthSuperConstructorFunctionDecl();
  2915. // Simulate a constructor call...
  2916. DeclRefExpr *DRE = new (Context)
  2917. DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
  2918. VK_LValue, SourceLocation());
  2919. SuperRep =
  2920. CallExpr::Create(*Context, DRE, InitExprs, superType, VK_LValue,
  2921. SourceLocation(), FPOptionsOverride());
  2922. // The code for super is a little tricky to prevent collision with
  2923. // the structure definition in the header. The rewriter has it's own
  2924. // internal definition (__rw_objc_super) that is uses. This is why
  2925. // we need the cast below. For example:
  2926. // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
  2927. //
  2928. SuperRep = UnaryOperator::Create(
  2929. const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf,
  2930. Context->getPointerType(SuperRep->getType()), VK_PRValue, OK_Ordinary,
  2931. SourceLocation(), false, FPOptionsOverride());
  2932. SuperRep = NoTypeInfoCStyleCastExpr(Context,
  2933. Context->getPointerType(superType),
  2934. CK_BitCast, SuperRep);
  2935. } else {
  2936. // (struct __rw_objc_super) { <exprs from above> }
  2937. InitListExpr *ILE =
  2938. new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
  2939. SourceLocation());
  2940. TypeSourceInfo *superTInfo
  2941. = Context->getTrivialTypeSourceInfo(superType);
  2942. SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
  2943. superType, VK_LValue,
  2944. ILE, false);
  2945. // struct __rw_objc_super *
  2946. SuperRep = UnaryOperator::Create(
  2947. const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf,
  2948. Context->getPointerType(SuperRep->getType()), VK_PRValue, OK_Ordinary,
  2949. SourceLocation(), false, FPOptionsOverride());
  2950. }
  2951. MsgExprs.push_back(SuperRep);
  2952. break;
  2953. }
  2954. case ObjCMessageExpr::Class: {
  2955. SmallVector<Expr*, 8> ClsExprs;
  2956. ObjCInterfaceDecl *Class
  2957. = Exp->getClassReceiver()->castAs<ObjCObjectType>()->getInterface();
  2958. IdentifierInfo *clsName = Class->getIdentifier();
  2959. ClsExprs.push_back(getStringLiteral(clsName->getName()));
  2960. CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
  2961. StartLoc, EndLoc);
  2962. CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
  2963. Context->getObjCIdType(),
  2964. CK_BitCast, Cls);
  2965. MsgExprs.push_back(ArgExpr);
  2966. break;
  2967. }
  2968. case ObjCMessageExpr::SuperInstance:{
  2969. MsgSendFlavor = MsgSendSuperFunctionDecl;
  2970. if (MsgSendStretFlavor)
  2971. MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
  2972. assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
  2973. ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
  2974. SmallVector<Expr*, 4> InitExprs;
  2975. InitExprs.push_back(NoTypeInfoCStyleCastExpr(
  2976. Context, Context->getObjCIdType(), CK_BitCast,
  2977. new (Context) DeclRefExpr(*Context, CurMethodDef->getSelfDecl(), false,
  2978. Context->getObjCIdType(), VK_PRValue,
  2979. SourceLocation()))); // set the 'receiver'.
  2980. // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
  2981. SmallVector<Expr*, 8> ClsExprs;
  2982. ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
  2983. // (Class)objc_getClass("CurrentClass")
  2984. CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
  2985. StartLoc, EndLoc);
  2986. ClsExprs.clear();
  2987. ClsExprs.push_back(Cls);
  2988. Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
  2989. StartLoc, EndLoc);
  2990. // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
  2991. // To turn off a warning, type-cast to 'id'
  2992. InitExprs.push_back(
  2993. // set 'super class', using class_getSuperclass().
  2994. NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
  2995. CK_BitCast, Cls));
  2996. // struct __rw_objc_super
  2997. QualType superType = getSuperStructType();
  2998. Expr *SuperRep;
  2999. if (LangOpts.MicrosoftExt) {
  3000. SynthSuperConstructorFunctionDecl();
  3001. // Simulate a constructor call...
  3002. DeclRefExpr *DRE = new (Context)
  3003. DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
  3004. VK_LValue, SourceLocation());
  3005. SuperRep =
  3006. CallExpr::Create(*Context, DRE, InitExprs, superType, VK_LValue,
  3007. SourceLocation(), FPOptionsOverride());
  3008. // The code for super is a little tricky to prevent collision with
  3009. // the structure definition in the header. The rewriter has it's own
  3010. // internal definition (__rw_objc_super) that is uses. This is why
  3011. // we need the cast below. For example:
  3012. // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
  3013. //
  3014. SuperRep = UnaryOperator::Create(
  3015. const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf,
  3016. Context->getPointerType(SuperRep->getType()), VK_PRValue, OK_Ordinary,
  3017. SourceLocation(), false, FPOptionsOverride());
  3018. SuperRep = NoTypeInfoCStyleCastExpr(Context,
  3019. Context->getPointerType(superType),
  3020. CK_BitCast, SuperRep);
  3021. } else {
  3022. // (struct __rw_objc_super) { <exprs from above> }
  3023. InitListExpr *ILE =
  3024. new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
  3025. SourceLocation());
  3026. TypeSourceInfo *superTInfo
  3027. = Context->getTrivialTypeSourceInfo(superType);
  3028. SuperRep = new (Context) CompoundLiteralExpr(
  3029. SourceLocation(), superTInfo, superType, VK_PRValue, ILE, false);
  3030. }
  3031. MsgExprs.push_back(SuperRep);
  3032. break;
  3033. }
  3034. case ObjCMessageExpr::Instance: {
  3035. // Remove all type-casts because it may contain objc-style types; e.g.
  3036. // Foo<Proto> *.
  3037. Expr *recExpr = Exp->getInstanceReceiver();
  3038. while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
  3039. recExpr = CE->getSubExpr();
  3040. CastKind CK = recExpr->getType()->isObjCObjectPointerType()
  3041. ? CK_BitCast : recExpr->getType()->isBlockPointerType()
  3042. ? CK_BlockPointerToObjCPointerCast
  3043. : CK_CPointerToObjCPointerCast;
  3044. recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
  3045. CK, recExpr);
  3046. MsgExprs.push_back(recExpr);
  3047. break;
  3048. }
  3049. }
  3050. // Create a call to sel_registerName("selName"), it will be the 2nd argument.
  3051. SmallVector<Expr*, 8> SelExprs;
  3052. SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
  3053. CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
  3054. SelExprs, StartLoc, EndLoc);
  3055. MsgExprs.push_back(SelExp);
  3056. // Now push any user supplied arguments.
  3057. for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
  3058. Expr *userExpr = Exp->getArg(i);
  3059. // Make all implicit casts explicit...ICE comes in handy:-)
  3060. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
  3061. // Reuse the ICE type, it is exactly what the doctor ordered.
  3062. QualType type = ICE->getType();
  3063. if (needToScanForQualifiers(type))
  3064. type = Context->getObjCIdType();
  3065. // Make sure we convert "type (^)(...)" to "type (*)(...)".
  3066. (void)convertBlockPointerToFunctionPointer(type);
  3067. const Expr *SubExpr = ICE->IgnoreParenImpCasts();
  3068. CastKind CK;
  3069. if (SubExpr->getType()->isIntegralType(*Context) &&
  3070. type->isBooleanType()) {
  3071. CK = CK_IntegralToBoolean;
  3072. } else if (type->isObjCObjectPointerType()) {
  3073. if (SubExpr->getType()->isBlockPointerType()) {
  3074. CK = CK_BlockPointerToObjCPointerCast;
  3075. } else if (SubExpr->getType()->isPointerType()) {
  3076. CK = CK_CPointerToObjCPointerCast;
  3077. } else {
  3078. CK = CK_BitCast;
  3079. }
  3080. } else {
  3081. CK = CK_BitCast;
  3082. }
  3083. userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
  3084. }
  3085. // Make id<P...> cast into an 'id' cast.
  3086. else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
  3087. if (CE->getType()->isObjCQualifiedIdType()) {
  3088. while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
  3089. userExpr = CE->getSubExpr();
  3090. CastKind CK;
  3091. if (userExpr->getType()->isIntegralType(*Context)) {
  3092. CK = CK_IntegralToPointer;
  3093. } else if (userExpr->getType()->isBlockPointerType()) {
  3094. CK = CK_BlockPointerToObjCPointerCast;
  3095. } else if (userExpr->getType()->isPointerType()) {
  3096. CK = CK_CPointerToObjCPointerCast;
  3097. } else {
  3098. CK = CK_BitCast;
  3099. }
  3100. userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
  3101. CK, userExpr);
  3102. }
  3103. }
  3104. MsgExprs.push_back(userExpr);
  3105. // We've transferred the ownership to MsgExprs. For now, we *don't* null
  3106. // out the argument in the original expression (since we aren't deleting
  3107. // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
  3108. //Exp->setArg(i, 0);
  3109. }
  3110. // Generate the funky cast.
  3111. CastExpr *cast;
  3112. SmallVector<QualType, 8> ArgTypes;
  3113. QualType returnType;
  3114. // Push 'id' and 'SEL', the 2 implicit arguments.
  3115. if (MsgSendFlavor == MsgSendSuperFunctionDecl)
  3116. ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
  3117. else
  3118. ArgTypes.push_back(Context->getObjCIdType());
  3119. ArgTypes.push_back(Context->getObjCSelType());
  3120. if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
  3121. // Push any user argument types.
  3122. for (const auto *PI : OMD->parameters()) {
  3123. QualType t = PI->getType()->isObjCQualifiedIdType()
  3124. ? Context->getObjCIdType()
  3125. : PI->getType();
  3126. // Make sure we convert "t (^)(...)" to "t (*)(...)".
  3127. (void)convertBlockPointerToFunctionPointer(t);
  3128. ArgTypes.push_back(t);
  3129. }
  3130. returnType = Exp->getType();
  3131. convertToUnqualifiedObjCType(returnType);
  3132. (void)convertBlockPointerToFunctionPointer(returnType);
  3133. } else {
  3134. returnType = Context->getObjCIdType();
  3135. }
  3136. // Get the type, we will need to reference it in a couple spots.
  3137. QualType msgSendType = MsgSendFlavor->getType();
  3138. // Create a reference to the objc_msgSend() declaration.
  3139. DeclRefExpr *DRE = new (Context) DeclRefExpr(
  3140. *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
  3141. // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
  3142. // If we don't do this cast, we get the following bizarre warning/note:
  3143. // xx.m:13: warning: function called through a non-compatible type
  3144. // xx.m:13: note: if this code is reached, the program will abort
  3145. cast = NoTypeInfoCStyleCastExpr(Context,
  3146. Context->getPointerType(Context->VoidTy),
  3147. CK_BitCast, DRE);
  3148. // Now do the "normal" pointer to function cast.
  3149. // If we don't have a method decl, force a variadic cast.
  3150. const ObjCMethodDecl *MD = Exp->getMethodDecl();
  3151. QualType castType =
  3152. getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
  3153. castType = Context->getPointerType(castType);
  3154. cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
  3155. cast);
  3156. // Don't forget the parens to enforce the proper binding.
  3157. ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
  3158. const FunctionType *FT = msgSendType->castAs<FunctionType>();
  3159. CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
  3160. VK_PRValue, EndLoc, FPOptionsOverride());
  3161. Stmt *ReplacingStmt = CE;
  3162. if (MsgSendStretFlavor) {
  3163. // We have the method which returns a struct/union. Must also generate
  3164. // call to objc_msgSend_stret and hang both varieties on a conditional
  3165. // expression which dictate which one to envoke depending on size of
  3166. // method's return type.
  3167. Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
  3168. returnType,
  3169. ArgTypes, MsgExprs,
  3170. Exp->getMethodDecl());
  3171. ReplacingStmt = STCE;
  3172. }
  3173. // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
  3174. return ReplacingStmt;
  3175. }
  3176. Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
  3177. Stmt *ReplacingStmt =
  3178. SynthMessageExpr(Exp, Exp->getBeginLoc(), Exp->getEndLoc());
  3179. // Now do the actual rewrite.
  3180. ReplaceStmt(Exp, ReplacingStmt);
  3181. // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
  3182. return ReplacingStmt;
  3183. }
  3184. // typedef struct objc_object Protocol;
  3185. QualType RewriteModernObjC::getProtocolType() {
  3186. if (!ProtocolTypeDecl) {
  3187. TypeSourceInfo *TInfo
  3188. = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
  3189. ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
  3190. SourceLocation(), SourceLocation(),
  3191. &Context->Idents.get("Protocol"),
  3192. TInfo);
  3193. }
  3194. return Context->getTypeDeclType(ProtocolTypeDecl);
  3195. }
  3196. /// RewriteObjCProtocolExpr - Rewrite a protocol expression into
  3197. /// a synthesized/forward data reference (to the protocol's metadata).
  3198. /// The forward references (and metadata) are generated in
  3199. /// RewriteModernObjC::HandleTranslationUnit().
  3200. Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
  3201. std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
  3202. Exp->getProtocol()->getNameAsString();
  3203. IdentifierInfo *ID = &Context->Idents.get(Name);
  3204. VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
  3205. SourceLocation(), ID, getProtocolType(),
  3206. nullptr, SC_Extern);
  3207. DeclRefExpr *DRE = new (Context) DeclRefExpr(
  3208. *Context, VD, false, getProtocolType(), VK_LValue, SourceLocation());
  3209. CastExpr *castExpr = NoTypeInfoCStyleCastExpr(
  3210. Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
  3211. ReplaceStmt(Exp, castExpr);
  3212. ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
  3213. // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
  3214. return castExpr;
  3215. }
  3216. /// IsTagDefinedInsideClass - This routine checks that a named tagged type
  3217. /// is defined inside an objective-c class. If so, it returns true.
  3218. bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
  3219. TagDecl *Tag,
  3220. bool &IsNamedDefinition) {
  3221. if (!IDecl)
  3222. return false;
  3223. SourceLocation TagLocation;
  3224. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
  3225. RD = RD->getDefinition();
  3226. if (!RD || !RD->getDeclName().getAsIdentifierInfo())
  3227. return false;
  3228. IsNamedDefinition = true;
  3229. TagLocation = RD->getLocation();
  3230. return Context->getSourceManager().isBeforeInTranslationUnit(
  3231. IDecl->getLocation(), TagLocation);
  3232. }
  3233. if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
  3234. if (!ED || !ED->getDeclName().getAsIdentifierInfo())
  3235. return false;
  3236. IsNamedDefinition = true;
  3237. TagLocation = ED->getLocation();
  3238. return Context->getSourceManager().isBeforeInTranslationUnit(
  3239. IDecl->getLocation(), TagLocation);
  3240. }
  3241. return false;
  3242. }
  3243. /// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
  3244. /// It handles elaborated types, as well as enum types in the process.
  3245. bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
  3246. std::string &Result) {
  3247. if (isa<TypedefType>(Type)) {
  3248. Result += "\t";
  3249. return false;
  3250. }
  3251. if (Type->isArrayType()) {
  3252. QualType ElemTy = Context->getBaseElementType(Type);
  3253. return RewriteObjCFieldDeclType(ElemTy, Result);
  3254. }
  3255. else if (Type->isRecordType()) {
  3256. RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
  3257. if (RD->isCompleteDefinition()) {
  3258. if (RD->isStruct())
  3259. Result += "\n\tstruct ";
  3260. else if (RD->isUnion())
  3261. Result += "\n\tunion ";
  3262. else
  3263. assert(false && "class not allowed as an ivar type");
  3264. Result += RD->getName();
  3265. if (GlobalDefinedTags.count(RD)) {
  3266. // struct/union is defined globally, use it.
  3267. Result += " ";
  3268. return true;
  3269. }
  3270. Result += " {\n";
  3271. for (auto *FD : RD->fields())
  3272. RewriteObjCFieldDecl(FD, Result);
  3273. Result += "\t} ";
  3274. return true;
  3275. }
  3276. }
  3277. else if (Type->isEnumeralType()) {
  3278. EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
  3279. if (ED->isCompleteDefinition()) {
  3280. Result += "\n\tenum ";
  3281. Result += ED->getName();
  3282. if (GlobalDefinedTags.count(ED)) {
  3283. // Enum is globall defined, use it.
  3284. Result += " ";
  3285. return true;
  3286. }
  3287. Result += " {\n";
  3288. for (const auto *EC : ED->enumerators()) {
  3289. Result += "\t"; Result += EC->getName(); Result += " = ";
  3290. Result += toString(EC->getInitVal(), 10);
  3291. Result += ",\n";
  3292. }
  3293. Result += "\t} ";
  3294. return true;
  3295. }
  3296. }
  3297. Result += "\t";
  3298. convertObjCTypeToCStyleType(Type);
  3299. return false;
  3300. }
  3301. /// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
  3302. /// It handles elaborated types, as well as enum types in the process.
  3303. void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
  3304. std::string &Result) {
  3305. QualType Type = fieldDecl->getType();
  3306. std::string Name = fieldDecl->getNameAsString();
  3307. bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
  3308. if (!EleboratedType)
  3309. Type.getAsStringInternal(Name, Context->getPrintingPolicy());
  3310. Result += Name;
  3311. if (fieldDecl->isBitField()) {
  3312. Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
  3313. }
  3314. else if (EleboratedType && Type->isArrayType()) {
  3315. const ArrayType *AT = Context->getAsArrayType(Type);
  3316. do {
  3317. if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
  3318. Result += "[";
  3319. llvm::APInt Dim = CAT->getSize();
  3320. Result += utostr(Dim.getZExtValue());
  3321. Result += "]";
  3322. }
  3323. AT = Context->getAsArrayType(AT->getElementType());
  3324. } while (AT);
  3325. }
  3326. Result += ";\n";
  3327. }
  3328. /// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
  3329. /// named aggregate types into the input buffer.
  3330. void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
  3331. std::string &Result) {
  3332. QualType Type = fieldDecl->getType();
  3333. if (isa<TypedefType>(Type))
  3334. return;
  3335. if (Type->isArrayType())
  3336. Type = Context->getBaseElementType(Type);
  3337. auto *IDecl = dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
  3338. TagDecl *TD = nullptr;
  3339. if (Type->isRecordType()) {
  3340. TD = Type->castAs<RecordType>()->getDecl();
  3341. }
  3342. else if (Type->isEnumeralType()) {
  3343. TD = Type->castAs<EnumType>()->getDecl();
  3344. }
  3345. if (TD) {
  3346. if (GlobalDefinedTags.count(TD))
  3347. return;
  3348. bool IsNamedDefinition = false;
  3349. if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
  3350. RewriteObjCFieldDeclType(Type, Result);
  3351. Result += ";";
  3352. }
  3353. if (IsNamedDefinition)
  3354. GlobalDefinedTags.insert(TD);
  3355. }
  3356. }
  3357. unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
  3358. const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
  3359. if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
  3360. return IvarGroupNumber[IV];
  3361. }
  3362. unsigned GroupNo = 0;
  3363. SmallVector<const ObjCIvarDecl *, 8> IVars;
  3364. for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
  3365. IVD; IVD = IVD->getNextIvar())
  3366. IVars.push_back(IVD);
  3367. for (unsigned i = 0, e = IVars.size(); i < e; i++)
  3368. if (IVars[i]->isBitField()) {
  3369. IvarGroupNumber[IVars[i++]] = ++GroupNo;
  3370. while (i < e && IVars[i]->isBitField())
  3371. IvarGroupNumber[IVars[i++]] = GroupNo;
  3372. if (i < e)
  3373. --i;
  3374. }
  3375. ObjCInterefaceHasBitfieldGroups.insert(CDecl);
  3376. return IvarGroupNumber[IV];
  3377. }
  3378. QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
  3379. ObjCIvarDecl *IV,
  3380. SmallVectorImpl<ObjCIvarDecl *> &IVars) {
  3381. std::string StructTagName;
  3382. ObjCIvarBitfieldGroupType(IV, StructTagName);
  3383. RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
  3384. Context->getTranslationUnitDecl(),
  3385. SourceLocation(), SourceLocation(),
  3386. &Context->Idents.get(StructTagName));
  3387. for (unsigned i=0, e = IVars.size(); i < e; i++) {
  3388. ObjCIvarDecl *Ivar = IVars[i];
  3389. RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
  3390. &Context->Idents.get(Ivar->getName()),
  3391. Ivar->getType(),
  3392. nullptr, /*Expr *BW */Ivar->getBitWidth(),
  3393. false, ICIS_NoInit));
  3394. }
  3395. RD->completeDefinition();
  3396. return Context->getTagDeclType(RD);
  3397. }
  3398. QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
  3399. const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
  3400. unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
  3401. std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
  3402. if (GroupRecordType.count(tuple))
  3403. return GroupRecordType[tuple];
  3404. SmallVector<ObjCIvarDecl *, 8> IVars;
  3405. for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
  3406. IVD; IVD = IVD->getNextIvar()) {
  3407. if (IVD->isBitField())
  3408. IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
  3409. else {
  3410. if (!IVars.empty()) {
  3411. unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
  3412. // Generate the struct type for this group of bitfield ivars.
  3413. GroupRecordType[std::make_pair(CDecl, GroupNo)] =
  3414. SynthesizeBitfieldGroupStructType(IVars[0], IVars);
  3415. IVars.clear();
  3416. }
  3417. }
  3418. }
  3419. if (!IVars.empty()) {
  3420. // Do the last one.
  3421. unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
  3422. GroupRecordType[std::make_pair(CDecl, GroupNo)] =
  3423. SynthesizeBitfieldGroupStructType(IVars[0], IVars);
  3424. }
  3425. QualType RetQT = GroupRecordType[tuple];
  3426. assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
  3427. return RetQT;
  3428. }
  3429. /// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
  3430. /// Name would be: classname__GRBF_n where n is the group number for this ivar.
  3431. void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
  3432. std::string &Result) {
  3433. const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
  3434. Result += CDecl->getName();
  3435. Result += "__GRBF_";
  3436. unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
  3437. Result += utostr(GroupNo);
  3438. }
  3439. /// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
  3440. /// Name of the struct would be: classname__T_n where n is the group number for
  3441. /// this ivar.
  3442. void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
  3443. std::string &Result) {
  3444. const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
  3445. Result += CDecl->getName();
  3446. Result += "__T_";
  3447. unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
  3448. Result += utostr(GroupNo);
  3449. }
  3450. /// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
  3451. /// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
  3452. /// this ivar.
  3453. void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
  3454. std::string &Result) {
  3455. Result += "OBJC_IVAR_$_";
  3456. ObjCIvarBitfieldGroupDecl(IV, Result);
  3457. }
  3458. #define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
  3459. while ((IX < ENDIX) && VEC[IX]->isBitField()) \
  3460. ++IX; \
  3461. if (IX < ENDIX) \
  3462. --IX; \
  3463. }
  3464. /// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
  3465. /// an objective-c class with ivars.
  3466. void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
  3467. std::string &Result) {
  3468. assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
  3469. assert(CDecl->getName() != "" &&
  3470. "Name missing in SynthesizeObjCInternalStruct");
  3471. ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
  3472. SmallVector<ObjCIvarDecl *, 8> IVars;
  3473. for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
  3474. IVD; IVD = IVD->getNextIvar())
  3475. IVars.push_back(IVD);
  3476. SourceLocation LocStart = CDecl->getBeginLoc();
  3477. SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
  3478. const char *startBuf = SM->getCharacterData(LocStart);
  3479. const char *endBuf = SM->getCharacterData(LocEnd);
  3480. // If no ivars and no root or if its root, directly or indirectly,
  3481. // have no ivars (thus not synthesized) then no need to synthesize this class.
  3482. if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
  3483. (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
  3484. endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
  3485. ReplaceText(LocStart, endBuf-startBuf, Result);
  3486. return;
  3487. }
  3488. // Insert named struct/union definitions inside class to
  3489. // outer scope. This follows semantics of locally defined
  3490. // struct/unions in objective-c classes.
  3491. for (unsigned i = 0, e = IVars.size(); i < e; i++)
  3492. RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
  3493. // Insert named structs which are syntheized to group ivar bitfields
  3494. // to outer scope as well.
  3495. for (unsigned i = 0, e = IVars.size(); i < e; i++)
  3496. if (IVars[i]->isBitField()) {
  3497. ObjCIvarDecl *IV = IVars[i];
  3498. QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
  3499. RewriteObjCFieldDeclType(QT, Result);
  3500. Result += ";";
  3501. // skip over ivar bitfields in this group.
  3502. SKIP_BITFIELDS(i , e, IVars);
  3503. }
  3504. Result += "\nstruct ";
  3505. Result += CDecl->getNameAsString();
  3506. Result += "_IMPL {\n";
  3507. if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
  3508. Result += "\tstruct "; Result += RCDecl->getNameAsString();
  3509. Result += "_IMPL "; Result += RCDecl->getNameAsString();
  3510. Result += "_IVARS;\n";
  3511. }
  3512. for (unsigned i = 0, e = IVars.size(); i < e; i++) {
  3513. if (IVars[i]->isBitField()) {
  3514. ObjCIvarDecl *IV = IVars[i];
  3515. Result += "\tstruct ";
  3516. ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
  3517. ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
  3518. // skip over ivar bitfields in this group.
  3519. SKIP_BITFIELDS(i , e, IVars);
  3520. }
  3521. else
  3522. RewriteObjCFieldDecl(IVars[i], Result);
  3523. }
  3524. Result += "};\n";
  3525. endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
  3526. ReplaceText(LocStart, endBuf-startBuf, Result);
  3527. // Mark this struct as having been generated.
  3528. if (!ObjCSynthesizedStructs.insert(CDecl).second)
  3529. llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
  3530. }
  3531. /// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
  3532. /// have been referenced in an ivar access expression.
  3533. void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
  3534. std::string &Result) {
  3535. // write out ivar offset symbols which have been referenced in an ivar
  3536. // access expression.
  3537. llvm::SmallSetVector<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
  3538. if (Ivars.empty())
  3539. return;
  3540. llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
  3541. for (ObjCIvarDecl *IvarDecl : Ivars) {
  3542. const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
  3543. unsigned GroupNo = 0;
  3544. if (IvarDecl->isBitField()) {
  3545. GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
  3546. if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
  3547. continue;
  3548. }
  3549. Result += "\n";
  3550. if (LangOpts.MicrosoftExt)
  3551. Result += "__declspec(allocate(\".objc_ivar$B\")) ";
  3552. Result += "extern \"C\" ";
  3553. if (LangOpts.MicrosoftExt &&
  3554. IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
  3555. IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
  3556. Result += "__declspec(dllimport) ";
  3557. Result += "unsigned long ";
  3558. if (IvarDecl->isBitField()) {
  3559. ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
  3560. GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
  3561. }
  3562. else
  3563. WriteInternalIvarName(CDecl, IvarDecl, Result);
  3564. Result += ";";
  3565. }
  3566. }
  3567. //===----------------------------------------------------------------------===//
  3568. // Meta Data Emission
  3569. //===----------------------------------------------------------------------===//
  3570. /// RewriteImplementations - This routine rewrites all method implementations
  3571. /// and emits meta-data.
  3572. void RewriteModernObjC::RewriteImplementations() {
  3573. int ClsDefCount = ClassImplementation.size();
  3574. int CatDefCount = CategoryImplementation.size();
  3575. // Rewrite implemented methods
  3576. for (int i = 0; i < ClsDefCount; i++) {
  3577. ObjCImplementationDecl *OIMP = ClassImplementation[i];
  3578. ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
  3579. if (CDecl->isImplicitInterfaceDecl())
  3580. assert(false &&
  3581. "Legacy implicit interface rewriting not supported in moder abi");
  3582. RewriteImplementationDecl(OIMP);
  3583. }
  3584. for (int i = 0; i < CatDefCount; i++) {
  3585. ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
  3586. ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
  3587. if (CDecl->isImplicitInterfaceDecl())
  3588. assert(false &&
  3589. "Legacy implicit interface rewriting not supported in moder abi");
  3590. RewriteImplementationDecl(CIMP);
  3591. }
  3592. }
  3593. void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
  3594. const std::string &Name,
  3595. ValueDecl *VD, bool def) {
  3596. assert(BlockByRefDeclNo.count(VD) &&
  3597. "RewriteByRefString: ByRef decl missing");
  3598. if (def)
  3599. ResultStr += "struct ";
  3600. ResultStr += "__Block_byref_" + Name +
  3601. "_" + utostr(BlockByRefDeclNo[VD]) ;
  3602. }
  3603. static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
  3604. if (VarDecl *Var = dyn_cast<VarDecl>(VD))
  3605. return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
  3606. return false;
  3607. }
  3608. std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
  3609. StringRef funcName,
  3610. std::string Tag) {
  3611. const FunctionType *AFT = CE->getFunctionType();
  3612. QualType RT = AFT->getReturnType();
  3613. std::string StructRef = "struct " + Tag;
  3614. SourceLocation BlockLoc = CE->getExprLoc();
  3615. std::string S;
  3616. ConvertSourceLocationToLineDirective(BlockLoc, S);
  3617. S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
  3618. funcName.str() + "_block_func_" + utostr(i);
  3619. BlockDecl *BD = CE->getBlockDecl();
  3620. if (isa<FunctionNoProtoType>(AFT)) {
  3621. // No user-supplied arguments. Still need to pass in a pointer to the
  3622. // block (to reference imported block decl refs).
  3623. S += "(" + StructRef + " *__cself)";
  3624. } else if (BD->param_empty()) {
  3625. S += "(" + StructRef + " *__cself)";
  3626. } else {
  3627. const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
  3628. assert(FT && "SynthesizeBlockFunc: No function proto");
  3629. S += '(';
  3630. // first add the implicit argument.
  3631. S += StructRef + " *__cself, ";
  3632. std::string ParamStr;
  3633. for (BlockDecl::param_iterator AI = BD->param_begin(),
  3634. E = BD->param_end(); AI != E; ++AI) {
  3635. if (AI != BD->param_begin()) S += ", ";
  3636. ParamStr = (*AI)->getNameAsString();
  3637. QualType QT = (*AI)->getType();
  3638. (void)convertBlockPointerToFunctionPointer(QT);
  3639. QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
  3640. S += ParamStr;
  3641. }
  3642. if (FT->isVariadic()) {
  3643. if (!BD->param_empty()) S += ", ";
  3644. S += "...";
  3645. }
  3646. S += ')';
  3647. }
  3648. S += " {\n";
  3649. // Create local declarations to avoid rewriting all closure decl ref exprs.
  3650. // First, emit a declaration for all "by ref" decls.
  3651. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
  3652. E = BlockByRefDecls.end(); I != E; ++I) {
  3653. S += " ";
  3654. std::string Name = (*I)->getNameAsString();
  3655. std::string TypeString;
  3656. RewriteByRefString(TypeString, Name, (*I));
  3657. TypeString += " *";
  3658. Name = TypeString + Name;
  3659. S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
  3660. }
  3661. // Next, emit a declaration for all "by copy" declarations.
  3662. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
  3663. E = BlockByCopyDecls.end(); I != E; ++I) {
  3664. S += " ";
  3665. // Handle nested closure invocation. For example:
  3666. //
  3667. // void (^myImportedClosure)(void);
  3668. // myImportedClosure = ^(void) { setGlobalInt(x + y); };
  3669. //
  3670. // void (^anotherClosure)(void);
  3671. // anotherClosure = ^(void) {
  3672. // myImportedClosure(); // import and invoke the closure
  3673. // };
  3674. //
  3675. if (isTopLevelBlockPointerType((*I)->getType())) {
  3676. RewriteBlockPointerTypeVariable(S, (*I));
  3677. S += " = (";
  3678. RewriteBlockPointerType(S, (*I)->getType());
  3679. S += ")";
  3680. S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
  3681. }
  3682. else {
  3683. std::string Name = (*I)->getNameAsString();
  3684. QualType QT = (*I)->getType();
  3685. if (HasLocalVariableExternalStorage(*I))
  3686. QT = Context->getPointerType(QT);
  3687. QT.getAsStringInternal(Name, Context->getPrintingPolicy());
  3688. S += Name + " = __cself->" +
  3689. (*I)->getNameAsString() + "; // bound by copy\n";
  3690. }
  3691. }
  3692. std::string RewrittenStr = RewrittenBlockExprs[CE];
  3693. const char *cstr = RewrittenStr.c_str();
  3694. while (*cstr++ != '{') ;
  3695. S += cstr;
  3696. S += "\n";
  3697. return S;
  3698. }
  3699. std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
  3700. StringRef funcName,
  3701. std::string Tag) {
  3702. std::string StructRef = "struct " + Tag;
  3703. std::string S = "static void __";
  3704. S += funcName;
  3705. S += "_block_copy_" + utostr(i);
  3706. S += "(" + StructRef;
  3707. S += "*dst, " + StructRef;
  3708. S += "*src) {";
  3709. for (ValueDecl *VD : ImportedBlockDecls) {
  3710. S += "_Block_object_assign((void*)&dst->";
  3711. S += VD->getNameAsString();
  3712. S += ", (void*)src->";
  3713. S += VD->getNameAsString();
  3714. if (BlockByRefDeclsPtrSet.count(VD))
  3715. S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
  3716. else if (VD->getType()->isBlockPointerType())
  3717. S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
  3718. else
  3719. S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
  3720. }
  3721. S += "}\n";
  3722. S += "\nstatic void __";
  3723. S += funcName;
  3724. S += "_block_dispose_" + utostr(i);
  3725. S += "(" + StructRef;
  3726. S += "*src) {";
  3727. for (ValueDecl *VD : ImportedBlockDecls) {
  3728. S += "_Block_object_dispose((void*)src->";
  3729. S += VD->getNameAsString();
  3730. if (BlockByRefDeclsPtrSet.count(VD))
  3731. S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
  3732. else if (VD->getType()->isBlockPointerType())
  3733. S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
  3734. else
  3735. S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
  3736. }
  3737. S += "}\n";
  3738. return S;
  3739. }
  3740. std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
  3741. std::string Desc) {
  3742. std::string S = "\nstruct " + Tag;
  3743. std::string Constructor = " " + Tag;
  3744. S += " {\n struct __block_impl impl;\n";
  3745. S += " struct " + Desc;
  3746. S += "* Desc;\n";
  3747. Constructor += "(void *fp, "; // Invoke function pointer.
  3748. Constructor += "struct " + Desc; // Descriptor pointer.
  3749. Constructor += " *desc";
  3750. if (BlockDeclRefs.size()) {
  3751. // Output all "by copy" declarations.
  3752. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
  3753. E = BlockByCopyDecls.end(); I != E; ++I) {
  3754. S += " ";
  3755. std::string FieldName = (*I)->getNameAsString();
  3756. std::string ArgName = "_" + FieldName;
  3757. // Handle nested closure invocation. For example:
  3758. //
  3759. // void (^myImportedBlock)(void);
  3760. // myImportedBlock = ^(void) { setGlobalInt(x + y); };
  3761. //
  3762. // void (^anotherBlock)(void);
  3763. // anotherBlock = ^(void) {
  3764. // myImportedBlock(); // import and invoke the closure
  3765. // };
  3766. //
  3767. if (isTopLevelBlockPointerType((*I)->getType())) {
  3768. S += "struct __block_impl *";
  3769. Constructor += ", void *" + ArgName;
  3770. } else {
  3771. QualType QT = (*I)->getType();
  3772. if (HasLocalVariableExternalStorage(*I))
  3773. QT = Context->getPointerType(QT);
  3774. QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
  3775. QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
  3776. Constructor += ", " + ArgName;
  3777. }
  3778. S += FieldName + ";\n";
  3779. }
  3780. // Output all "by ref" declarations.
  3781. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
  3782. E = BlockByRefDecls.end(); I != E; ++I) {
  3783. S += " ";
  3784. std::string FieldName = (*I)->getNameAsString();
  3785. std::string ArgName = "_" + FieldName;
  3786. {
  3787. std::string TypeString;
  3788. RewriteByRefString(TypeString, FieldName, (*I));
  3789. TypeString += " *";
  3790. FieldName = TypeString + FieldName;
  3791. ArgName = TypeString + ArgName;
  3792. Constructor += ", " + ArgName;
  3793. }
  3794. S += FieldName + "; // by ref\n";
  3795. }
  3796. // Finish writing the constructor.
  3797. Constructor += ", int flags=0)";
  3798. // Initialize all "by copy" arguments.
  3799. bool firsTime = true;
  3800. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
  3801. E = BlockByCopyDecls.end(); I != E; ++I) {
  3802. std::string Name = (*I)->getNameAsString();
  3803. if (firsTime) {
  3804. Constructor += " : ";
  3805. firsTime = false;
  3806. }
  3807. else
  3808. Constructor += ", ";
  3809. if (isTopLevelBlockPointerType((*I)->getType()))
  3810. Constructor += Name + "((struct __block_impl *)_" + Name + ")";
  3811. else
  3812. Constructor += Name + "(_" + Name + ")";
  3813. }
  3814. // Initialize all "by ref" arguments.
  3815. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
  3816. E = BlockByRefDecls.end(); I != E; ++I) {
  3817. std::string Name = (*I)->getNameAsString();
  3818. if (firsTime) {
  3819. Constructor += " : ";
  3820. firsTime = false;
  3821. }
  3822. else
  3823. Constructor += ", ";
  3824. Constructor += Name + "(_" + Name + "->__forwarding)";
  3825. }
  3826. Constructor += " {\n";
  3827. if (GlobalVarDecl)
  3828. Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
  3829. else
  3830. Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
  3831. Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
  3832. Constructor += " Desc = desc;\n";
  3833. } else {
  3834. // Finish writing the constructor.
  3835. Constructor += ", int flags=0) {\n";
  3836. if (GlobalVarDecl)
  3837. Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
  3838. else
  3839. Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
  3840. Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
  3841. Constructor += " Desc = desc;\n";
  3842. }
  3843. Constructor += " ";
  3844. Constructor += "}\n";
  3845. S += Constructor;
  3846. S += "};\n";
  3847. return S;
  3848. }
  3849. std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
  3850. std::string ImplTag, int i,
  3851. StringRef FunName,
  3852. unsigned hasCopy) {
  3853. std::string S = "\nstatic struct " + DescTag;
  3854. S += " {\n size_t reserved;\n";
  3855. S += " size_t Block_size;\n";
  3856. if (hasCopy) {
  3857. S += " void (*copy)(struct ";
  3858. S += ImplTag; S += "*, struct ";
  3859. S += ImplTag; S += "*);\n";
  3860. S += " void (*dispose)(struct ";
  3861. S += ImplTag; S += "*);\n";
  3862. }
  3863. S += "} ";
  3864. S += DescTag + "_DATA = { 0, sizeof(struct ";
  3865. S += ImplTag + ")";
  3866. if (hasCopy) {
  3867. S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
  3868. S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
  3869. }
  3870. S += "};\n";
  3871. return S;
  3872. }
  3873. void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
  3874. StringRef FunName) {
  3875. bool RewriteSC = (GlobalVarDecl &&
  3876. !Blocks.empty() &&
  3877. GlobalVarDecl->getStorageClass() == SC_Static &&
  3878. GlobalVarDecl->getType().getCVRQualifiers());
  3879. if (RewriteSC) {
  3880. std::string SC(" void __");
  3881. SC += GlobalVarDecl->getNameAsString();
  3882. SC += "() {}";
  3883. InsertText(FunLocStart, SC);
  3884. }
  3885. // Insert closures that were part of the function.
  3886. for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
  3887. CollectBlockDeclRefInfo(Blocks[i]);
  3888. // Need to copy-in the inner copied-in variables not actually used in this
  3889. // block.
  3890. for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
  3891. DeclRefExpr *Exp = InnerDeclRefs[count++];
  3892. ValueDecl *VD = Exp->getDecl();
  3893. BlockDeclRefs.push_back(Exp);
  3894. if (!VD->hasAttr<BlocksAttr>()) {
  3895. if (!BlockByCopyDeclsPtrSet.count(VD)) {
  3896. BlockByCopyDeclsPtrSet.insert(VD);
  3897. BlockByCopyDecls.push_back(VD);
  3898. }
  3899. continue;
  3900. }
  3901. if (!BlockByRefDeclsPtrSet.count(VD)) {
  3902. BlockByRefDeclsPtrSet.insert(VD);
  3903. BlockByRefDecls.push_back(VD);
  3904. }
  3905. // imported objects in the inner blocks not used in the outer
  3906. // blocks must be copied/disposed in the outer block as well.
  3907. if (VD->getType()->isObjCObjectPointerType() ||
  3908. VD->getType()->isBlockPointerType())
  3909. ImportedBlockDecls.insert(VD);
  3910. }
  3911. std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
  3912. std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
  3913. std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
  3914. InsertText(FunLocStart, CI);
  3915. std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
  3916. InsertText(FunLocStart, CF);
  3917. if (ImportedBlockDecls.size()) {
  3918. std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
  3919. InsertText(FunLocStart, HF);
  3920. }
  3921. std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
  3922. ImportedBlockDecls.size() > 0);
  3923. InsertText(FunLocStart, BD);
  3924. BlockDeclRefs.clear();
  3925. BlockByRefDecls.clear();
  3926. BlockByRefDeclsPtrSet.clear();
  3927. BlockByCopyDecls.clear();
  3928. BlockByCopyDeclsPtrSet.clear();
  3929. ImportedBlockDecls.clear();
  3930. }
  3931. if (RewriteSC) {
  3932. // Must insert any 'const/volatile/static here. Since it has been
  3933. // removed as result of rewriting of block literals.
  3934. std::string SC;
  3935. if (GlobalVarDecl->getStorageClass() == SC_Static)
  3936. SC = "static ";
  3937. if (GlobalVarDecl->getType().isConstQualified())
  3938. SC += "const ";
  3939. if (GlobalVarDecl->getType().isVolatileQualified())
  3940. SC += "volatile ";
  3941. if (GlobalVarDecl->getType().isRestrictQualified())
  3942. SC += "restrict ";
  3943. InsertText(FunLocStart, SC);
  3944. }
  3945. if (GlobalConstructionExp) {
  3946. // extra fancy dance for global literal expression.
  3947. // Always the latest block expression on the block stack.
  3948. std::string Tag = "__";
  3949. Tag += FunName;
  3950. Tag += "_block_impl_";
  3951. Tag += utostr(Blocks.size()-1);
  3952. std::string globalBuf = "static ";
  3953. globalBuf += Tag; globalBuf += " ";
  3954. std::string SStr;
  3955. llvm::raw_string_ostream constructorExprBuf(SStr);
  3956. GlobalConstructionExp->printPretty(constructorExprBuf, nullptr,
  3957. PrintingPolicy(LangOpts));
  3958. globalBuf += constructorExprBuf.str();
  3959. globalBuf += ";\n";
  3960. InsertText(FunLocStart, globalBuf);
  3961. GlobalConstructionExp = nullptr;
  3962. }
  3963. Blocks.clear();
  3964. InnerDeclRefsCount.clear();
  3965. InnerDeclRefs.clear();
  3966. RewrittenBlockExprs.clear();
  3967. }
  3968. void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
  3969. SourceLocation FunLocStart =
  3970. (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
  3971. : FD->getTypeSpecStartLoc();
  3972. StringRef FuncName = FD->getName();
  3973. SynthesizeBlockLiterals(FunLocStart, FuncName);
  3974. }
  3975. static void BuildUniqueMethodName(std::string &Name,
  3976. ObjCMethodDecl *MD) {
  3977. ObjCInterfaceDecl *IFace = MD->getClassInterface();
  3978. Name = std::string(IFace->getName());
  3979. Name += "__" + MD->getSelector().getAsString();
  3980. // Convert colons to underscores.
  3981. std::string::size_type loc = 0;
  3982. while ((loc = Name.find(':', loc)) != std::string::npos)
  3983. Name.replace(loc, 1, "_");
  3984. }
  3985. void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
  3986. // fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
  3987. // SourceLocation FunLocStart = MD->getBeginLoc();
  3988. SourceLocation FunLocStart = MD->getBeginLoc();
  3989. std::string FuncName;
  3990. BuildUniqueMethodName(FuncName, MD);
  3991. SynthesizeBlockLiterals(FunLocStart, FuncName);
  3992. }
  3993. void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
  3994. for (Stmt *SubStmt : S->children())
  3995. if (SubStmt) {
  3996. if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
  3997. GetBlockDeclRefExprs(CBE->getBody());
  3998. else
  3999. GetBlockDeclRefExprs(SubStmt);
  4000. }
  4001. // Handle specific things.
  4002. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
  4003. if (DRE->refersToEnclosingVariableOrCapture() ||
  4004. HasLocalVariableExternalStorage(DRE->getDecl()))
  4005. // FIXME: Handle enums.
  4006. BlockDeclRefs.push_back(DRE);
  4007. }
  4008. void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
  4009. SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
  4010. llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
  4011. for (Stmt *SubStmt : S->children())
  4012. if (SubStmt) {
  4013. if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
  4014. InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
  4015. GetInnerBlockDeclRefExprs(CBE->getBody(),
  4016. InnerBlockDeclRefs,
  4017. InnerContexts);
  4018. }
  4019. else
  4020. GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
  4021. }
  4022. // Handle specific things.
  4023. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
  4024. if (DRE->refersToEnclosingVariableOrCapture() ||
  4025. HasLocalVariableExternalStorage(DRE->getDecl())) {
  4026. if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
  4027. InnerBlockDeclRefs.push_back(DRE);
  4028. if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
  4029. if (Var->isFunctionOrMethodVarDecl())
  4030. ImportedLocalExternalDecls.insert(Var);
  4031. }
  4032. }
  4033. }
  4034. /// convertObjCTypeToCStyleType - This routine converts such objc types
  4035. /// as qualified objects, and blocks to their closest c/c++ types that
  4036. /// it can. It returns true if input type was modified.
  4037. bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
  4038. QualType oldT = T;
  4039. convertBlockPointerToFunctionPointer(T);
  4040. if (T->isFunctionPointerType()) {
  4041. QualType PointeeTy;
  4042. if (const PointerType* PT = T->getAs<PointerType>()) {
  4043. PointeeTy = PT->getPointeeType();
  4044. if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
  4045. T = convertFunctionTypeOfBlocks(FT);
  4046. T = Context->getPointerType(T);
  4047. }
  4048. }
  4049. }
  4050. convertToUnqualifiedObjCType(T);
  4051. return T != oldT;
  4052. }
  4053. /// convertFunctionTypeOfBlocks - This routine converts a function type
  4054. /// whose result type may be a block pointer or whose argument type(s)
  4055. /// might be block pointers to an equivalent function type replacing
  4056. /// all block pointers to function pointers.
  4057. QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
  4058. const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
  4059. // FTP will be null for closures that don't take arguments.
  4060. // Generate a funky cast.
  4061. SmallVector<QualType, 8> ArgTypes;
  4062. QualType Res = FT->getReturnType();
  4063. bool modified = convertObjCTypeToCStyleType(Res);
  4064. if (FTP) {
  4065. for (auto &I : FTP->param_types()) {
  4066. QualType t = I;
  4067. // Make sure we convert "t (^)(...)" to "t (*)(...)".
  4068. if (convertObjCTypeToCStyleType(t))
  4069. modified = true;
  4070. ArgTypes.push_back(t);
  4071. }
  4072. }
  4073. QualType FuncType;
  4074. if (modified)
  4075. FuncType = getSimpleFunctionType(Res, ArgTypes);
  4076. else FuncType = QualType(FT, 0);
  4077. return FuncType;
  4078. }
  4079. Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
  4080. // Navigate to relevant type information.
  4081. const BlockPointerType *CPT = nullptr;
  4082. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
  4083. CPT = DRE->getType()->getAs<BlockPointerType>();
  4084. } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
  4085. CPT = MExpr->getType()->getAs<BlockPointerType>();
  4086. }
  4087. else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
  4088. return SynthesizeBlockCall(Exp, PRE->getSubExpr());
  4089. }
  4090. else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
  4091. CPT = IEXPR->getType()->getAs<BlockPointerType>();
  4092. else if (const ConditionalOperator *CEXPR =
  4093. dyn_cast<ConditionalOperator>(BlockExp)) {
  4094. Expr *LHSExp = CEXPR->getLHS();
  4095. Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
  4096. Expr *RHSExp = CEXPR->getRHS();
  4097. Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
  4098. Expr *CONDExp = CEXPR->getCond();
  4099. ConditionalOperator *CondExpr = new (Context) ConditionalOperator(
  4100. CONDExp, SourceLocation(), cast<Expr>(LHSStmt), SourceLocation(),
  4101. cast<Expr>(RHSStmt), Exp->getType(), VK_PRValue, OK_Ordinary);
  4102. return CondExpr;
  4103. } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
  4104. CPT = IRE->getType()->getAs<BlockPointerType>();
  4105. } else if (const PseudoObjectExpr *POE
  4106. = dyn_cast<PseudoObjectExpr>(BlockExp)) {
  4107. CPT = POE->getType()->castAs<BlockPointerType>();
  4108. } else {
  4109. assert(false && "RewriteBlockClass: Bad type");
  4110. }
  4111. assert(CPT && "RewriteBlockClass: Bad type");
  4112. const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
  4113. assert(FT && "RewriteBlockClass: Bad type");
  4114. const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
  4115. // FTP will be null for closures that don't take arguments.
  4116. RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
  4117. SourceLocation(), SourceLocation(),
  4118. &Context->Idents.get("__block_impl"));
  4119. QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
  4120. // Generate a funky cast.
  4121. SmallVector<QualType, 8> ArgTypes;
  4122. // Push the block argument type.
  4123. ArgTypes.push_back(PtrBlock);
  4124. if (FTP) {
  4125. for (auto &I : FTP->param_types()) {
  4126. QualType t = I;
  4127. // Make sure we convert "t (^)(...)" to "t (*)(...)".
  4128. if (!convertBlockPointerToFunctionPointer(t))
  4129. convertToUnqualifiedObjCType(t);
  4130. ArgTypes.push_back(t);
  4131. }
  4132. }
  4133. // Now do the pointer to function cast.
  4134. QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
  4135. PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
  4136. CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
  4137. CK_BitCast,
  4138. const_cast<Expr*>(BlockExp));
  4139. // Don't forget the parens to enforce the proper binding.
  4140. ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
  4141. BlkCast);
  4142. //PE->dump();
  4143. FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
  4144. SourceLocation(),
  4145. &Context->Idents.get("FuncPtr"),
  4146. Context->VoidPtrTy, nullptr,
  4147. /*BitWidth=*/nullptr, /*Mutable=*/true,
  4148. ICIS_NoInit);
  4149. MemberExpr *ME = MemberExpr::CreateImplicit(
  4150. *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
  4151. CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
  4152. CK_BitCast, ME);
  4153. PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
  4154. SmallVector<Expr*, 8> BlkExprs;
  4155. // Add the implicit argument.
  4156. BlkExprs.push_back(BlkCast);
  4157. // Add the user arguments.
  4158. for (CallExpr::arg_iterator I = Exp->arg_begin(),
  4159. E = Exp->arg_end(); I != E; ++I) {
  4160. BlkExprs.push_back(*I);
  4161. }
  4162. CallExpr *CE =
  4163. CallExpr::Create(*Context, PE, BlkExprs, Exp->getType(), VK_PRValue,
  4164. SourceLocation(), FPOptionsOverride());
  4165. return CE;
  4166. }
  4167. // We need to return the rewritten expression to handle cases where the
  4168. // DeclRefExpr is embedded in another expression being rewritten.
  4169. // For example:
  4170. //
  4171. // int main() {
  4172. // __block Foo *f;
  4173. // __block int i;
  4174. //
  4175. // void (^myblock)() = ^() {
  4176. // [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
  4177. // i = 77;
  4178. // };
  4179. //}
  4180. Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
  4181. // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
  4182. // for each DeclRefExp where BYREFVAR is name of the variable.
  4183. ValueDecl *VD = DeclRefExp->getDecl();
  4184. bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
  4185. HasLocalVariableExternalStorage(DeclRefExp->getDecl());
  4186. FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
  4187. SourceLocation(),
  4188. &Context->Idents.get("__forwarding"),
  4189. Context->VoidPtrTy, nullptr,
  4190. /*BitWidth=*/nullptr, /*Mutable=*/true,
  4191. ICIS_NoInit);
  4192. MemberExpr *ME = MemberExpr::CreateImplicit(
  4193. *Context, DeclRefExp, isArrow, FD, FD->getType(), VK_LValue, OK_Ordinary);
  4194. StringRef Name = VD->getName();
  4195. FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
  4196. &Context->Idents.get(Name),
  4197. Context->VoidPtrTy, nullptr,
  4198. /*BitWidth=*/nullptr, /*Mutable=*/true,
  4199. ICIS_NoInit);
  4200. ME = MemberExpr::CreateImplicit(*Context, ME, true, FD, DeclRefExp->getType(),
  4201. VK_LValue, OK_Ordinary);
  4202. // Need parens to enforce precedence.
  4203. ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
  4204. DeclRefExp->getExprLoc(),
  4205. ME);
  4206. ReplaceStmt(DeclRefExp, PE);
  4207. return PE;
  4208. }
  4209. // Rewrites the imported local variable V with external storage
  4210. // (static, extern, etc.) as *V
  4211. //
  4212. Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
  4213. ValueDecl *VD = DRE->getDecl();
  4214. if (VarDecl *Var = dyn_cast<VarDecl>(VD))
  4215. if (!ImportedLocalExternalDecls.count(Var))
  4216. return DRE;
  4217. Expr *Exp = UnaryOperator::Create(
  4218. const_cast<ASTContext &>(*Context), DRE, UO_Deref, DRE->getType(),
  4219. VK_LValue, OK_Ordinary, DRE->getLocation(), false, FPOptionsOverride());
  4220. // Need parens to enforce precedence.
  4221. ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
  4222. Exp);
  4223. ReplaceStmt(DRE, PE);
  4224. return PE;
  4225. }
  4226. void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
  4227. SourceLocation LocStart = CE->getLParenLoc();
  4228. SourceLocation LocEnd = CE->getRParenLoc();
  4229. // Need to avoid trying to rewrite synthesized casts.
  4230. if (LocStart.isInvalid())
  4231. return;
  4232. // Need to avoid trying to rewrite casts contained in macros.
  4233. if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
  4234. return;
  4235. const char *startBuf = SM->getCharacterData(LocStart);
  4236. const char *endBuf = SM->getCharacterData(LocEnd);
  4237. QualType QT = CE->getType();
  4238. const Type* TypePtr = QT->getAs<Type>();
  4239. if (isa<TypeOfExprType>(TypePtr)) {
  4240. const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
  4241. QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
  4242. std::string TypeAsString = "(";
  4243. RewriteBlockPointerType(TypeAsString, QT);
  4244. TypeAsString += ")";
  4245. ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
  4246. return;
  4247. }
  4248. // advance the location to startArgList.
  4249. const char *argPtr = startBuf;
  4250. while (*argPtr++ && (argPtr < endBuf)) {
  4251. switch (*argPtr) {
  4252. case '^':
  4253. // Replace the '^' with '*'.
  4254. LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
  4255. ReplaceText(LocStart, 1, "*");
  4256. break;
  4257. }
  4258. }
  4259. }
  4260. void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
  4261. CastKind CastKind = IC->getCastKind();
  4262. if (CastKind != CK_BlockPointerToObjCPointerCast &&
  4263. CastKind != CK_AnyPointerToBlockPointerCast)
  4264. return;
  4265. QualType QT = IC->getType();
  4266. (void)convertBlockPointerToFunctionPointer(QT);
  4267. std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
  4268. std::string Str = "(";
  4269. Str += TypeString;
  4270. Str += ")";
  4271. InsertText(IC->getSubExpr()->getBeginLoc(), Str);
  4272. }
  4273. void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
  4274. SourceLocation DeclLoc = FD->getLocation();
  4275. unsigned parenCount = 0;
  4276. // We have 1 or more arguments that have closure pointers.
  4277. const char *startBuf = SM->getCharacterData(DeclLoc);
  4278. const char *startArgList = strchr(startBuf, '(');
  4279. assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
  4280. parenCount++;
  4281. // advance the location to startArgList.
  4282. DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
  4283. assert((DeclLoc.isValid()) && "Invalid DeclLoc");
  4284. const char *argPtr = startArgList;
  4285. while (*argPtr++ && parenCount) {
  4286. switch (*argPtr) {
  4287. case '^':
  4288. // Replace the '^' with '*'.
  4289. DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
  4290. ReplaceText(DeclLoc, 1, "*");
  4291. break;
  4292. case '(':
  4293. parenCount++;
  4294. break;
  4295. case ')':
  4296. parenCount--;
  4297. break;
  4298. }
  4299. }
  4300. }
  4301. bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
  4302. const FunctionProtoType *FTP;
  4303. const PointerType *PT = QT->getAs<PointerType>();
  4304. if (PT) {
  4305. FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
  4306. } else {
  4307. const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
  4308. assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
  4309. FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
  4310. }
  4311. if (FTP) {
  4312. for (const auto &I : FTP->param_types())
  4313. if (isTopLevelBlockPointerType(I))
  4314. return true;
  4315. }
  4316. return false;
  4317. }
  4318. bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
  4319. const FunctionProtoType *FTP;
  4320. const PointerType *PT = QT->getAs<PointerType>();
  4321. if (PT) {
  4322. FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
  4323. } else {
  4324. const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
  4325. assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
  4326. FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
  4327. }
  4328. if (FTP) {
  4329. for (const auto &I : FTP->param_types()) {
  4330. if (I->isObjCQualifiedIdType())
  4331. return true;
  4332. if (I->isObjCObjectPointerType() &&
  4333. I->getPointeeType()->isObjCQualifiedInterfaceType())
  4334. return true;
  4335. }
  4336. }
  4337. return false;
  4338. }
  4339. void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
  4340. const char *&RParen) {
  4341. const char *argPtr = strchr(Name, '(');
  4342. assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
  4343. LParen = argPtr; // output the start.
  4344. argPtr++; // skip past the left paren.
  4345. unsigned parenCount = 1;
  4346. while (*argPtr && parenCount) {
  4347. switch (*argPtr) {
  4348. case '(': parenCount++; break;
  4349. case ')': parenCount--; break;
  4350. default: break;
  4351. }
  4352. if (parenCount) argPtr++;
  4353. }
  4354. assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
  4355. RParen = argPtr; // output the end
  4356. }
  4357. void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
  4358. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  4359. RewriteBlockPointerFunctionArgs(FD);
  4360. return;
  4361. }
  4362. // Handle Variables and Typedefs.
  4363. SourceLocation DeclLoc = ND->getLocation();
  4364. QualType DeclT;
  4365. if (VarDecl *VD = dyn_cast<VarDecl>(ND))
  4366. DeclT = VD->getType();
  4367. else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
  4368. DeclT = TDD->getUnderlyingType();
  4369. else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
  4370. DeclT = FD->getType();
  4371. else
  4372. llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
  4373. const char *startBuf = SM->getCharacterData(DeclLoc);
  4374. const char *endBuf = startBuf;
  4375. // scan backward (from the decl location) for the end of the previous decl.
  4376. while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
  4377. startBuf--;
  4378. SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
  4379. std::string buf;
  4380. unsigned OrigLength=0;
  4381. // *startBuf != '^' if we are dealing with a pointer to function that
  4382. // may take block argument types (which will be handled below).
  4383. if (*startBuf == '^') {
  4384. // Replace the '^' with '*', computing a negative offset.
  4385. buf = '*';
  4386. startBuf++;
  4387. OrigLength++;
  4388. }
  4389. while (*startBuf != ')') {
  4390. buf += *startBuf;
  4391. startBuf++;
  4392. OrigLength++;
  4393. }
  4394. buf += ')';
  4395. OrigLength++;
  4396. if (PointerTypeTakesAnyBlockArguments(DeclT) ||
  4397. PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
  4398. // Replace the '^' with '*' for arguments.
  4399. // Replace id<P> with id/*<>*/
  4400. DeclLoc = ND->getLocation();
  4401. startBuf = SM->getCharacterData(DeclLoc);
  4402. const char *argListBegin, *argListEnd;
  4403. GetExtentOfArgList(startBuf, argListBegin, argListEnd);
  4404. while (argListBegin < argListEnd) {
  4405. if (*argListBegin == '^')
  4406. buf += '*';
  4407. else if (*argListBegin == '<') {
  4408. buf += "/*";
  4409. buf += *argListBegin++;
  4410. OrigLength++;
  4411. while (*argListBegin != '>') {
  4412. buf += *argListBegin++;
  4413. OrigLength++;
  4414. }
  4415. buf += *argListBegin;
  4416. buf += "*/";
  4417. }
  4418. else
  4419. buf += *argListBegin;
  4420. argListBegin++;
  4421. OrigLength++;
  4422. }
  4423. buf += ')';
  4424. OrigLength++;
  4425. }
  4426. ReplaceText(Start, OrigLength, buf);
  4427. }
  4428. /// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
  4429. /// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
  4430. /// struct Block_byref_id_object *src) {
  4431. /// _Block_object_assign (&_dest->object, _src->object,
  4432. /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
  4433. /// [|BLOCK_FIELD_IS_WEAK]) // object
  4434. /// _Block_object_assign(&_dest->object, _src->object,
  4435. /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
  4436. /// [|BLOCK_FIELD_IS_WEAK]) // block
  4437. /// }
  4438. /// And:
  4439. /// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
  4440. /// _Block_object_dispose(_src->object,
  4441. /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
  4442. /// [|BLOCK_FIELD_IS_WEAK]) // object
  4443. /// _Block_object_dispose(_src->object,
  4444. /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
  4445. /// [|BLOCK_FIELD_IS_WEAK]) // block
  4446. /// }
  4447. std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
  4448. int flag) {
  4449. std::string S;
  4450. if (CopyDestroyCache.count(flag))
  4451. return S;
  4452. CopyDestroyCache.insert(flag);
  4453. S = "static void __Block_byref_id_object_copy_";
  4454. S += utostr(flag);
  4455. S += "(void *dst, void *src) {\n";
  4456. // offset into the object pointer is computed as:
  4457. // void * + void* + int + int + void* + void *
  4458. unsigned IntSize =
  4459. static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
  4460. unsigned VoidPtrSize =
  4461. static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
  4462. unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
  4463. S += " _Block_object_assign((char*)dst + ";
  4464. S += utostr(offset);
  4465. S += ", *(void * *) ((char*)src + ";
  4466. S += utostr(offset);
  4467. S += "), ";
  4468. S += utostr(flag);
  4469. S += ");\n}\n";
  4470. S += "static void __Block_byref_id_object_dispose_";
  4471. S += utostr(flag);
  4472. S += "(void *src) {\n";
  4473. S += " _Block_object_dispose(*(void * *) ((char*)src + ";
  4474. S += utostr(offset);
  4475. S += "), ";
  4476. S += utostr(flag);
  4477. S += ");\n}\n";
  4478. return S;
  4479. }
  4480. /// RewriteByRefVar - For each __block typex ND variable this routine transforms
  4481. /// the declaration into:
  4482. /// struct __Block_byref_ND {
  4483. /// void *__isa; // NULL for everything except __weak pointers
  4484. /// struct __Block_byref_ND *__forwarding;
  4485. /// int32_t __flags;
  4486. /// int32_t __size;
  4487. /// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
  4488. /// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
  4489. /// typex ND;
  4490. /// };
  4491. ///
  4492. /// It then replaces declaration of ND variable with:
  4493. /// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
  4494. /// __size=sizeof(struct __Block_byref_ND),
  4495. /// ND=initializer-if-any};
  4496. ///
  4497. ///
  4498. void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
  4499. bool lastDecl) {
  4500. int flag = 0;
  4501. int isa = 0;
  4502. SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
  4503. if (DeclLoc.isInvalid())
  4504. // If type location is missing, it is because of missing type (a warning).
  4505. // Use variable's location which is good for this case.
  4506. DeclLoc = ND->getLocation();
  4507. const char *startBuf = SM->getCharacterData(DeclLoc);
  4508. SourceLocation X = ND->getEndLoc();
  4509. X = SM->getExpansionLoc(X);
  4510. const char *endBuf = SM->getCharacterData(X);
  4511. std::string Name(ND->getNameAsString());
  4512. std::string ByrefType;
  4513. RewriteByRefString(ByrefType, Name, ND, true);
  4514. ByrefType += " {\n";
  4515. ByrefType += " void *__isa;\n";
  4516. RewriteByRefString(ByrefType, Name, ND);
  4517. ByrefType += " *__forwarding;\n";
  4518. ByrefType += " int __flags;\n";
  4519. ByrefType += " int __size;\n";
  4520. // Add void *__Block_byref_id_object_copy;
  4521. // void *__Block_byref_id_object_dispose; if needed.
  4522. QualType Ty = ND->getType();
  4523. bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
  4524. if (HasCopyAndDispose) {
  4525. ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
  4526. ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
  4527. }
  4528. QualType T = Ty;
  4529. (void)convertBlockPointerToFunctionPointer(T);
  4530. T.getAsStringInternal(Name, Context->getPrintingPolicy());
  4531. ByrefType += " " + Name + ";\n";
  4532. ByrefType += "};\n";
  4533. // Insert this type in global scope. It is needed by helper function.
  4534. SourceLocation FunLocStart;
  4535. if (CurFunctionDef)
  4536. FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
  4537. else {
  4538. assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
  4539. FunLocStart = CurMethodDef->getBeginLoc();
  4540. }
  4541. InsertText(FunLocStart, ByrefType);
  4542. if (Ty.isObjCGCWeak()) {
  4543. flag |= BLOCK_FIELD_IS_WEAK;
  4544. isa = 1;
  4545. }
  4546. if (HasCopyAndDispose) {
  4547. flag = BLOCK_BYREF_CALLER;
  4548. QualType Ty = ND->getType();
  4549. // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
  4550. if (Ty->isBlockPointerType())
  4551. flag |= BLOCK_FIELD_IS_BLOCK;
  4552. else
  4553. flag |= BLOCK_FIELD_IS_OBJECT;
  4554. std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
  4555. if (!HF.empty())
  4556. Preamble += HF;
  4557. }
  4558. // struct __Block_byref_ND ND =
  4559. // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
  4560. // initializer-if-any};
  4561. bool hasInit = (ND->getInit() != nullptr);
  4562. // FIXME. rewriter does not support __block c++ objects which
  4563. // require construction.
  4564. if (hasInit)
  4565. if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
  4566. CXXConstructorDecl *CXXDecl = CExp->getConstructor();
  4567. if (CXXDecl && CXXDecl->isDefaultConstructor())
  4568. hasInit = false;
  4569. }
  4570. unsigned flags = 0;
  4571. if (HasCopyAndDispose)
  4572. flags |= BLOCK_HAS_COPY_DISPOSE;
  4573. Name = ND->getNameAsString();
  4574. ByrefType.clear();
  4575. RewriteByRefString(ByrefType, Name, ND);
  4576. std::string ForwardingCastType("(");
  4577. ForwardingCastType += ByrefType + " *)";
  4578. ByrefType += " " + Name + " = {(void*)";
  4579. ByrefType += utostr(isa);
  4580. ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
  4581. ByrefType += utostr(flags);
  4582. ByrefType += ", ";
  4583. ByrefType += "sizeof(";
  4584. RewriteByRefString(ByrefType, Name, ND);
  4585. ByrefType += ")";
  4586. if (HasCopyAndDispose) {
  4587. ByrefType += ", __Block_byref_id_object_copy_";
  4588. ByrefType += utostr(flag);
  4589. ByrefType += ", __Block_byref_id_object_dispose_";
  4590. ByrefType += utostr(flag);
  4591. }
  4592. if (!firstDecl) {
  4593. // In multiple __block declarations, and for all but 1st declaration,
  4594. // find location of the separating comma. This would be start location
  4595. // where new text is to be inserted.
  4596. DeclLoc = ND->getLocation();
  4597. const char *startDeclBuf = SM->getCharacterData(DeclLoc);
  4598. const char *commaBuf = startDeclBuf;
  4599. while (*commaBuf != ',')
  4600. commaBuf--;
  4601. assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
  4602. DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
  4603. startBuf = commaBuf;
  4604. }
  4605. if (!hasInit) {
  4606. ByrefType += "};\n";
  4607. unsigned nameSize = Name.size();
  4608. // for block or function pointer declaration. Name is already
  4609. // part of the declaration.
  4610. if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
  4611. nameSize = 1;
  4612. ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
  4613. }
  4614. else {
  4615. ByrefType += ", ";
  4616. SourceLocation startLoc;
  4617. Expr *E = ND->getInit();
  4618. if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
  4619. startLoc = ECE->getLParenLoc();
  4620. else
  4621. startLoc = E->getBeginLoc();
  4622. startLoc = SM->getExpansionLoc(startLoc);
  4623. endBuf = SM->getCharacterData(startLoc);
  4624. ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
  4625. const char separator = lastDecl ? ';' : ',';
  4626. const char *startInitializerBuf = SM->getCharacterData(startLoc);
  4627. const char *separatorBuf = strchr(startInitializerBuf, separator);
  4628. assert((*separatorBuf == separator) &&
  4629. "RewriteByRefVar: can't find ';' or ','");
  4630. SourceLocation separatorLoc =
  4631. startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
  4632. InsertText(separatorLoc, lastDecl ? "}" : "};\n");
  4633. }
  4634. }
  4635. void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
  4636. // Add initializers for any closure decl refs.
  4637. GetBlockDeclRefExprs(Exp->getBody());
  4638. if (BlockDeclRefs.size()) {
  4639. // Unique all "by copy" declarations.
  4640. for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
  4641. if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
  4642. if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
  4643. BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
  4644. BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
  4645. }
  4646. }
  4647. // Unique all "by ref" declarations.
  4648. for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
  4649. if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
  4650. if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
  4651. BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
  4652. BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
  4653. }
  4654. }
  4655. // Find any imported blocks...they will need special attention.
  4656. for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
  4657. if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
  4658. BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
  4659. BlockDeclRefs[i]->getType()->isBlockPointerType())
  4660. ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
  4661. }
  4662. }
  4663. FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
  4664. IdentifierInfo *ID = &Context->Idents.get(name);
  4665. QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
  4666. return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
  4667. SourceLocation(), ID, FType, nullptr, SC_Extern,
  4668. false, false);
  4669. }
  4670. Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
  4671. const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
  4672. const BlockDecl *block = Exp->getBlockDecl();
  4673. Blocks.push_back(Exp);
  4674. CollectBlockDeclRefInfo(Exp);
  4675. // Add inner imported variables now used in current block.
  4676. int countOfInnerDecls = 0;
  4677. if (!InnerBlockDeclRefs.empty()) {
  4678. for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
  4679. DeclRefExpr *Exp = InnerBlockDeclRefs[i];
  4680. ValueDecl *VD = Exp->getDecl();
  4681. if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
  4682. // We need to save the copied-in variables in nested
  4683. // blocks because it is needed at the end for some of the API generations.
  4684. // See SynthesizeBlockLiterals routine.
  4685. InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
  4686. BlockDeclRefs.push_back(Exp);
  4687. BlockByCopyDeclsPtrSet.insert(VD);
  4688. BlockByCopyDecls.push_back(VD);
  4689. }
  4690. if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
  4691. InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
  4692. BlockDeclRefs.push_back(Exp);
  4693. BlockByRefDeclsPtrSet.insert(VD);
  4694. BlockByRefDecls.push_back(VD);
  4695. }
  4696. }
  4697. // Find any imported blocks...they will need special attention.
  4698. for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
  4699. if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
  4700. InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
  4701. InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
  4702. ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
  4703. }
  4704. InnerDeclRefsCount.push_back(countOfInnerDecls);
  4705. std::string FuncName;
  4706. if (CurFunctionDef)
  4707. FuncName = CurFunctionDef->getNameAsString();
  4708. else if (CurMethodDef)
  4709. BuildUniqueMethodName(FuncName, CurMethodDef);
  4710. else if (GlobalVarDecl)
  4711. FuncName = std::string(GlobalVarDecl->getNameAsString());
  4712. bool GlobalBlockExpr =
  4713. block->getDeclContext()->getRedeclContext()->isFileContext();
  4714. if (GlobalBlockExpr && !GlobalVarDecl) {
  4715. Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
  4716. GlobalBlockExpr = false;
  4717. }
  4718. std::string BlockNumber = utostr(Blocks.size()-1);
  4719. std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
  4720. // Get a pointer to the function type so we can cast appropriately.
  4721. QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
  4722. QualType FType = Context->getPointerType(BFT);
  4723. FunctionDecl *FD;
  4724. Expr *NewRep;
  4725. // Simulate a constructor call...
  4726. std::string Tag;
  4727. if (GlobalBlockExpr)
  4728. Tag = "__global_";
  4729. else
  4730. Tag = "__";
  4731. Tag += FuncName + "_block_impl_" + BlockNumber;
  4732. FD = SynthBlockInitFunctionDecl(Tag);
  4733. DeclRefExpr *DRE = new (Context)
  4734. DeclRefExpr(*Context, FD, false, FType, VK_PRValue, SourceLocation());
  4735. SmallVector<Expr*, 4> InitExprs;
  4736. // Initialize the block function.
  4737. FD = SynthBlockInitFunctionDecl(Func);
  4738. DeclRefExpr *Arg = new (Context) DeclRefExpr(
  4739. *Context, FD, false, FD->getType(), VK_LValue, SourceLocation());
  4740. CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
  4741. CK_BitCast, Arg);
  4742. InitExprs.push_back(castExpr);
  4743. // Initialize the block descriptor.
  4744. std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
  4745. VarDecl *NewVD = VarDecl::Create(
  4746. *Context, TUDecl, SourceLocation(), SourceLocation(),
  4747. &Context->Idents.get(DescData), Context->VoidPtrTy, nullptr, SC_Static);
  4748. UnaryOperator *DescRefExpr = UnaryOperator::Create(
  4749. const_cast<ASTContext &>(*Context),
  4750. new (Context) DeclRefExpr(*Context, NewVD, false, Context->VoidPtrTy,
  4751. VK_LValue, SourceLocation()),
  4752. UO_AddrOf, Context->getPointerType(Context->VoidPtrTy), VK_PRValue,
  4753. OK_Ordinary, SourceLocation(), false, FPOptionsOverride());
  4754. InitExprs.push_back(DescRefExpr);
  4755. // Add initializers for any closure decl refs.
  4756. if (BlockDeclRefs.size()) {
  4757. Expr *Exp;
  4758. // Output all "by copy" declarations.
  4759. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
  4760. E = BlockByCopyDecls.end(); I != E; ++I) {
  4761. if (isObjCType((*I)->getType())) {
  4762. // FIXME: Conform to ABI ([[obj retain] autorelease]).
  4763. FD = SynthBlockInitFunctionDecl((*I)->getName());
  4764. Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
  4765. VK_LValue, SourceLocation());
  4766. if (HasLocalVariableExternalStorage(*I)) {
  4767. QualType QT = (*I)->getType();
  4768. QT = Context->getPointerType(QT);
  4769. Exp = UnaryOperator::Create(const_cast<ASTContext &>(*Context), Exp,
  4770. UO_AddrOf, QT, VK_PRValue, OK_Ordinary,
  4771. SourceLocation(), false,
  4772. FPOptionsOverride());
  4773. }
  4774. } else if (isTopLevelBlockPointerType((*I)->getType())) {
  4775. FD = SynthBlockInitFunctionDecl((*I)->getName());
  4776. Arg = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
  4777. VK_LValue, SourceLocation());
  4778. Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
  4779. CK_BitCast, Arg);
  4780. } else {
  4781. FD = SynthBlockInitFunctionDecl((*I)->getName());
  4782. Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
  4783. VK_LValue, SourceLocation());
  4784. if (HasLocalVariableExternalStorage(*I)) {
  4785. QualType QT = (*I)->getType();
  4786. QT = Context->getPointerType(QT);
  4787. Exp = UnaryOperator::Create(const_cast<ASTContext &>(*Context), Exp,
  4788. UO_AddrOf, QT, VK_PRValue, OK_Ordinary,
  4789. SourceLocation(), false,
  4790. FPOptionsOverride());
  4791. }
  4792. }
  4793. InitExprs.push_back(Exp);
  4794. }
  4795. // Output all "by ref" declarations.
  4796. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
  4797. E = BlockByRefDecls.end(); I != E; ++I) {
  4798. ValueDecl *ND = (*I);
  4799. std::string Name(ND->getNameAsString());
  4800. std::string RecName;
  4801. RewriteByRefString(RecName, Name, ND, true);
  4802. IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
  4803. + sizeof("struct"));
  4804. RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
  4805. SourceLocation(), SourceLocation(),
  4806. II);
  4807. assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
  4808. QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
  4809. FD = SynthBlockInitFunctionDecl((*I)->getName());
  4810. Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
  4811. VK_LValue, SourceLocation());
  4812. bool isNestedCapturedVar = false;
  4813. if (block)
  4814. for (const auto &CI : block->captures()) {
  4815. const VarDecl *variable = CI.getVariable();
  4816. if (variable == ND && CI.isNested()) {
  4817. assert (CI.isByRef() &&
  4818. "SynthBlockInitExpr - captured block variable is not byref");
  4819. isNestedCapturedVar = true;
  4820. break;
  4821. }
  4822. }
  4823. // captured nested byref variable has its address passed. Do not take
  4824. // its address again.
  4825. if (!isNestedCapturedVar)
  4826. Exp = UnaryOperator::Create(
  4827. const_cast<ASTContext &>(*Context), Exp, UO_AddrOf,
  4828. Context->getPointerType(Exp->getType()), VK_PRValue, OK_Ordinary,
  4829. SourceLocation(), false, FPOptionsOverride());
  4830. Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
  4831. InitExprs.push_back(Exp);
  4832. }
  4833. }
  4834. if (ImportedBlockDecls.size()) {
  4835. // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
  4836. int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
  4837. unsigned IntSize =
  4838. static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
  4839. Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
  4840. Context->IntTy, SourceLocation());
  4841. InitExprs.push_back(FlagExp);
  4842. }
  4843. NewRep = CallExpr::Create(*Context, DRE, InitExprs, FType, VK_LValue,
  4844. SourceLocation(), FPOptionsOverride());
  4845. if (GlobalBlockExpr) {
  4846. assert (!GlobalConstructionExp &&
  4847. "SynthBlockInitExpr - GlobalConstructionExp must be null");
  4848. GlobalConstructionExp = NewRep;
  4849. NewRep = DRE;
  4850. }
  4851. NewRep = UnaryOperator::Create(
  4852. const_cast<ASTContext &>(*Context), NewRep, UO_AddrOf,
  4853. Context->getPointerType(NewRep->getType()), VK_PRValue, OK_Ordinary,
  4854. SourceLocation(), false, FPOptionsOverride());
  4855. NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
  4856. NewRep);
  4857. // Put Paren around the call.
  4858. NewRep = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
  4859. NewRep);
  4860. BlockDeclRefs.clear();
  4861. BlockByRefDecls.clear();
  4862. BlockByRefDeclsPtrSet.clear();
  4863. BlockByCopyDecls.clear();
  4864. BlockByCopyDeclsPtrSet.clear();
  4865. ImportedBlockDecls.clear();
  4866. return NewRep;
  4867. }
  4868. bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
  4869. if (const ObjCForCollectionStmt * CS =
  4870. dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
  4871. return CS->getElement() == DS;
  4872. return false;
  4873. }
  4874. //===----------------------------------------------------------------------===//
  4875. // Function Body / Expression rewriting
  4876. //===----------------------------------------------------------------------===//
  4877. Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
  4878. if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
  4879. isa<DoStmt>(S) || isa<ForStmt>(S))
  4880. Stmts.push_back(S);
  4881. else if (isa<ObjCForCollectionStmt>(S)) {
  4882. Stmts.push_back(S);
  4883. ObjCBcLabelNo.push_back(++BcLabelCount);
  4884. }
  4885. // Pseudo-object operations and ivar references need special
  4886. // treatment because we're going to recursively rewrite them.
  4887. if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
  4888. if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
  4889. return RewritePropertyOrImplicitSetter(PseudoOp);
  4890. } else {
  4891. return RewritePropertyOrImplicitGetter(PseudoOp);
  4892. }
  4893. } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
  4894. return RewriteObjCIvarRefExpr(IvarRefExpr);
  4895. }
  4896. else if (isa<OpaqueValueExpr>(S))
  4897. S = cast<OpaqueValueExpr>(S)->getSourceExpr();
  4898. SourceRange OrigStmtRange = S->getSourceRange();
  4899. // Perform a bottom up rewrite of all children.
  4900. for (Stmt *&childStmt : S->children())
  4901. if (childStmt) {
  4902. Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
  4903. if (newStmt) {
  4904. childStmt = newStmt;
  4905. }
  4906. }
  4907. if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
  4908. SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
  4909. llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
  4910. InnerContexts.insert(BE->getBlockDecl());
  4911. ImportedLocalExternalDecls.clear();
  4912. GetInnerBlockDeclRefExprs(BE->getBody(),
  4913. InnerBlockDeclRefs, InnerContexts);
  4914. // Rewrite the block body in place.
  4915. Stmt *SaveCurrentBody = CurrentBody;
  4916. CurrentBody = BE->getBody();
  4917. PropParentMap = nullptr;
  4918. // block literal on rhs of a property-dot-sytax assignment
  4919. // must be replaced by its synthesize ast so getRewrittenText
  4920. // works as expected. In this case, what actually ends up on RHS
  4921. // is the blockTranscribed which is the helper function for the
  4922. // block literal; as in: self.c = ^() {[ace ARR];};
  4923. bool saveDisableReplaceStmt = DisableReplaceStmt;
  4924. DisableReplaceStmt = false;
  4925. RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
  4926. DisableReplaceStmt = saveDisableReplaceStmt;
  4927. CurrentBody = SaveCurrentBody;
  4928. PropParentMap = nullptr;
  4929. ImportedLocalExternalDecls.clear();
  4930. // Now we snarf the rewritten text and stash it away for later use.
  4931. std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
  4932. RewrittenBlockExprs[BE] = Str;
  4933. Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
  4934. //blockTranscribed->dump();
  4935. ReplaceStmt(S, blockTranscribed);
  4936. return blockTranscribed;
  4937. }
  4938. // Handle specific things.
  4939. if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
  4940. return RewriteAtEncode(AtEncode);
  4941. if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
  4942. return RewriteAtSelector(AtSelector);
  4943. if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
  4944. return RewriteObjCStringLiteral(AtString);
  4945. if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
  4946. return RewriteObjCBoolLiteralExpr(BoolLitExpr);
  4947. if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
  4948. return RewriteObjCBoxedExpr(BoxedExpr);
  4949. if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
  4950. return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
  4951. if (ObjCDictionaryLiteral *DictionaryLitExpr =
  4952. dyn_cast<ObjCDictionaryLiteral>(S))
  4953. return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
  4954. if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
  4955. #if 0
  4956. // Before we rewrite it, put the original message expression in a comment.
  4957. SourceLocation startLoc = MessExpr->getBeginLoc();
  4958. SourceLocation endLoc = MessExpr->getEndLoc();
  4959. const char *startBuf = SM->getCharacterData(startLoc);
  4960. const char *endBuf = SM->getCharacterData(endLoc);
  4961. std::string messString;
  4962. messString += "// ";
  4963. messString.append(startBuf, endBuf-startBuf+1);
  4964. messString += "\n";
  4965. // FIXME: Missing definition of
  4966. // InsertText(clang::SourceLocation, char const*, unsigned int).
  4967. // InsertText(startLoc, messString);
  4968. // Tried this, but it didn't work either...
  4969. // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
  4970. #endif
  4971. return RewriteMessageExpr(MessExpr);
  4972. }
  4973. if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
  4974. dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
  4975. return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
  4976. }
  4977. if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
  4978. return RewriteObjCTryStmt(StmtTry);
  4979. if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
  4980. return RewriteObjCSynchronizedStmt(StmtTry);
  4981. if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
  4982. return RewriteObjCThrowStmt(StmtThrow);
  4983. if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
  4984. return RewriteObjCProtocolExpr(ProtocolExp);
  4985. if (ObjCForCollectionStmt *StmtForCollection =
  4986. dyn_cast<ObjCForCollectionStmt>(S))
  4987. return RewriteObjCForCollectionStmt(StmtForCollection,
  4988. OrigStmtRange.getEnd());
  4989. if (BreakStmt *StmtBreakStmt =
  4990. dyn_cast<BreakStmt>(S))
  4991. return RewriteBreakStmt(StmtBreakStmt);
  4992. if (ContinueStmt *StmtContinueStmt =
  4993. dyn_cast<ContinueStmt>(S))
  4994. return RewriteContinueStmt(StmtContinueStmt);
  4995. // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
  4996. // and cast exprs.
  4997. if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
  4998. // FIXME: What we're doing here is modifying the type-specifier that
  4999. // precedes the first Decl. In the future the DeclGroup should have
  5000. // a separate type-specifier that we can rewrite.
  5001. // NOTE: We need to avoid rewriting the DeclStmt if it is within
  5002. // the context of an ObjCForCollectionStmt. For example:
  5003. // NSArray *someArray;
  5004. // for (id <FooProtocol> index in someArray) ;
  5005. // This is because RewriteObjCForCollectionStmt() does textual rewriting
  5006. // and it depends on the original text locations/positions.
  5007. if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
  5008. RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
  5009. // Blocks rewrite rules.
  5010. for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
  5011. DI != DE; ++DI) {
  5012. Decl *SD = *DI;
  5013. if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
  5014. if (isTopLevelBlockPointerType(ND->getType()))
  5015. RewriteBlockPointerDecl(ND);
  5016. else if (ND->getType()->isFunctionPointerType())
  5017. CheckFunctionPointerDecl(ND->getType(), ND);
  5018. if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
  5019. if (VD->hasAttr<BlocksAttr>()) {
  5020. static unsigned uniqueByrefDeclCount = 0;
  5021. assert(!BlockByRefDeclNo.count(ND) &&
  5022. "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
  5023. BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
  5024. RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
  5025. }
  5026. else
  5027. RewriteTypeOfDecl(VD);
  5028. }
  5029. }
  5030. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
  5031. if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
  5032. RewriteBlockPointerDecl(TD);
  5033. else if (TD->getUnderlyingType()->isFunctionPointerType())
  5034. CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
  5035. }
  5036. }
  5037. }
  5038. if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
  5039. RewriteObjCQualifiedInterfaceTypes(CE);
  5040. if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
  5041. isa<DoStmt>(S) || isa<ForStmt>(S)) {
  5042. assert(!Stmts.empty() && "Statement stack is empty");
  5043. assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
  5044. isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
  5045. && "Statement stack mismatch");
  5046. Stmts.pop_back();
  5047. }
  5048. // Handle blocks rewriting.
  5049. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
  5050. ValueDecl *VD = DRE->getDecl();
  5051. if (VD->hasAttr<BlocksAttr>())
  5052. return RewriteBlockDeclRefExpr(DRE);
  5053. if (HasLocalVariableExternalStorage(VD))
  5054. return RewriteLocalVariableExternalStorage(DRE);
  5055. }
  5056. if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
  5057. if (CE->getCallee()->getType()->isBlockPointerType()) {
  5058. Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
  5059. ReplaceStmt(S, BlockCall);
  5060. return BlockCall;
  5061. }
  5062. }
  5063. if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
  5064. RewriteCastExpr(CE);
  5065. }
  5066. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
  5067. RewriteImplicitCastObjCExpr(ICE);
  5068. }
  5069. #if 0
  5070. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
  5071. CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
  5072. ICE->getSubExpr(),
  5073. SourceLocation());
  5074. // Get the new text.
  5075. std::string SStr;
  5076. llvm::raw_string_ostream Buf(SStr);
  5077. Replacement->printPretty(Buf);
  5078. const std::string &Str = Buf.str();
  5079. printf("CAST = %s\n", &Str[0]);
  5080. InsertText(ICE->getSubExpr()->getBeginLoc(), Str);
  5081. delete S;
  5082. return Replacement;
  5083. }
  5084. #endif
  5085. // Return this stmt unmodified.
  5086. return S;
  5087. }
  5088. void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
  5089. for (auto *FD : RD->fields()) {
  5090. if (isTopLevelBlockPointerType(FD->getType()))
  5091. RewriteBlockPointerDecl(FD);
  5092. if (FD->getType()->isObjCQualifiedIdType() ||
  5093. FD->getType()->isObjCQualifiedInterfaceType())
  5094. RewriteObjCQualifiedInterfaceTypes(FD);
  5095. }
  5096. }
  5097. /// HandleDeclInMainFile - This is called for each top-level decl defined in the
  5098. /// main file of the input.
  5099. void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
  5100. switch (D->getKind()) {
  5101. case Decl::Function: {
  5102. FunctionDecl *FD = cast<FunctionDecl>(D);
  5103. if (FD->isOverloadedOperator())
  5104. return;
  5105. // Since function prototypes don't have ParmDecl's, we check the function
  5106. // prototype. This enables us to rewrite function declarations and
  5107. // definitions using the same code.
  5108. RewriteBlocksInFunctionProtoType(FD->getType(), FD);
  5109. if (!FD->isThisDeclarationADefinition())
  5110. break;
  5111. // FIXME: If this should support Obj-C++, support CXXTryStmt
  5112. if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
  5113. CurFunctionDef = FD;
  5114. CurrentBody = Body;
  5115. Body =
  5116. cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
  5117. FD->setBody(Body);
  5118. CurrentBody = nullptr;
  5119. if (PropParentMap) {
  5120. delete PropParentMap;
  5121. PropParentMap = nullptr;
  5122. }
  5123. // This synthesizes and inserts the block "impl" struct, invoke function,
  5124. // and any copy/dispose helper functions.
  5125. InsertBlockLiteralsWithinFunction(FD);
  5126. RewriteLineDirective(D);
  5127. CurFunctionDef = nullptr;
  5128. }
  5129. break;
  5130. }
  5131. case Decl::ObjCMethod: {
  5132. ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
  5133. if (CompoundStmt *Body = MD->getCompoundBody()) {
  5134. CurMethodDef = MD;
  5135. CurrentBody = Body;
  5136. Body =
  5137. cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
  5138. MD->setBody(Body);
  5139. CurrentBody = nullptr;
  5140. if (PropParentMap) {
  5141. delete PropParentMap;
  5142. PropParentMap = nullptr;
  5143. }
  5144. InsertBlockLiteralsWithinMethod(MD);
  5145. RewriteLineDirective(D);
  5146. CurMethodDef = nullptr;
  5147. }
  5148. break;
  5149. }
  5150. case Decl::ObjCImplementation: {
  5151. ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
  5152. ClassImplementation.push_back(CI);
  5153. break;
  5154. }
  5155. case Decl::ObjCCategoryImpl: {
  5156. ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
  5157. CategoryImplementation.push_back(CI);
  5158. break;
  5159. }
  5160. case Decl::Var: {
  5161. VarDecl *VD = cast<VarDecl>(D);
  5162. RewriteObjCQualifiedInterfaceTypes(VD);
  5163. if (isTopLevelBlockPointerType(VD->getType()))
  5164. RewriteBlockPointerDecl(VD);
  5165. else if (VD->getType()->isFunctionPointerType()) {
  5166. CheckFunctionPointerDecl(VD->getType(), VD);
  5167. if (VD->getInit()) {
  5168. if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
  5169. RewriteCastExpr(CE);
  5170. }
  5171. }
  5172. } else if (VD->getType()->isRecordType()) {
  5173. RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl();
  5174. if (RD->isCompleteDefinition())
  5175. RewriteRecordBody(RD);
  5176. }
  5177. if (VD->getInit()) {
  5178. GlobalVarDecl = VD;
  5179. CurrentBody = VD->getInit();
  5180. RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
  5181. CurrentBody = nullptr;
  5182. if (PropParentMap) {
  5183. delete PropParentMap;
  5184. PropParentMap = nullptr;
  5185. }
  5186. SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
  5187. GlobalVarDecl = nullptr;
  5188. // This is needed for blocks.
  5189. if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
  5190. RewriteCastExpr(CE);
  5191. }
  5192. }
  5193. break;
  5194. }
  5195. case Decl::TypeAlias:
  5196. case Decl::Typedef: {
  5197. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
  5198. if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
  5199. RewriteBlockPointerDecl(TD);
  5200. else if (TD->getUnderlyingType()->isFunctionPointerType())
  5201. CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
  5202. else
  5203. RewriteObjCQualifiedInterfaceTypes(TD);
  5204. }
  5205. break;
  5206. }
  5207. case Decl::CXXRecord:
  5208. case Decl::Record: {
  5209. RecordDecl *RD = cast<RecordDecl>(D);
  5210. if (RD->isCompleteDefinition())
  5211. RewriteRecordBody(RD);
  5212. break;
  5213. }
  5214. default:
  5215. break;
  5216. }
  5217. // Nothing yet.
  5218. }
  5219. /// Write_ProtocolExprReferencedMetadata - This routine writer out the
  5220. /// protocol reference symbols in the for of:
  5221. /// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
  5222. static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
  5223. ObjCProtocolDecl *PDecl,
  5224. std::string &Result) {
  5225. // Also output .objc_protorefs$B section and its meta-data.
  5226. if (Context->getLangOpts().MicrosoftExt)
  5227. Result += "static ";
  5228. Result += "struct _protocol_t *";
  5229. Result += "_OBJC_PROTOCOL_REFERENCE_$_";
  5230. Result += PDecl->getNameAsString();
  5231. Result += " = &";
  5232. Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
  5233. Result += ";\n";
  5234. }
  5235. void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
  5236. if (Diags.hasErrorOccurred())
  5237. return;
  5238. RewriteInclude();
  5239. for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
  5240. // translation of function bodies were postponed until all class and
  5241. // their extensions and implementations are seen. This is because, we
  5242. // cannot build grouping structs for bitfields until they are all seen.
  5243. FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
  5244. HandleTopLevelSingleDecl(FDecl);
  5245. }
  5246. // Here's a great place to add any extra declarations that may be needed.
  5247. // Write out meta data for each @protocol(<expr>).
  5248. for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
  5249. RewriteObjCProtocolMetaData(ProtDecl, Preamble);
  5250. Write_ProtocolExprReferencedMetadata(Context, ProtDecl, Preamble);
  5251. }
  5252. InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
  5253. if (ClassImplementation.size() || CategoryImplementation.size())
  5254. RewriteImplementations();
  5255. for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
  5256. ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
  5257. // Write struct declaration for the class matching its ivar declarations.
  5258. // Note that for modern abi, this is postponed until the end of TU
  5259. // because class extensions and the implementation might declare their own
  5260. // private ivars.
  5261. RewriteInterfaceDecl(CDecl);
  5262. }
  5263. // Get the buffer corresponding to MainFileID. If we haven't changed it, then
  5264. // we are done.
  5265. if (const RewriteBuffer *RewriteBuf =
  5266. Rewrite.getRewriteBufferFor(MainFileID)) {
  5267. //printf("Changed:\n");
  5268. *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
  5269. } else {
  5270. llvm::errs() << "No changes\n";
  5271. }
  5272. if (ClassImplementation.size() || CategoryImplementation.size() ||
  5273. ProtocolExprDecls.size()) {
  5274. // Rewrite Objective-c meta data*
  5275. std::string ResultStr;
  5276. RewriteMetaDataIntoBuffer(ResultStr);
  5277. // Emit metadata.
  5278. *OutFile << ResultStr;
  5279. }
  5280. // Emit ImageInfo;
  5281. {
  5282. std::string ResultStr;
  5283. WriteImageInfo(ResultStr);
  5284. *OutFile << ResultStr;
  5285. }
  5286. OutFile->flush();
  5287. }
  5288. void RewriteModernObjC::Initialize(ASTContext &context) {
  5289. InitializeCommon(context);
  5290. Preamble += "#ifndef __OBJC2__\n";
  5291. Preamble += "#define __OBJC2__\n";
  5292. Preamble += "#endif\n";
  5293. // declaring objc_selector outside the parameter list removes a silly
  5294. // scope related warning...
  5295. if (IsHeader)
  5296. Preamble = "#pragma once\n";
  5297. Preamble += "struct objc_selector; struct objc_class;\n";
  5298. Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
  5299. Preamble += "\n\tstruct objc_object *superClass; ";
  5300. // Add a constructor for creating temporary objects.
  5301. Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
  5302. Preamble += ": object(o), superClass(s) {} ";
  5303. Preamble += "\n};\n";
  5304. if (LangOpts.MicrosoftExt) {
  5305. // Define all sections using syntax that makes sense.
  5306. // These are currently generated.
  5307. Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
  5308. Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
  5309. Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
  5310. Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
  5311. Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
  5312. // These are generated but not necessary for functionality.
  5313. Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
  5314. Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
  5315. Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
  5316. Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
  5317. // These need be generated for performance. Currently they are not,
  5318. // using API calls instead.
  5319. Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
  5320. Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
  5321. Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
  5322. }
  5323. Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
  5324. Preamble += "typedef struct objc_object Protocol;\n";
  5325. Preamble += "#define _REWRITER_typedef_Protocol\n";
  5326. Preamble += "#endif\n";
  5327. if (LangOpts.MicrosoftExt) {
  5328. Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
  5329. Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
  5330. }
  5331. else
  5332. Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
  5333. Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
  5334. Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
  5335. Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
  5336. Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
  5337. Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
  5338. Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
  5339. Preamble += "(const char *);\n";
  5340. Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
  5341. Preamble += "(struct objc_class *);\n";
  5342. Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
  5343. Preamble += "(const char *);\n";
  5344. Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
  5345. // @synchronized hooks.
  5346. Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
  5347. Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
  5348. Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
  5349. Preamble += "#ifdef _WIN64\n";
  5350. Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
  5351. Preamble += "#else\n";
  5352. Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
  5353. Preamble += "#endif\n";
  5354. Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
  5355. Preamble += "struct __objcFastEnumerationState {\n\t";
  5356. Preamble += "unsigned long state;\n\t";
  5357. Preamble += "void **itemsPtr;\n\t";
  5358. Preamble += "unsigned long *mutationsPtr;\n\t";
  5359. Preamble += "unsigned long extra[5];\n};\n";
  5360. Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
  5361. Preamble += "#define __FASTENUMERATIONSTATE\n";
  5362. Preamble += "#endif\n";
  5363. Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
  5364. Preamble += "struct __NSConstantStringImpl {\n";
  5365. Preamble += " int *isa;\n";
  5366. Preamble += " int flags;\n";
  5367. Preamble += " char *str;\n";
  5368. Preamble += "#if _WIN64\n";
  5369. Preamble += " long long length;\n";
  5370. Preamble += "#else\n";
  5371. Preamble += " long length;\n";
  5372. Preamble += "#endif\n";
  5373. Preamble += "};\n";
  5374. Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
  5375. Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
  5376. Preamble += "#else\n";
  5377. Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
  5378. Preamble += "#endif\n";
  5379. Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
  5380. Preamble += "#endif\n";
  5381. // Blocks preamble.
  5382. Preamble += "#ifndef BLOCK_IMPL\n";
  5383. Preamble += "#define BLOCK_IMPL\n";
  5384. Preamble += "struct __block_impl {\n";
  5385. Preamble += " void *isa;\n";
  5386. Preamble += " int Flags;\n";
  5387. Preamble += " int Reserved;\n";
  5388. Preamble += " void *FuncPtr;\n";
  5389. Preamble += "};\n";
  5390. Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
  5391. Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
  5392. Preamble += "extern \"C\" __declspec(dllexport) "
  5393. "void _Block_object_assign(void *, const void *, const int);\n";
  5394. Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
  5395. Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
  5396. Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
  5397. Preamble += "#else\n";
  5398. Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
  5399. Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
  5400. Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
  5401. Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
  5402. Preamble += "#endif\n";
  5403. Preamble += "#endif\n";
  5404. if (LangOpts.MicrosoftExt) {
  5405. Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
  5406. Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
  5407. Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
  5408. Preamble += "#define __attribute__(X)\n";
  5409. Preamble += "#endif\n";
  5410. Preamble += "#ifndef __weak\n";
  5411. Preamble += "#define __weak\n";
  5412. Preamble += "#endif\n";
  5413. Preamble += "#ifndef __block\n";
  5414. Preamble += "#define __block\n";
  5415. Preamble += "#endif\n";
  5416. }
  5417. else {
  5418. Preamble += "#define __block\n";
  5419. Preamble += "#define __weak\n";
  5420. }
  5421. // Declarations required for modern objective-c array and dictionary literals.
  5422. Preamble += "\n#include <stdarg.h>\n";
  5423. Preamble += "struct __NSContainer_literal {\n";
  5424. Preamble += " void * *arr;\n";
  5425. Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
  5426. Preamble += "\tva_list marker;\n";
  5427. Preamble += "\tva_start(marker, count);\n";
  5428. Preamble += "\tarr = new void *[count];\n";
  5429. Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
  5430. Preamble += "\t arr[i] = va_arg(marker, void *);\n";
  5431. Preamble += "\tva_end( marker );\n";
  5432. Preamble += " };\n";
  5433. Preamble += " ~__NSContainer_literal() {\n";
  5434. Preamble += "\tdelete[] arr;\n";
  5435. Preamble += " }\n";
  5436. Preamble += "};\n";
  5437. // Declaration required for implementation of @autoreleasepool statement.
  5438. Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
  5439. Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
  5440. Preamble += "struct __AtAutoreleasePool {\n";
  5441. Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
  5442. Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
  5443. Preamble += " void * atautoreleasepoolobj;\n";
  5444. Preamble += "};\n";
  5445. // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
  5446. // as this avoids warning in any 64bit/32bit compilation model.
  5447. Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
  5448. }
  5449. /// RewriteIvarOffsetComputation - This routine synthesizes computation of
  5450. /// ivar offset.
  5451. void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
  5452. std::string &Result) {
  5453. Result += "__OFFSETOFIVAR__(struct ";
  5454. Result += ivar->getContainingInterface()->getNameAsString();
  5455. if (LangOpts.MicrosoftExt)
  5456. Result += "_IMPL";
  5457. Result += ", ";
  5458. if (ivar->isBitField())
  5459. ObjCIvarBitfieldGroupDecl(ivar, Result);
  5460. else
  5461. Result += ivar->getNameAsString();
  5462. Result += ")";
  5463. }
  5464. /// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
  5465. /// struct _prop_t {
  5466. /// const char *name;
  5467. /// char *attributes;
  5468. /// }
  5469. /// struct _prop_list_t {
  5470. /// uint32_t entsize; // sizeof(struct _prop_t)
  5471. /// uint32_t count_of_properties;
  5472. /// struct _prop_t prop_list[count_of_properties];
  5473. /// }
  5474. /// struct _protocol_t;
  5475. /// struct _protocol_list_t {
  5476. /// long protocol_count; // Note, this is 32/64 bit
  5477. /// struct _protocol_t * protocol_list[protocol_count];
  5478. /// }
  5479. /// struct _objc_method {
  5480. /// SEL _cmd;
  5481. /// const char *method_type;
  5482. /// char *_imp;
  5483. /// }
  5484. /// struct _method_list_t {
  5485. /// uint32_t entsize; // sizeof(struct _objc_method)
  5486. /// uint32_t method_count;
  5487. /// struct _objc_method method_list[method_count];
  5488. /// }
  5489. /// struct _protocol_t {
  5490. /// id isa; // NULL
  5491. /// const char *protocol_name;
  5492. /// const struct _protocol_list_t * protocol_list; // super protocols
  5493. /// const struct method_list_t *instance_methods;
  5494. /// const struct method_list_t *class_methods;
  5495. /// const struct method_list_t *optionalInstanceMethods;
  5496. /// const struct method_list_t *optionalClassMethods;
  5497. /// const struct _prop_list_t * properties;
  5498. /// const uint32_t size; // sizeof(struct _protocol_t)
  5499. /// const uint32_t flags; // = 0
  5500. /// const char ** extendedMethodTypes;
  5501. /// }
  5502. /// struct _ivar_t {
  5503. /// unsigned long int *offset; // pointer to ivar offset location
  5504. /// const char *name;
  5505. /// const char *type;
  5506. /// uint32_t alignment;
  5507. /// uint32_t size;
  5508. /// }
  5509. /// struct _ivar_list_t {
  5510. /// uint32 entsize; // sizeof(struct _ivar_t)
  5511. /// uint32 count;
  5512. /// struct _ivar_t list[count];
  5513. /// }
  5514. /// struct _class_ro_t {
  5515. /// uint32_t flags;
  5516. /// uint32_t instanceStart;
  5517. /// uint32_t instanceSize;
  5518. /// uint32_t reserved; // only when building for 64bit targets
  5519. /// const uint8_t *ivarLayout;
  5520. /// const char *name;
  5521. /// const struct _method_list_t *baseMethods;
  5522. /// const struct _protocol_list_t *baseProtocols;
  5523. /// const struct _ivar_list_t *ivars;
  5524. /// const uint8_t *weakIvarLayout;
  5525. /// const struct _prop_list_t *properties;
  5526. /// }
  5527. /// struct _class_t {
  5528. /// struct _class_t *isa;
  5529. /// struct _class_t *superclass;
  5530. /// void *cache;
  5531. /// IMP *vtable;
  5532. /// struct _class_ro_t *ro;
  5533. /// }
  5534. /// struct _category_t {
  5535. /// const char *name;
  5536. /// struct _class_t *cls;
  5537. /// const struct _method_list_t *instance_methods;
  5538. /// const struct _method_list_t *class_methods;
  5539. /// const struct _protocol_list_t *protocols;
  5540. /// const struct _prop_list_t *properties;
  5541. /// }
  5542. /// MessageRefTy - LLVM for:
  5543. /// struct _message_ref_t {
  5544. /// IMP messenger;
  5545. /// SEL name;
  5546. /// };
  5547. /// SuperMessageRefTy - LLVM for:
  5548. /// struct _super_message_ref_t {
  5549. /// SUPER_IMP messenger;
  5550. /// SEL name;
  5551. /// };
  5552. static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
  5553. static bool meta_data_declared = false;
  5554. if (meta_data_declared)
  5555. return;
  5556. Result += "\nstruct _prop_t {\n";
  5557. Result += "\tconst char *name;\n";
  5558. Result += "\tconst char *attributes;\n";
  5559. Result += "};\n";
  5560. Result += "\nstruct _protocol_t;\n";
  5561. Result += "\nstruct _objc_method {\n";
  5562. Result += "\tstruct objc_selector * _cmd;\n";
  5563. Result += "\tconst char *method_type;\n";
  5564. Result += "\tvoid *_imp;\n";
  5565. Result += "};\n";
  5566. Result += "\nstruct _protocol_t {\n";
  5567. Result += "\tvoid * isa; // NULL\n";
  5568. Result += "\tconst char *protocol_name;\n";
  5569. Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
  5570. Result += "\tconst struct method_list_t *instance_methods;\n";
  5571. Result += "\tconst struct method_list_t *class_methods;\n";
  5572. Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
  5573. Result += "\tconst struct method_list_t *optionalClassMethods;\n";
  5574. Result += "\tconst struct _prop_list_t * properties;\n";
  5575. Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
  5576. Result += "\tconst unsigned int flags; // = 0\n";
  5577. Result += "\tconst char ** extendedMethodTypes;\n";
  5578. Result += "};\n";
  5579. Result += "\nstruct _ivar_t {\n";
  5580. Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
  5581. Result += "\tconst char *name;\n";
  5582. Result += "\tconst char *type;\n";
  5583. Result += "\tunsigned int alignment;\n";
  5584. Result += "\tunsigned int size;\n";
  5585. Result += "};\n";
  5586. Result += "\nstruct _class_ro_t {\n";
  5587. Result += "\tunsigned int flags;\n";
  5588. Result += "\tunsigned int instanceStart;\n";
  5589. Result += "\tunsigned int instanceSize;\n";
  5590. const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
  5591. if (Triple.getArch() == llvm::Triple::x86_64)
  5592. Result += "\tunsigned int reserved;\n";
  5593. Result += "\tconst unsigned char *ivarLayout;\n";
  5594. Result += "\tconst char *name;\n";
  5595. Result += "\tconst struct _method_list_t *baseMethods;\n";
  5596. Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
  5597. Result += "\tconst struct _ivar_list_t *ivars;\n";
  5598. Result += "\tconst unsigned char *weakIvarLayout;\n";
  5599. Result += "\tconst struct _prop_list_t *properties;\n";
  5600. Result += "};\n";
  5601. Result += "\nstruct _class_t {\n";
  5602. Result += "\tstruct _class_t *isa;\n";
  5603. Result += "\tstruct _class_t *superclass;\n";
  5604. Result += "\tvoid *cache;\n";
  5605. Result += "\tvoid *vtable;\n";
  5606. Result += "\tstruct _class_ro_t *ro;\n";
  5607. Result += "};\n";
  5608. Result += "\nstruct _category_t {\n";
  5609. Result += "\tconst char *name;\n";
  5610. Result += "\tstruct _class_t *cls;\n";
  5611. Result += "\tconst struct _method_list_t *instance_methods;\n";
  5612. Result += "\tconst struct _method_list_t *class_methods;\n";
  5613. Result += "\tconst struct _protocol_list_t *protocols;\n";
  5614. Result += "\tconst struct _prop_list_t *properties;\n";
  5615. Result += "};\n";
  5616. Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
  5617. Result += "#pragma warning(disable:4273)\n";
  5618. meta_data_declared = true;
  5619. }
  5620. static void Write_protocol_list_t_TypeDecl(std::string &Result,
  5621. long super_protocol_count) {
  5622. Result += "struct /*_protocol_list_t*/"; Result += " {\n";
  5623. Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
  5624. Result += "\tstruct _protocol_t *super_protocols[";
  5625. Result += utostr(super_protocol_count); Result += "];\n";
  5626. Result += "}";
  5627. }
  5628. static void Write_method_list_t_TypeDecl(std::string &Result,
  5629. unsigned int method_count) {
  5630. Result += "struct /*_method_list_t*/"; Result += " {\n";
  5631. Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
  5632. Result += "\tunsigned int method_count;\n";
  5633. Result += "\tstruct _objc_method method_list[";
  5634. Result += utostr(method_count); Result += "];\n";
  5635. Result += "}";
  5636. }
  5637. static void Write__prop_list_t_TypeDecl(std::string &Result,
  5638. unsigned int property_count) {
  5639. Result += "struct /*_prop_list_t*/"; Result += " {\n";
  5640. Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
  5641. Result += "\tunsigned int count_of_properties;\n";
  5642. Result += "\tstruct _prop_t prop_list[";
  5643. Result += utostr(property_count); Result += "];\n";
  5644. Result += "}";
  5645. }
  5646. static void Write__ivar_list_t_TypeDecl(std::string &Result,
  5647. unsigned int ivar_count) {
  5648. Result += "struct /*_ivar_list_t*/"; Result += " {\n";
  5649. Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
  5650. Result += "\tunsigned int count;\n";
  5651. Result += "\tstruct _ivar_t ivar_list[";
  5652. Result += utostr(ivar_count); Result += "];\n";
  5653. Result += "}";
  5654. }
  5655. static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
  5656. ArrayRef<ObjCProtocolDecl *> SuperProtocols,
  5657. StringRef VarName,
  5658. StringRef ProtocolName) {
  5659. if (SuperProtocols.size() > 0) {
  5660. Result += "\nstatic ";
  5661. Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
  5662. Result += " "; Result += VarName;
  5663. Result += ProtocolName;
  5664. Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
  5665. Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
  5666. for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
  5667. ObjCProtocolDecl *SuperPD = SuperProtocols[i];
  5668. Result += "\t&"; Result += "_OBJC_PROTOCOL_";
  5669. Result += SuperPD->getNameAsString();
  5670. if (i == e-1)
  5671. Result += "\n};\n";
  5672. else
  5673. Result += ",\n";
  5674. }
  5675. }
  5676. }
  5677. static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
  5678. ASTContext *Context, std::string &Result,
  5679. ArrayRef<ObjCMethodDecl *> Methods,
  5680. StringRef VarName,
  5681. StringRef TopLevelDeclName,
  5682. bool MethodImpl) {
  5683. if (Methods.size() > 0) {
  5684. Result += "\nstatic ";
  5685. Write_method_list_t_TypeDecl(Result, Methods.size());
  5686. Result += " "; Result += VarName;
  5687. Result += TopLevelDeclName;
  5688. Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
  5689. Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
  5690. Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
  5691. for (unsigned i = 0, e = Methods.size(); i < e; i++) {
  5692. ObjCMethodDecl *MD = Methods[i];
  5693. if (i == 0)
  5694. Result += "\t{{(struct objc_selector *)\"";
  5695. else
  5696. Result += "\t{(struct objc_selector *)\"";
  5697. Result += (MD)->getSelector().getAsString(); Result += "\"";
  5698. Result += ", ";
  5699. std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(MD);
  5700. Result += "\""; Result += MethodTypeString; Result += "\"";
  5701. Result += ", ";
  5702. if (!MethodImpl)
  5703. Result += "0";
  5704. else {
  5705. Result += "(void *)";
  5706. Result += RewriteObj.MethodInternalNames[MD];
  5707. }
  5708. if (i == e-1)
  5709. Result += "}}\n";
  5710. else
  5711. Result += "},\n";
  5712. }
  5713. Result += "};\n";
  5714. }
  5715. }
  5716. static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
  5717. ASTContext *Context, std::string &Result,
  5718. ArrayRef<ObjCPropertyDecl *> Properties,
  5719. const Decl *Container,
  5720. StringRef VarName,
  5721. StringRef ProtocolName) {
  5722. if (Properties.size() > 0) {
  5723. Result += "\nstatic ";
  5724. Write__prop_list_t_TypeDecl(Result, Properties.size());
  5725. Result += " "; Result += VarName;
  5726. Result += ProtocolName;
  5727. Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
  5728. Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
  5729. Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
  5730. for (unsigned i = 0, e = Properties.size(); i < e; i++) {
  5731. ObjCPropertyDecl *PropDecl = Properties[i];
  5732. if (i == 0)
  5733. Result += "\t{{\"";
  5734. else
  5735. Result += "\t{\"";
  5736. Result += PropDecl->getName(); Result += "\",";
  5737. std::string PropertyTypeString =
  5738. Context->getObjCEncodingForPropertyDecl(PropDecl, Container);
  5739. std::string QuotePropertyTypeString;
  5740. RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
  5741. Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
  5742. if (i == e-1)
  5743. Result += "}}\n";
  5744. else
  5745. Result += "},\n";
  5746. }
  5747. Result += "};\n";
  5748. }
  5749. }
  5750. // Metadata flags
  5751. enum MetaDataDlags {
  5752. CLS = 0x0,
  5753. CLS_META = 0x1,
  5754. CLS_ROOT = 0x2,
  5755. OBJC2_CLS_HIDDEN = 0x10,
  5756. CLS_EXCEPTION = 0x20,
  5757. /// (Obsolete) ARC-specific: this class has a .release_ivars method
  5758. CLS_HAS_IVAR_RELEASER = 0x40,
  5759. /// class was compiled with -fobjc-arr
  5760. CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
  5761. };
  5762. static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
  5763. unsigned int flags,
  5764. const std::string &InstanceStart,
  5765. const std::string &InstanceSize,
  5766. ArrayRef<ObjCMethodDecl *>baseMethods,
  5767. ArrayRef<ObjCProtocolDecl *>baseProtocols,
  5768. ArrayRef<ObjCIvarDecl *>ivars,
  5769. ArrayRef<ObjCPropertyDecl *>Properties,
  5770. StringRef VarName,
  5771. StringRef ClassName) {
  5772. Result += "\nstatic struct _class_ro_t ";
  5773. Result += VarName; Result += ClassName;
  5774. Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
  5775. Result += "\t";
  5776. Result += llvm::utostr(flags); Result += ", ";
  5777. Result += InstanceStart; Result += ", ";
  5778. Result += InstanceSize; Result += ", \n";
  5779. Result += "\t";
  5780. const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
  5781. if (Triple.getArch() == llvm::Triple::x86_64)
  5782. // uint32_t const reserved; // only when building for 64bit targets
  5783. Result += "(unsigned int)0, \n\t";
  5784. // const uint8_t * const ivarLayout;
  5785. Result += "0, \n\t";
  5786. Result += "\""; Result += ClassName; Result += "\",\n\t";
  5787. bool metaclass = ((flags & CLS_META) != 0);
  5788. if (baseMethods.size() > 0) {
  5789. Result += "(const struct _method_list_t *)&";
  5790. if (metaclass)
  5791. Result += "_OBJC_$_CLASS_METHODS_";
  5792. else
  5793. Result += "_OBJC_$_INSTANCE_METHODS_";
  5794. Result += ClassName;
  5795. Result += ",\n\t";
  5796. }
  5797. else
  5798. Result += "0, \n\t";
  5799. if (!metaclass && baseProtocols.size() > 0) {
  5800. Result += "(const struct _objc_protocol_list *)&";
  5801. Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
  5802. Result += ",\n\t";
  5803. }
  5804. else
  5805. Result += "0, \n\t";
  5806. if (!metaclass && ivars.size() > 0) {
  5807. Result += "(const struct _ivar_list_t *)&";
  5808. Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
  5809. Result += ",\n\t";
  5810. }
  5811. else
  5812. Result += "0, \n\t";
  5813. // weakIvarLayout
  5814. Result += "0, \n\t";
  5815. if (!metaclass && Properties.size() > 0) {
  5816. Result += "(const struct _prop_list_t *)&";
  5817. Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
  5818. Result += ",\n";
  5819. }
  5820. else
  5821. Result += "0, \n";
  5822. Result += "};\n";
  5823. }
  5824. static void Write_class_t(ASTContext *Context, std::string &Result,
  5825. StringRef VarName,
  5826. const ObjCInterfaceDecl *CDecl, bool metaclass) {
  5827. bool rootClass = (!CDecl->getSuperClass());
  5828. const ObjCInterfaceDecl *RootClass = CDecl;
  5829. if (!rootClass) {
  5830. // Find the Root class
  5831. RootClass = CDecl->getSuperClass();
  5832. while (RootClass->getSuperClass()) {
  5833. RootClass = RootClass->getSuperClass();
  5834. }
  5835. }
  5836. if (metaclass && rootClass) {
  5837. // Need to handle a case of use of forward declaration.
  5838. Result += "\n";
  5839. Result += "extern \"C\" ";
  5840. if (CDecl->getImplementation())
  5841. Result += "__declspec(dllexport) ";
  5842. else
  5843. Result += "__declspec(dllimport) ";
  5844. Result += "struct _class_t OBJC_CLASS_$_";
  5845. Result += CDecl->getNameAsString();
  5846. Result += ";\n";
  5847. }
  5848. // Also, for possibility of 'super' metadata class not having been defined yet.
  5849. if (!rootClass) {
  5850. ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
  5851. Result += "\n";
  5852. Result += "extern \"C\" ";
  5853. if (SuperClass->getImplementation())
  5854. Result += "__declspec(dllexport) ";
  5855. else
  5856. Result += "__declspec(dllimport) ";
  5857. Result += "struct _class_t ";
  5858. Result += VarName;
  5859. Result += SuperClass->getNameAsString();
  5860. Result += ";\n";
  5861. if (metaclass && RootClass != SuperClass) {
  5862. Result += "extern \"C\" ";
  5863. if (RootClass->getImplementation())
  5864. Result += "__declspec(dllexport) ";
  5865. else
  5866. Result += "__declspec(dllimport) ";
  5867. Result += "struct _class_t ";
  5868. Result += VarName;
  5869. Result += RootClass->getNameAsString();
  5870. Result += ";\n";
  5871. }
  5872. }
  5873. Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
  5874. Result += VarName; Result += CDecl->getNameAsString();
  5875. Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
  5876. Result += "\t";
  5877. if (metaclass) {
  5878. if (!rootClass) {
  5879. Result += "0, // &"; Result += VarName;
  5880. Result += RootClass->getNameAsString();
  5881. Result += ",\n\t";
  5882. Result += "0, // &"; Result += VarName;
  5883. Result += CDecl->getSuperClass()->getNameAsString();
  5884. Result += ",\n\t";
  5885. }
  5886. else {
  5887. Result += "0, // &"; Result += VarName;
  5888. Result += CDecl->getNameAsString();
  5889. Result += ",\n\t";
  5890. Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
  5891. Result += ",\n\t";
  5892. }
  5893. }
  5894. else {
  5895. Result += "0, // &OBJC_METACLASS_$_";
  5896. Result += CDecl->getNameAsString();
  5897. Result += ",\n\t";
  5898. if (!rootClass) {
  5899. Result += "0, // &"; Result += VarName;
  5900. Result += CDecl->getSuperClass()->getNameAsString();
  5901. Result += ",\n\t";
  5902. }
  5903. else
  5904. Result += "0,\n\t";
  5905. }
  5906. Result += "0, // (void *)&_objc_empty_cache,\n\t";
  5907. Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
  5908. if (metaclass)
  5909. Result += "&_OBJC_METACLASS_RO_$_";
  5910. else
  5911. Result += "&_OBJC_CLASS_RO_$_";
  5912. Result += CDecl->getNameAsString();
  5913. Result += ",\n};\n";
  5914. // Add static function to initialize some of the meta-data fields.
  5915. // avoid doing it twice.
  5916. if (metaclass)
  5917. return;
  5918. const ObjCInterfaceDecl *SuperClass =
  5919. rootClass ? CDecl : CDecl->getSuperClass();
  5920. Result += "static void OBJC_CLASS_SETUP_$_";
  5921. Result += CDecl->getNameAsString();
  5922. Result += "(void ) {\n";
  5923. Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
  5924. Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
  5925. Result += RootClass->getNameAsString(); Result += ";\n";
  5926. Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
  5927. Result += ".superclass = ";
  5928. if (rootClass)
  5929. Result += "&OBJC_CLASS_$_";
  5930. else
  5931. Result += "&OBJC_METACLASS_$_";
  5932. Result += SuperClass->getNameAsString(); Result += ";\n";
  5933. Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
  5934. Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
  5935. Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
  5936. Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
  5937. Result += CDecl->getNameAsString(); Result += ";\n";
  5938. if (!rootClass) {
  5939. Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
  5940. Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
  5941. Result += SuperClass->getNameAsString(); Result += ";\n";
  5942. }
  5943. Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
  5944. Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
  5945. Result += "}\n";
  5946. }
  5947. static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
  5948. std::string &Result,
  5949. ObjCCategoryDecl *CatDecl,
  5950. ObjCInterfaceDecl *ClassDecl,
  5951. ArrayRef<ObjCMethodDecl *> InstanceMethods,
  5952. ArrayRef<ObjCMethodDecl *> ClassMethods,
  5953. ArrayRef<ObjCProtocolDecl *> RefedProtocols,
  5954. ArrayRef<ObjCPropertyDecl *> ClassProperties) {
  5955. StringRef CatName = CatDecl->getName();
  5956. StringRef ClassName = ClassDecl->getName();
  5957. // must declare an extern class object in case this class is not implemented
  5958. // in this TU.
  5959. Result += "\n";
  5960. Result += "extern \"C\" ";
  5961. if (ClassDecl->getImplementation())
  5962. Result += "__declspec(dllexport) ";
  5963. else
  5964. Result += "__declspec(dllimport) ";
  5965. Result += "struct _class_t ";
  5966. Result += "OBJC_CLASS_$_"; Result += ClassName;
  5967. Result += ";\n";
  5968. Result += "\nstatic struct _category_t ";
  5969. Result += "_OBJC_$_CATEGORY_";
  5970. Result += ClassName; Result += "_$_"; Result += CatName;
  5971. Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
  5972. Result += "{\n";
  5973. Result += "\t\""; Result += ClassName; Result += "\",\n";
  5974. Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
  5975. Result += ",\n";
  5976. if (InstanceMethods.size() > 0) {
  5977. Result += "\t(const struct _method_list_t *)&";
  5978. Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
  5979. Result += ClassName; Result += "_$_"; Result += CatName;
  5980. Result += ",\n";
  5981. }
  5982. else
  5983. Result += "\t0,\n";
  5984. if (ClassMethods.size() > 0) {
  5985. Result += "\t(const struct _method_list_t *)&";
  5986. Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
  5987. Result += ClassName; Result += "_$_"; Result += CatName;
  5988. Result += ",\n";
  5989. }
  5990. else
  5991. Result += "\t0,\n";
  5992. if (RefedProtocols.size() > 0) {
  5993. Result += "\t(const struct _protocol_list_t *)&";
  5994. Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
  5995. Result += ClassName; Result += "_$_"; Result += CatName;
  5996. Result += ",\n";
  5997. }
  5998. else
  5999. Result += "\t0,\n";
  6000. if (ClassProperties.size() > 0) {
  6001. Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
  6002. Result += ClassName; Result += "_$_"; Result += CatName;
  6003. Result += ",\n";
  6004. }
  6005. else
  6006. Result += "\t0,\n";
  6007. Result += "};\n";
  6008. // Add static function to initialize the class pointer in the category structure.
  6009. Result += "static void OBJC_CATEGORY_SETUP_$_";
  6010. Result += ClassDecl->getNameAsString();
  6011. Result += "_$_";
  6012. Result += CatName;
  6013. Result += "(void ) {\n";
  6014. Result += "\t_OBJC_$_CATEGORY_";
  6015. Result += ClassDecl->getNameAsString();
  6016. Result += "_$_";
  6017. Result += CatName;
  6018. Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
  6019. Result += ";\n}\n";
  6020. }
  6021. static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
  6022. ASTContext *Context, std::string &Result,
  6023. ArrayRef<ObjCMethodDecl *> Methods,
  6024. StringRef VarName,
  6025. StringRef ProtocolName) {
  6026. if (Methods.size() == 0)
  6027. return;
  6028. Result += "\nstatic const char *";
  6029. Result += VarName; Result += ProtocolName;
  6030. Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
  6031. Result += "{\n";
  6032. for (unsigned i = 0, e = Methods.size(); i < e; i++) {
  6033. ObjCMethodDecl *MD = Methods[i];
  6034. std::string MethodTypeString =
  6035. Context->getObjCEncodingForMethodDecl(MD, true);
  6036. std::string QuoteMethodTypeString;
  6037. RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
  6038. Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
  6039. if (i == e-1)
  6040. Result += "\n};\n";
  6041. else {
  6042. Result += ",\n";
  6043. }
  6044. }
  6045. }
  6046. static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
  6047. ASTContext *Context,
  6048. std::string &Result,
  6049. ArrayRef<ObjCIvarDecl *> Ivars,
  6050. ObjCInterfaceDecl *CDecl) {
  6051. // FIXME. visibilty of offset symbols may have to be set; for Darwin
  6052. // this is what happens:
  6053. /**
  6054. if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
  6055. Ivar->getAccessControl() == ObjCIvarDecl::Package ||
  6056. Class->getVisibility() == HiddenVisibility)
  6057. Visibility should be: HiddenVisibility;
  6058. else
  6059. Visibility should be: DefaultVisibility;
  6060. */
  6061. Result += "\n";
  6062. for (unsigned i =0, e = Ivars.size(); i < e; i++) {
  6063. ObjCIvarDecl *IvarDecl = Ivars[i];
  6064. if (Context->getLangOpts().MicrosoftExt)
  6065. Result += "__declspec(allocate(\".objc_ivar$B\")) ";
  6066. if (!Context->getLangOpts().MicrosoftExt ||
  6067. IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
  6068. IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
  6069. Result += "extern \"C\" unsigned long int ";
  6070. else
  6071. Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
  6072. if (Ivars[i]->isBitField())
  6073. RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
  6074. else
  6075. WriteInternalIvarName(CDecl, IvarDecl, Result);
  6076. Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
  6077. Result += " = ";
  6078. RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
  6079. Result += ";\n";
  6080. if (Ivars[i]->isBitField()) {
  6081. // skip over rest of the ivar bitfields.
  6082. SKIP_BITFIELDS(i , e, Ivars);
  6083. }
  6084. }
  6085. }
  6086. static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
  6087. ASTContext *Context, std::string &Result,
  6088. ArrayRef<ObjCIvarDecl *> OriginalIvars,
  6089. StringRef VarName,
  6090. ObjCInterfaceDecl *CDecl) {
  6091. if (OriginalIvars.size() > 0) {
  6092. Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
  6093. SmallVector<ObjCIvarDecl *, 8> Ivars;
  6094. // strip off all but the first ivar bitfield from each group of ivars.
  6095. // Such ivars in the ivar list table will be replaced by their grouping struct
  6096. // 'ivar'.
  6097. for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
  6098. if (OriginalIvars[i]->isBitField()) {
  6099. Ivars.push_back(OriginalIvars[i]);
  6100. // skip over rest of the ivar bitfields.
  6101. SKIP_BITFIELDS(i , e, OriginalIvars);
  6102. }
  6103. else
  6104. Ivars.push_back(OriginalIvars[i]);
  6105. }
  6106. Result += "\nstatic ";
  6107. Write__ivar_list_t_TypeDecl(Result, Ivars.size());
  6108. Result += " "; Result += VarName;
  6109. Result += CDecl->getNameAsString();
  6110. Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
  6111. Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
  6112. Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
  6113. for (unsigned i =0, e = Ivars.size(); i < e; i++) {
  6114. ObjCIvarDecl *IvarDecl = Ivars[i];
  6115. if (i == 0)
  6116. Result += "\t{{";
  6117. else
  6118. Result += "\t {";
  6119. Result += "(unsigned long int *)&";
  6120. if (Ivars[i]->isBitField())
  6121. RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
  6122. else
  6123. WriteInternalIvarName(CDecl, IvarDecl, Result);
  6124. Result += ", ";
  6125. Result += "\"";
  6126. if (Ivars[i]->isBitField())
  6127. RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
  6128. else
  6129. Result += IvarDecl->getName();
  6130. Result += "\", ";
  6131. QualType IVQT = IvarDecl->getType();
  6132. if (IvarDecl->isBitField())
  6133. IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
  6134. std::string IvarTypeString, QuoteIvarTypeString;
  6135. Context->getObjCEncodingForType(IVQT, IvarTypeString,
  6136. IvarDecl);
  6137. RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
  6138. Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
  6139. // FIXME. this alignment represents the host alignment and need be changed to
  6140. // represent the target alignment.
  6141. unsigned Align = Context->getTypeAlign(IVQT)/8;
  6142. Align = llvm::Log2_32(Align);
  6143. Result += llvm::utostr(Align); Result += ", ";
  6144. CharUnits Size = Context->getTypeSizeInChars(IVQT);
  6145. Result += llvm::utostr(Size.getQuantity());
  6146. if (i == e-1)
  6147. Result += "}}\n";
  6148. else
  6149. Result += "},\n";
  6150. }
  6151. Result += "};\n";
  6152. }
  6153. }
  6154. /// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
  6155. void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
  6156. std::string &Result) {
  6157. // Do not synthesize the protocol more than once.
  6158. if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
  6159. return;
  6160. WriteModernMetadataDeclarations(Context, Result);
  6161. if (ObjCProtocolDecl *Def = PDecl->getDefinition())
  6162. PDecl = Def;
  6163. // Must write out all protocol definitions in current qualifier list,
  6164. // and in their nested qualifiers before writing out current definition.
  6165. for (auto *I : PDecl->protocols())
  6166. RewriteObjCProtocolMetaData(I, Result);
  6167. // Construct method lists.
  6168. std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
  6169. std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
  6170. for (auto *MD : PDecl->instance_methods()) {
  6171. if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
  6172. OptInstanceMethods.push_back(MD);
  6173. } else {
  6174. InstanceMethods.push_back(MD);
  6175. }
  6176. }
  6177. for (auto *MD : PDecl->class_methods()) {
  6178. if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
  6179. OptClassMethods.push_back(MD);
  6180. } else {
  6181. ClassMethods.push_back(MD);
  6182. }
  6183. }
  6184. std::vector<ObjCMethodDecl *> AllMethods;
  6185. for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
  6186. AllMethods.push_back(InstanceMethods[i]);
  6187. for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
  6188. AllMethods.push_back(ClassMethods[i]);
  6189. for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
  6190. AllMethods.push_back(OptInstanceMethods[i]);
  6191. for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
  6192. AllMethods.push_back(OptClassMethods[i]);
  6193. Write__extendedMethodTypes_initializer(*this, Context, Result,
  6194. AllMethods,
  6195. "_OBJC_PROTOCOL_METHOD_TYPES_",
  6196. PDecl->getNameAsString());
  6197. // Protocol's super protocol list
  6198. SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols());
  6199. Write_protocol_list_initializer(Context, Result, SuperProtocols,
  6200. "_OBJC_PROTOCOL_REFS_",
  6201. PDecl->getNameAsString());
  6202. Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
  6203. "_OBJC_PROTOCOL_INSTANCE_METHODS_",
  6204. PDecl->getNameAsString(), false);
  6205. Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
  6206. "_OBJC_PROTOCOL_CLASS_METHODS_",
  6207. PDecl->getNameAsString(), false);
  6208. Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
  6209. "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
  6210. PDecl->getNameAsString(), false);
  6211. Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
  6212. "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
  6213. PDecl->getNameAsString(), false);
  6214. // Protocol's property metadata.
  6215. SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties(
  6216. PDecl->instance_properties());
  6217. Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
  6218. /* Container */nullptr,
  6219. "_OBJC_PROTOCOL_PROPERTIES_",
  6220. PDecl->getNameAsString());
  6221. // Writer out root metadata for current protocol: struct _protocol_t
  6222. Result += "\n";
  6223. if (LangOpts.MicrosoftExt)
  6224. Result += "static ";
  6225. Result += "struct _protocol_t _OBJC_PROTOCOL_";
  6226. Result += PDecl->getNameAsString();
  6227. Result += " __attribute__ ((used)) = {\n";
  6228. Result += "\t0,\n"; // id is; is null
  6229. Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
  6230. if (SuperProtocols.size() > 0) {
  6231. Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
  6232. Result += PDecl->getNameAsString(); Result += ",\n";
  6233. }
  6234. else
  6235. Result += "\t0,\n";
  6236. if (InstanceMethods.size() > 0) {
  6237. Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
  6238. Result += PDecl->getNameAsString(); Result += ",\n";
  6239. }
  6240. else
  6241. Result += "\t0,\n";
  6242. if (ClassMethods.size() > 0) {
  6243. Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
  6244. Result += PDecl->getNameAsString(); Result += ",\n";
  6245. }
  6246. else
  6247. Result += "\t0,\n";
  6248. if (OptInstanceMethods.size() > 0) {
  6249. Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
  6250. Result += PDecl->getNameAsString(); Result += ",\n";
  6251. }
  6252. else
  6253. Result += "\t0,\n";
  6254. if (OptClassMethods.size() > 0) {
  6255. Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
  6256. Result += PDecl->getNameAsString(); Result += ",\n";
  6257. }
  6258. else
  6259. Result += "\t0,\n";
  6260. if (ProtocolProperties.size() > 0) {
  6261. Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
  6262. Result += PDecl->getNameAsString(); Result += ",\n";
  6263. }
  6264. else
  6265. Result += "\t0,\n";
  6266. Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
  6267. Result += "\t0,\n";
  6268. if (AllMethods.size() > 0) {
  6269. Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
  6270. Result += PDecl->getNameAsString();
  6271. Result += "\n};\n";
  6272. }
  6273. else
  6274. Result += "\t0\n};\n";
  6275. if (LangOpts.MicrosoftExt)
  6276. Result += "static ";
  6277. Result += "struct _protocol_t *";
  6278. Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
  6279. Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
  6280. Result += ";\n";
  6281. // Mark this protocol as having been generated.
  6282. if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
  6283. llvm_unreachable("protocol already synthesized");
  6284. }
  6285. /// hasObjCExceptionAttribute - Return true if this class or any super
  6286. /// class has the __objc_exception__ attribute.
  6287. /// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
  6288. static bool hasObjCExceptionAttribute(ASTContext &Context,
  6289. const ObjCInterfaceDecl *OID) {
  6290. if (OID->hasAttr<ObjCExceptionAttr>())
  6291. return true;
  6292. if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
  6293. return hasObjCExceptionAttribute(Context, Super);
  6294. return false;
  6295. }
  6296. void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
  6297. std::string &Result) {
  6298. ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
  6299. // Explicitly declared @interface's are already synthesized.
  6300. if (CDecl->isImplicitInterfaceDecl())
  6301. assert(false &&
  6302. "Legacy implicit interface rewriting not supported in moder abi");
  6303. WriteModernMetadataDeclarations(Context, Result);
  6304. SmallVector<ObjCIvarDecl *, 8> IVars;
  6305. for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
  6306. IVD; IVD = IVD->getNextIvar()) {
  6307. // Ignore unnamed bit-fields.
  6308. if (!IVD->getDeclName())
  6309. continue;
  6310. IVars.push_back(IVD);
  6311. }
  6312. Write__ivar_list_t_initializer(*this, Context, Result, IVars,
  6313. "_OBJC_$_INSTANCE_VARIABLES_",
  6314. CDecl);
  6315. // Build _objc_method_list for class's instance methods if needed
  6316. SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
  6317. // If any of our property implementations have associated getters or
  6318. // setters, produce metadata for them as well.
  6319. for (const auto *Prop : IDecl->property_impls()) {
  6320. if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
  6321. continue;
  6322. if (!Prop->getPropertyIvarDecl())
  6323. continue;
  6324. ObjCPropertyDecl *PD = Prop->getPropertyDecl();
  6325. if (!PD)
  6326. continue;
  6327. if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl())
  6328. if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
  6329. InstanceMethods.push_back(Getter);
  6330. if (PD->isReadOnly())
  6331. continue;
  6332. if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl())
  6333. if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
  6334. InstanceMethods.push_back(Setter);
  6335. }
  6336. Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
  6337. "_OBJC_$_INSTANCE_METHODS_",
  6338. IDecl->getNameAsString(), true);
  6339. SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
  6340. Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
  6341. "_OBJC_$_CLASS_METHODS_",
  6342. IDecl->getNameAsString(), true);
  6343. // Protocols referenced in class declaration?
  6344. // Protocol's super protocol list
  6345. std::vector<ObjCProtocolDecl *> RefedProtocols;
  6346. const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
  6347. for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
  6348. E = Protocols.end();
  6349. I != E; ++I) {
  6350. RefedProtocols.push_back(*I);
  6351. // Must write out all protocol definitions in current qualifier list,
  6352. // and in their nested qualifiers before writing out current definition.
  6353. RewriteObjCProtocolMetaData(*I, Result);
  6354. }
  6355. Write_protocol_list_initializer(Context, Result,
  6356. RefedProtocols,
  6357. "_OBJC_CLASS_PROTOCOLS_$_",
  6358. IDecl->getNameAsString());
  6359. // Protocol's property metadata.
  6360. SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
  6361. CDecl->instance_properties());
  6362. Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
  6363. /* Container */IDecl,
  6364. "_OBJC_$_PROP_LIST_",
  6365. CDecl->getNameAsString());
  6366. // Data for initializing _class_ro_t metaclass meta-data
  6367. uint32_t flags = CLS_META;
  6368. std::string InstanceSize;
  6369. std::string InstanceStart;
  6370. bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
  6371. if (classIsHidden)
  6372. flags |= OBJC2_CLS_HIDDEN;
  6373. if (!CDecl->getSuperClass())
  6374. // class is root
  6375. flags |= CLS_ROOT;
  6376. InstanceSize = "sizeof(struct _class_t)";
  6377. InstanceStart = InstanceSize;
  6378. Write__class_ro_t_initializer(Context, Result, flags,
  6379. InstanceStart, InstanceSize,
  6380. ClassMethods,
  6381. nullptr,
  6382. nullptr,
  6383. nullptr,
  6384. "_OBJC_METACLASS_RO_$_",
  6385. CDecl->getNameAsString());
  6386. // Data for initializing _class_ro_t meta-data
  6387. flags = CLS;
  6388. if (classIsHidden)
  6389. flags |= OBJC2_CLS_HIDDEN;
  6390. if (hasObjCExceptionAttribute(*Context, CDecl))
  6391. flags |= CLS_EXCEPTION;
  6392. if (!CDecl->getSuperClass())
  6393. // class is root
  6394. flags |= CLS_ROOT;
  6395. InstanceSize.clear();
  6396. InstanceStart.clear();
  6397. if (!ObjCSynthesizedStructs.count(CDecl)) {
  6398. InstanceSize = "0";
  6399. InstanceStart = "0";
  6400. }
  6401. else {
  6402. InstanceSize = "sizeof(struct ";
  6403. InstanceSize += CDecl->getNameAsString();
  6404. InstanceSize += "_IMPL)";
  6405. ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
  6406. if (IVD) {
  6407. RewriteIvarOffsetComputation(IVD, InstanceStart);
  6408. }
  6409. else
  6410. InstanceStart = InstanceSize;
  6411. }
  6412. Write__class_ro_t_initializer(Context, Result, flags,
  6413. InstanceStart, InstanceSize,
  6414. InstanceMethods,
  6415. RefedProtocols,
  6416. IVars,
  6417. ClassProperties,
  6418. "_OBJC_CLASS_RO_$_",
  6419. CDecl->getNameAsString());
  6420. Write_class_t(Context, Result,
  6421. "OBJC_METACLASS_$_",
  6422. CDecl, /*metaclass*/true);
  6423. Write_class_t(Context, Result,
  6424. "OBJC_CLASS_$_",
  6425. CDecl, /*metaclass*/false);
  6426. if (ImplementationIsNonLazy(IDecl))
  6427. DefinedNonLazyClasses.push_back(CDecl);
  6428. }
  6429. void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
  6430. int ClsDefCount = ClassImplementation.size();
  6431. if (!ClsDefCount)
  6432. return;
  6433. Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
  6434. Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
  6435. Result += "static void *OBJC_CLASS_SETUP[] = {\n";
  6436. for (int i = 0; i < ClsDefCount; i++) {
  6437. ObjCImplementationDecl *IDecl = ClassImplementation[i];
  6438. ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
  6439. Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
  6440. Result += CDecl->getName(); Result += ",\n";
  6441. }
  6442. Result += "};\n";
  6443. }
  6444. void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
  6445. int ClsDefCount = ClassImplementation.size();
  6446. int CatDefCount = CategoryImplementation.size();
  6447. // For each implemented class, write out all its meta data.
  6448. for (int i = 0; i < ClsDefCount; i++)
  6449. RewriteObjCClassMetaData(ClassImplementation[i], Result);
  6450. RewriteClassSetupInitHook(Result);
  6451. // For each implemented category, write out all its meta data.
  6452. for (int i = 0; i < CatDefCount; i++)
  6453. RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
  6454. RewriteCategorySetupInitHook(Result);
  6455. if (ClsDefCount > 0) {
  6456. if (LangOpts.MicrosoftExt)
  6457. Result += "__declspec(allocate(\".objc_classlist$B\")) ";
  6458. Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
  6459. Result += llvm::utostr(ClsDefCount); Result += "]";
  6460. Result +=
  6461. " __attribute__((used, section (\"__DATA, __objc_classlist,"
  6462. "regular,no_dead_strip\")))= {\n";
  6463. for (int i = 0; i < ClsDefCount; i++) {
  6464. Result += "\t&OBJC_CLASS_$_";
  6465. Result += ClassImplementation[i]->getNameAsString();
  6466. Result += ",\n";
  6467. }
  6468. Result += "};\n";
  6469. if (!DefinedNonLazyClasses.empty()) {
  6470. if (LangOpts.MicrosoftExt)
  6471. Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
  6472. Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
  6473. for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
  6474. Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
  6475. Result += ",\n";
  6476. }
  6477. Result += "};\n";
  6478. }
  6479. }
  6480. if (CatDefCount > 0) {
  6481. if (LangOpts.MicrosoftExt)
  6482. Result += "__declspec(allocate(\".objc_catlist$B\")) ";
  6483. Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
  6484. Result += llvm::utostr(CatDefCount); Result += "]";
  6485. Result +=
  6486. " __attribute__((used, section (\"__DATA, __objc_catlist,"
  6487. "regular,no_dead_strip\")))= {\n";
  6488. for (int i = 0; i < CatDefCount; i++) {
  6489. Result += "\t&_OBJC_$_CATEGORY_";
  6490. Result +=
  6491. CategoryImplementation[i]->getClassInterface()->getNameAsString();
  6492. Result += "_$_";
  6493. Result += CategoryImplementation[i]->getNameAsString();
  6494. Result += ",\n";
  6495. }
  6496. Result += "};\n";
  6497. }
  6498. if (!DefinedNonLazyCategories.empty()) {
  6499. if (LangOpts.MicrosoftExt)
  6500. Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
  6501. Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
  6502. for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
  6503. Result += "\t&_OBJC_$_CATEGORY_";
  6504. Result +=
  6505. DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
  6506. Result += "_$_";
  6507. Result += DefinedNonLazyCategories[i]->getNameAsString();
  6508. Result += ",\n";
  6509. }
  6510. Result += "};\n";
  6511. }
  6512. }
  6513. void RewriteModernObjC::WriteImageInfo(std::string &Result) {
  6514. if (LangOpts.MicrosoftExt)
  6515. Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
  6516. Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
  6517. // version 0, ObjCABI is 2
  6518. Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
  6519. }
  6520. /// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
  6521. /// implementation.
  6522. void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
  6523. std::string &Result) {
  6524. WriteModernMetadataDeclarations(Context, Result);
  6525. ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
  6526. // Find category declaration for this implementation.
  6527. ObjCCategoryDecl *CDecl
  6528. = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
  6529. std::string FullCategoryName = ClassDecl->getNameAsString();
  6530. FullCategoryName += "_$_";
  6531. FullCategoryName += CDecl->getNameAsString();
  6532. // Build _objc_method_list for class's instance methods if needed
  6533. SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
  6534. // If any of our property implementations have associated getters or
  6535. // setters, produce metadata for them as well.
  6536. for (const auto *Prop : IDecl->property_impls()) {
  6537. if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
  6538. continue;
  6539. if (!Prop->getPropertyIvarDecl())
  6540. continue;
  6541. ObjCPropertyDecl *PD = Prop->getPropertyDecl();
  6542. if (!PD)
  6543. continue;
  6544. if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl())
  6545. InstanceMethods.push_back(Getter);
  6546. if (PD->isReadOnly())
  6547. continue;
  6548. if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl())
  6549. InstanceMethods.push_back(Setter);
  6550. }
  6551. Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
  6552. "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
  6553. FullCategoryName, true);
  6554. SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
  6555. Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
  6556. "_OBJC_$_CATEGORY_CLASS_METHODS_",
  6557. FullCategoryName, true);
  6558. // Protocols referenced in class declaration?
  6559. // Protocol's super protocol list
  6560. SmallVector<ObjCProtocolDecl *, 8> RefedProtocols(CDecl->protocols());
  6561. for (auto *I : CDecl->protocols())
  6562. // Must write out all protocol definitions in current qualifier list,
  6563. // and in their nested qualifiers before writing out current definition.
  6564. RewriteObjCProtocolMetaData(I, Result);
  6565. Write_protocol_list_initializer(Context, Result,
  6566. RefedProtocols,
  6567. "_OBJC_CATEGORY_PROTOCOLS_$_",
  6568. FullCategoryName);
  6569. // Protocol's property metadata.
  6570. SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
  6571. CDecl->instance_properties());
  6572. Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
  6573. /* Container */IDecl,
  6574. "_OBJC_$_PROP_LIST_",
  6575. FullCategoryName);
  6576. Write_category_t(*this, Context, Result,
  6577. CDecl,
  6578. ClassDecl,
  6579. InstanceMethods,
  6580. ClassMethods,
  6581. RefedProtocols,
  6582. ClassProperties);
  6583. // Determine if this category is also "non-lazy".
  6584. if (ImplementationIsNonLazy(IDecl))
  6585. DefinedNonLazyCategories.push_back(CDecl);
  6586. }
  6587. void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
  6588. int CatDefCount = CategoryImplementation.size();
  6589. if (!CatDefCount)
  6590. return;
  6591. Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
  6592. Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
  6593. Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
  6594. for (int i = 0; i < CatDefCount; i++) {
  6595. ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
  6596. ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
  6597. ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
  6598. Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
  6599. Result += ClassDecl->getName();
  6600. Result += "_$_";
  6601. Result += CatDecl->getName();
  6602. Result += ",\n";
  6603. }
  6604. Result += "};\n";
  6605. }
  6606. // RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
  6607. /// class methods.
  6608. template<typename MethodIterator>
  6609. void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
  6610. MethodIterator MethodEnd,
  6611. bool IsInstanceMethod,
  6612. StringRef prefix,
  6613. StringRef ClassName,
  6614. std::string &Result) {
  6615. if (MethodBegin == MethodEnd) return;
  6616. if (!objc_impl_method) {
  6617. /* struct _objc_method {
  6618. SEL _cmd;
  6619. char *method_types;
  6620. void *_imp;
  6621. }
  6622. */
  6623. Result += "\nstruct _objc_method {\n";
  6624. Result += "\tSEL _cmd;\n";
  6625. Result += "\tchar *method_types;\n";
  6626. Result += "\tvoid *_imp;\n";
  6627. Result += "};\n";
  6628. objc_impl_method = true;
  6629. }
  6630. // Build _objc_method_list for class's methods if needed
  6631. /* struct {
  6632. struct _objc_method_list *next_method;
  6633. int method_count;
  6634. struct _objc_method method_list[];
  6635. }
  6636. */
  6637. unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
  6638. Result += "\n";
  6639. if (LangOpts.MicrosoftExt) {
  6640. if (IsInstanceMethod)
  6641. Result += "__declspec(allocate(\".inst_meth$B\")) ";
  6642. else
  6643. Result += "__declspec(allocate(\".cls_meth$B\")) ";
  6644. }
  6645. Result += "static struct {\n";
  6646. Result += "\tstruct _objc_method_list *next_method;\n";
  6647. Result += "\tint method_count;\n";
  6648. Result += "\tstruct _objc_method method_list[";
  6649. Result += utostr(NumMethods);
  6650. Result += "];\n} _OBJC_";
  6651. Result += prefix;
  6652. Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
  6653. Result += "_METHODS_";
  6654. Result += ClassName;
  6655. Result += " __attribute__ ((used, section (\"__OBJC, __";
  6656. Result += IsInstanceMethod ? "inst" : "cls";
  6657. Result += "_meth\")))= ";
  6658. Result += "{\n\t0, " + utostr(NumMethods) + "\n";
  6659. Result += "\t,{{(SEL)\"";
  6660. Result += (*MethodBegin)->getSelector().getAsString().c_str();
  6661. std::string MethodTypeString;
  6662. Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
  6663. Result += "\", \"";
  6664. Result += MethodTypeString;
  6665. Result += "\", (void *)";
  6666. Result += MethodInternalNames[*MethodBegin];
  6667. Result += "}\n";
  6668. for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
  6669. Result += "\t ,{(SEL)\"";
  6670. Result += (*MethodBegin)->getSelector().getAsString().c_str();
  6671. std::string MethodTypeString;
  6672. Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
  6673. Result += "\", \"";
  6674. Result += MethodTypeString;
  6675. Result += "\", (void *)";
  6676. Result += MethodInternalNames[*MethodBegin];
  6677. Result += "}\n";
  6678. }
  6679. Result += "\t }\n};\n";
  6680. }
  6681. Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
  6682. SourceRange OldRange = IV->getSourceRange();
  6683. Expr *BaseExpr = IV->getBase();
  6684. // Rewrite the base, but without actually doing replaces.
  6685. {
  6686. DisableReplaceStmtScope S(*this);
  6687. BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
  6688. IV->setBase(BaseExpr);
  6689. }
  6690. ObjCIvarDecl *D = IV->getDecl();
  6691. Expr *Replacement = IV;
  6692. if (BaseExpr->getType()->isObjCObjectPointerType()) {
  6693. const ObjCInterfaceType *iFaceDecl =
  6694. dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
  6695. assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
  6696. // lookup which class implements the instance variable.
  6697. ObjCInterfaceDecl *clsDeclared = nullptr;
  6698. iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
  6699. clsDeclared);
  6700. assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
  6701. // Build name of symbol holding ivar offset.
  6702. std::string IvarOffsetName;
  6703. if (D->isBitField())
  6704. ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
  6705. else
  6706. WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
  6707. ReferencedIvars[clsDeclared].insert(D);
  6708. // cast offset to "char *".
  6709. CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
  6710. Context->getPointerType(Context->CharTy),
  6711. CK_BitCast,
  6712. BaseExpr);
  6713. VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
  6714. SourceLocation(), &Context->Idents.get(IvarOffsetName),
  6715. Context->UnsignedLongTy, nullptr,
  6716. SC_Extern);
  6717. DeclRefExpr *DRE = new (Context)
  6718. DeclRefExpr(*Context, NewVD, false, Context->UnsignedLongTy,
  6719. VK_LValue, SourceLocation());
  6720. BinaryOperator *addExpr = BinaryOperator::Create(
  6721. *Context, castExpr, DRE, BO_Add,
  6722. Context->getPointerType(Context->CharTy), VK_PRValue, OK_Ordinary,
  6723. SourceLocation(), FPOptionsOverride());
  6724. // Don't forget the parens to enforce the proper binding.
  6725. ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
  6726. SourceLocation(),
  6727. addExpr);
  6728. QualType IvarT = D->getType();
  6729. if (D->isBitField())
  6730. IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
  6731. if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
  6732. RecordDecl *RD = IvarT->castAs<RecordType>()->getDecl();
  6733. RD = RD->getDefinition();
  6734. if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
  6735. // decltype(((Foo_IMPL*)0)->bar) *
  6736. auto *CDecl = cast<ObjCContainerDecl>(D->getDeclContext());
  6737. // ivar in class extensions requires special treatment.
  6738. if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
  6739. CDecl = CatDecl->getClassInterface();
  6740. std::string RecName = std::string(CDecl->getName());
  6741. RecName += "_IMPL";
  6742. RecordDecl *RD = RecordDecl::Create(
  6743. *Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(),
  6744. &Context->Idents.get(RecName));
  6745. QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
  6746. unsigned UnsignedIntSize =
  6747. static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
  6748. Expr *Zero = IntegerLiteral::Create(*Context,
  6749. llvm::APInt(UnsignedIntSize, 0),
  6750. Context->UnsignedIntTy, SourceLocation());
  6751. Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
  6752. ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
  6753. Zero);
  6754. FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
  6755. SourceLocation(),
  6756. &Context->Idents.get(D->getNameAsString()),
  6757. IvarT, nullptr,
  6758. /*BitWidth=*/nullptr,
  6759. /*Mutable=*/true, ICIS_NoInit);
  6760. MemberExpr *ME = MemberExpr::CreateImplicit(
  6761. *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
  6762. IvarT = Context->getDecltypeType(ME, ME->getType());
  6763. }
  6764. }
  6765. convertObjCTypeToCStyleType(IvarT);
  6766. QualType castT = Context->getPointerType(IvarT);
  6767. castExpr = NoTypeInfoCStyleCastExpr(Context,
  6768. castT,
  6769. CK_BitCast,
  6770. PE);
  6771. Expr *Exp = UnaryOperator::Create(
  6772. const_cast<ASTContext &>(*Context), castExpr, UO_Deref, IvarT,
  6773. VK_LValue, OK_Ordinary, SourceLocation(), false, FPOptionsOverride());
  6774. PE = new (Context) ParenExpr(OldRange.getBegin(),
  6775. OldRange.getEnd(),
  6776. Exp);
  6777. if (D->isBitField()) {
  6778. FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
  6779. SourceLocation(),
  6780. &Context->Idents.get(D->getNameAsString()),
  6781. D->getType(), nullptr,
  6782. /*BitWidth=*/D->getBitWidth(),
  6783. /*Mutable=*/true, ICIS_NoInit);
  6784. MemberExpr *ME =
  6785. MemberExpr::CreateImplicit(*Context, PE, /*isArrow*/ false, FD,
  6786. FD->getType(), VK_LValue, OK_Ordinary);
  6787. Replacement = ME;
  6788. }
  6789. else
  6790. Replacement = PE;
  6791. }
  6792. ReplaceStmtWithRange(IV, Replacement, OldRange);
  6793. return Replacement;
  6794. }
  6795. #endif // CLANG_ENABLE_OBJC_REWRITER