RewriteObjC.cpp 225 KB

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