RewriteObjC.cpp 227 KB

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