RewriteObjC.cpp 225 KB

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