CGObjCMac.cpp 246 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313
  1. //===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This provides Objective-C code generation targeting the Apple runtime.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CGObjCRuntime.h"
  14. #include "CGRecordLayout.h"
  15. #include "CodeGenModule.h"
  16. #include "CodeGenFunction.h"
  17. #include "CGBlocks.h"
  18. #include "CGCleanup.h"
  19. #include "clang/AST/ASTContext.h"
  20. #include "clang/AST/Decl.h"
  21. #include "clang/AST/DeclObjC.h"
  22. #include "clang/AST/RecordLayout.h"
  23. #include "clang/AST/StmtObjC.h"
  24. #include "clang/Basic/LangOptions.h"
  25. #include "clang/Frontend/CodeGenOptions.h"
  26. #include "llvm/InlineAsm.h"
  27. #include "llvm/IntrinsicInst.h"
  28. #include "llvm/LLVMContext.h"
  29. #include "llvm/Module.h"
  30. #include "llvm/ADT/DenseSet.h"
  31. #include "llvm/ADT/SetVector.h"
  32. #include "llvm/ADT/SmallString.h"
  33. #include "llvm/ADT/SmallPtrSet.h"
  34. #include "llvm/Support/CallSite.h"
  35. #include "llvm/Support/raw_ostream.h"
  36. #include "llvm/Target/TargetData.h"
  37. #include <cstdio>
  38. using namespace clang;
  39. using namespace CodeGen;
  40. namespace {
  41. // FIXME: We should find a nicer way to make the labels for metadata, string
  42. // concatenation is lame.
  43. class ObjCCommonTypesHelper {
  44. protected:
  45. llvm::LLVMContext &VMContext;
  46. private:
  47. // The types of these functions don't really matter because we
  48. // should always bitcast before calling them.
  49. /// id objc_msgSend (id, SEL, ...)
  50. ///
  51. /// The default messenger, used for sends whose ABI is unchanged from
  52. /// the all-integer/pointer case.
  53. llvm::Constant *getMessageSendFn() const {
  54. // Add the non-lazy-bind attribute, since objc_msgSend is likely to
  55. // be called a lot.
  56. llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
  57. return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
  58. params, true),
  59. "objc_msgSend",
  60. llvm::Attribute::NonLazyBind);
  61. }
  62. /// void objc_msgSend_stret (id, SEL, ...)
  63. ///
  64. /// The messenger used when the return value is an aggregate returned
  65. /// by indirect reference in the first argument, and therefore the
  66. /// self and selector parameters are shifted over by one.
  67. llvm::Constant *getMessageSendStretFn() const {
  68. llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
  69. return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.VoidTy,
  70. params, true),
  71. "objc_msgSend_stret");
  72. }
  73. /// [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
  74. ///
  75. /// The messenger used when the return value is returned on the x87
  76. /// floating-point stack; without a special entrypoint, the nil case
  77. /// would be unbalanced.
  78. llvm::Constant *getMessageSendFpretFn() const {
  79. llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
  80. return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.DoubleTy,
  81. params, true),
  82. "objc_msgSend_fpret");
  83. }
  84. /// _Complex long double objc_msgSend_fp2ret(id self, SEL op, ...)
  85. ///
  86. /// The messenger used when the return value is returned in two values on the
  87. /// x87 floating point stack; without a special entrypoint, the nil case
  88. /// would be unbalanced. Only used on 64-bit X86.
  89. llvm::Constant *getMessageSendFp2retFn() const {
  90. llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
  91. llvm::Type *longDoubleType = llvm::Type::getX86_FP80Ty(VMContext);
  92. llvm::Type *resultType =
  93. llvm::StructType::get(longDoubleType, longDoubleType, NULL);
  94. return CGM.CreateRuntimeFunction(llvm::FunctionType::get(resultType,
  95. params, true),
  96. "objc_msgSend_fp2ret");
  97. }
  98. /// id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
  99. ///
  100. /// The messenger used for super calls, which have different dispatch
  101. /// semantics. The class passed is the superclass of the current
  102. /// class.
  103. llvm::Constant *getMessageSendSuperFn() const {
  104. llvm::Type *params[] = { SuperPtrTy, SelectorPtrTy };
  105. return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
  106. params, true),
  107. "objc_msgSendSuper");
  108. }
  109. /// id objc_msgSendSuper2(struct objc_super *super, SEL op, ...)
  110. ///
  111. /// A slightly different messenger used for super calls. The class
  112. /// passed is the current class.
  113. llvm::Constant *getMessageSendSuperFn2() const {
  114. llvm::Type *params[] = { SuperPtrTy, SelectorPtrTy };
  115. return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
  116. params, true),
  117. "objc_msgSendSuper2");
  118. }
  119. /// void objc_msgSendSuper_stret(void *stretAddr, struct objc_super *super,
  120. /// SEL op, ...)
  121. ///
  122. /// The messenger used for super calls which return an aggregate indirectly.
  123. llvm::Constant *getMessageSendSuperStretFn() const {
  124. llvm::Type *params[] = { Int8PtrTy, SuperPtrTy, SelectorPtrTy };
  125. return CGM.CreateRuntimeFunction(
  126. llvm::FunctionType::get(CGM.VoidTy, params, true),
  127. "objc_msgSendSuper_stret");
  128. }
  129. /// void objc_msgSendSuper2_stret(void * stretAddr, struct objc_super *super,
  130. /// SEL op, ...)
  131. ///
  132. /// objc_msgSendSuper_stret with the super2 semantics.
  133. llvm::Constant *getMessageSendSuperStretFn2() const {
  134. llvm::Type *params[] = { Int8PtrTy, SuperPtrTy, SelectorPtrTy };
  135. return CGM.CreateRuntimeFunction(
  136. llvm::FunctionType::get(CGM.VoidTy, params, true),
  137. "objc_msgSendSuper2_stret");
  138. }
  139. llvm::Constant *getMessageSendSuperFpretFn() const {
  140. // There is no objc_msgSendSuper_fpret? How can that work?
  141. return getMessageSendSuperFn();
  142. }
  143. llvm::Constant *getMessageSendSuperFpretFn2() const {
  144. // There is no objc_msgSendSuper_fpret? How can that work?
  145. return getMessageSendSuperFn2();
  146. }
  147. protected:
  148. CodeGen::CodeGenModule &CGM;
  149. public:
  150. llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
  151. llvm::Type *Int8PtrTy, *Int8PtrPtrTy;
  152. /// ObjectPtrTy - LLVM type for object handles (typeof(id))
  153. llvm::Type *ObjectPtrTy;
  154. /// PtrObjectPtrTy - LLVM type for id *
  155. llvm::Type *PtrObjectPtrTy;
  156. /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
  157. llvm::Type *SelectorPtrTy;
  158. private:
  159. /// ProtocolPtrTy - LLVM type for external protocol handles
  160. /// (typeof(Protocol))
  161. llvm::Type *ExternalProtocolPtrTy;
  162. public:
  163. llvm::Type *getExternalProtocolPtrTy() {
  164. if (!ExternalProtocolPtrTy) {
  165. // FIXME: It would be nice to unify this with the opaque type, so that the
  166. // IR comes out a bit cleaner.
  167. CodeGen::CodeGenTypes &Types = CGM.getTypes();
  168. ASTContext &Ctx = CGM.getContext();
  169. llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
  170. ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
  171. }
  172. return ExternalProtocolPtrTy;
  173. }
  174. // SuperCTy - clang type for struct objc_super.
  175. QualType SuperCTy;
  176. // SuperPtrCTy - clang type for struct objc_super *.
  177. QualType SuperPtrCTy;
  178. /// SuperTy - LLVM type for struct objc_super.
  179. llvm::StructType *SuperTy;
  180. /// SuperPtrTy - LLVM type for struct objc_super *.
  181. llvm::Type *SuperPtrTy;
  182. /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
  183. /// in GCC parlance).
  184. llvm::StructType *PropertyTy;
  185. /// PropertyListTy - LLVM type for struct objc_property_list
  186. /// (_prop_list_t in GCC parlance).
  187. llvm::StructType *PropertyListTy;
  188. /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
  189. llvm::Type *PropertyListPtrTy;
  190. // MethodTy - LLVM type for struct objc_method.
  191. llvm::StructType *MethodTy;
  192. /// CacheTy - LLVM type for struct objc_cache.
  193. llvm::Type *CacheTy;
  194. /// CachePtrTy - LLVM type for struct objc_cache *.
  195. llvm::Type *CachePtrTy;
  196. llvm::Constant *getGetPropertyFn() {
  197. CodeGen::CodeGenTypes &Types = CGM.getTypes();
  198. ASTContext &Ctx = CGM.getContext();
  199. // id objc_getProperty (id, SEL, ptrdiff_t, bool)
  200. SmallVector<CanQualType,4> Params;
  201. CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType());
  202. CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType());
  203. Params.push_back(IdType);
  204. Params.push_back(SelType);
  205. Params.push_back(Ctx.getPointerDiffType()->getCanonicalTypeUnqualified());
  206. Params.push_back(Ctx.BoolTy);
  207. llvm::FunctionType *FTy =
  208. Types.GetFunctionType(Types.arrangeFunctionType(IdType, Params,
  209. FunctionType::ExtInfo(),
  210. RequiredArgs::All));
  211. return CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
  212. }
  213. llvm::Constant *getSetPropertyFn() {
  214. CodeGen::CodeGenTypes &Types = CGM.getTypes();
  215. ASTContext &Ctx = CGM.getContext();
  216. // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
  217. SmallVector<CanQualType,6> Params;
  218. CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType());
  219. CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType());
  220. Params.push_back(IdType);
  221. Params.push_back(SelType);
  222. Params.push_back(Ctx.getPointerDiffType()->getCanonicalTypeUnqualified());
  223. Params.push_back(IdType);
  224. Params.push_back(Ctx.BoolTy);
  225. Params.push_back(Ctx.BoolTy);
  226. llvm::FunctionType *FTy =
  227. Types.GetFunctionType(Types.arrangeFunctionType(Ctx.VoidTy, Params,
  228. FunctionType::ExtInfo(),
  229. RequiredArgs::All));
  230. return CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
  231. }
  232. llvm::Constant *getCopyStructFn() {
  233. CodeGen::CodeGenTypes &Types = CGM.getTypes();
  234. ASTContext &Ctx = CGM.getContext();
  235. // void objc_copyStruct (void *, const void *, size_t, bool, bool)
  236. SmallVector<CanQualType,5> Params;
  237. Params.push_back(Ctx.VoidPtrTy);
  238. Params.push_back(Ctx.VoidPtrTy);
  239. Params.push_back(Ctx.LongTy);
  240. Params.push_back(Ctx.BoolTy);
  241. Params.push_back(Ctx.BoolTy);
  242. llvm::FunctionType *FTy =
  243. Types.GetFunctionType(Types.arrangeFunctionType(Ctx.VoidTy, Params,
  244. FunctionType::ExtInfo(),
  245. RequiredArgs::All));
  246. return CGM.CreateRuntimeFunction(FTy, "objc_copyStruct");
  247. }
  248. /// This routine declares and returns address of:
  249. /// void objc_copyCppObjectAtomic(
  250. /// void *dest, const void *src,
  251. /// void (*copyHelper) (void *dest, const void *source));
  252. llvm::Constant *getCppAtomicObjectFunction() {
  253. CodeGen::CodeGenTypes &Types = CGM.getTypes();
  254. ASTContext &Ctx = CGM.getContext();
  255. /// void objc_copyCppObjectAtomic(void *dest, const void *src, void *helper);
  256. SmallVector<CanQualType,3> Params;
  257. Params.push_back(Ctx.VoidPtrTy);
  258. Params.push_back(Ctx.VoidPtrTy);
  259. Params.push_back(Ctx.VoidPtrTy);
  260. llvm::FunctionType *FTy =
  261. Types.GetFunctionType(Types.arrangeFunctionType(Ctx.VoidTy, Params,
  262. FunctionType::ExtInfo(),
  263. RequiredArgs::All));
  264. return CGM.CreateRuntimeFunction(FTy, "objc_copyCppObjectAtomic");
  265. }
  266. llvm::Constant *getEnumerationMutationFn() {
  267. CodeGen::CodeGenTypes &Types = CGM.getTypes();
  268. ASTContext &Ctx = CGM.getContext();
  269. // void objc_enumerationMutation (id)
  270. SmallVector<CanQualType,1> Params;
  271. Params.push_back(Ctx.getCanonicalParamType(Ctx.getObjCIdType()));
  272. llvm::FunctionType *FTy =
  273. Types.GetFunctionType(Types.arrangeFunctionType(Ctx.VoidTy, Params,
  274. FunctionType::ExtInfo(),
  275. RequiredArgs::All));
  276. return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
  277. }
  278. /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
  279. llvm::Constant *getGcReadWeakFn() {
  280. // id objc_read_weak (id *)
  281. llvm::Type *args[] = { ObjectPtrTy->getPointerTo() };
  282. llvm::FunctionType *FTy =
  283. llvm::FunctionType::get(ObjectPtrTy, args, false);
  284. return CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
  285. }
  286. /// GcAssignWeakFn -- LLVM objc_assign_weak function.
  287. llvm::Constant *getGcAssignWeakFn() {
  288. // id objc_assign_weak (id, id *)
  289. llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
  290. llvm::FunctionType *FTy =
  291. llvm::FunctionType::get(ObjectPtrTy, args, false);
  292. return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
  293. }
  294. /// GcAssignGlobalFn -- LLVM objc_assign_global function.
  295. llvm::Constant *getGcAssignGlobalFn() {
  296. // id objc_assign_global(id, id *)
  297. llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
  298. llvm::FunctionType *FTy =
  299. llvm::FunctionType::get(ObjectPtrTy, args, false);
  300. return CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
  301. }
  302. /// GcAssignThreadLocalFn -- LLVM objc_assign_threadlocal function.
  303. llvm::Constant *getGcAssignThreadLocalFn() {
  304. // id objc_assign_threadlocal(id src, id * dest)
  305. llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
  306. llvm::FunctionType *FTy =
  307. llvm::FunctionType::get(ObjectPtrTy, args, false);
  308. return CGM.CreateRuntimeFunction(FTy, "objc_assign_threadlocal");
  309. }
  310. /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
  311. llvm::Constant *getGcAssignIvarFn() {
  312. // id objc_assign_ivar(id, id *, ptrdiff_t)
  313. llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo(),
  314. CGM.PtrDiffTy };
  315. llvm::FunctionType *FTy =
  316. llvm::FunctionType::get(ObjectPtrTy, args, false);
  317. return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
  318. }
  319. /// GcMemmoveCollectableFn -- LLVM objc_memmove_collectable function.
  320. llvm::Constant *GcMemmoveCollectableFn() {
  321. // void *objc_memmove_collectable(void *dst, const void *src, size_t size)
  322. llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, LongTy };
  323. llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, args, false);
  324. return CGM.CreateRuntimeFunction(FTy, "objc_memmove_collectable");
  325. }
  326. /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
  327. llvm::Constant *getGcAssignStrongCastFn() {
  328. // id objc_assign_strongCast(id, id *)
  329. llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
  330. llvm::FunctionType *FTy =
  331. llvm::FunctionType::get(ObjectPtrTy, args, false);
  332. return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
  333. }
  334. /// ExceptionThrowFn - LLVM objc_exception_throw function.
  335. llvm::Constant *getExceptionThrowFn() {
  336. // void objc_exception_throw(id)
  337. llvm::Type *args[] = { ObjectPtrTy };
  338. llvm::FunctionType *FTy =
  339. llvm::FunctionType::get(CGM.VoidTy, args, false);
  340. return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
  341. }
  342. /// ExceptionRethrowFn - LLVM objc_exception_rethrow function.
  343. llvm::Constant *getExceptionRethrowFn() {
  344. // void objc_exception_rethrow(void)
  345. llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, false);
  346. return CGM.CreateRuntimeFunction(FTy, "objc_exception_rethrow");
  347. }
  348. /// SyncEnterFn - LLVM object_sync_enter function.
  349. llvm::Constant *getSyncEnterFn() {
  350. // void objc_sync_enter (id)
  351. llvm::Type *args[] = { ObjectPtrTy };
  352. llvm::FunctionType *FTy =
  353. llvm::FunctionType::get(CGM.VoidTy, args, false);
  354. return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
  355. }
  356. /// SyncExitFn - LLVM object_sync_exit function.
  357. llvm::Constant *getSyncExitFn() {
  358. // void objc_sync_exit (id)
  359. llvm::Type *args[] = { ObjectPtrTy };
  360. llvm::FunctionType *FTy =
  361. llvm::FunctionType::get(CGM.VoidTy, args, false);
  362. return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
  363. }
  364. llvm::Constant *getSendFn(bool IsSuper) const {
  365. return IsSuper ? getMessageSendSuperFn() : getMessageSendFn();
  366. }
  367. llvm::Constant *getSendFn2(bool IsSuper) const {
  368. return IsSuper ? getMessageSendSuperFn2() : getMessageSendFn();
  369. }
  370. llvm::Constant *getSendStretFn(bool IsSuper) const {
  371. return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn();
  372. }
  373. llvm::Constant *getSendStretFn2(bool IsSuper) const {
  374. return IsSuper ? getMessageSendSuperStretFn2() : getMessageSendStretFn();
  375. }
  376. llvm::Constant *getSendFpretFn(bool IsSuper) const {
  377. return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn();
  378. }
  379. llvm::Constant *getSendFpretFn2(bool IsSuper) const {
  380. return IsSuper ? getMessageSendSuperFpretFn2() : getMessageSendFpretFn();
  381. }
  382. llvm::Constant *getSendFp2retFn(bool IsSuper) const {
  383. return IsSuper ? getMessageSendSuperFn() : getMessageSendFp2retFn();
  384. }
  385. llvm::Constant *getSendFp2RetFn2(bool IsSuper) const {
  386. return IsSuper ? getMessageSendSuperFn2() : getMessageSendFp2retFn();
  387. }
  388. ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
  389. ~ObjCCommonTypesHelper(){}
  390. };
  391. /// ObjCTypesHelper - Helper class that encapsulates lazy
  392. /// construction of varies types used during ObjC generation.
  393. class ObjCTypesHelper : public ObjCCommonTypesHelper {
  394. public:
  395. /// SymtabTy - LLVM type for struct objc_symtab.
  396. llvm::StructType *SymtabTy;
  397. /// SymtabPtrTy - LLVM type for struct objc_symtab *.
  398. llvm::Type *SymtabPtrTy;
  399. /// ModuleTy - LLVM type for struct objc_module.
  400. llvm::StructType *ModuleTy;
  401. /// ProtocolTy - LLVM type for struct objc_protocol.
  402. llvm::StructType *ProtocolTy;
  403. /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
  404. llvm::Type *ProtocolPtrTy;
  405. /// ProtocolExtensionTy - LLVM type for struct
  406. /// objc_protocol_extension.
  407. llvm::StructType *ProtocolExtensionTy;
  408. /// ProtocolExtensionTy - LLVM type for struct
  409. /// objc_protocol_extension *.
  410. llvm::Type *ProtocolExtensionPtrTy;
  411. /// MethodDescriptionTy - LLVM type for struct
  412. /// objc_method_description.
  413. llvm::StructType *MethodDescriptionTy;
  414. /// MethodDescriptionListTy - LLVM type for struct
  415. /// objc_method_description_list.
  416. llvm::StructType *MethodDescriptionListTy;
  417. /// MethodDescriptionListPtrTy - LLVM type for struct
  418. /// objc_method_description_list *.
  419. llvm::Type *MethodDescriptionListPtrTy;
  420. /// ProtocolListTy - LLVM type for struct objc_property_list.
  421. llvm::StructType *ProtocolListTy;
  422. /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
  423. llvm::Type *ProtocolListPtrTy;
  424. /// CategoryTy - LLVM type for struct objc_category.
  425. llvm::StructType *CategoryTy;
  426. /// ClassTy - LLVM type for struct objc_class.
  427. llvm::StructType *ClassTy;
  428. /// ClassPtrTy - LLVM type for struct objc_class *.
  429. llvm::Type *ClassPtrTy;
  430. /// ClassExtensionTy - LLVM type for struct objc_class_ext.
  431. llvm::StructType *ClassExtensionTy;
  432. /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
  433. llvm::Type *ClassExtensionPtrTy;
  434. // IvarTy - LLVM type for struct objc_ivar.
  435. llvm::StructType *IvarTy;
  436. /// IvarListTy - LLVM type for struct objc_ivar_list.
  437. llvm::Type *IvarListTy;
  438. /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
  439. llvm::Type *IvarListPtrTy;
  440. /// MethodListTy - LLVM type for struct objc_method_list.
  441. llvm::Type *MethodListTy;
  442. /// MethodListPtrTy - LLVM type for struct objc_method_list *.
  443. llvm::Type *MethodListPtrTy;
  444. /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
  445. llvm::Type *ExceptionDataTy;
  446. /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
  447. llvm::Constant *getExceptionTryEnterFn() {
  448. llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
  449. return CGM.CreateRuntimeFunction(
  450. llvm::FunctionType::get(CGM.VoidTy, params, false),
  451. "objc_exception_try_enter");
  452. }
  453. /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
  454. llvm::Constant *getExceptionTryExitFn() {
  455. llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
  456. return CGM.CreateRuntimeFunction(
  457. llvm::FunctionType::get(CGM.VoidTy, params, false),
  458. "objc_exception_try_exit");
  459. }
  460. /// ExceptionExtractFn - LLVM objc_exception_extract function.
  461. llvm::Constant *getExceptionExtractFn() {
  462. llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
  463. return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
  464. params, false),
  465. "objc_exception_extract");
  466. }
  467. /// ExceptionMatchFn - LLVM objc_exception_match function.
  468. llvm::Constant *getExceptionMatchFn() {
  469. llvm::Type *params[] = { ClassPtrTy, ObjectPtrTy };
  470. return CGM.CreateRuntimeFunction(
  471. llvm::FunctionType::get(CGM.Int32Ty, params, false),
  472. "objc_exception_match");
  473. }
  474. /// SetJmpFn - LLVM _setjmp function.
  475. llvm::Constant *getSetJmpFn() {
  476. // This is specifically the prototype for x86.
  477. llvm::Type *params[] = { CGM.Int32Ty->getPointerTo() };
  478. return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty,
  479. params, false),
  480. "_setjmp",
  481. llvm::Attribute::ReturnsTwice);
  482. }
  483. public:
  484. ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
  485. ~ObjCTypesHelper() {}
  486. };
  487. /// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
  488. /// modern abi
  489. class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
  490. public:
  491. // MethodListnfABITy - LLVM for struct _method_list_t
  492. llvm::StructType *MethodListnfABITy;
  493. // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
  494. llvm::Type *MethodListnfABIPtrTy;
  495. // ProtocolnfABITy = LLVM for struct _protocol_t
  496. llvm::StructType *ProtocolnfABITy;
  497. // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
  498. llvm::Type *ProtocolnfABIPtrTy;
  499. // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
  500. llvm::StructType *ProtocolListnfABITy;
  501. // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
  502. llvm::Type *ProtocolListnfABIPtrTy;
  503. // ClassnfABITy - LLVM for struct _class_t
  504. llvm::StructType *ClassnfABITy;
  505. // ClassnfABIPtrTy - LLVM for struct _class_t*
  506. llvm::Type *ClassnfABIPtrTy;
  507. // IvarnfABITy - LLVM for struct _ivar_t
  508. llvm::StructType *IvarnfABITy;
  509. // IvarListnfABITy - LLVM for struct _ivar_list_t
  510. llvm::StructType *IvarListnfABITy;
  511. // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
  512. llvm::Type *IvarListnfABIPtrTy;
  513. // ClassRonfABITy - LLVM for struct _class_ro_t
  514. llvm::StructType *ClassRonfABITy;
  515. // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
  516. llvm::Type *ImpnfABITy;
  517. // CategorynfABITy - LLVM for struct _category_t
  518. llvm::StructType *CategorynfABITy;
  519. // New types for nonfragile abi messaging.
  520. // MessageRefTy - LLVM for:
  521. // struct _message_ref_t {
  522. // IMP messenger;
  523. // SEL name;
  524. // };
  525. llvm::StructType *MessageRefTy;
  526. // MessageRefCTy - clang type for struct _message_ref_t
  527. QualType MessageRefCTy;
  528. // MessageRefPtrTy - LLVM for struct _message_ref_t*
  529. llvm::Type *MessageRefPtrTy;
  530. // MessageRefCPtrTy - clang type for struct _message_ref_t*
  531. QualType MessageRefCPtrTy;
  532. // MessengerTy - Type of the messenger (shown as IMP above)
  533. llvm::FunctionType *MessengerTy;
  534. // SuperMessageRefTy - LLVM for:
  535. // struct _super_message_ref_t {
  536. // SUPER_IMP messenger;
  537. // SEL name;
  538. // };
  539. llvm::StructType *SuperMessageRefTy;
  540. // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
  541. llvm::Type *SuperMessageRefPtrTy;
  542. llvm::Constant *getMessageSendFixupFn() {
  543. // id objc_msgSend_fixup(id, struct message_ref_t*, ...)
  544. llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
  545. return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
  546. params, true),
  547. "objc_msgSend_fixup");
  548. }
  549. llvm::Constant *getMessageSendFpretFixupFn() {
  550. // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...)
  551. llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
  552. return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
  553. params, true),
  554. "objc_msgSend_fpret_fixup");
  555. }
  556. llvm::Constant *getMessageSendStretFixupFn() {
  557. // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...)
  558. llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
  559. return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
  560. params, true),
  561. "objc_msgSend_stret_fixup");
  562. }
  563. llvm::Constant *getMessageSendSuper2FixupFn() {
  564. // id objc_msgSendSuper2_fixup (struct objc_super *,
  565. // struct _super_message_ref_t*, ...)
  566. llvm::Type *params[] = { SuperPtrTy, SuperMessageRefPtrTy };
  567. return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
  568. params, true),
  569. "objc_msgSendSuper2_fixup");
  570. }
  571. llvm::Constant *getMessageSendSuper2StretFixupFn() {
  572. // id objc_msgSendSuper2_stret_fixup(struct objc_super *,
  573. // struct _super_message_ref_t*, ...)
  574. llvm::Type *params[] = { SuperPtrTy, SuperMessageRefPtrTy };
  575. return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
  576. params, true),
  577. "objc_msgSendSuper2_stret_fixup");
  578. }
  579. llvm::Constant *getObjCEndCatchFn() {
  580. return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.VoidTy, false),
  581. "objc_end_catch");
  582. }
  583. llvm::Constant *getObjCBeginCatchFn() {
  584. llvm::Type *params[] = { Int8PtrTy };
  585. return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
  586. params, false),
  587. "objc_begin_catch");
  588. }
  589. llvm::StructType *EHTypeTy;
  590. llvm::Type *EHTypePtrTy;
  591. ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
  592. ~ObjCNonFragileABITypesHelper(){}
  593. };
  594. class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
  595. public:
  596. // FIXME - accessibility
  597. class GC_IVAR {
  598. public:
  599. unsigned ivar_bytepos;
  600. unsigned ivar_size;
  601. GC_IVAR(unsigned bytepos = 0, unsigned size = 0)
  602. : ivar_bytepos(bytepos), ivar_size(size) {}
  603. // Allow sorting based on byte pos.
  604. bool operator<(const GC_IVAR &b) const {
  605. return ivar_bytepos < b.ivar_bytepos;
  606. }
  607. };
  608. class SKIP_SCAN {
  609. public:
  610. unsigned skip;
  611. unsigned scan;
  612. SKIP_SCAN(unsigned _skip = 0, unsigned _scan = 0)
  613. : skip(_skip), scan(_scan) {}
  614. };
  615. protected:
  616. llvm::LLVMContext &VMContext;
  617. // FIXME! May not be needing this after all.
  618. unsigned ObjCABI;
  619. // gc ivar layout bitmap calculation helper caches.
  620. SmallVector<GC_IVAR, 16> SkipIvars;
  621. SmallVector<GC_IVAR, 16> IvarsInfo;
  622. /// LazySymbols - Symbols to generate a lazy reference for. See
  623. /// DefinedSymbols and FinishModule().
  624. llvm::SetVector<IdentifierInfo*> LazySymbols;
  625. /// DefinedSymbols - External symbols which are defined by this
  626. /// module. The symbols in this list and LazySymbols are used to add
  627. /// special linker symbols which ensure that Objective-C modules are
  628. /// linked properly.
  629. llvm::SetVector<IdentifierInfo*> DefinedSymbols;
  630. /// ClassNames - uniqued class names.
  631. llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
  632. /// MethodVarNames - uniqued method variable names.
  633. llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
  634. /// DefinedCategoryNames - list of category names in form Class_Category.
  635. llvm::SetVector<std::string> DefinedCategoryNames;
  636. /// MethodVarTypes - uniqued method type signatures. We have to use
  637. /// a StringMap here because have no other unique reference.
  638. llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
  639. /// MethodDefinitions - map of methods which have been defined in
  640. /// this translation unit.
  641. llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
  642. /// PropertyNames - uniqued method variable names.
  643. llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
  644. /// ClassReferences - uniqued class references.
  645. llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
  646. /// SelectorReferences - uniqued selector references.
  647. llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
  648. /// Protocols - Protocols for which an objc_protocol structure has
  649. /// been emitted. Forward declarations are handled by creating an
  650. /// empty structure whose initializer is filled in when/if defined.
  651. llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
  652. /// DefinedProtocols - Protocols which have actually been
  653. /// defined. We should not need this, see FIXME in GenerateProtocol.
  654. llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
  655. /// DefinedClasses - List of defined classes.
  656. llvm::SmallVector<llvm::GlobalValue*, 16> DefinedClasses;
  657. /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
  658. llvm::SmallVector<llvm::GlobalValue*, 16> DefinedNonLazyClasses;
  659. /// DefinedCategories - List of defined categories.
  660. llvm::SmallVector<llvm::GlobalValue*, 16> DefinedCategories;
  661. /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
  662. llvm::SmallVector<llvm::GlobalValue*, 16> DefinedNonLazyCategories;
  663. /// GetNameForMethod - Return a name for the given method.
  664. /// \param[out] NameOut - The return value.
  665. void GetNameForMethod(const ObjCMethodDecl *OMD,
  666. const ObjCContainerDecl *CD,
  667. SmallVectorImpl<char> &NameOut);
  668. /// GetMethodVarName - Return a unique constant for the given
  669. /// selector's name. The return value has type char *.
  670. llvm::Constant *GetMethodVarName(Selector Sel);
  671. llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
  672. /// GetMethodVarType - Return a unique constant for the given
  673. /// method's type encoding string. The return value has type char *.
  674. // FIXME: This is a horrible name.
  675. llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D,
  676. bool Extended = false);
  677. llvm::Constant *GetMethodVarType(const FieldDecl *D);
  678. /// GetPropertyName - Return a unique constant for the given
  679. /// name. The return value has type char *.
  680. llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
  681. // FIXME: This can be dropped once string functions are unified.
  682. llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
  683. const Decl *Container);
  684. /// GetClassName - Return a unique constant for the given selector's
  685. /// name. The return value has type char *.
  686. llvm::Constant *GetClassName(IdentifierInfo *Ident);
  687. llvm::Function *GetMethodDefinition(const ObjCMethodDecl *MD);
  688. /// BuildIvarLayout - Builds ivar layout bitmap for the class
  689. /// implementation for the __strong or __weak case.
  690. ///
  691. llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
  692. bool ForStrongLayout);
  693. llvm::Constant *BuildIvarLayoutBitmap(std::string &BitMap);
  694. void BuildAggrIvarRecordLayout(const RecordType *RT,
  695. unsigned int BytePos, bool ForStrongLayout,
  696. bool &HasUnion);
  697. void BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
  698. const llvm::StructLayout *Layout,
  699. const RecordDecl *RD,
  700. const SmallVectorImpl<const FieldDecl*> &RecFields,
  701. unsigned int BytePos, bool ForStrongLayout,
  702. bool &HasUnion);
  703. /// GetIvarLayoutName - Returns a unique constant for the given
  704. /// ivar layout bitmap.
  705. llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
  706. const ObjCCommonTypesHelper &ObjCTypes);
  707. /// EmitPropertyList - Emit the given property list. The return
  708. /// value has type PropertyListPtrTy.
  709. llvm::Constant *EmitPropertyList(Twine Name,
  710. const Decl *Container,
  711. const ObjCContainerDecl *OCD,
  712. const ObjCCommonTypesHelper &ObjCTypes);
  713. /// EmitProtocolMethodTypes - Generate the array of extended method type
  714. /// strings. The return value has type Int8PtrPtrTy.
  715. llvm::Constant *EmitProtocolMethodTypes(Twine Name,
  716. ArrayRef<llvm::Constant*> MethodTypes,
  717. const ObjCCommonTypesHelper &ObjCTypes);
  718. /// PushProtocolProperties - Push protocol's property on the input stack.
  719. void PushProtocolProperties(
  720. llvm::SmallPtrSet<const IdentifierInfo*, 16> &PropertySet,
  721. llvm::SmallVectorImpl<llvm::Constant*> &Properties,
  722. const Decl *Container,
  723. const ObjCProtocolDecl *PROTO,
  724. const ObjCCommonTypesHelper &ObjCTypes);
  725. /// GetProtocolRef - Return a reference to the internal protocol
  726. /// description, creating an empty one if it has not been
  727. /// defined. The return value has type ProtocolPtrTy.
  728. llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
  729. /// CreateMetadataVar - Create a global variable with internal
  730. /// linkage for use by the Objective-C runtime.
  731. ///
  732. /// This is a convenience wrapper which not only creates the
  733. /// variable, but also sets the section and alignment and adds the
  734. /// global to the "llvm.used" list.
  735. ///
  736. /// \param Name - The variable name.
  737. /// \param Init - The variable initializer; this is also used to
  738. /// define the type of the variable.
  739. /// \param Section - The section the variable should go into, or 0.
  740. /// \param Align - The alignment for the variable, or 0.
  741. /// \param AddToUsed - Whether the variable should be added to
  742. /// "llvm.used".
  743. llvm::GlobalVariable *CreateMetadataVar(Twine Name,
  744. llvm::Constant *Init,
  745. const char *Section,
  746. unsigned Align,
  747. bool AddToUsed);
  748. CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
  749. ReturnValueSlot Return,
  750. QualType ResultType,
  751. llvm::Value *Sel,
  752. llvm::Value *Arg0,
  753. QualType Arg0Ty,
  754. bool IsSuper,
  755. const CallArgList &CallArgs,
  756. const ObjCMethodDecl *OMD,
  757. const ObjCCommonTypesHelper &ObjCTypes);
  758. /// EmitImageInfo - Emit the image info marker used to encode some module
  759. /// level information.
  760. void EmitImageInfo();
  761. public:
  762. CGObjCCommonMac(CodeGen::CodeGenModule &cgm) :
  763. CGObjCRuntime(cgm), VMContext(cgm.getLLVMContext()) { }
  764. virtual llvm::Constant *GenerateConstantString(const StringLiteral *SL);
  765. virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
  766. const ObjCContainerDecl *CD=0);
  767. virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
  768. /// GetOrEmitProtocol - Get the protocol object for the given
  769. /// declaration, emitting it if necessary. The return value has type
  770. /// ProtocolPtrTy.
  771. virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
  772. /// GetOrEmitProtocolRef - Get a forward reference to the protocol
  773. /// object for the given declaration, emitting it if needed. These
  774. /// forward references will be filled in with empty bodies if no
  775. /// definition is seen. The return value has type ProtocolPtrTy.
  776. virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
  777. virtual llvm::Constant *BuildGCBlockLayout(CodeGen::CodeGenModule &CGM,
  778. const CGBlockInfo &blockInfo);
  779. };
  780. class CGObjCMac : public CGObjCCommonMac {
  781. private:
  782. ObjCTypesHelper ObjCTypes;
  783. /// EmitModuleInfo - Another marker encoding module level
  784. /// information.
  785. void EmitModuleInfo();
  786. /// EmitModuleSymols - Emit module symbols, the list of defined
  787. /// classes and categories. The result has type SymtabPtrTy.
  788. llvm::Constant *EmitModuleSymbols();
  789. /// FinishModule - Write out global data structures at the end of
  790. /// processing a translation unit.
  791. void FinishModule();
  792. /// EmitClassExtension - Generate the class extension structure used
  793. /// to store the weak ivar layout and properties. The return value
  794. /// has type ClassExtensionPtrTy.
  795. llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
  796. /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
  797. /// for the given class.
  798. llvm::Value *EmitClassRef(CGBuilderTy &Builder,
  799. const ObjCInterfaceDecl *ID);
  800. llvm::Value *EmitClassRefFromId(CGBuilderTy &Builder,
  801. IdentifierInfo *II);
  802. llvm::Value *EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder);
  803. /// EmitSuperClassRef - Emits reference to class's main metadata class.
  804. llvm::Value *EmitSuperClassRef(const ObjCInterfaceDecl *ID);
  805. /// EmitIvarList - Emit the ivar list for the given
  806. /// implementation. If ForClass is true the list of class ivars
  807. /// (i.e. metaclass ivars) is emitted, otherwise the list of
  808. /// interface ivars will be emitted. The return value has type
  809. /// IvarListPtrTy.
  810. llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
  811. bool ForClass);
  812. /// EmitMetaClass - Emit a forward reference to the class structure
  813. /// for the metaclass of the given interface. The return value has
  814. /// type ClassPtrTy.
  815. llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
  816. /// EmitMetaClass - Emit a class structure for the metaclass of the
  817. /// given implementation. The return value has type ClassPtrTy.
  818. llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
  819. llvm::Constant *Protocols,
  820. ArrayRef<llvm::Constant*> Methods);
  821. llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
  822. llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
  823. /// EmitMethodList - Emit the method list for the given
  824. /// implementation. The return value has type MethodListPtrTy.
  825. llvm::Constant *EmitMethodList(Twine Name,
  826. const char *Section,
  827. ArrayRef<llvm::Constant*> Methods);
  828. /// EmitMethodDescList - Emit a method description list for a list of
  829. /// method declarations.
  830. /// - TypeName: The name for the type containing the methods.
  831. /// - IsProtocol: True iff these methods are for a protocol.
  832. /// - ClassMethds: True iff these are class methods.
  833. /// - Required: When true, only "required" methods are
  834. /// listed. Similarly, when false only "optional" methods are
  835. /// listed. For classes this should always be true.
  836. /// - begin, end: The method list to output.
  837. ///
  838. /// The return value has type MethodDescriptionListPtrTy.
  839. llvm::Constant *EmitMethodDescList(Twine Name,
  840. const char *Section,
  841. ArrayRef<llvm::Constant*> Methods);
  842. /// GetOrEmitProtocol - Get the protocol object for the given
  843. /// declaration, emitting it if necessary. The return value has type
  844. /// ProtocolPtrTy.
  845. virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
  846. /// GetOrEmitProtocolRef - Get a forward reference to the protocol
  847. /// object for the given declaration, emitting it if needed. These
  848. /// forward references will be filled in with empty bodies if no
  849. /// definition is seen. The return value has type ProtocolPtrTy.
  850. virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
  851. /// EmitProtocolExtension - Generate the protocol extension
  852. /// structure used to store optional instance and class methods, and
  853. /// protocol properties. The return value has type
  854. /// ProtocolExtensionPtrTy.
  855. llvm::Constant *
  856. EmitProtocolExtension(const ObjCProtocolDecl *PD,
  857. ArrayRef<llvm::Constant*> OptInstanceMethods,
  858. ArrayRef<llvm::Constant*> OptClassMethods,
  859. ArrayRef<llvm::Constant*> MethodTypesExt);
  860. /// EmitProtocolList - Generate the list of referenced
  861. /// protocols. The return value has type ProtocolListPtrTy.
  862. llvm::Constant *EmitProtocolList(Twine Name,
  863. ObjCProtocolDecl::protocol_iterator begin,
  864. ObjCProtocolDecl::protocol_iterator end);
  865. /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
  866. /// for the given selector.
  867. llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel,
  868. bool lval=false);
  869. public:
  870. CGObjCMac(CodeGen::CodeGenModule &cgm);
  871. virtual llvm::Function *ModuleInitFunction();
  872. virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
  873. ReturnValueSlot Return,
  874. QualType ResultType,
  875. Selector Sel,
  876. llvm::Value *Receiver,
  877. const CallArgList &CallArgs,
  878. const ObjCInterfaceDecl *Class,
  879. const ObjCMethodDecl *Method);
  880. virtual CodeGen::RValue
  881. GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
  882. ReturnValueSlot Return,
  883. QualType ResultType,
  884. Selector Sel,
  885. const ObjCInterfaceDecl *Class,
  886. bool isCategoryImpl,
  887. llvm::Value *Receiver,
  888. bool IsClassMessage,
  889. const CallArgList &CallArgs,
  890. const ObjCMethodDecl *Method);
  891. virtual llvm::Value *GetClass(CGBuilderTy &Builder,
  892. const ObjCInterfaceDecl *ID);
  893. virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
  894. bool lval = false);
  895. /// The NeXT/Apple runtimes do not support typed selectors; just emit an
  896. /// untyped one.
  897. virtual llvm::Value *GetSelector(CGBuilderTy &Builder,
  898. const ObjCMethodDecl *Method);
  899. virtual llvm::Constant *GetEHType(QualType T);
  900. virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
  901. virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
  902. virtual void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {};
  903. virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
  904. const ObjCProtocolDecl *PD);
  905. virtual llvm::Constant *GetPropertyGetFunction();
  906. virtual llvm::Constant *GetPropertySetFunction();
  907. virtual llvm::Constant *GetGetStructFunction();
  908. virtual llvm::Constant *GetSetStructFunction();
  909. virtual llvm::Constant *GetCppAtomicObjectFunction();
  910. virtual llvm::Constant *EnumerationMutationFunction();
  911. virtual void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
  912. const ObjCAtTryStmt &S);
  913. virtual void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
  914. const ObjCAtSynchronizedStmt &S);
  915. void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, const Stmt &S);
  916. virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
  917. const ObjCAtThrowStmt &S);
  918. virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
  919. llvm::Value *AddrWeakObj);
  920. virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
  921. llvm::Value *src, llvm::Value *dst);
  922. virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
  923. llvm::Value *src, llvm::Value *dest,
  924. bool threadlocal = false);
  925. virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
  926. llvm::Value *src, llvm::Value *dest,
  927. llvm::Value *ivarOffset);
  928. virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
  929. llvm::Value *src, llvm::Value *dest);
  930. virtual void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
  931. llvm::Value *dest, llvm::Value *src,
  932. llvm::Value *size);
  933. virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
  934. QualType ObjectTy,
  935. llvm::Value *BaseValue,
  936. const ObjCIvarDecl *Ivar,
  937. unsigned CVRQualifiers);
  938. virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
  939. const ObjCInterfaceDecl *Interface,
  940. const ObjCIvarDecl *Ivar);
  941. /// GetClassGlobal - Return the global variable for the Objective-C
  942. /// class of the given name.
  943. virtual llvm::GlobalVariable *GetClassGlobal(const std::string &Name) {
  944. llvm_unreachable("CGObjCMac::GetClassGlobal");
  945. }
  946. };
  947. class CGObjCNonFragileABIMac : public CGObjCCommonMac {
  948. private:
  949. ObjCNonFragileABITypesHelper ObjCTypes;
  950. llvm::GlobalVariable* ObjCEmptyCacheVar;
  951. llvm::GlobalVariable* ObjCEmptyVtableVar;
  952. /// SuperClassReferences - uniqued super class references.
  953. llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
  954. /// MetaClassReferences - uniqued meta class references.
  955. llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
  956. /// EHTypeReferences - uniqued class ehtype references.
  957. llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
  958. /// VTableDispatchMethods - List of methods for which we generate
  959. /// vtable-based message dispatch.
  960. llvm::DenseSet<Selector> VTableDispatchMethods;
  961. /// DefinedMetaClasses - List of defined meta-classes.
  962. std::vector<llvm::GlobalValue*> DefinedMetaClasses;
  963. /// isVTableDispatchedSelector - Returns true if SEL is a
  964. /// vtable-based selector.
  965. bool isVTableDispatchedSelector(Selector Sel);
  966. /// FinishNonFragileABIModule - Write out global data structures at the end of
  967. /// processing a translation unit.
  968. void FinishNonFragileABIModule();
  969. /// AddModuleClassList - Add the given list of class pointers to the
  970. /// module with the provided symbol and section names.
  971. void AddModuleClassList(ArrayRef<llvm::GlobalValue*> Container,
  972. const char *SymbolName,
  973. const char *SectionName);
  974. llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
  975. unsigned InstanceStart,
  976. unsigned InstanceSize,
  977. const ObjCImplementationDecl *ID);
  978. llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
  979. llvm::Constant *IsAGV,
  980. llvm::Constant *SuperClassGV,
  981. llvm::Constant *ClassRoGV,
  982. bool HiddenVisibility);
  983. llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
  984. llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
  985. /// EmitMethodList - Emit the method list for the given
  986. /// implementation. The return value has type MethodListnfABITy.
  987. llvm::Constant *EmitMethodList(Twine Name,
  988. const char *Section,
  989. ArrayRef<llvm::Constant*> Methods);
  990. /// EmitIvarList - Emit the ivar list for the given
  991. /// implementation. If ForClass is true the list of class ivars
  992. /// (i.e. metaclass ivars) is emitted, otherwise the list of
  993. /// interface ivars will be emitted. The return value has type
  994. /// IvarListnfABIPtrTy.
  995. llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
  996. llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
  997. const ObjCIvarDecl *Ivar,
  998. unsigned long int offset);
  999. /// GetOrEmitProtocol - Get the protocol object for the given
  1000. /// declaration, emitting it if necessary. The return value has type
  1001. /// ProtocolPtrTy.
  1002. virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
  1003. /// GetOrEmitProtocolRef - Get a forward reference to the protocol
  1004. /// object for the given declaration, emitting it if needed. These
  1005. /// forward references will be filled in with empty bodies if no
  1006. /// definition is seen. The return value has type ProtocolPtrTy.
  1007. virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
  1008. /// EmitProtocolList - Generate the list of referenced
  1009. /// protocols. The return value has type ProtocolListPtrTy.
  1010. llvm::Constant *EmitProtocolList(Twine Name,
  1011. ObjCProtocolDecl::protocol_iterator begin,
  1012. ObjCProtocolDecl::protocol_iterator end);
  1013. CodeGen::RValue EmitVTableMessageSend(CodeGen::CodeGenFunction &CGF,
  1014. ReturnValueSlot Return,
  1015. QualType ResultType,
  1016. Selector Sel,
  1017. llvm::Value *Receiver,
  1018. QualType Arg0Ty,
  1019. bool IsSuper,
  1020. const CallArgList &CallArgs,
  1021. const ObjCMethodDecl *Method);
  1022. /// GetClassGlobal - Return the global variable for the Objective-C
  1023. /// class of the given name.
  1024. llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
  1025. /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
  1026. /// for the given class reference.
  1027. llvm::Value *EmitClassRef(CGBuilderTy &Builder,
  1028. const ObjCInterfaceDecl *ID);
  1029. llvm::Value *EmitClassRefFromId(CGBuilderTy &Builder,
  1030. IdentifierInfo *II);
  1031. llvm::Value *EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder);
  1032. /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
  1033. /// for the given super class reference.
  1034. llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
  1035. const ObjCInterfaceDecl *ID);
  1036. /// EmitMetaClassRef - Return a Value * of the address of _class_t
  1037. /// meta-data
  1038. llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
  1039. const ObjCInterfaceDecl *ID);
  1040. /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
  1041. /// the given ivar.
  1042. ///
  1043. llvm::GlobalVariable * ObjCIvarOffsetVariable(
  1044. const ObjCInterfaceDecl *ID,
  1045. const ObjCIvarDecl *Ivar);
  1046. /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
  1047. /// for the given selector.
  1048. llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel,
  1049. bool lval=false);
  1050. /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
  1051. /// interface. The return value has type EHTypePtrTy.
  1052. llvm::Constant *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
  1053. bool ForDefinition);
  1054. const char *getMetaclassSymbolPrefix() const {
  1055. return "OBJC_METACLASS_$_";
  1056. }
  1057. const char *getClassSymbolPrefix() const {
  1058. return "OBJC_CLASS_$_";
  1059. }
  1060. void GetClassSizeInfo(const ObjCImplementationDecl *OID,
  1061. uint32_t &InstanceStart,
  1062. uint32_t &InstanceSize);
  1063. // Shamelessly stolen from Analysis/CFRefCount.cpp
  1064. Selector GetNullarySelector(const char* name) const {
  1065. IdentifierInfo* II = &CGM.getContext().Idents.get(name);
  1066. return CGM.getContext().Selectors.getSelector(0, &II);
  1067. }
  1068. Selector GetUnarySelector(const char* name) const {
  1069. IdentifierInfo* II = &CGM.getContext().Idents.get(name);
  1070. return CGM.getContext().Selectors.getSelector(1, &II);
  1071. }
  1072. /// ImplementationIsNonLazy - Check whether the given category or
  1073. /// class implementation is "non-lazy".
  1074. bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const;
  1075. public:
  1076. CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
  1077. // FIXME. All stubs for now!
  1078. virtual llvm::Function *ModuleInitFunction();
  1079. virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
  1080. ReturnValueSlot Return,
  1081. QualType ResultType,
  1082. Selector Sel,
  1083. llvm::Value *Receiver,
  1084. const CallArgList &CallArgs,
  1085. const ObjCInterfaceDecl *Class,
  1086. const ObjCMethodDecl *Method);
  1087. virtual CodeGen::RValue
  1088. GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
  1089. ReturnValueSlot Return,
  1090. QualType ResultType,
  1091. Selector Sel,
  1092. const ObjCInterfaceDecl *Class,
  1093. bool isCategoryImpl,
  1094. llvm::Value *Receiver,
  1095. bool IsClassMessage,
  1096. const CallArgList &CallArgs,
  1097. const ObjCMethodDecl *Method);
  1098. virtual llvm::Value *GetClass(CGBuilderTy &Builder,
  1099. const ObjCInterfaceDecl *ID);
  1100. virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
  1101. bool lvalue = false)
  1102. { return EmitSelector(Builder, Sel, lvalue); }
  1103. /// The NeXT/Apple runtimes do not support typed selectors; just emit an
  1104. /// untyped one.
  1105. virtual llvm::Value *GetSelector(CGBuilderTy &Builder,
  1106. const ObjCMethodDecl *Method)
  1107. { return EmitSelector(Builder, Method->getSelector()); }
  1108. virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
  1109. virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
  1110. virtual void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {};
  1111. virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
  1112. const ObjCProtocolDecl *PD);
  1113. virtual llvm::Constant *GetEHType(QualType T);
  1114. virtual llvm::Constant *GetPropertyGetFunction() {
  1115. return ObjCTypes.getGetPropertyFn();
  1116. }
  1117. virtual llvm::Constant *GetPropertySetFunction() {
  1118. return ObjCTypes.getSetPropertyFn();
  1119. }
  1120. virtual llvm::Constant *GetSetStructFunction() {
  1121. return ObjCTypes.getCopyStructFn();
  1122. }
  1123. virtual llvm::Constant *GetGetStructFunction() {
  1124. return ObjCTypes.getCopyStructFn();
  1125. }
  1126. virtual llvm::Constant *GetCppAtomicObjectFunction() {
  1127. return ObjCTypes.getCppAtomicObjectFunction();
  1128. }
  1129. virtual llvm::Constant *EnumerationMutationFunction() {
  1130. return ObjCTypes.getEnumerationMutationFn();
  1131. }
  1132. virtual void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
  1133. const ObjCAtTryStmt &S);
  1134. virtual void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
  1135. const ObjCAtSynchronizedStmt &S);
  1136. virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
  1137. const ObjCAtThrowStmt &S);
  1138. virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
  1139. llvm::Value *AddrWeakObj);
  1140. virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
  1141. llvm::Value *src, llvm::Value *dst);
  1142. virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
  1143. llvm::Value *src, llvm::Value *dest,
  1144. bool threadlocal = false);
  1145. virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
  1146. llvm::Value *src, llvm::Value *dest,
  1147. llvm::Value *ivarOffset);
  1148. virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
  1149. llvm::Value *src, llvm::Value *dest);
  1150. virtual void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
  1151. llvm::Value *dest, llvm::Value *src,
  1152. llvm::Value *size);
  1153. virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
  1154. QualType ObjectTy,
  1155. llvm::Value *BaseValue,
  1156. const ObjCIvarDecl *Ivar,
  1157. unsigned CVRQualifiers);
  1158. virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
  1159. const ObjCInterfaceDecl *Interface,
  1160. const ObjCIvarDecl *Ivar);
  1161. };
  1162. /// A helper class for performing the null-initialization of a return
  1163. /// value.
  1164. struct NullReturnState {
  1165. llvm::BasicBlock *NullBB;
  1166. llvm::BasicBlock *callBB;
  1167. NullReturnState() : NullBB(0), callBB(0) {}
  1168. void init(CodeGenFunction &CGF, llvm::Value *receiver) {
  1169. // Make blocks for the null-init and call edges.
  1170. NullBB = CGF.createBasicBlock("msgSend.nullinit");
  1171. callBB = CGF.createBasicBlock("msgSend.call");
  1172. // Check for a null receiver and, if there is one, jump to the
  1173. // null-init test.
  1174. llvm::Value *isNull = CGF.Builder.CreateIsNull(receiver);
  1175. CGF.Builder.CreateCondBr(isNull, NullBB, callBB);
  1176. // Otherwise, start performing the call.
  1177. CGF.EmitBlock(callBB);
  1178. }
  1179. RValue complete(CodeGenFunction &CGF, RValue result, QualType resultType,
  1180. const CallArgList &CallArgs,
  1181. const ObjCMethodDecl *Method) {
  1182. if (!NullBB) return result;
  1183. llvm::Value *NullInitPtr = 0;
  1184. if (result.isScalar() && !resultType->isVoidType()) {
  1185. NullInitPtr = CGF.CreateTempAlloca(result.getScalarVal()->getType());
  1186. CGF.Builder.CreateStore(result.getScalarVal(), NullInitPtr);
  1187. }
  1188. // Finish the call path.
  1189. llvm::BasicBlock *contBB = CGF.createBasicBlock("msgSend.cont");
  1190. if (CGF.HaveInsertPoint()) CGF.Builder.CreateBr(contBB);
  1191. // Emit the null-init block and perform the null-initialization there.
  1192. CGF.EmitBlock(NullBB);
  1193. // Release consumed arguments along the null-receiver path.
  1194. if (Method) {
  1195. CallArgList::const_iterator I = CallArgs.begin();
  1196. for (ObjCMethodDecl::param_const_iterator i = Method->param_begin(),
  1197. e = Method->param_end(); i != e; ++i, ++I) {
  1198. const ParmVarDecl *ParamDecl = (*i);
  1199. if (ParamDecl->hasAttr<NSConsumedAttr>()) {
  1200. RValue RV = I->RV;
  1201. assert(RV.isScalar() &&
  1202. "NullReturnState::complete - arg not on object");
  1203. CGF.EmitARCRelease(RV.getScalarVal(), true);
  1204. }
  1205. }
  1206. }
  1207. if (result.isScalar()) {
  1208. if (NullInitPtr)
  1209. CGF.EmitNullInitialization(NullInitPtr, resultType);
  1210. // Jump to the continuation block.
  1211. CGF.EmitBlock(contBB);
  1212. return NullInitPtr ? RValue::get(CGF.Builder.CreateLoad(NullInitPtr))
  1213. : result;
  1214. }
  1215. if (!resultType->isAnyComplexType()) {
  1216. assert(result.isAggregate() && "null init of non-aggregate result?");
  1217. CGF.EmitNullInitialization(result.getAggregateAddr(), resultType);
  1218. // Jump to the continuation block.
  1219. CGF.EmitBlock(contBB);
  1220. return result;
  1221. }
  1222. // _Complex type
  1223. // FIXME. Now easy to handle any other scalar type whose result is returned
  1224. // in memory due to ABI limitations.
  1225. CGF.EmitBlock(contBB);
  1226. CodeGenFunction::ComplexPairTy CallCV = result.getComplexVal();
  1227. llvm::Type *MemberType = CallCV.first->getType();
  1228. llvm::Constant *ZeroCV = llvm::Constant::getNullValue(MemberType);
  1229. // Create phi instruction for scalar complex value.
  1230. llvm::PHINode *PHIReal = CGF.Builder.CreatePHI(MemberType, 2);
  1231. PHIReal->addIncoming(ZeroCV, NullBB);
  1232. PHIReal->addIncoming(CallCV.first, callBB);
  1233. llvm::PHINode *PHIImag = CGF.Builder.CreatePHI(MemberType, 2);
  1234. PHIImag->addIncoming(ZeroCV, NullBB);
  1235. PHIImag->addIncoming(CallCV.second, callBB);
  1236. return RValue::getComplex(PHIReal, PHIImag);
  1237. }
  1238. };
  1239. } // end anonymous namespace
  1240. /* *** Helper Functions *** */
  1241. /// getConstantGEP() - Help routine to construct simple GEPs.
  1242. static llvm::Constant *getConstantGEP(llvm::LLVMContext &VMContext,
  1243. llvm::Constant *C,
  1244. unsigned idx0,
  1245. unsigned idx1) {
  1246. llvm::Value *Idxs[] = {
  1247. llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), idx0),
  1248. llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), idx1)
  1249. };
  1250. return llvm::ConstantExpr::getGetElementPtr(C, Idxs);
  1251. }
  1252. /// hasObjCExceptionAttribute - Return true if this class or any super
  1253. /// class has the __objc_exception__ attribute.
  1254. static bool hasObjCExceptionAttribute(ASTContext &Context,
  1255. const ObjCInterfaceDecl *OID) {
  1256. if (OID->hasAttr<ObjCExceptionAttr>())
  1257. return true;
  1258. if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
  1259. return hasObjCExceptionAttribute(Context, Super);
  1260. return false;
  1261. }
  1262. /* *** CGObjCMac Public Interface *** */
  1263. CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
  1264. ObjCTypes(cgm) {
  1265. ObjCABI = 1;
  1266. EmitImageInfo();
  1267. }
  1268. /// GetClass - Return a reference to the class for the given interface
  1269. /// decl.
  1270. llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
  1271. const ObjCInterfaceDecl *ID) {
  1272. return EmitClassRef(Builder, ID);
  1273. }
  1274. /// GetSelector - Return the pointer to the unique'd string for this selector.
  1275. llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel,
  1276. bool lval) {
  1277. return EmitSelector(Builder, Sel, lval);
  1278. }
  1279. llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
  1280. *Method) {
  1281. return EmitSelector(Builder, Method->getSelector());
  1282. }
  1283. llvm::Constant *CGObjCMac::GetEHType(QualType T) {
  1284. if (T->isObjCIdType() ||
  1285. T->isObjCQualifiedIdType()) {
  1286. return CGM.GetAddrOfRTTIDescriptor(
  1287. CGM.getContext().getObjCIdRedefinitionType(), /*ForEH=*/true);
  1288. }
  1289. if (T->isObjCClassType() ||
  1290. T->isObjCQualifiedClassType()) {
  1291. return CGM.GetAddrOfRTTIDescriptor(
  1292. CGM.getContext().getObjCClassRedefinitionType(), /*ForEH=*/true);
  1293. }
  1294. if (T->isObjCObjectPointerType())
  1295. return CGM.GetAddrOfRTTIDescriptor(T, /*ForEH=*/true);
  1296. llvm_unreachable("asking for catch type for ObjC type in fragile runtime");
  1297. }
  1298. /// Generate a constant CFString object.
  1299. /*
  1300. struct __builtin_CFString {
  1301. const int *isa; // point to __CFConstantStringClassReference
  1302. int flags;
  1303. const char *str;
  1304. long length;
  1305. };
  1306. */
  1307. /// or Generate a constant NSString object.
  1308. /*
  1309. struct __builtin_NSString {
  1310. const int *isa; // point to __NSConstantStringClassReference
  1311. const char *str;
  1312. unsigned int length;
  1313. };
  1314. */
  1315. llvm::Constant *CGObjCCommonMac::GenerateConstantString(
  1316. const StringLiteral *SL) {
  1317. return (CGM.getLangOptions().NoConstantCFStrings == 0 ?
  1318. CGM.GetAddrOfConstantCFString(SL) :
  1319. CGM.GetAddrOfConstantString(SL));
  1320. }
  1321. /// Generates a message send where the super is the receiver. This is
  1322. /// a message send to self with special delivery semantics indicating
  1323. /// which class's method should be called.
  1324. CodeGen::RValue
  1325. CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
  1326. ReturnValueSlot Return,
  1327. QualType ResultType,
  1328. Selector Sel,
  1329. const ObjCInterfaceDecl *Class,
  1330. bool isCategoryImpl,
  1331. llvm::Value *Receiver,
  1332. bool IsClassMessage,
  1333. const CodeGen::CallArgList &CallArgs,
  1334. const ObjCMethodDecl *Method) {
  1335. // Create and init a super structure; this is a (receiver, class)
  1336. // pair we will pass to objc_msgSendSuper.
  1337. llvm::Value *ObjCSuper =
  1338. CGF.CreateTempAlloca(ObjCTypes.SuperTy, "objc_super");
  1339. llvm::Value *ReceiverAsObject =
  1340. CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
  1341. CGF.Builder.CreateStore(ReceiverAsObject,
  1342. CGF.Builder.CreateStructGEP(ObjCSuper, 0));
  1343. // If this is a class message the metaclass is passed as the target.
  1344. llvm::Value *Target;
  1345. if (IsClassMessage) {
  1346. if (isCategoryImpl) {
  1347. // Message sent to 'super' in a class method defined in a category
  1348. // implementation requires an odd treatment.
  1349. // If we are in a class method, we must retrieve the
  1350. // _metaclass_ for the current class, pointed at by
  1351. // the class's "isa" pointer. The following assumes that
  1352. // isa" is the first ivar in a class (which it must be).
  1353. Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
  1354. Target = CGF.Builder.CreateStructGEP(Target, 0);
  1355. Target = CGF.Builder.CreateLoad(Target);
  1356. } else {
  1357. llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
  1358. llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
  1359. llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
  1360. Target = Super;
  1361. }
  1362. }
  1363. else if (isCategoryImpl)
  1364. Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
  1365. else {
  1366. llvm::Value *ClassPtr = EmitSuperClassRef(Class);
  1367. ClassPtr = CGF.Builder.CreateStructGEP(ClassPtr, 1);
  1368. Target = CGF.Builder.CreateLoad(ClassPtr);
  1369. }
  1370. // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
  1371. // ObjCTypes types.
  1372. llvm::Type *ClassTy =
  1373. CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
  1374. Target = CGF.Builder.CreateBitCast(Target, ClassTy);
  1375. CGF.Builder.CreateStore(Target,
  1376. CGF.Builder.CreateStructGEP(ObjCSuper, 1));
  1377. return EmitMessageSend(CGF, Return, ResultType,
  1378. EmitSelector(CGF.Builder, Sel),
  1379. ObjCSuper, ObjCTypes.SuperPtrCTy,
  1380. true, CallArgs, Method, ObjCTypes);
  1381. }
  1382. /// Generate code for a message send expression.
  1383. CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
  1384. ReturnValueSlot Return,
  1385. QualType ResultType,
  1386. Selector Sel,
  1387. llvm::Value *Receiver,
  1388. const CallArgList &CallArgs,
  1389. const ObjCInterfaceDecl *Class,
  1390. const ObjCMethodDecl *Method) {
  1391. return EmitMessageSend(CGF, Return, ResultType,
  1392. EmitSelector(CGF.Builder, Sel),
  1393. Receiver, CGF.getContext().getObjCIdType(),
  1394. false, CallArgs, Method, ObjCTypes);
  1395. }
  1396. CodeGen::RValue
  1397. CGObjCCommonMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
  1398. ReturnValueSlot Return,
  1399. QualType ResultType,
  1400. llvm::Value *Sel,
  1401. llvm::Value *Arg0,
  1402. QualType Arg0Ty,
  1403. bool IsSuper,
  1404. const CallArgList &CallArgs,
  1405. const ObjCMethodDecl *Method,
  1406. const ObjCCommonTypesHelper &ObjCTypes) {
  1407. CallArgList ActualArgs;
  1408. if (!IsSuper)
  1409. Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy);
  1410. ActualArgs.add(RValue::get(Arg0), Arg0Ty);
  1411. ActualArgs.add(RValue::get(Sel), CGF.getContext().getObjCSelType());
  1412. ActualArgs.addFrom(CallArgs);
  1413. // If we're calling a method, use the formal signature.
  1414. MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
  1415. if (Method)
  1416. assert(CGM.getContext().getCanonicalType(Method->getResultType()) ==
  1417. CGM.getContext().getCanonicalType(ResultType) &&
  1418. "Result type mismatch!");
  1419. NullReturnState nullReturn;
  1420. llvm::Constant *Fn = NULL;
  1421. if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
  1422. if (!IsSuper) nullReturn.init(CGF, Arg0);
  1423. Fn = (ObjCABI == 2) ? ObjCTypes.getSendStretFn2(IsSuper)
  1424. : ObjCTypes.getSendStretFn(IsSuper);
  1425. } else if (CGM.ReturnTypeUsesFPRet(ResultType)) {
  1426. Fn = (ObjCABI == 2) ? ObjCTypes.getSendFpretFn2(IsSuper)
  1427. : ObjCTypes.getSendFpretFn(IsSuper);
  1428. } else if (CGM.ReturnTypeUsesFP2Ret(ResultType)) {
  1429. Fn = (ObjCABI == 2) ? ObjCTypes.getSendFp2RetFn2(IsSuper)
  1430. : ObjCTypes.getSendFp2retFn(IsSuper);
  1431. } else {
  1432. Fn = (ObjCABI == 2) ? ObjCTypes.getSendFn2(IsSuper)
  1433. : ObjCTypes.getSendFn(IsSuper);
  1434. }
  1435. bool requiresnullCheck = false;
  1436. if (CGM.getLangOptions().ObjCAutoRefCount && Method)
  1437. for (ObjCMethodDecl::param_const_iterator i = Method->param_begin(),
  1438. e = Method->param_end(); i != e; ++i) {
  1439. const ParmVarDecl *ParamDecl = (*i);
  1440. if (ParamDecl->hasAttr<NSConsumedAttr>()) {
  1441. if (!nullReturn.NullBB)
  1442. nullReturn.init(CGF, Arg0);
  1443. requiresnullCheck = true;
  1444. break;
  1445. }
  1446. }
  1447. Fn = llvm::ConstantExpr::getBitCast(Fn, MSI.MessengerType);
  1448. RValue rvalue = CGF.EmitCall(MSI.CallInfo, Fn, Return, ActualArgs);
  1449. return nullReturn.complete(CGF, rvalue, ResultType, CallArgs,
  1450. requiresnullCheck ? Method : 0);
  1451. }
  1452. static Qualifiers::GC GetGCAttrTypeForType(ASTContext &Ctx, QualType FQT) {
  1453. if (FQT.isObjCGCStrong())
  1454. return Qualifiers::Strong;
  1455. if (FQT.isObjCGCWeak() || FQT.getObjCLifetime() == Qualifiers::OCL_Weak)
  1456. return Qualifiers::Weak;
  1457. // check for __unsafe_unretained
  1458. if (FQT.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
  1459. return Qualifiers::GCNone;
  1460. if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType())
  1461. return Qualifiers::Strong;
  1462. if (const PointerType *PT = FQT->getAs<PointerType>())
  1463. return GetGCAttrTypeForType(Ctx, PT->getPointeeType());
  1464. return Qualifiers::GCNone;
  1465. }
  1466. llvm::Constant *CGObjCCommonMac::BuildGCBlockLayout(CodeGenModule &CGM,
  1467. const CGBlockInfo &blockInfo) {
  1468. llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
  1469. if (CGM.getLangOptions().getGC() == LangOptions::NonGC &&
  1470. !CGM.getLangOptions().ObjCAutoRefCount)
  1471. return nullPtr;
  1472. bool hasUnion = false;
  1473. SkipIvars.clear();
  1474. IvarsInfo.clear();
  1475. unsigned WordSizeInBits = CGM.getContext().getTargetInfo().getPointerWidth(0);
  1476. unsigned ByteSizeInBits = CGM.getContext().getTargetInfo().getCharWidth();
  1477. // __isa is the first field in block descriptor and must assume by runtime's
  1478. // convention that it is GC'able.
  1479. IvarsInfo.push_back(GC_IVAR(0, 1));
  1480. const BlockDecl *blockDecl = blockInfo.getBlockDecl();
  1481. // Calculate the basic layout of the block structure.
  1482. const llvm::StructLayout *layout =
  1483. CGM.getTargetData().getStructLayout(blockInfo.StructureType);
  1484. // Ignore the optional 'this' capture: C++ objects are not assumed
  1485. // to be GC'ed.
  1486. // Walk the captured variables.
  1487. for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
  1488. ce = blockDecl->capture_end(); ci != ce; ++ci) {
  1489. const VarDecl *variable = ci->getVariable();
  1490. QualType type = variable->getType();
  1491. const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
  1492. // Ignore constant captures.
  1493. if (capture.isConstant()) continue;
  1494. uint64_t fieldOffset = layout->getElementOffset(capture.getIndex());
  1495. // __block variables are passed by their descriptor address.
  1496. if (ci->isByRef()) {
  1497. IvarsInfo.push_back(GC_IVAR(fieldOffset, /*size in words*/ 1));
  1498. continue;
  1499. }
  1500. assert(!type->isArrayType() && "array variable should not be caught");
  1501. if (const RecordType *record = type->getAs<RecordType>()) {
  1502. BuildAggrIvarRecordLayout(record, fieldOffset, true, hasUnion);
  1503. continue;
  1504. }
  1505. Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), type);
  1506. unsigned fieldSize = CGM.getContext().getTypeSize(type);
  1507. if (GCAttr == Qualifiers::Strong)
  1508. IvarsInfo.push_back(GC_IVAR(fieldOffset,
  1509. fieldSize / WordSizeInBits));
  1510. else if (GCAttr == Qualifiers::GCNone || GCAttr == Qualifiers::Weak)
  1511. SkipIvars.push_back(GC_IVAR(fieldOffset,
  1512. fieldSize / ByteSizeInBits));
  1513. }
  1514. if (IvarsInfo.empty())
  1515. return nullPtr;
  1516. // Sort on byte position; captures might not be allocated in order,
  1517. // and unions can do funny things.
  1518. llvm::array_pod_sort(IvarsInfo.begin(), IvarsInfo.end());
  1519. llvm::array_pod_sort(SkipIvars.begin(), SkipIvars.end());
  1520. std::string BitMap;
  1521. llvm::Constant *C = BuildIvarLayoutBitmap(BitMap);
  1522. if (CGM.getLangOptions().ObjCGCBitmapPrint) {
  1523. printf("\n block variable layout for block: ");
  1524. const unsigned char *s = (unsigned char*)BitMap.c_str();
  1525. for (unsigned i = 0, e = BitMap.size(); i < e; i++)
  1526. if (!(s[i] & 0xf0))
  1527. printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
  1528. else
  1529. printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
  1530. printf("\n");
  1531. }
  1532. return C;
  1533. }
  1534. llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
  1535. const ObjCProtocolDecl *PD) {
  1536. // FIXME: I don't understand why gcc generates this, or where it is
  1537. // resolved. Investigate. Its also wasteful to look this up over and over.
  1538. LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
  1539. return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
  1540. ObjCTypes.getExternalProtocolPtrTy());
  1541. }
  1542. void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
  1543. // FIXME: We shouldn't need this, the protocol decl should contain enough
  1544. // information to tell us whether this was a declaration or a definition.
  1545. DefinedProtocols.insert(PD->getIdentifier());
  1546. // If we have generated a forward reference to this protocol, emit
  1547. // it now. Otherwise do nothing, the protocol objects are lazily
  1548. // emitted.
  1549. if (Protocols.count(PD->getIdentifier()))
  1550. GetOrEmitProtocol(PD);
  1551. }
  1552. llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
  1553. if (DefinedProtocols.count(PD->getIdentifier()))
  1554. return GetOrEmitProtocol(PD);
  1555. return GetOrEmitProtocolRef(PD);
  1556. }
  1557. /*
  1558. // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
  1559. struct _objc_protocol {
  1560. struct _objc_protocol_extension *isa;
  1561. char *protocol_name;
  1562. struct _objc_protocol_list *protocol_list;
  1563. struct _objc__method_prototype_list *instance_methods;
  1564. struct _objc__method_prototype_list *class_methods
  1565. };
  1566. See EmitProtocolExtension().
  1567. */
  1568. llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
  1569. llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
  1570. // Early exit if a defining object has already been generated.
  1571. if (Entry && Entry->hasInitializer())
  1572. return Entry;
  1573. // Use the protocol definition, if there is one.
  1574. if (const ObjCProtocolDecl *Def = PD->getDefinition())
  1575. PD = Def;
  1576. // FIXME: I don't understand why gcc generates this, or where it is
  1577. // resolved. Investigate. Its also wasteful to look this up over and over.
  1578. LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
  1579. // Construct method lists.
  1580. std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
  1581. std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
  1582. std::vector<llvm::Constant*> MethodTypesExt, OptMethodTypesExt;
  1583. for (ObjCProtocolDecl::instmeth_iterator
  1584. i = PD->instmeth_begin(), e = PD->instmeth_end(); i != e; ++i) {
  1585. ObjCMethodDecl *MD = *i;
  1586. llvm::Constant *C = GetMethodDescriptionConstant(MD);
  1587. if (!C)
  1588. return GetOrEmitProtocolRef(PD);
  1589. if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
  1590. OptInstanceMethods.push_back(C);
  1591. OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
  1592. } else {
  1593. InstanceMethods.push_back(C);
  1594. MethodTypesExt.push_back(GetMethodVarType(MD, true));
  1595. }
  1596. }
  1597. for (ObjCProtocolDecl::classmeth_iterator
  1598. i = PD->classmeth_begin(), e = PD->classmeth_end(); i != e; ++i) {
  1599. ObjCMethodDecl *MD = *i;
  1600. llvm::Constant *C = GetMethodDescriptionConstant(MD);
  1601. if (!C)
  1602. return GetOrEmitProtocolRef(PD);
  1603. if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
  1604. OptClassMethods.push_back(C);
  1605. OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
  1606. } else {
  1607. ClassMethods.push_back(C);
  1608. MethodTypesExt.push_back(GetMethodVarType(MD, true));
  1609. }
  1610. }
  1611. MethodTypesExt.insert(MethodTypesExt.end(),
  1612. OptMethodTypesExt.begin(), OptMethodTypesExt.end());
  1613. llvm::Constant *Values[] = {
  1614. EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods,
  1615. MethodTypesExt),
  1616. GetClassName(PD->getIdentifier()),
  1617. EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getName(),
  1618. PD->protocol_begin(),
  1619. PD->protocol_end()),
  1620. EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_" + PD->getName(),
  1621. "__OBJC,__cat_inst_meth,regular,no_dead_strip",
  1622. InstanceMethods),
  1623. EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_" + PD->getName(),
  1624. "__OBJC,__cat_cls_meth,regular,no_dead_strip",
  1625. ClassMethods)
  1626. };
  1627. llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
  1628. Values);
  1629. if (Entry) {
  1630. // Already created, fix the linkage and update the initializer.
  1631. Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
  1632. Entry->setInitializer(Init);
  1633. } else {
  1634. Entry =
  1635. new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolTy, false,
  1636. llvm::GlobalValue::InternalLinkage,
  1637. Init,
  1638. "\01L_OBJC_PROTOCOL_" + PD->getName());
  1639. Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
  1640. // FIXME: Is this necessary? Why only for protocol?
  1641. Entry->setAlignment(4);
  1642. }
  1643. CGM.AddUsedGlobal(Entry);
  1644. return Entry;
  1645. }
  1646. llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
  1647. llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
  1648. if (!Entry) {
  1649. // We use the initializer as a marker of whether this is a forward
  1650. // reference or not. At module finalization we add the empty
  1651. // contents for protocols which were referenced but never defined.
  1652. Entry =
  1653. new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolTy, false,
  1654. llvm::GlobalValue::ExternalLinkage,
  1655. 0,
  1656. "\01L_OBJC_PROTOCOL_" + PD->getName());
  1657. Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
  1658. // FIXME: Is this necessary? Why only for protocol?
  1659. Entry->setAlignment(4);
  1660. }
  1661. return Entry;
  1662. }
  1663. /*
  1664. struct _objc_protocol_extension {
  1665. uint32_t size;
  1666. struct objc_method_description_list *optional_instance_methods;
  1667. struct objc_method_description_list *optional_class_methods;
  1668. struct objc_property_list *instance_properties;
  1669. const char ** extendedMethodTypes;
  1670. };
  1671. */
  1672. llvm::Constant *
  1673. CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
  1674. ArrayRef<llvm::Constant*> OptInstanceMethods,
  1675. ArrayRef<llvm::Constant*> OptClassMethods,
  1676. ArrayRef<llvm::Constant*> MethodTypesExt) {
  1677. uint64_t Size =
  1678. CGM.getTargetData().getTypeAllocSize(ObjCTypes.ProtocolExtensionTy);
  1679. llvm::Constant *Values[] = {
  1680. llvm::ConstantInt::get(ObjCTypes.IntTy, Size),
  1681. EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
  1682. + PD->getName(),
  1683. "__OBJC,__cat_inst_meth,regular,no_dead_strip",
  1684. OptInstanceMethods),
  1685. EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_" + PD->getName(),
  1686. "__OBJC,__cat_cls_meth,regular,no_dead_strip",
  1687. OptClassMethods),
  1688. EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" + PD->getName(), 0, PD,
  1689. ObjCTypes),
  1690. EmitProtocolMethodTypes("\01L_OBJC_PROTOCOL_METHOD_TYPES_" + PD->getName(),
  1691. MethodTypesExt, ObjCTypes)
  1692. };
  1693. // Return null if no extension bits are used.
  1694. if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
  1695. Values[3]->isNullValue() && Values[4]->isNullValue())
  1696. return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
  1697. llvm::Constant *Init =
  1698. llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
  1699. // No special section, but goes in llvm.used
  1700. return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getName(),
  1701. Init,
  1702. 0, 0, true);
  1703. }
  1704. /*
  1705. struct objc_protocol_list {
  1706. struct objc_protocol_list *next;
  1707. long count;
  1708. Protocol *list[];
  1709. };
  1710. */
  1711. llvm::Constant *
  1712. CGObjCMac::EmitProtocolList(Twine Name,
  1713. ObjCProtocolDecl::protocol_iterator begin,
  1714. ObjCProtocolDecl::protocol_iterator end) {
  1715. llvm::SmallVector<llvm::Constant*, 16> ProtocolRefs;
  1716. for (; begin != end; ++begin)
  1717. ProtocolRefs.push_back(GetProtocolRef(*begin));
  1718. // Just return null for empty protocol lists
  1719. if (ProtocolRefs.empty())
  1720. return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
  1721. // This list is null terminated.
  1722. ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
  1723. llvm::Constant *Values[3];
  1724. // This field is only used by the runtime.
  1725. Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
  1726. Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy,
  1727. ProtocolRefs.size() - 1);
  1728. Values[2] =
  1729. llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
  1730. ProtocolRefs.size()),
  1731. ProtocolRefs);
  1732. llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
  1733. llvm::GlobalVariable *GV =
  1734. CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
  1735. 4, false);
  1736. return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
  1737. }
  1738. void CGObjCCommonMac::
  1739. PushProtocolProperties(llvm::SmallPtrSet<const IdentifierInfo*,16> &PropertySet,
  1740. llvm::SmallVectorImpl<llvm::Constant*> &Properties,
  1741. const Decl *Container,
  1742. const ObjCProtocolDecl *PROTO,
  1743. const ObjCCommonTypesHelper &ObjCTypes) {
  1744. for (ObjCProtocolDecl::protocol_iterator P = PROTO->protocol_begin(),
  1745. E = PROTO->protocol_end(); P != E; ++P)
  1746. PushProtocolProperties(PropertySet, Properties, Container, (*P), ObjCTypes);
  1747. for (ObjCContainerDecl::prop_iterator I = PROTO->prop_begin(),
  1748. E = PROTO->prop_end(); I != E; ++I) {
  1749. const ObjCPropertyDecl *PD = *I;
  1750. if (!PropertySet.insert(PD->getIdentifier()))
  1751. continue;
  1752. llvm::Constant *Prop[] = {
  1753. GetPropertyName(PD->getIdentifier()),
  1754. GetPropertyTypeString(PD, Container)
  1755. };
  1756. Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy, Prop));
  1757. }
  1758. }
  1759. /*
  1760. struct _objc_property {
  1761. const char * const name;
  1762. const char * const attributes;
  1763. };
  1764. struct _objc_property_list {
  1765. uint32_t entsize; // sizeof (struct _objc_property)
  1766. uint32_t prop_count;
  1767. struct _objc_property[prop_count];
  1768. };
  1769. */
  1770. llvm::Constant *CGObjCCommonMac::EmitPropertyList(Twine Name,
  1771. const Decl *Container,
  1772. const ObjCContainerDecl *OCD,
  1773. const ObjCCommonTypesHelper &ObjCTypes) {
  1774. llvm::SmallVector<llvm::Constant*, 16> Properties;
  1775. llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
  1776. for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(),
  1777. E = OCD->prop_end(); I != E; ++I) {
  1778. const ObjCPropertyDecl *PD = *I;
  1779. PropertySet.insert(PD->getIdentifier());
  1780. llvm::Constant *Prop[] = {
  1781. GetPropertyName(PD->getIdentifier()),
  1782. GetPropertyTypeString(PD, Container)
  1783. };
  1784. Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
  1785. Prop));
  1786. }
  1787. if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD)) {
  1788. for (ObjCInterfaceDecl::all_protocol_iterator
  1789. P = OID->all_referenced_protocol_begin(),
  1790. E = OID->all_referenced_protocol_end(); P != E; ++P)
  1791. PushProtocolProperties(PropertySet, Properties, Container, (*P),
  1792. ObjCTypes);
  1793. }
  1794. else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD)) {
  1795. for (ObjCCategoryDecl::protocol_iterator P = CD->protocol_begin(),
  1796. E = CD->protocol_end(); P != E; ++P)
  1797. PushProtocolProperties(PropertySet, Properties, Container, (*P),
  1798. ObjCTypes);
  1799. }
  1800. // Return null for empty list.
  1801. if (Properties.empty())
  1802. return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
  1803. unsigned PropertySize =
  1804. CGM.getTargetData().getTypeAllocSize(ObjCTypes.PropertyTy);
  1805. llvm::Constant *Values[3];
  1806. Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
  1807. Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
  1808. llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
  1809. Properties.size());
  1810. Values[2] = llvm::ConstantArray::get(AT, Properties);
  1811. llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
  1812. llvm::GlobalVariable *GV =
  1813. CreateMetadataVar(Name, Init,
  1814. (ObjCABI == 2) ? "__DATA, __objc_const" :
  1815. "__OBJC,__property,regular,no_dead_strip",
  1816. (ObjCABI == 2) ? 8 : 4,
  1817. true);
  1818. return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
  1819. }
  1820. llvm::Constant *
  1821. CGObjCCommonMac::EmitProtocolMethodTypes(Twine Name,
  1822. ArrayRef<llvm::Constant*> MethodTypes,
  1823. const ObjCCommonTypesHelper &ObjCTypes) {
  1824. // Return null for empty list.
  1825. if (MethodTypes.empty())
  1826. return llvm::Constant::getNullValue(ObjCTypes.Int8PtrPtrTy);
  1827. llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
  1828. MethodTypes.size());
  1829. llvm::Constant *Init = llvm::ConstantArray::get(AT, MethodTypes);
  1830. llvm::GlobalVariable *GV =
  1831. CreateMetadataVar(Name, Init,
  1832. (ObjCABI == 2) ? "__DATA, __objc_const" : 0,
  1833. (ObjCABI == 2) ? 8 : 4,
  1834. true);
  1835. return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.Int8PtrPtrTy);
  1836. }
  1837. /*
  1838. struct objc_method_description_list {
  1839. int count;
  1840. struct objc_method_description list[];
  1841. };
  1842. */
  1843. llvm::Constant *
  1844. CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
  1845. llvm::Constant *Desc[] = {
  1846. llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
  1847. ObjCTypes.SelectorPtrTy),
  1848. GetMethodVarType(MD)
  1849. };
  1850. if (!Desc[1])
  1851. return 0;
  1852. return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
  1853. Desc);
  1854. }
  1855. llvm::Constant *
  1856. CGObjCMac::EmitMethodDescList(Twine Name, const char *Section,
  1857. ArrayRef<llvm::Constant*> Methods) {
  1858. // Return null for empty list.
  1859. if (Methods.empty())
  1860. return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
  1861. llvm::Constant *Values[2];
  1862. Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
  1863. llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
  1864. Methods.size());
  1865. Values[1] = llvm::ConstantArray::get(AT, Methods);
  1866. llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
  1867. llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
  1868. return llvm::ConstantExpr::getBitCast(GV,
  1869. ObjCTypes.MethodDescriptionListPtrTy);
  1870. }
  1871. /*
  1872. struct _objc_category {
  1873. char *category_name;
  1874. char *class_name;
  1875. struct _objc_method_list *instance_methods;
  1876. struct _objc_method_list *class_methods;
  1877. struct _objc_protocol_list *protocols;
  1878. uint32_t size; // <rdar://4585769>
  1879. struct _objc_property_list *instance_properties;
  1880. };
  1881. */
  1882. void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
  1883. unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.CategoryTy);
  1884. // FIXME: This is poor design, the OCD should have a pointer to the category
  1885. // decl. Additionally, note that Category can be null for the @implementation
  1886. // w/o an @interface case. Sema should just create one for us as it does for
  1887. // @implementation so everyone else can live life under a clear blue sky.
  1888. const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
  1889. const ObjCCategoryDecl *Category =
  1890. Interface->FindCategoryDeclaration(OCD->getIdentifier());
  1891. SmallString<256> ExtName;
  1892. llvm::raw_svector_ostream(ExtName) << Interface->getName() << '_'
  1893. << OCD->getName();
  1894. llvm::SmallVector<llvm::Constant*, 16> InstanceMethods, ClassMethods;
  1895. for (ObjCCategoryImplDecl::instmeth_iterator
  1896. i = OCD->instmeth_begin(), e = OCD->instmeth_end(); i != e; ++i) {
  1897. // Instance methods should always be defined.
  1898. InstanceMethods.push_back(GetMethodConstant(*i));
  1899. }
  1900. for (ObjCCategoryImplDecl::classmeth_iterator
  1901. i = OCD->classmeth_begin(), e = OCD->classmeth_end(); i != e; ++i) {
  1902. // Class methods should always be defined.
  1903. ClassMethods.push_back(GetMethodConstant(*i));
  1904. }
  1905. llvm::Constant *Values[7];
  1906. Values[0] = GetClassName(OCD->getIdentifier());
  1907. Values[1] = GetClassName(Interface->getIdentifier());
  1908. LazySymbols.insert(Interface->getIdentifier());
  1909. Values[2] =
  1910. EmitMethodList("\01L_OBJC_CATEGORY_INSTANCE_METHODS_" + ExtName.str(),
  1911. "__OBJC,__cat_inst_meth,regular,no_dead_strip",
  1912. InstanceMethods);
  1913. Values[3] =
  1914. EmitMethodList("\01L_OBJC_CATEGORY_CLASS_METHODS_" + ExtName.str(),
  1915. "__OBJC,__cat_cls_meth,regular,no_dead_strip",
  1916. ClassMethods);
  1917. if (Category) {
  1918. Values[4] =
  1919. EmitProtocolList("\01L_OBJC_CATEGORY_PROTOCOLS_" + ExtName.str(),
  1920. Category->protocol_begin(),
  1921. Category->protocol_end());
  1922. } else {
  1923. Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
  1924. }
  1925. Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
  1926. // If there is no category @interface then there can be no properties.
  1927. if (Category) {
  1928. Values[6] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ExtName.str(),
  1929. OCD, Category, ObjCTypes);
  1930. } else {
  1931. Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
  1932. }
  1933. llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
  1934. Values);
  1935. llvm::GlobalVariable *GV =
  1936. CreateMetadataVar("\01L_OBJC_CATEGORY_" + ExtName.str(), Init,
  1937. "__OBJC,__category,regular,no_dead_strip",
  1938. 4, true);
  1939. DefinedCategories.push_back(GV);
  1940. DefinedCategoryNames.insert(ExtName.str());
  1941. // method definition entries must be clear for next implementation.
  1942. MethodDefinitions.clear();
  1943. }
  1944. // FIXME: Get from somewhere?
  1945. enum ClassFlags {
  1946. eClassFlags_Factory = 0x00001,
  1947. eClassFlags_Meta = 0x00002,
  1948. // <rdr://5142207>
  1949. eClassFlags_HasCXXStructors = 0x02000,
  1950. eClassFlags_Hidden = 0x20000,
  1951. eClassFlags_ABI2_Hidden = 0x00010,
  1952. eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634>
  1953. };
  1954. /*
  1955. struct _objc_class {
  1956. Class isa;
  1957. Class super_class;
  1958. const char *name;
  1959. long version;
  1960. long info;
  1961. long instance_size;
  1962. struct _objc_ivar_list *ivars;
  1963. struct _objc_method_list *methods;
  1964. struct _objc_cache *cache;
  1965. struct _objc_protocol_list *protocols;
  1966. // Objective-C 1.0 extensions (<rdr://4585769>)
  1967. const char *ivar_layout;
  1968. struct _objc_class_ext *ext;
  1969. };
  1970. See EmitClassExtension();
  1971. */
  1972. void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
  1973. DefinedSymbols.insert(ID->getIdentifier());
  1974. std::string ClassName = ID->getNameAsString();
  1975. // FIXME: Gross
  1976. ObjCInterfaceDecl *Interface =
  1977. const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
  1978. llvm::Constant *Protocols =
  1979. EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getName(),
  1980. Interface->all_referenced_protocol_begin(),
  1981. Interface->all_referenced_protocol_end());
  1982. unsigned Flags = eClassFlags_Factory;
  1983. if (ID->hasCXXStructors())
  1984. Flags |= eClassFlags_HasCXXStructors;
  1985. unsigned Size =
  1986. CGM.getContext().getASTObjCImplementationLayout(ID).getSize().getQuantity();
  1987. // FIXME: Set CXX-structors flag.
  1988. if (ID->getClassInterface()->getVisibility() == HiddenVisibility)
  1989. Flags |= eClassFlags_Hidden;
  1990. llvm::SmallVector<llvm::Constant*, 16> InstanceMethods, ClassMethods;
  1991. for (ObjCImplementationDecl::instmeth_iterator
  1992. i = ID->instmeth_begin(), e = ID->instmeth_end(); i != e; ++i) {
  1993. // Instance methods should always be defined.
  1994. InstanceMethods.push_back(GetMethodConstant(*i));
  1995. }
  1996. for (ObjCImplementationDecl::classmeth_iterator
  1997. i = ID->classmeth_begin(), e = ID->classmeth_end(); i != e; ++i) {
  1998. // Class methods should always be defined.
  1999. ClassMethods.push_back(GetMethodConstant(*i));
  2000. }
  2001. for (ObjCImplementationDecl::propimpl_iterator
  2002. i = ID->propimpl_begin(), e = ID->propimpl_end(); i != e; ++i) {
  2003. ObjCPropertyImplDecl *PID = *i;
  2004. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
  2005. ObjCPropertyDecl *PD = PID->getPropertyDecl();
  2006. if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
  2007. if (llvm::Constant *C = GetMethodConstant(MD))
  2008. InstanceMethods.push_back(C);
  2009. if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
  2010. if (llvm::Constant *C = GetMethodConstant(MD))
  2011. InstanceMethods.push_back(C);
  2012. }
  2013. }
  2014. llvm::Constant *Values[12];
  2015. Values[ 0] = EmitMetaClass(ID, Protocols, ClassMethods);
  2016. if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
  2017. // Record a reference to the super class.
  2018. LazySymbols.insert(Super->getIdentifier());
  2019. Values[ 1] =
  2020. llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
  2021. ObjCTypes.ClassPtrTy);
  2022. } else {
  2023. Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
  2024. }
  2025. Values[ 2] = GetClassName(ID->getIdentifier());
  2026. // Version is always 0.
  2027. Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
  2028. Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
  2029. Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
  2030. Values[ 6] = EmitIvarList(ID, false);
  2031. Values[ 7] =
  2032. EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getName(),
  2033. "__OBJC,__inst_meth,regular,no_dead_strip",
  2034. InstanceMethods);
  2035. // cache is always NULL.
  2036. Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
  2037. Values[ 9] = Protocols;
  2038. Values[10] = BuildIvarLayout(ID, true);
  2039. Values[11] = EmitClassExtension(ID);
  2040. llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
  2041. Values);
  2042. std::string Name("\01L_OBJC_CLASS_");
  2043. Name += ClassName;
  2044. const char *Section = "__OBJC,__class,regular,no_dead_strip";
  2045. // Check for a forward reference.
  2046. llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
  2047. if (GV) {
  2048. assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
  2049. "Forward metaclass reference has incorrect type.");
  2050. GV->setLinkage(llvm::GlobalValue::InternalLinkage);
  2051. GV->setInitializer(Init);
  2052. GV->setSection(Section);
  2053. GV->setAlignment(4);
  2054. CGM.AddUsedGlobal(GV);
  2055. }
  2056. else
  2057. GV = CreateMetadataVar(Name, Init, Section, 4, true);
  2058. DefinedClasses.push_back(GV);
  2059. // method definition entries must be clear for next implementation.
  2060. MethodDefinitions.clear();
  2061. }
  2062. llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
  2063. llvm::Constant *Protocols,
  2064. ArrayRef<llvm::Constant*> Methods) {
  2065. unsigned Flags = eClassFlags_Meta;
  2066. unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassTy);
  2067. if (ID->getClassInterface()->getVisibility() == HiddenVisibility)
  2068. Flags |= eClassFlags_Hidden;
  2069. llvm::Constant *Values[12];
  2070. // The isa for the metaclass is the root of the hierarchy.
  2071. const ObjCInterfaceDecl *Root = ID->getClassInterface();
  2072. while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
  2073. Root = Super;
  2074. Values[ 0] =
  2075. llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
  2076. ObjCTypes.ClassPtrTy);
  2077. // The super class for the metaclass is emitted as the name of the
  2078. // super class. The runtime fixes this up to point to the
  2079. // *metaclass* for the super class.
  2080. if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
  2081. Values[ 1] =
  2082. llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
  2083. ObjCTypes.ClassPtrTy);
  2084. } else {
  2085. Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
  2086. }
  2087. Values[ 2] = GetClassName(ID->getIdentifier());
  2088. // Version is always 0.
  2089. Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
  2090. Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
  2091. Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
  2092. Values[ 6] = EmitIvarList(ID, true);
  2093. Values[ 7] =
  2094. EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
  2095. "__OBJC,__cls_meth,regular,no_dead_strip",
  2096. Methods);
  2097. // cache is always NULL.
  2098. Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
  2099. Values[ 9] = Protocols;
  2100. // ivar_layout for metaclass is always NULL.
  2101. Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
  2102. // The class extension is always unused for metaclasses.
  2103. Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
  2104. llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
  2105. Values);
  2106. std::string Name("\01L_OBJC_METACLASS_");
  2107. Name += ID->getNameAsCString();
  2108. // Check for a forward reference.
  2109. llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
  2110. if (GV) {
  2111. assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
  2112. "Forward metaclass reference has incorrect type.");
  2113. GV->setLinkage(llvm::GlobalValue::InternalLinkage);
  2114. GV->setInitializer(Init);
  2115. } else {
  2116. GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
  2117. llvm::GlobalValue::InternalLinkage,
  2118. Init, Name);
  2119. }
  2120. GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
  2121. GV->setAlignment(4);
  2122. CGM.AddUsedGlobal(GV);
  2123. return GV;
  2124. }
  2125. llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
  2126. std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
  2127. // FIXME: Should we look these up somewhere other than the module. Its a bit
  2128. // silly since we only generate these while processing an implementation, so
  2129. // exactly one pointer would work if know when we entered/exitted an
  2130. // implementation block.
  2131. // Check for an existing forward reference.
  2132. // Previously, metaclass with internal linkage may have been defined.
  2133. // pass 'true' as 2nd argument so it is returned.
  2134. if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name,
  2135. true)) {
  2136. assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
  2137. "Forward metaclass reference has incorrect type.");
  2138. return GV;
  2139. } else {
  2140. // Generate as an external reference to keep a consistent
  2141. // module. This will be patched up when we emit the metaclass.
  2142. return new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
  2143. llvm::GlobalValue::ExternalLinkage,
  2144. 0,
  2145. Name);
  2146. }
  2147. }
  2148. llvm::Value *CGObjCMac::EmitSuperClassRef(const ObjCInterfaceDecl *ID) {
  2149. std::string Name = "\01L_OBJC_CLASS_" + ID->getNameAsString();
  2150. if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name,
  2151. true)) {
  2152. assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
  2153. "Forward class metadata reference has incorrect type.");
  2154. return GV;
  2155. } else {
  2156. return new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
  2157. llvm::GlobalValue::ExternalLinkage,
  2158. 0,
  2159. Name);
  2160. }
  2161. }
  2162. /*
  2163. struct objc_class_ext {
  2164. uint32_t size;
  2165. const char *weak_ivar_layout;
  2166. struct _objc_property_list *properties;
  2167. };
  2168. */
  2169. llvm::Constant *
  2170. CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
  2171. uint64_t Size =
  2172. CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassExtensionTy);
  2173. llvm::Constant *Values[3];
  2174. Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
  2175. Values[1] = BuildIvarLayout(ID, false);
  2176. Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getName(),
  2177. ID, ID->getClassInterface(), ObjCTypes);
  2178. // Return null if no extension bits are used.
  2179. if (Values[1]->isNullValue() && Values[2]->isNullValue())
  2180. return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
  2181. llvm::Constant *Init =
  2182. llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
  2183. return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getName(),
  2184. Init, "__OBJC,__class_ext,regular,no_dead_strip",
  2185. 4, true);
  2186. }
  2187. /*
  2188. struct objc_ivar {
  2189. char *ivar_name;
  2190. char *ivar_type;
  2191. int ivar_offset;
  2192. };
  2193. struct objc_ivar_list {
  2194. int ivar_count;
  2195. struct objc_ivar list[count];
  2196. };
  2197. */
  2198. llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
  2199. bool ForClass) {
  2200. std::vector<llvm::Constant*> Ivars;
  2201. // When emitting the root class GCC emits ivar entries for the
  2202. // actual class structure. It is not clear if we need to follow this
  2203. // behavior; for now lets try and get away with not doing it. If so,
  2204. // the cleanest solution would be to make up an ObjCInterfaceDecl
  2205. // for the class.
  2206. if (ForClass)
  2207. return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
  2208. const ObjCInterfaceDecl *OID = ID->getClassInterface();
  2209. for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin();
  2210. IVD; IVD = IVD->getNextIvar()) {
  2211. // Ignore unnamed bit-fields.
  2212. if (!IVD->getDeclName())
  2213. continue;
  2214. llvm::Constant *Ivar[] = {
  2215. GetMethodVarName(IVD->getIdentifier()),
  2216. GetMethodVarType(IVD),
  2217. llvm::ConstantInt::get(ObjCTypes.IntTy,
  2218. ComputeIvarBaseOffset(CGM, OID, IVD))
  2219. };
  2220. Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
  2221. }
  2222. // Return null for empty list.
  2223. if (Ivars.empty())
  2224. return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
  2225. llvm::Constant *Values[2];
  2226. Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
  2227. llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
  2228. Ivars.size());
  2229. Values[1] = llvm::ConstantArray::get(AT, Ivars);
  2230. llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
  2231. llvm::GlobalVariable *GV;
  2232. if (ForClass)
  2233. GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getName(),
  2234. Init, "__OBJC,__class_vars,regular,no_dead_strip",
  2235. 4, true);
  2236. else
  2237. GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_" + ID->getName(),
  2238. Init, "__OBJC,__instance_vars,regular,no_dead_strip",
  2239. 4, true);
  2240. return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
  2241. }
  2242. /*
  2243. struct objc_method {
  2244. SEL method_name;
  2245. char *method_types;
  2246. void *method;
  2247. };
  2248. struct objc_method_list {
  2249. struct objc_method_list *obsolete;
  2250. int count;
  2251. struct objc_method methods_list[count];
  2252. };
  2253. */
  2254. /// GetMethodConstant - Return a struct objc_method constant for the
  2255. /// given method if it has been defined. The result is null if the
  2256. /// method has not been defined. The return value has type MethodPtrTy.
  2257. llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
  2258. llvm::Function *Fn = GetMethodDefinition(MD);
  2259. if (!Fn)
  2260. return 0;
  2261. llvm::Constant *Method[] = {
  2262. llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
  2263. ObjCTypes.SelectorPtrTy),
  2264. GetMethodVarType(MD),
  2265. llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy)
  2266. };
  2267. return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
  2268. }
  2269. llvm::Constant *CGObjCMac::EmitMethodList(Twine Name,
  2270. const char *Section,
  2271. ArrayRef<llvm::Constant*> Methods) {
  2272. // Return null for empty list.
  2273. if (Methods.empty())
  2274. return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
  2275. llvm::Constant *Values[3];
  2276. Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
  2277. Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
  2278. llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
  2279. Methods.size());
  2280. Values[2] = llvm::ConstantArray::get(AT, Methods);
  2281. llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
  2282. llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
  2283. return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodListPtrTy);
  2284. }
  2285. llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
  2286. const ObjCContainerDecl *CD) {
  2287. SmallString<256> Name;
  2288. GetNameForMethod(OMD, CD, Name);
  2289. CodeGenTypes &Types = CGM.getTypes();
  2290. llvm::FunctionType *MethodTy =
  2291. Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
  2292. llvm::Function *Method =
  2293. llvm::Function::Create(MethodTy,
  2294. llvm::GlobalValue::InternalLinkage,
  2295. Name.str(),
  2296. &CGM.getModule());
  2297. MethodDefinitions.insert(std::make_pair(OMD, Method));
  2298. return Method;
  2299. }
  2300. llvm::GlobalVariable *
  2301. CGObjCCommonMac::CreateMetadataVar(Twine Name,
  2302. llvm::Constant *Init,
  2303. const char *Section,
  2304. unsigned Align,
  2305. bool AddToUsed) {
  2306. llvm::Type *Ty = Init->getType();
  2307. llvm::GlobalVariable *GV =
  2308. new llvm::GlobalVariable(CGM.getModule(), Ty, false,
  2309. llvm::GlobalValue::InternalLinkage, Init, Name);
  2310. if (Section)
  2311. GV->setSection(Section);
  2312. if (Align)
  2313. GV->setAlignment(Align);
  2314. if (AddToUsed)
  2315. CGM.AddUsedGlobal(GV);
  2316. return GV;
  2317. }
  2318. llvm::Function *CGObjCMac::ModuleInitFunction() {
  2319. // Abuse this interface function as a place to finalize.
  2320. FinishModule();
  2321. return NULL;
  2322. }
  2323. llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
  2324. return ObjCTypes.getGetPropertyFn();
  2325. }
  2326. llvm::Constant *CGObjCMac::GetPropertySetFunction() {
  2327. return ObjCTypes.getSetPropertyFn();
  2328. }
  2329. llvm::Constant *CGObjCMac::GetGetStructFunction() {
  2330. return ObjCTypes.getCopyStructFn();
  2331. }
  2332. llvm::Constant *CGObjCMac::GetSetStructFunction() {
  2333. return ObjCTypes.getCopyStructFn();
  2334. }
  2335. llvm::Constant *CGObjCMac::GetCppAtomicObjectFunction() {
  2336. return ObjCTypes.getCppAtomicObjectFunction();
  2337. }
  2338. llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
  2339. return ObjCTypes.getEnumerationMutationFn();
  2340. }
  2341. void CGObjCMac::EmitTryStmt(CodeGenFunction &CGF, const ObjCAtTryStmt &S) {
  2342. return EmitTryOrSynchronizedStmt(CGF, S);
  2343. }
  2344. void CGObjCMac::EmitSynchronizedStmt(CodeGenFunction &CGF,
  2345. const ObjCAtSynchronizedStmt &S) {
  2346. return EmitTryOrSynchronizedStmt(CGF, S);
  2347. }
  2348. namespace {
  2349. struct PerformFragileFinally : EHScopeStack::Cleanup {
  2350. const Stmt &S;
  2351. llvm::Value *SyncArgSlot;
  2352. llvm::Value *CallTryExitVar;
  2353. llvm::Value *ExceptionData;
  2354. ObjCTypesHelper &ObjCTypes;
  2355. PerformFragileFinally(const Stmt *S,
  2356. llvm::Value *SyncArgSlot,
  2357. llvm::Value *CallTryExitVar,
  2358. llvm::Value *ExceptionData,
  2359. ObjCTypesHelper *ObjCTypes)
  2360. : S(*S), SyncArgSlot(SyncArgSlot), CallTryExitVar(CallTryExitVar),
  2361. ExceptionData(ExceptionData), ObjCTypes(*ObjCTypes) {}
  2362. void Emit(CodeGenFunction &CGF, Flags flags) {
  2363. // Check whether we need to call objc_exception_try_exit.
  2364. // In optimized code, this branch will always be folded.
  2365. llvm::BasicBlock *FinallyCallExit =
  2366. CGF.createBasicBlock("finally.call_exit");
  2367. llvm::BasicBlock *FinallyNoCallExit =
  2368. CGF.createBasicBlock("finally.no_call_exit");
  2369. CGF.Builder.CreateCondBr(CGF.Builder.CreateLoad(CallTryExitVar),
  2370. FinallyCallExit, FinallyNoCallExit);
  2371. CGF.EmitBlock(FinallyCallExit);
  2372. CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData)
  2373. ->setDoesNotThrow();
  2374. CGF.EmitBlock(FinallyNoCallExit);
  2375. if (isa<ObjCAtTryStmt>(S)) {
  2376. if (const ObjCAtFinallyStmt* FinallyStmt =
  2377. cast<ObjCAtTryStmt>(S).getFinallyStmt()) {
  2378. // Save the current cleanup destination in case there's
  2379. // control flow inside the finally statement.
  2380. llvm::Value *CurCleanupDest =
  2381. CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot());
  2382. CGF.EmitStmt(FinallyStmt->getFinallyBody());
  2383. if (CGF.HaveInsertPoint()) {
  2384. CGF.Builder.CreateStore(CurCleanupDest,
  2385. CGF.getNormalCleanupDestSlot());
  2386. } else {
  2387. // Currently, the end of the cleanup must always exist.
  2388. CGF.EnsureInsertPoint();
  2389. }
  2390. }
  2391. } else {
  2392. // Emit objc_sync_exit(expr); as finally's sole statement for
  2393. // @synchronized.
  2394. llvm::Value *SyncArg = CGF.Builder.CreateLoad(SyncArgSlot);
  2395. CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg)
  2396. ->setDoesNotThrow();
  2397. }
  2398. }
  2399. };
  2400. class FragileHazards {
  2401. CodeGenFunction &CGF;
  2402. SmallVector<llvm::Value*, 20> Locals;
  2403. llvm::DenseSet<llvm::BasicBlock*> BlocksBeforeTry;
  2404. llvm::InlineAsm *ReadHazard;
  2405. llvm::InlineAsm *WriteHazard;
  2406. llvm::FunctionType *GetAsmFnType();
  2407. void collectLocals();
  2408. void emitReadHazard(CGBuilderTy &Builder);
  2409. public:
  2410. FragileHazards(CodeGenFunction &CGF);
  2411. void emitWriteHazard();
  2412. void emitHazardsInNewBlocks();
  2413. };
  2414. }
  2415. /// Create the fragile-ABI read and write hazards based on the current
  2416. /// state of the function, which is presumed to be immediately prior
  2417. /// to a @try block. These hazards are used to maintain correct
  2418. /// semantics in the face of optimization and the fragile ABI's
  2419. /// cavalier use of setjmp/longjmp.
  2420. FragileHazards::FragileHazards(CodeGenFunction &CGF) : CGF(CGF) {
  2421. collectLocals();
  2422. if (Locals.empty()) return;
  2423. // Collect all the blocks in the function.
  2424. for (llvm::Function::iterator
  2425. I = CGF.CurFn->begin(), E = CGF.CurFn->end(); I != E; ++I)
  2426. BlocksBeforeTry.insert(&*I);
  2427. llvm::FunctionType *AsmFnTy = GetAsmFnType();
  2428. // Create a read hazard for the allocas. This inhibits dead-store
  2429. // optimizations and forces the values to memory. This hazard is
  2430. // inserted before any 'throwing' calls in the protected scope to
  2431. // reflect the possibility that the variables might be read from the
  2432. // catch block if the call throws.
  2433. {
  2434. std::string Constraint;
  2435. for (unsigned I = 0, E = Locals.size(); I != E; ++I) {
  2436. if (I) Constraint += ',';
  2437. Constraint += "*m";
  2438. }
  2439. ReadHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false);
  2440. }
  2441. // Create a write hazard for the allocas. This inhibits folding
  2442. // loads across the hazard. This hazard is inserted at the
  2443. // beginning of the catch path to reflect the possibility that the
  2444. // variables might have been written within the protected scope.
  2445. {
  2446. std::string Constraint;
  2447. for (unsigned I = 0, E = Locals.size(); I != E; ++I) {
  2448. if (I) Constraint += ',';
  2449. Constraint += "=*m";
  2450. }
  2451. WriteHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false);
  2452. }
  2453. }
  2454. /// Emit a write hazard at the current location.
  2455. void FragileHazards::emitWriteHazard() {
  2456. if (Locals.empty()) return;
  2457. CGF.Builder.CreateCall(WriteHazard, Locals)->setDoesNotThrow();
  2458. }
  2459. void FragileHazards::emitReadHazard(CGBuilderTy &Builder) {
  2460. assert(!Locals.empty());
  2461. Builder.CreateCall(ReadHazard, Locals)->setDoesNotThrow();
  2462. }
  2463. /// Emit read hazards in all the protected blocks, i.e. all the blocks
  2464. /// which have been inserted since the beginning of the try.
  2465. void FragileHazards::emitHazardsInNewBlocks() {
  2466. if (Locals.empty()) return;
  2467. CGBuilderTy Builder(CGF.getLLVMContext());
  2468. // Iterate through all blocks, skipping those prior to the try.
  2469. for (llvm::Function::iterator
  2470. FI = CGF.CurFn->begin(), FE = CGF.CurFn->end(); FI != FE; ++FI) {
  2471. llvm::BasicBlock &BB = *FI;
  2472. if (BlocksBeforeTry.count(&BB)) continue;
  2473. // Walk through all the calls in the block.
  2474. for (llvm::BasicBlock::iterator
  2475. BI = BB.begin(), BE = BB.end(); BI != BE; ++BI) {
  2476. llvm::Instruction &I = *BI;
  2477. // Ignore instructions that aren't non-intrinsic calls.
  2478. // These are the only calls that can possibly call longjmp.
  2479. if (!isa<llvm::CallInst>(I) && !isa<llvm::InvokeInst>(I)) continue;
  2480. if (isa<llvm::IntrinsicInst>(I))
  2481. continue;
  2482. // Ignore call sites marked nounwind. This may be questionable,
  2483. // since 'nounwind' doesn't necessarily mean 'does not call longjmp'.
  2484. llvm::CallSite CS(&I);
  2485. if (CS.doesNotThrow()) continue;
  2486. // Insert a read hazard before the call. This will ensure that
  2487. // any writes to the locals are performed before making the
  2488. // call. If the call throws, then this is sufficient to
  2489. // guarantee correctness as long as it doesn't also write to any
  2490. // locals.
  2491. Builder.SetInsertPoint(&BB, BI);
  2492. emitReadHazard(Builder);
  2493. }
  2494. }
  2495. }
  2496. static void addIfPresent(llvm::DenseSet<llvm::Value*> &S, llvm::Value *V) {
  2497. if (V) S.insert(V);
  2498. }
  2499. void FragileHazards::collectLocals() {
  2500. // Compute a set of allocas to ignore.
  2501. llvm::DenseSet<llvm::Value*> AllocasToIgnore;
  2502. addIfPresent(AllocasToIgnore, CGF.ReturnValue);
  2503. addIfPresent(AllocasToIgnore, CGF.NormalCleanupDest);
  2504. // Collect all the allocas currently in the function. This is
  2505. // probably way too aggressive.
  2506. llvm::BasicBlock &Entry = CGF.CurFn->getEntryBlock();
  2507. for (llvm::BasicBlock::iterator
  2508. I = Entry.begin(), E = Entry.end(); I != E; ++I)
  2509. if (isa<llvm::AllocaInst>(*I) && !AllocasToIgnore.count(&*I))
  2510. Locals.push_back(&*I);
  2511. }
  2512. llvm::FunctionType *FragileHazards::GetAsmFnType() {
  2513. SmallVector<llvm::Type *, 16> tys(Locals.size());
  2514. for (unsigned i = 0, e = Locals.size(); i != e; ++i)
  2515. tys[i] = Locals[i]->getType();
  2516. return llvm::FunctionType::get(CGF.VoidTy, tys, false);
  2517. }
  2518. /*
  2519. Objective-C setjmp-longjmp (sjlj) Exception Handling
  2520. --
  2521. A catch buffer is a setjmp buffer plus:
  2522. - a pointer to the exception that was caught
  2523. - a pointer to the previous exception data buffer
  2524. - two pointers of reserved storage
  2525. Therefore catch buffers form a stack, with a pointer to the top
  2526. of the stack kept in thread-local storage.
  2527. objc_exception_try_enter pushes a catch buffer onto the EH stack.
  2528. objc_exception_try_exit pops the given catch buffer, which is
  2529. required to be the top of the EH stack.
  2530. objc_exception_throw pops the top of the EH stack, writes the
  2531. thrown exception into the appropriate field, and longjmps
  2532. to the setjmp buffer. It crashes the process (with a printf
  2533. and an abort()) if there are no catch buffers on the stack.
  2534. objc_exception_extract just reads the exception pointer out of the
  2535. catch buffer.
  2536. There's no reason an implementation couldn't use a light-weight
  2537. setjmp here --- something like __builtin_setjmp, but API-compatible
  2538. with the heavyweight setjmp. This will be more important if we ever
  2539. want to implement correct ObjC/C++ exception interactions for the
  2540. fragile ABI.
  2541. Note that for this use of setjmp/longjmp to be correct, we may need
  2542. to mark some local variables volatile: if a non-volatile local
  2543. variable is modified between the setjmp and the longjmp, it has
  2544. indeterminate value. For the purposes of LLVM IR, it may be
  2545. sufficient to make loads and stores within the @try (to variables
  2546. declared outside the @try) volatile. This is necessary for
  2547. optimized correctness, but is not currently being done; this is
  2548. being tracked as rdar://problem/8160285
  2549. The basic framework for a @try-catch-finally is as follows:
  2550. {
  2551. objc_exception_data d;
  2552. id _rethrow = null;
  2553. bool _call_try_exit = true;
  2554. objc_exception_try_enter(&d);
  2555. if (!setjmp(d.jmp_buf)) {
  2556. ... try body ...
  2557. } else {
  2558. // exception path
  2559. id _caught = objc_exception_extract(&d);
  2560. // enter new try scope for handlers
  2561. if (!setjmp(d.jmp_buf)) {
  2562. ... match exception and execute catch blocks ...
  2563. // fell off end, rethrow.
  2564. _rethrow = _caught;
  2565. ... jump-through-finally to finally_rethrow ...
  2566. } else {
  2567. // exception in catch block
  2568. _rethrow = objc_exception_extract(&d);
  2569. _call_try_exit = false;
  2570. ... jump-through-finally to finally_rethrow ...
  2571. }
  2572. }
  2573. ... jump-through-finally to finally_end ...
  2574. finally:
  2575. if (_call_try_exit)
  2576. objc_exception_try_exit(&d);
  2577. ... finally block ....
  2578. ... dispatch to finally destination ...
  2579. finally_rethrow:
  2580. objc_exception_throw(_rethrow);
  2581. finally_end:
  2582. }
  2583. This framework differs slightly from the one gcc uses, in that gcc
  2584. uses _rethrow to determine if objc_exception_try_exit should be called
  2585. and if the object should be rethrown. This breaks in the face of
  2586. throwing nil and introduces unnecessary branches.
  2587. We specialize this framework for a few particular circumstances:
  2588. - If there are no catch blocks, then we avoid emitting the second
  2589. exception handling context.
  2590. - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
  2591. e)) we avoid emitting the code to rethrow an uncaught exception.
  2592. - FIXME: If there is no @finally block we can do a few more
  2593. simplifications.
  2594. Rethrows and Jumps-Through-Finally
  2595. --
  2596. '@throw;' is supported by pushing the currently-caught exception
  2597. onto ObjCEHStack while the @catch blocks are emitted.
  2598. Branches through the @finally block are handled with an ordinary
  2599. normal cleanup. We do not register an EH cleanup; fragile-ABI ObjC
  2600. exceptions are not compatible with C++ exceptions, and this is
  2601. hardly the only place where this will go wrong.
  2602. @synchronized(expr) { stmt; } is emitted as if it were:
  2603. id synch_value = expr;
  2604. objc_sync_enter(synch_value);
  2605. @try { stmt; } @finally { objc_sync_exit(synch_value); }
  2606. */
  2607. void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
  2608. const Stmt &S) {
  2609. bool isTry = isa<ObjCAtTryStmt>(S);
  2610. // A destination for the fall-through edges of the catch handlers to
  2611. // jump to.
  2612. CodeGenFunction::JumpDest FinallyEnd =
  2613. CGF.getJumpDestInCurrentScope("finally.end");
  2614. // A destination for the rethrow edge of the catch handlers to jump
  2615. // to.
  2616. CodeGenFunction::JumpDest FinallyRethrow =
  2617. CGF.getJumpDestInCurrentScope("finally.rethrow");
  2618. // For @synchronized, call objc_sync_enter(sync.expr). The
  2619. // evaluation of the expression must occur before we enter the
  2620. // @synchronized. We can't avoid a temp here because we need the
  2621. // value to be preserved. If the backend ever does liveness
  2622. // correctly after setjmp, this will be unnecessary.
  2623. llvm::Value *SyncArgSlot = 0;
  2624. if (!isTry) {
  2625. llvm::Value *SyncArg =
  2626. CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
  2627. SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
  2628. CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg)
  2629. ->setDoesNotThrow();
  2630. SyncArgSlot = CGF.CreateTempAlloca(SyncArg->getType(), "sync.arg");
  2631. CGF.Builder.CreateStore(SyncArg, SyncArgSlot);
  2632. }
  2633. // Allocate memory for the setjmp buffer. This needs to be kept
  2634. // live throughout the try and catch blocks.
  2635. llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
  2636. "exceptiondata.ptr");
  2637. // Create the fragile hazards. Note that this will not capture any
  2638. // of the allocas required for exception processing, but will
  2639. // capture the current basic block (which extends all the way to the
  2640. // setjmp call) as "before the @try".
  2641. FragileHazards Hazards(CGF);
  2642. // Create a flag indicating whether the cleanup needs to call
  2643. // objc_exception_try_exit. This is true except when
  2644. // - no catches match and we're branching through the cleanup
  2645. // just to rethrow the exception, or
  2646. // - a catch matched and we're falling out of the catch handler.
  2647. // The setjmp-safety rule here is that we should always store to this
  2648. // variable in a place that dominates the branch through the cleanup
  2649. // without passing through any setjmps.
  2650. llvm::Value *CallTryExitVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(),
  2651. "_call_try_exit");
  2652. // A slot containing the exception to rethrow. Only needed when we
  2653. // have both a @catch and a @finally.
  2654. llvm::Value *PropagatingExnVar = 0;
  2655. // Push a normal cleanup to leave the try scope.
  2656. CGF.EHStack.pushCleanup<PerformFragileFinally>(NormalCleanup, &S,
  2657. SyncArgSlot,
  2658. CallTryExitVar,
  2659. ExceptionData,
  2660. &ObjCTypes);
  2661. // Enter a try block:
  2662. // - Call objc_exception_try_enter to push ExceptionData on top of
  2663. // the EH stack.
  2664. CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData)
  2665. ->setDoesNotThrow();
  2666. // - Call setjmp on the exception data buffer.
  2667. llvm::Constant *Zero = llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
  2668. llvm::Value *GEPIndexes[] = { Zero, Zero, Zero };
  2669. llvm::Value *SetJmpBuffer =
  2670. CGF.Builder.CreateGEP(ExceptionData, GEPIndexes, "setjmp_buffer");
  2671. llvm::CallInst *SetJmpResult =
  2672. CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(), SetJmpBuffer, "setjmp_result");
  2673. SetJmpResult->setDoesNotThrow();
  2674. SetJmpResult->setCanReturnTwice();
  2675. // If setjmp returned 0, enter the protected block; otherwise,
  2676. // branch to the handler.
  2677. llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
  2678. llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
  2679. llvm::Value *DidCatch =
  2680. CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception");
  2681. CGF.Builder.CreateCondBr(DidCatch, TryHandler, TryBlock);
  2682. // Emit the protected block.
  2683. CGF.EmitBlock(TryBlock);
  2684. CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar);
  2685. CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
  2686. : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
  2687. CGBuilderTy::InsertPoint TryFallthroughIP = CGF.Builder.saveAndClearIP();
  2688. // Emit the exception handler block.
  2689. CGF.EmitBlock(TryHandler);
  2690. // Don't optimize loads of the in-scope locals across this point.
  2691. Hazards.emitWriteHazard();
  2692. // For a @synchronized (or a @try with no catches), just branch
  2693. // through the cleanup to the rethrow block.
  2694. if (!isTry || !cast<ObjCAtTryStmt>(S).getNumCatchStmts()) {
  2695. // Tell the cleanup not to re-pop the exit.
  2696. CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar);
  2697. CGF.EmitBranchThroughCleanup(FinallyRethrow);
  2698. // Otherwise, we have to match against the caught exceptions.
  2699. } else {
  2700. // Retrieve the exception object. We may emit multiple blocks but
  2701. // nothing can cross this so the value is already in SSA form.
  2702. llvm::CallInst *Caught =
  2703. CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
  2704. ExceptionData, "caught");
  2705. Caught->setDoesNotThrow();
  2706. // Push the exception to rethrow onto the EH value stack for the
  2707. // benefit of any @throws in the handlers.
  2708. CGF.ObjCEHValueStack.push_back(Caught);
  2709. const ObjCAtTryStmt* AtTryStmt = cast<ObjCAtTryStmt>(&S);
  2710. bool HasFinally = (AtTryStmt->getFinallyStmt() != 0);
  2711. llvm::BasicBlock *CatchBlock = 0;
  2712. llvm::BasicBlock *CatchHandler = 0;
  2713. if (HasFinally) {
  2714. // Save the currently-propagating exception before
  2715. // objc_exception_try_enter clears the exception slot.
  2716. PropagatingExnVar = CGF.CreateTempAlloca(Caught->getType(),
  2717. "propagating_exception");
  2718. CGF.Builder.CreateStore(Caught, PropagatingExnVar);
  2719. // Enter a new exception try block (in case a @catch block
  2720. // throws an exception).
  2721. CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData)
  2722. ->setDoesNotThrow();
  2723. llvm::CallInst *SetJmpResult =
  2724. CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(), SetJmpBuffer,
  2725. "setjmp.result");
  2726. SetJmpResult->setDoesNotThrow();
  2727. SetJmpResult->setCanReturnTwice();
  2728. llvm::Value *Threw =
  2729. CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception");
  2730. CatchBlock = CGF.createBasicBlock("catch");
  2731. CatchHandler = CGF.createBasicBlock("catch_for_catch");
  2732. CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
  2733. CGF.EmitBlock(CatchBlock);
  2734. }
  2735. CGF.Builder.CreateStore(CGF.Builder.getInt1(HasFinally), CallTryExitVar);
  2736. // Handle catch list. As a special case we check if everything is
  2737. // matched and avoid generating code for falling off the end if
  2738. // so.
  2739. bool AllMatched = false;
  2740. for (unsigned I = 0, N = AtTryStmt->getNumCatchStmts(); I != N; ++I) {
  2741. const ObjCAtCatchStmt *CatchStmt = AtTryStmt->getCatchStmt(I);
  2742. const VarDecl *CatchParam = CatchStmt->getCatchParamDecl();
  2743. const ObjCObjectPointerType *OPT = 0;
  2744. // catch(...) always matches.
  2745. if (!CatchParam) {
  2746. AllMatched = true;
  2747. } else {
  2748. OPT = CatchParam->getType()->getAs<ObjCObjectPointerType>();
  2749. // catch(id e) always matches under this ABI, since only
  2750. // ObjC exceptions end up here in the first place.
  2751. // FIXME: For the time being we also match id<X>; this should
  2752. // be rejected by Sema instead.
  2753. if (OPT && (OPT->isObjCIdType() || OPT->isObjCQualifiedIdType()))
  2754. AllMatched = true;
  2755. }
  2756. // If this is a catch-all, we don't need to test anything.
  2757. if (AllMatched) {
  2758. CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF);
  2759. if (CatchParam) {
  2760. CGF.EmitAutoVarDecl(*CatchParam);
  2761. assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
  2762. // These types work out because ConvertType(id) == i8*.
  2763. CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
  2764. }
  2765. CGF.EmitStmt(CatchStmt->getCatchBody());
  2766. // The scope of the catch variable ends right here.
  2767. CatchVarCleanups.ForceCleanup();
  2768. CGF.EmitBranchThroughCleanup(FinallyEnd);
  2769. break;
  2770. }
  2771. assert(OPT && "Unexpected non-object pointer type in @catch");
  2772. const ObjCObjectType *ObjTy = OPT->getObjectType();
  2773. // FIXME: @catch (Class c) ?
  2774. ObjCInterfaceDecl *IDecl = ObjTy->getInterface();
  2775. assert(IDecl && "Catch parameter must have Objective-C type!");
  2776. // Check if the @catch block matches the exception object.
  2777. llvm::Value *Class = EmitClassRef(CGF.Builder, IDecl);
  2778. llvm::CallInst *Match =
  2779. CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(),
  2780. Class, Caught, "match");
  2781. Match->setDoesNotThrow();
  2782. llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("match");
  2783. llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch.next");
  2784. CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
  2785. MatchedBlock, NextCatchBlock);
  2786. // Emit the @catch block.
  2787. CGF.EmitBlock(MatchedBlock);
  2788. // Collect any cleanups for the catch variable. The scope lasts until
  2789. // the end of the catch body.
  2790. CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF);
  2791. CGF.EmitAutoVarDecl(*CatchParam);
  2792. assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
  2793. // Initialize the catch variable.
  2794. llvm::Value *Tmp =
  2795. CGF.Builder.CreateBitCast(Caught,
  2796. CGF.ConvertType(CatchParam->getType()));
  2797. CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
  2798. CGF.EmitStmt(CatchStmt->getCatchBody());
  2799. // We're done with the catch variable.
  2800. CatchVarCleanups.ForceCleanup();
  2801. CGF.EmitBranchThroughCleanup(FinallyEnd);
  2802. CGF.EmitBlock(NextCatchBlock);
  2803. }
  2804. CGF.ObjCEHValueStack.pop_back();
  2805. // If nothing wanted anything to do with the caught exception,
  2806. // kill the extract call.
  2807. if (Caught->use_empty())
  2808. Caught->eraseFromParent();
  2809. if (!AllMatched)
  2810. CGF.EmitBranchThroughCleanup(FinallyRethrow);
  2811. if (HasFinally) {
  2812. // Emit the exception handler for the @catch blocks.
  2813. CGF.EmitBlock(CatchHandler);
  2814. // In theory we might now need a write hazard, but actually it's
  2815. // unnecessary because there's no local-accessing code between
  2816. // the try's write hazard and here.
  2817. //Hazards.emitWriteHazard();
  2818. // Extract the new exception and save it to the
  2819. // propagating-exception slot.
  2820. assert(PropagatingExnVar);
  2821. llvm::CallInst *NewCaught =
  2822. CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
  2823. ExceptionData, "caught");
  2824. NewCaught->setDoesNotThrow();
  2825. CGF.Builder.CreateStore(NewCaught, PropagatingExnVar);
  2826. // Don't pop the catch handler; the throw already did.
  2827. CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar);
  2828. CGF.EmitBranchThroughCleanup(FinallyRethrow);
  2829. }
  2830. }
  2831. // Insert read hazards as required in the new blocks.
  2832. Hazards.emitHazardsInNewBlocks();
  2833. // Pop the cleanup.
  2834. CGF.Builder.restoreIP(TryFallthroughIP);
  2835. if (CGF.HaveInsertPoint())
  2836. CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar);
  2837. CGF.PopCleanupBlock();
  2838. CGF.EmitBlock(FinallyEnd.getBlock(), true);
  2839. // Emit the rethrow block.
  2840. CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
  2841. CGF.EmitBlock(FinallyRethrow.getBlock(), true);
  2842. if (CGF.HaveInsertPoint()) {
  2843. // If we have a propagating-exception variable, check it.
  2844. llvm::Value *PropagatingExn;
  2845. if (PropagatingExnVar) {
  2846. PropagatingExn = CGF.Builder.CreateLoad(PropagatingExnVar);
  2847. // Otherwise, just look in the buffer for the exception to throw.
  2848. } else {
  2849. llvm::CallInst *Caught =
  2850. CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
  2851. ExceptionData);
  2852. Caught->setDoesNotThrow();
  2853. PropagatingExn = Caught;
  2854. }
  2855. CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), PropagatingExn)
  2856. ->setDoesNotThrow();
  2857. CGF.Builder.CreateUnreachable();
  2858. }
  2859. CGF.Builder.restoreIP(SavedIP);
  2860. }
  2861. void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
  2862. const ObjCAtThrowStmt &S) {
  2863. llvm::Value *ExceptionAsObject;
  2864. if (const Expr *ThrowExpr = S.getThrowExpr()) {
  2865. llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
  2866. ExceptionAsObject =
  2867. CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy);
  2868. } else {
  2869. assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
  2870. "Unexpected rethrow outside @catch block.");
  2871. ExceptionAsObject = CGF.ObjCEHValueStack.back();
  2872. }
  2873. CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject)
  2874. ->setDoesNotReturn();
  2875. CGF.Builder.CreateUnreachable();
  2876. // Clear the insertion point to indicate we are in unreachable code.
  2877. CGF.Builder.ClearInsertionPoint();
  2878. }
  2879. /// EmitObjCWeakRead - Code gen for loading value of a __weak
  2880. /// object: objc_read_weak (id *src)
  2881. ///
  2882. llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
  2883. llvm::Value *AddrWeakObj) {
  2884. llvm::Type* DestTy =
  2885. cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
  2886. AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj,
  2887. ObjCTypes.PtrObjectPtrTy);
  2888. llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
  2889. AddrWeakObj, "weakread");
  2890. read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
  2891. return read_weak;
  2892. }
  2893. /// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
  2894. /// objc_assign_weak (id src, id *dst)
  2895. ///
  2896. void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
  2897. llvm::Value *src, llvm::Value *dst) {
  2898. llvm::Type * SrcTy = src->getType();
  2899. if (!isa<llvm::PointerType>(SrcTy)) {
  2900. unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
  2901. assert(Size <= 8 && "does not support size > 8");
  2902. src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
  2903. : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
  2904. src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
  2905. }
  2906. src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
  2907. dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
  2908. CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
  2909. src, dst, "weakassign");
  2910. return;
  2911. }
  2912. /// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
  2913. /// objc_assign_global (id src, id *dst)
  2914. ///
  2915. void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
  2916. llvm::Value *src, llvm::Value *dst,
  2917. bool threadlocal) {
  2918. llvm::Type * SrcTy = src->getType();
  2919. if (!isa<llvm::PointerType>(SrcTy)) {
  2920. unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
  2921. assert(Size <= 8 && "does not support size > 8");
  2922. src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
  2923. : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
  2924. src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
  2925. }
  2926. src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
  2927. dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
  2928. if (!threadlocal)
  2929. CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
  2930. src, dst, "globalassign");
  2931. else
  2932. CGF.Builder.CreateCall2(ObjCTypes.getGcAssignThreadLocalFn(),
  2933. src, dst, "threadlocalassign");
  2934. return;
  2935. }
  2936. /// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
  2937. /// objc_assign_ivar (id src, id *dst, ptrdiff_t ivaroffset)
  2938. ///
  2939. void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
  2940. llvm::Value *src, llvm::Value *dst,
  2941. llvm::Value *ivarOffset) {
  2942. assert(ivarOffset && "EmitObjCIvarAssign - ivarOffset is NULL");
  2943. llvm::Type * SrcTy = src->getType();
  2944. if (!isa<llvm::PointerType>(SrcTy)) {
  2945. unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
  2946. assert(Size <= 8 && "does not support size > 8");
  2947. src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
  2948. : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
  2949. src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
  2950. }
  2951. src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
  2952. dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
  2953. CGF.Builder.CreateCall3(ObjCTypes.getGcAssignIvarFn(),
  2954. src, dst, ivarOffset);
  2955. return;
  2956. }
  2957. /// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
  2958. /// objc_assign_strongCast (id src, id *dst)
  2959. ///
  2960. void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
  2961. llvm::Value *src, llvm::Value *dst) {
  2962. llvm::Type * SrcTy = src->getType();
  2963. if (!isa<llvm::PointerType>(SrcTy)) {
  2964. unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
  2965. assert(Size <= 8 && "does not support size > 8");
  2966. src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
  2967. : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
  2968. src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
  2969. }
  2970. src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
  2971. dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
  2972. CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
  2973. src, dst, "weakassign");
  2974. return;
  2975. }
  2976. void CGObjCMac::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
  2977. llvm::Value *DestPtr,
  2978. llvm::Value *SrcPtr,
  2979. llvm::Value *size) {
  2980. SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy);
  2981. DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy);
  2982. CGF.Builder.CreateCall3(ObjCTypes.GcMemmoveCollectableFn(),
  2983. DestPtr, SrcPtr, size);
  2984. return;
  2985. }
  2986. /// EmitObjCValueForIvar - Code Gen for ivar reference.
  2987. ///
  2988. LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
  2989. QualType ObjectTy,
  2990. llvm::Value *BaseValue,
  2991. const ObjCIvarDecl *Ivar,
  2992. unsigned CVRQualifiers) {
  2993. const ObjCInterfaceDecl *ID =
  2994. ObjectTy->getAs<ObjCObjectType>()->getInterface();
  2995. return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
  2996. EmitIvarOffset(CGF, ID, Ivar));
  2997. }
  2998. llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
  2999. const ObjCInterfaceDecl *Interface,
  3000. const ObjCIvarDecl *Ivar) {
  3001. uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
  3002. return llvm::ConstantInt::get(
  3003. CGM.getTypes().ConvertType(CGM.getContext().LongTy),
  3004. Offset);
  3005. }
  3006. /* *** Private Interface *** */
  3007. /// EmitImageInfo - Emit the image info marker used to encode some module
  3008. /// level information.
  3009. ///
  3010. /// See: <rdr://4810609&4810587&4810587>
  3011. /// struct IMAGE_INFO {
  3012. /// unsigned version;
  3013. /// unsigned flags;
  3014. /// };
  3015. enum ImageInfoFlags {
  3016. eImageInfo_FixAndContinue = (1 << 0),
  3017. eImageInfo_GarbageCollected = (1 << 1),
  3018. eImageInfo_GCOnly = (1 << 2),
  3019. eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set.
  3020. // A flag indicating that the module has no instances of a @synthesize of a
  3021. // superclass variable. <rdar://problem/6803242>
  3022. eImageInfo_CorrectedSynthesize = (1 << 4)
  3023. };
  3024. void CGObjCCommonMac::EmitImageInfo() {
  3025. unsigned version = 0; // Version is unused?
  3026. const char *Section = (ObjCABI == 1) ?
  3027. "__OBJC, __image_info,regular" :
  3028. "__DATA, __objc_imageinfo, regular, no_dead_strip";
  3029. // Generate module-level named metadata to convey this information to the
  3030. // linker and code-gen.
  3031. llvm::Module &Mod = CGM.getModule();
  3032. // Add the ObjC ABI version to the module flags.
  3033. Mod.addModuleFlag(llvm::Module::Error, "Objective-C Version", ObjCABI);
  3034. Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Version",
  3035. version);
  3036. Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Section",
  3037. llvm::MDString::get(VMContext,Section));
  3038. if (CGM.getLangOptions().getGC() == LangOptions::NonGC) {
  3039. // Non-GC overrides those files which specify GC.
  3040. Mod.addModuleFlag(llvm::Module::Override,
  3041. "Objective-C Garbage Collection", (uint32_t)0);
  3042. } else {
  3043. // Add the ObjC garbage collection value.
  3044. Mod.addModuleFlag(llvm::Module::Error,
  3045. "Objective-C Garbage Collection",
  3046. eImageInfo_GarbageCollected);
  3047. if (CGM.getLangOptions().getGC() == LangOptions::GCOnly) {
  3048. // Add the ObjC GC Only value.
  3049. Mod.addModuleFlag(llvm::Module::Error, "Objective-C GC Only",
  3050. eImageInfo_GCOnly);
  3051. // Require that GC be specified and set to eImageInfo_GarbageCollected.
  3052. llvm::Value *Ops[2] = {
  3053. llvm::MDString::get(VMContext, "Objective-C Garbage Collection"),
  3054. llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
  3055. eImageInfo_GarbageCollected)
  3056. };
  3057. Mod.addModuleFlag(llvm::Module::Require, "Objective-C GC Only",
  3058. llvm::MDNode::get(VMContext, Ops));
  3059. }
  3060. }
  3061. }
  3062. // struct objc_module {
  3063. // unsigned long version;
  3064. // unsigned long size;
  3065. // const char *name;
  3066. // Symtab symtab;
  3067. // };
  3068. // FIXME: Get from somewhere
  3069. static const int ModuleVersion = 7;
  3070. void CGObjCMac::EmitModuleInfo() {
  3071. uint64_t Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.ModuleTy);
  3072. llvm::Constant *Values[] = {
  3073. llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion),
  3074. llvm::ConstantInt::get(ObjCTypes.LongTy, Size),
  3075. // This used to be the filename, now it is unused. <rdr://4327263>
  3076. GetClassName(&CGM.getContext().Idents.get("")),
  3077. EmitModuleSymbols()
  3078. };
  3079. CreateMetadataVar("\01L_OBJC_MODULES",
  3080. llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
  3081. "__OBJC,__module_info,regular,no_dead_strip",
  3082. 4, true);
  3083. }
  3084. llvm::Constant *CGObjCMac::EmitModuleSymbols() {
  3085. unsigned NumClasses = DefinedClasses.size();
  3086. unsigned NumCategories = DefinedCategories.size();
  3087. // Return null if no symbols were defined.
  3088. if (!NumClasses && !NumCategories)
  3089. return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
  3090. llvm::Constant *Values[5];
  3091. Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
  3092. Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
  3093. Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
  3094. Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
  3095. // The runtime expects exactly the list of defined classes followed
  3096. // by the list of defined categories, in a single array.
  3097. SmallVector<llvm::Constant*, 8> Symbols(NumClasses + NumCategories);
  3098. for (unsigned i=0; i<NumClasses; i++)
  3099. Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
  3100. ObjCTypes.Int8PtrTy);
  3101. for (unsigned i=0; i<NumCategories; i++)
  3102. Symbols[NumClasses + i] =
  3103. llvm::ConstantExpr::getBitCast(DefinedCategories[i],
  3104. ObjCTypes.Int8PtrTy);
  3105. Values[4] =
  3106. llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
  3107. Symbols.size()),
  3108. Symbols);
  3109. llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
  3110. llvm::GlobalVariable *GV =
  3111. CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
  3112. "__OBJC,__symbols,regular,no_dead_strip",
  3113. 4, true);
  3114. return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
  3115. }
  3116. llvm::Value *CGObjCMac::EmitClassRefFromId(CGBuilderTy &Builder,
  3117. IdentifierInfo *II) {
  3118. LazySymbols.insert(II);
  3119. llvm::GlobalVariable *&Entry = ClassReferences[II];
  3120. if (!Entry) {
  3121. llvm::Constant *Casted =
  3122. llvm::ConstantExpr::getBitCast(GetClassName(II),
  3123. ObjCTypes.ClassPtrTy);
  3124. Entry =
  3125. CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
  3126. "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
  3127. 4, true);
  3128. }
  3129. return Builder.CreateLoad(Entry);
  3130. }
  3131. llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
  3132. const ObjCInterfaceDecl *ID) {
  3133. return EmitClassRefFromId(Builder, ID->getIdentifier());
  3134. }
  3135. llvm::Value *CGObjCMac::EmitNSAutoreleasePoolClassRef(CGBuilderTy &Builder) {
  3136. IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool");
  3137. return EmitClassRefFromId(Builder, II);
  3138. }
  3139. llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel,
  3140. bool lvalue) {
  3141. llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
  3142. if (!Entry) {
  3143. llvm::Constant *Casted =
  3144. llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
  3145. ObjCTypes.SelectorPtrTy);
  3146. Entry =
  3147. CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
  3148. "__OBJC,__message_refs,literal_pointers,no_dead_strip",
  3149. 4, true);
  3150. }
  3151. if (lvalue)
  3152. return Entry;
  3153. return Builder.CreateLoad(Entry);
  3154. }
  3155. llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
  3156. llvm::GlobalVariable *&Entry = ClassNames[Ident];
  3157. if (!Entry)
  3158. Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
  3159. llvm::ConstantDataArray::getString(VMContext,
  3160. Ident->getNameStart()),
  3161. ((ObjCABI == 2) ?
  3162. "__TEXT,__objc_classname,cstring_literals" :
  3163. "__TEXT,__cstring,cstring_literals"),
  3164. 1, true);
  3165. return getConstantGEP(VMContext, Entry, 0, 0);
  3166. }
  3167. llvm::Function *CGObjCCommonMac::GetMethodDefinition(const ObjCMethodDecl *MD) {
  3168. llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*>::iterator
  3169. I = MethodDefinitions.find(MD);
  3170. if (I != MethodDefinitions.end())
  3171. return I->second;
  3172. return NULL;
  3173. }
  3174. /// GetIvarLayoutName - Returns a unique constant for the given
  3175. /// ivar layout bitmap.
  3176. llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
  3177. const ObjCCommonTypesHelper &ObjCTypes) {
  3178. return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
  3179. }
  3180. void CGObjCCommonMac::BuildAggrIvarRecordLayout(const RecordType *RT,
  3181. unsigned int BytePos,
  3182. bool ForStrongLayout,
  3183. bool &HasUnion) {
  3184. const RecordDecl *RD = RT->getDecl();
  3185. // FIXME - Use iterator.
  3186. SmallVector<const FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
  3187. llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));
  3188. const llvm::StructLayout *RecLayout =
  3189. CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
  3190. BuildAggrIvarLayout(0, RecLayout, RD, Fields, BytePos,
  3191. ForStrongLayout, HasUnion);
  3192. }
  3193. void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
  3194. const llvm::StructLayout *Layout,
  3195. const RecordDecl *RD,
  3196. const SmallVectorImpl<const FieldDecl*> &RecFields,
  3197. unsigned int BytePos, bool ForStrongLayout,
  3198. bool &HasUnion) {
  3199. bool IsUnion = (RD && RD->isUnion());
  3200. uint64_t MaxUnionIvarSize = 0;
  3201. uint64_t MaxSkippedUnionIvarSize = 0;
  3202. const FieldDecl *MaxField = 0;
  3203. const FieldDecl *MaxSkippedField = 0;
  3204. const FieldDecl *LastFieldBitfieldOrUnnamed = 0;
  3205. uint64_t MaxFieldOffset = 0;
  3206. uint64_t MaxSkippedFieldOffset = 0;
  3207. uint64_t LastBitfieldOrUnnamedOffset = 0;
  3208. uint64_t FirstFieldDelta = 0;
  3209. if (RecFields.empty())
  3210. return;
  3211. unsigned WordSizeInBits = CGM.getContext().getTargetInfo().getPointerWidth(0);
  3212. unsigned ByteSizeInBits = CGM.getContext().getTargetInfo().getCharWidth();
  3213. if (!RD && CGM.getLangOptions().ObjCAutoRefCount) {
  3214. const FieldDecl *FirstField = RecFields[0];
  3215. FirstFieldDelta =
  3216. ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(FirstField));
  3217. }
  3218. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  3219. const FieldDecl *Field = RecFields[i];
  3220. uint64_t FieldOffset;
  3221. if (RD) {
  3222. // Note that 'i' here is actually the field index inside RD of Field,
  3223. // although this dependency is hidden.
  3224. const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
  3225. FieldOffset = (RL.getFieldOffset(i) / ByteSizeInBits) - FirstFieldDelta;
  3226. } else
  3227. FieldOffset =
  3228. ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field)) - FirstFieldDelta;
  3229. // Skip over unnamed or bitfields
  3230. if (!Field->getIdentifier() || Field->isBitField()) {
  3231. LastFieldBitfieldOrUnnamed = Field;
  3232. LastBitfieldOrUnnamedOffset = FieldOffset;
  3233. continue;
  3234. }
  3235. LastFieldBitfieldOrUnnamed = 0;
  3236. QualType FQT = Field->getType();
  3237. if (FQT->isRecordType() || FQT->isUnionType()) {
  3238. if (FQT->isUnionType())
  3239. HasUnion = true;
  3240. BuildAggrIvarRecordLayout(FQT->getAs<RecordType>(),
  3241. BytePos + FieldOffset,
  3242. ForStrongLayout, HasUnion);
  3243. continue;
  3244. }
  3245. if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
  3246. const ConstantArrayType *CArray =
  3247. dyn_cast_or_null<ConstantArrayType>(Array);
  3248. uint64_t ElCount = CArray->getSize().getZExtValue();
  3249. assert(CArray && "only array with known element size is supported");
  3250. FQT = CArray->getElementType();
  3251. while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
  3252. const ConstantArrayType *CArray =
  3253. dyn_cast_or_null<ConstantArrayType>(Array);
  3254. ElCount *= CArray->getSize().getZExtValue();
  3255. FQT = CArray->getElementType();
  3256. }
  3257. assert(!FQT->isUnionType() &&
  3258. "layout for array of unions not supported");
  3259. if (FQT->isRecordType() && ElCount) {
  3260. int OldIndex = IvarsInfo.size() - 1;
  3261. int OldSkIndex = SkipIvars.size() -1;
  3262. const RecordType *RT = FQT->getAs<RecordType>();
  3263. BuildAggrIvarRecordLayout(RT, BytePos + FieldOffset,
  3264. ForStrongLayout, HasUnion);
  3265. // Replicate layout information for each array element. Note that
  3266. // one element is already done.
  3267. uint64_t ElIx = 1;
  3268. for (int FirstIndex = IvarsInfo.size() - 1,
  3269. FirstSkIndex = SkipIvars.size() - 1 ;ElIx < ElCount; ElIx++) {
  3270. uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
  3271. for (int i = OldIndex+1; i <= FirstIndex; ++i)
  3272. IvarsInfo.push_back(GC_IVAR(IvarsInfo[i].ivar_bytepos + Size*ElIx,
  3273. IvarsInfo[i].ivar_size));
  3274. for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i)
  3275. SkipIvars.push_back(GC_IVAR(SkipIvars[i].ivar_bytepos + Size*ElIx,
  3276. SkipIvars[i].ivar_size));
  3277. }
  3278. continue;
  3279. }
  3280. }
  3281. // At this point, we are done with Record/Union and array there of.
  3282. // For other arrays we are down to its element type.
  3283. Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), FQT);
  3284. unsigned FieldSize = CGM.getContext().getTypeSize(Field->getType());
  3285. if ((ForStrongLayout && GCAttr == Qualifiers::Strong)
  3286. || (!ForStrongLayout && GCAttr == Qualifiers::Weak)) {
  3287. if (IsUnion) {
  3288. uint64_t UnionIvarSize = FieldSize / WordSizeInBits;
  3289. if (UnionIvarSize > MaxUnionIvarSize) {
  3290. MaxUnionIvarSize = UnionIvarSize;
  3291. MaxField = Field;
  3292. MaxFieldOffset = FieldOffset;
  3293. }
  3294. } else {
  3295. IvarsInfo.push_back(GC_IVAR(BytePos + FieldOffset,
  3296. FieldSize / WordSizeInBits));
  3297. }
  3298. } else if ((ForStrongLayout &&
  3299. (GCAttr == Qualifiers::GCNone || GCAttr == Qualifiers::Weak))
  3300. || (!ForStrongLayout && GCAttr != Qualifiers::Weak)) {
  3301. if (IsUnion) {
  3302. // FIXME: Why the asymmetry? We divide by word size in bits on other
  3303. // side.
  3304. uint64_t UnionIvarSize = FieldSize;
  3305. if (UnionIvarSize > MaxSkippedUnionIvarSize) {
  3306. MaxSkippedUnionIvarSize = UnionIvarSize;
  3307. MaxSkippedField = Field;
  3308. MaxSkippedFieldOffset = FieldOffset;
  3309. }
  3310. } else {
  3311. // FIXME: Why the asymmetry, we divide by byte size in bits here?
  3312. SkipIvars.push_back(GC_IVAR(BytePos + FieldOffset,
  3313. FieldSize / ByteSizeInBits));
  3314. }
  3315. }
  3316. }
  3317. if (LastFieldBitfieldOrUnnamed) {
  3318. if (LastFieldBitfieldOrUnnamed->isBitField()) {
  3319. // Last field was a bitfield. Must update skip info.
  3320. uint64_t BitFieldSize
  3321. = LastFieldBitfieldOrUnnamed->getBitWidthValue(CGM.getContext());
  3322. GC_IVAR skivar;
  3323. skivar.ivar_bytepos = BytePos + LastBitfieldOrUnnamedOffset;
  3324. skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
  3325. + ((BitFieldSize % ByteSizeInBits) != 0);
  3326. SkipIvars.push_back(skivar);
  3327. } else {
  3328. assert(!LastFieldBitfieldOrUnnamed->getIdentifier() &&"Expected unnamed");
  3329. // Last field was unnamed. Must update skip info.
  3330. unsigned FieldSize
  3331. = CGM.getContext().getTypeSize(LastFieldBitfieldOrUnnamed->getType());
  3332. SkipIvars.push_back(GC_IVAR(BytePos + LastBitfieldOrUnnamedOffset,
  3333. FieldSize / ByteSizeInBits));
  3334. }
  3335. }
  3336. if (MaxField)
  3337. IvarsInfo.push_back(GC_IVAR(BytePos + MaxFieldOffset,
  3338. MaxUnionIvarSize));
  3339. if (MaxSkippedField)
  3340. SkipIvars.push_back(GC_IVAR(BytePos + MaxSkippedFieldOffset,
  3341. MaxSkippedUnionIvarSize));
  3342. }
  3343. /// BuildIvarLayoutBitmap - This routine is the horsework for doing all
  3344. /// the computations and returning the layout bitmap (for ivar or blocks) in
  3345. /// the given argument BitMap string container. Routine reads
  3346. /// two containers, IvarsInfo and SkipIvars which are assumed to be
  3347. /// filled already by the caller.
  3348. llvm::Constant *CGObjCCommonMac::BuildIvarLayoutBitmap(std::string &BitMap) {
  3349. unsigned int WordsToScan, WordsToSkip;
  3350. llvm::Type *PtrTy = CGM.Int8PtrTy;
  3351. // Build the string of skip/scan nibbles
  3352. SmallVector<SKIP_SCAN, 32> SkipScanIvars;
  3353. unsigned int WordSize =
  3354. CGM.getTypes().getTargetData().getTypeAllocSize(PtrTy);
  3355. if (IvarsInfo[0].ivar_bytepos == 0) {
  3356. WordsToSkip = 0;
  3357. WordsToScan = IvarsInfo[0].ivar_size;
  3358. } else {
  3359. WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
  3360. WordsToScan = IvarsInfo[0].ivar_size;
  3361. }
  3362. for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++) {
  3363. unsigned int TailPrevGCObjC =
  3364. IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
  3365. if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC) {
  3366. // consecutive 'scanned' object pointers.
  3367. WordsToScan += IvarsInfo[i].ivar_size;
  3368. } else {
  3369. // Skip over 'gc'able object pointer which lay over each other.
  3370. if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
  3371. continue;
  3372. // Must skip over 1 or more words. We save current skip/scan values
  3373. // and start a new pair.
  3374. SKIP_SCAN SkScan;
  3375. SkScan.skip = WordsToSkip;
  3376. SkScan.scan = WordsToScan;
  3377. SkipScanIvars.push_back(SkScan);
  3378. // Skip the hole.
  3379. SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
  3380. SkScan.scan = 0;
  3381. SkipScanIvars.push_back(SkScan);
  3382. WordsToSkip = 0;
  3383. WordsToScan = IvarsInfo[i].ivar_size;
  3384. }
  3385. }
  3386. if (WordsToScan > 0) {
  3387. SKIP_SCAN SkScan;
  3388. SkScan.skip = WordsToSkip;
  3389. SkScan.scan = WordsToScan;
  3390. SkipScanIvars.push_back(SkScan);
  3391. }
  3392. if (!SkipIvars.empty()) {
  3393. unsigned int LastIndex = SkipIvars.size()-1;
  3394. int LastByteSkipped =
  3395. SkipIvars[LastIndex].ivar_bytepos + SkipIvars[LastIndex].ivar_size;
  3396. LastIndex = IvarsInfo.size()-1;
  3397. int LastByteScanned =
  3398. IvarsInfo[LastIndex].ivar_bytepos +
  3399. IvarsInfo[LastIndex].ivar_size * WordSize;
  3400. // Compute number of bytes to skip at the tail end of the last ivar scanned.
  3401. if (LastByteSkipped > LastByteScanned) {
  3402. unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
  3403. SKIP_SCAN SkScan;
  3404. SkScan.skip = TotalWords - (LastByteScanned/WordSize);
  3405. SkScan.scan = 0;
  3406. SkipScanIvars.push_back(SkScan);
  3407. }
  3408. }
  3409. // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
  3410. // as 0xMN.
  3411. int SkipScan = SkipScanIvars.size()-1;
  3412. for (int i = 0; i <= SkipScan; i++) {
  3413. if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
  3414. && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
  3415. // 0xM0 followed by 0x0N detected.
  3416. SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
  3417. for (int j = i+1; j < SkipScan; j++)
  3418. SkipScanIvars[j] = SkipScanIvars[j+1];
  3419. --SkipScan;
  3420. }
  3421. }
  3422. // Generate the string.
  3423. for (int i = 0; i <= SkipScan; i++) {
  3424. unsigned char byte;
  3425. unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
  3426. unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
  3427. unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
  3428. unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
  3429. // first skip big.
  3430. for (unsigned int ix = 0; ix < skip_big; ix++)
  3431. BitMap += (unsigned char)(0xf0);
  3432. // next (skip small, scan)
  3433. if (skip_small) {
  3434. byte = skip_small << 4;
  3435. if (scan_big > 0) {
  3436. byte |= 0xf;
  3437. --scan_big;
  3438. } else if (scan_small) {
  3439. byte |= scan_small;
  3440. scan_small = 0;
  3441. }
  3442. BitMap += byte;
  3443. }
  3444. // next scan big
  3445. for (unsigned int ix = 0; ix < scan_big; ix++)
  3446. BitMap += (unsigned char)(0x0f);
  3447. // last scan small
  3448. if (scan_small) {
  3449. byte = scan_small;
  3450. BitMap += byte;
  3451. }
  3452. }
  3453. // null terminate string.
  3454. unsigned char zero = 0;
  3455. BitMap += zero;
  3456. llvm::GlobalVariable * Entry =
  3457. CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
  3458. llvm::ConstantDataArray::getString(VMContext, BitMap,false),
  3459. ((ObjCABI == 2) ?
  3460. "__TEXT,__objc_classname,cstring_literals" :
  3461. "__TEXT,__cstring,cstring_literals"),
  3462. 1, true);
  3463. return getConstantGEP(VMContext, Entry, 0, 0);
  3464. }
  3465. /// BuildIvarLayout - Builds ivar layout bitmap for the class
  3466. /// implementation for the __strong or __weak case.
  3467. /// The layout map displays which words in ivar list must be skipped
  3468. /// and which must be scanned by GC (see below). String is built of bytes.
  3469. /// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
  3470. /// of words to skip and right nibble is count of words to scan. So, each
  3471. /// nibble represents up to 15 workds to skip or scan. Skipping the rest is
  3472. /// represented by a 0x00 byte which also ends the string.
  3473. /// 1. when ForStrongLayout is true, following ivars are scanned:
  3474. /// - id, Class
  3475. /// - object *
  3476. /// - __strong anything
  3477. ///
  3478. /// 2. When ForStrongLayout is false, following ivars are scanned:
  3479. /// - __weak anything
  3480. ///
  3481. llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
  3482. const ObjCImplementationDecl *OMD,
  3483. bool ForStrongLayout) {
  3484. bool hasUnion = false;
  3485. llvm::Type *PtrTy = CGM.Int8PtrTy;
  3486. if (CGM.getLangOptions().getGC() == LangOptions::NonGC &&
  3487. !CGM.getLangOptions().ObjCAutoRefCount)
  3488. return llvm::Constant::getNullValue(PtrTy);
  3489. const ObjCInterfaceDecl *OI = OMD->getClassInterface();
  3490. SmallVector<const FieldDecl*, 32> RecFields;
  3491. if (CGM.getLangOptions().ObjCAutoRefCount) {
  3492. for (const ObjCIvarDecl *IVD = OI->all_declared_ivar_begin();
  3493. IVD; IVD = IVD->getNextIvar())
  3494. RecFields.push_back(cast<FieldDecl>(IVD));
  3495. }
  3496. else {
  3497. SmallVector<const ObjCIvarDecl*, 32> Ivars;
  3498. CGM.getContext().DeepCollectObjCIvars(OI, true, Ivars);
  3499. // FIXME: This is not ideal; we shouldn't have to do this copy.
  3500. RecFields.append(Ivars.begin(), Ivars.end());
  3501. }
  3502. if (RecFields.empty())
  3503. return llvm::Constant::getNullValue(PtrTy);
  3504. SkipIvars.clear();
  3505. IvarsInfo.clear();
  3506. BuildAggrIvarLayout(OMD, 0, 0, RecFields, 0, ForStrongLayout, hasUnion);
  3507. if (IvarsInfo.empty())
  3508. return llvm::Constant::getNullValue(PtrTy);
  3509. // Sort on byte position in case we encounterred a union nested in
  3510. // the ivar list.
  3511. if (hasUnion && !IvarsInfo.empty())
  3512. std::sort(IvarsInfo.begin(), IvarsInfo.end());
  3513. if (hasUnion && !SkipIvars.empty())
  3514. std::sort(SkipIvars.begin(), SkipIvars.end());
  3515. std::string BitMap;
  3516. llvm::Constant *C = BuildIvarLayoutBitmap(BitMap);
  3517. if (CGM.getLangOptions().ObjCGCBitmapPrint) {
  3518. printf("\n%s ivar layout for class '%s': ",
  3519. ForStrongLayout ? "strong" : "weak",
  3520. OMD->getClassInterface()->getName().data());
  3521. const unsigned char *s = (unsigned char*)BitMap.c_str();
  3522. for (unsigned i = 0, e = BitMap.size(); i < e; i++)
  3523. if (!(s[i] & 0xf0))
  3524. printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
  3525. else
  3526. printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
  3527. printf("\n");
  3528. }
  3529. return C;
  3530. }
  3531. llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
  3532. llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
  3533. // FIXME: Avoid std::string in "Sel.getAsString()"
  3534. if (!Entry)
  3535. Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
  3536. llvm::ConstantDataArray::getString(VMContext, Sel.getAsString()),
  3537. ((ObjCABI == 2) ?
  3538. "__TEXT,__objc_methname,cstring_literals" :
  3539. "__TEXT,__cstring,cstring_literals"),
  3540. 1, true);
  3541. return getConstantGEP(VMContext, Entry, 0, 0);
  3542. }
  3543. // FIXME: Merge into a single cstring creation function.
  3544. llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
  3545. return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
  3546. }
  3547. llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
  3548. std::string TypeStr;
  3549. CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
  3550. llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
  3551. if (!Entry)
  3552. Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
  3553. llvm::ConstantDataArray::getString(VMContext, TypeStr),
  3554. ((ObjCABI == 2) ?
  3555. "__TEXT,__objc_methtype,cstring_literals" :
  3556. "__TEXT,__cstring,cstring_literals"),
  3557. 1, true);
  3558. return getConstantGEP(VMContext, Entry, 0, 0);
  3559. }
  3560. llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D,
  3561. bool Extended) {
  3562. std::string TypeStr;
  3563. if (CGM.getContext().getObjCEncodingForMethodDecl(D, TypeStr, Extended))
  3564. return 0;
  3565. llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
  3566. if (!Entry)
  3567. Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
  3568. llvm::ConstantDataArray::getString(VMContext, TypeStr),
  3569. ((ObjCABI == 2) ?
  3570. "__TEXT,__objc_methtype,cstring_literals" :
  3571. "__TEXT,__cstring,cstring_literals"),
  3572. 1, true);
  3573. return getConstantGEP(VMContext, Entry, 0, 0);
  3574. }
  3575. // FIXME: Merge into a single cstring creation function.
  3576. llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
  3577. llvm::GlobalVariable *&Entry = PropertyNames[Ident];
  3578. if (!Entry)
  3579. Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
  3580. llvm::ConstantDataArray::getString(VMContext,
  3581. Ident->getNameStart()),
  3582. "__TEXT,__cstring,cstring_literals",
  3583. 1, true);
  3584. return getConstantGEP(VMContext, Entry, 0, 0);
  3585. }
  3586. // FIXME: Merge into a single cstring creation function.
  3587. // FIXME: This Decl should be more precise.
  3588. llvm::Constant *
  3589. CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
  3590. const Decl *Container) {
  3591. std::string TypeStr;
  3592. CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
  3593. return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
  3594. }
  3595. void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
  3596. const ObjCContainerDecl *CD,
  3597. SmallVectorImpl<char> &Name) {
  3598. llvm::raw_svector_ostream OS(Name);
  3599. assert (CD && "Missing container decl in GetNameForMethod");
  3600. OS << '\01' << (D->isInstanceMethod() ? '-' : '+')
  3601. << '[' << CD->getName();
  3602. if (const ObjCCategoryImplDecl *CID =
  3603. dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext()))
  3604. OS << '(' << *CID << ')';
  3605. OS << ' ' << D->getSelector().getAsString() << ']';
  3606. }
  3607. void CGObjCMac::FinishModule() {
  3608. EmitModuleInfo();
  3609. // Emit the dummy bodies for any protocols which were referenced but
  3610. // never defined.
  3611. for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
  3612. I = Protocols.begin(), e = Protocols.end(); I != e; ++I) {
  3613. if (I->second->hasInitializer())
  3614. continue;
  3615. llvm::Constant *Values[5];
  3616. Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
  3617. Values[1] = GetClassName(I->first);
  3618. Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
  3619. Values[3] = Values[4] =
  3620. llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
  3621. I->second->setLinkage(llvm::GlobalValue::InternalLinkage);
  3622. I->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
  3623. Values));
  3624. CGM.AddUsedGlobal(I->second);
  3625. }
  3626. // Add assembler directives to add lazy undefined symbol references
  3627. // for classes which are referenced but not defined. This is
  3628. // important for correct linker interaction.
  3629. //
  3630. // FIXME: It would be nice if we had an LLVM construct for this.
  3631. if (!LazySymbols.empty() || !DefinedSymbols.empty()) {
  3632. SmallString<256> Asm;
  3633. Asm += CGM.getModule().getModuleInlineAsm();
  3634. if (!Asm.empty() && Asm.back() != '\n')
  3635. Asm += '\n';
  3636. llvm::raw_svector_ostream OS(Asm);
  3637. for (llvm::SetVector<IdentifierInfo*>::iterator I = DefinedSymbols.begin(),
  3638. e = DefinedSymbols.end(); I != e; ++I)
  3639. OS << "\t.objc_class_name_" << (*I)->getName() << "=0\n"
  3640. << "\t.globl .objc_class_name_" << (*I)->getName() << "\n";
  3641. for (llvm::SetVector<IdentifierInfo*>::iterator I = LazySymbols.begin(),
  3642. e = LazySymbols.end(); I != e; ++I) {
  3643. OS << "\t.lazy_reference .objc_class_name_" << (*I)->getName() << "\n";
  3644. }
  3645. for (size_t i = 0, e = DefinedCategoryNames.size(); i < e; ++i) {
  3646. OS << "\t.objc_category_name_" << DefinedCategoryNames[i] << "=0\n"
  3647. << "\t.globl .objc_category_name_" << DefinedCategoryNames[i] << "\n";
  3648. }
  3649. CGM.getModule().setModuleInlineAsm(OS.str());
  3650. }
  3651. }
  3652. CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
  3653. : CGObjCCommonMac(cgm),
  3654. ObjCTypes(cgm) {
  3655. ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
  3656. ObjCABI = 2;
  3657. }
  3658. /* *** */
  3659. ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
  3660. : VMContext(cgm.getLLVMContext()), CGM(cgm), ExternalProtocolPtrTy(0)
  3661. {
  3662. CodeGen::CodeGenTypes &Types = CGM.getTypes();
  3663. ASTContext &Ctx = CGM.getContext();
  3664. ShortTy = Types.ConvertType(Ctx.ShortTy);
  3665. IntTy = Types.ConvertType(Ctx.IntTy);
  3666. LongTy = Types.ConvertType(Ctx.LongTy);
  3667. LongLongTy = Types.ConvertType(Ctx.LongLongTy);
  3668. Int8PtrTy = CGM.Int8PtrTy;
  3669. Int8PtrPtrTy = CGM.Int8PtrPtrTy;
  3670. ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
  3671. PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
  3672. SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
  3673. // I'm not sure I like this. The implicit coordination is a bit
  3674. // gross. We should solve this in a reasonable fashion because this
  3675. // is a pretty common task (match some runtime data structure with
  3676. // an LLVM data structure).
  3677. // FIXME: This is leaked.
  3678. // FIXME: Merge with rewriter code?
  3679. // struct _objc_super {
  3680. // id self;
  3681. // Class cls;
  3682. // }
  3683. RecordDecl *RD = RecordDecl::Create(Ctx, TTK_Struct,
  3684. Ctx.getTranslationUnitDecl(),
  3685. SourceLocation(), SourceLocation(),
  3686. &Ctx.Idents.get("_objc_super"));
  3687. RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(), 0,
  3688. Ctx.getObjCIdType(), 0, 0, false, false));
  3689. RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(), 0,
  3690. Ctx.getObjCClassType(), 0, 0, false, false));
  3691. RD->completeDefinition();
  3692. SuperCTy = Ctx.getTagDeclType(RD);
  3693. SuperPtrCTy = Ctx.getPointerType(SuperCTy);
  3694. SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
  3695. SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
  3696. // struct _prop_t {
  3697. // char *name;
  3698. // char *attributes;
  3699. // }
  3700. PropertyTy = llvm::StructType::create("struct._prop_t",
  3701. Int8PtrTy, Int8PtrTy, NULL);
  3702. // struct _prop_list_t {
  3703. // uint32_t entsize; // sizeof(struct _prop_t)
  3704. // uint32_t count_of_properties;
  3705. // struct _prop_t prop_list[count_of_properties];
  3706. // }
  3707. PropertyListTy =
  3708. llvm::StructType::create("struct._prop_list_t", IntTy, IntTy,
  3709. llvm::ArrayType::get(PropertyTy, 0), NULL);
  3710. // struct _prop_list_t *
  3711. PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
  3712. // struct _objc_method {
  3713. // SEL _cmd;
  3714. // char *method_type;
  3715. // char *_imp;
  3716. // }
  3717. MethodTy = llvm::StructType::create("struct._objc_method",
  3718. SelectorPtrTy, Int8PtrTy, Int8PtrTy,
  3719. NULL);
  3720. // struct _objc_cache *
  3721. CacheTy = llvm::StructType::create(VMContext, "struct._objc_cache");
  3722. CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
  3723. }
  3724. ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
  3725. : ObjCCommonTypesHelper(cgm) {
  3726. // struct _objc_method_description {
  3727. // SEL name;
  3728. // char *types;
  3729. // }
  3730. MethodDescriptionTy =
  3731. llvm::StructType::create("struct._objc_method_description",
  3732. SelectorPtrTy, Int8PtrTy, NULL);
  3733. // struct _objc_method_description_list {
  3734. // int count;
  3735. // struct _objc_method_description[1];
  3736. // }
  3737. MethodDescriptionListTy =
  3738. llvm::StructType::create("struct._objc_method_description_list",
  3739. IntTy,
  3740. llvm::ArrayType::get(MethodDescriptionTy, 0),NULL);
  3741. // struct _objc_method_description_list *
  3742. MethodDescriptionListPtrTy =
  3743. llvm::PointerType::getUnqual(MethodDescriptionListTy);
  3744. // Protocol description structures
  3745. // struct _objc_protocol_extension {
  3746. // uint32_t size; // sizeof(struct _objc_protocol_extension)
  3747. // struct _objc_method_description_list *optional_instance_methods;
  3748. // struct _objc_method_description_list *optional_class_methods;
  3749. // struct _objc_property_list *instance_properties;
  3750. // const char ** extendedMethodTypes;
  3751. // }
  3752. ProtocolExtensionTy =
  3753. llvm::StructType::create("struct._objc_protocol_extension",
  3754. IntTy, MethodDescriptionListPtrTy,
  3755. MethodDescriptionListPtrTy, PropertyListPtrTy,
  3756. Int8PtrPtrTy, NULL);
  3757. // struct _objc_protocol_extension *
  3758. ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
  3759. // Handle recursive construction of Protocol and ProtocolList types
  3760. ProtocolTy =
  3761. llvm::StructType::create(VMContext, "struct._objc_protocol");
  3762. ProtocolListTy =
  3763. llvm::StructType::create(VMContext, "struct._objc_protocol_list");
  3764. ProtocolListTy->setBody(llvm::PointerType::getUnqual(ProtocolListTy),
  3765. LongTy,
  3766. llvm::ArrayType::get(ProtocolTy, 0),
  3767. NULL);
  3768. // struct _objc_protocol {
  3769. // struct _objc_protocol_extension *isa;
  3770. // char *protocol_name;
  3771. // struct _objc_protocol **_objc_protocol_list;
  3772. // struct _objc_method_description_list *instance_methods;
  3773. // struct _objc_method_description_list *class_methods;
  3774. // }
  3775. ProtocolTy->setBody(ProtocolExtensionPtrTy, Int8PtrTy,
  3776. llvm::PointerType::getUnqual(ProtocolListTy),
  3777. MethodDescriptionListPtrTy,
  3778. MethodDescriptionListPtrTy,
  3779. NULL);
  3780. // struct _objc_protocol_list *
  3781. ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
  3782. ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
  3783. // Class description structures
  3784. // struct _objc_ivar {
  3785. // char *ivar_name;
  3786. // char *ivar_type;
  3787. // int ivar_offset;
  3788. // }
  3789. IvarTy = llvm::StructType::create("struct._objc_ivar",
  3790. Int8PtrTy, Int8PtrTy, IntTy, NULL);
  3791. // struct _objc_ivar_list *
  3792. IvarListTy =
  3793. llvm::StructType::create(VMContext, "struct._objc_ivar_list");
  3794. IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
  3795. // struct _objc_method_list *
  3796. MethodListTy =
  3797. llvm::StructType::create(VMContext, "struct._objc_method_list");
  3798. MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
  3799. // struct _objc_class_extension *
  3800. ClassExtensionTy =
  3801. llvm::StructType::create("struct._objc_class_extension",
  3802. IntTy, Int8PtrTy, PropertyListPtrTy, NULL);
  3803. ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
  3804. ClassTy = llvm::StructType::create(VMContext, "struct._objc_class");
  3805. // struct _objc_class {
  3806. // Class isa;
  3807. // Class super_class;
  3808. // char *name;
  3809. // long version;
  3810. // long info;
  3811. // long instance_size;
  3812. // struct _objc_ivar_list *ivars;
  3813. // struct _objc_method_list *methods;
  3814. // struct _objc_cache *cache;
  3815. // struct _objc_protocol_list *protocols;
  3816. // char *ivar_layout;
  3817. // struct _objc_class_ext *ext;
  3818. // };
  3819. ClassTy->setBody(llvm::PointerType::getUnqual(ClassTy),
  3820. llvm::PointerType::getUnqual(ClassTy),
  3821. Int8PtrTy,
  3822. LongTy,
  3823. LongTy,
  3824. LongTy,
  3825. IvarListPtrTy,
  3826. MethodListPtrTy,
  3827. CachePtrTy,
  3828. ProtocolListPtrTy,
  3829. Int8PtrTy,
  3830. ClassExtensionPtrTy,
  3831. NULL);
  3832. ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
  3833. // struct _objc_category {
  3834. // char *category_name;
  3835. // char *class_name;
  3836. // struct _objc_method_list *instance_method;
  3837. // struct _objc_method_list *class_method;
  3838. // uint32_t size; // sizeof(struct _objc_category)
  3839. // struct _objc_property_list *instance_properties;// category's @property
  3840. // }
  3841. CategoryTy =
  3842. llvm::StructType::create("struct._objc_category",
  3843. Int8PtrTy, Int8PtrTy, MethodListPtrTy,
  3844. MethodListPtrTy, ProtocolListPtrTy,
  3845. IntTy, PropertyListPtrTy, NULL);
  3846. // Global metadata structures
  3847. // struct _objc_symtab {
  3848. // long sel_ref_cnt;
  3849. // SEL *refs;
  3850. // short cls_def_cnt;
  3851. // short cat_def_cnt;
  3852. // char *defs[cls_def_cnt + cat_def_cnt];
  3853. // }
  3854. SymtabTy =
  3855. llvm::StructType::create("struct._objc_symtab",
  3856. LongTy, SelectorPtrTy, ShortTy, ShortTy,
  3857. llvm::ArrayType::get(Int8PtrTy, 0), NULL);
  3858. SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
  3859. // struct _objc_module {
  3860. // long version;
  3861. // long size; // sizeof(struct _objc_module)
  3862. // char *name;
  3863. // struct _objc_symtab* symtab;
  3864. // }
  3865. ModuleTy =
  3866. llvm::StructType::create("struct._objc_module",
  3867. LongTy, LongTy, Int8PtrTy, SymtabPtrTy, NULL);
  3868. // FIXME: This is the size of the setjmp buffer and should be target
  3869. // specific. 18 is what's used on 32-bit X86.
  3870. uint64_t SetJmpBufferSize = 18;
  3871. // Exceptions
  3872. llvm::Type *StackPtrTy = llvm::ArrayType::get(CGM.Int8PtrTy, 4);
  3873. ExceptionDataTy =
  3874. llvm::StructType::create("struct._objc_exception_data",
  3875. llvm::ArrayType::get(CGM.Int32Ty,SetJmpBufferSize),
  3876. StackPtrTy, NULL);
  3877. }
  3878. ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
  3879. : ObjCCommonTypesHelper(cgm) {
  3880. // struct _method_list_t {
  3881. // uint32_t entsize; // sizeof(struct _objc_method)
  3882. // uint32_t method_count;
  3883. // struct _objc_method method_list[method_count];
  3884. // }
  3885. MethodListnfABITy =
  3886. llvm::StructType::create("struct.__method_list_t", IntTy, IntTy,
  3887. llvm::ArrayType::get(MethodTy, 0), NULL);
  3888. // struct method_list_t *
  3889. MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
  3890. // struct _protocol_t {
  3891. // id isa; // NULL
  3892. // const char * const protocol_name;
  3893. // const struct _protocol_list_t * protocol_list; // super protocols
  3894. // const struct method_list_t * const instance_methods;
  3895. // const struct method_list_t * const class_methods;
  3896. // const struct method_list_t *optionalInstanceMethods;
  3897. // const struct method_list_t *optionalClassMethods;
  3898. // const struct _prop_list_t * properties;
  3899. // const uint32_t size; // sizeof(struct _protocol_t)
  3900. // const uint32_t flags; // = 0
  3901. // const char ** extendedMethodTypes;
  3902. // }
  3903. // Holder for struct _protocol_list_t *
  3904. ProtocolListnfABITy =
  3905. llvm::StructType::create(VMContext, "struct._objc_protocol_list");
  3906. ProtocolnfABITy =
  3907. llvm::StructType::create("struct._protocol_t", ObjectPtrTy, Int8PtrTy,
  3908. llvm::PointerType::getUnqual(ProtocolListnfABITy),
  3909. MethodListnfABIPtrTy, MethodListnfABIPtrTy,
  3910. MethodListnfABIPtrTy, MethodListnfABIPtrTy,
  3911. PropertyListPtrTy, IntTy, IntTy, Int8PtrPtrTy,
  3912. NULL);
  3913. // struct _protocol_t*
  3914. ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
  3915. // struct _protocol_list_t {
  3916. // long protocol_count; // Note, this is 32/64 bit
  3917. // struct _protocol_t *[protocol_count];
  3918. // }
  3919. ProtocolListnfABITy->setBody(LongTy,
  3920. llvm::ArrayType::get(ProtocolnfABIPtrTy, 0),
  3921. NULL);
  3922. // struct _objc_protocol_list*
  3923. ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
  3924. // struct _ivar_t {
  3925. // unsigned long int *offset; // pointer to ivar offset location
  3926. // char *name;
  3927. // char *type;
  3928. // uint32_t alignment;
  3929. // uint32_t size;
  3930. // }
  3931. IvarnfABITy =
  3932. llvm::StructType::create("struct._ivar_t",
  3933. llvm::PointerType::getUnqual(LongTy),
  3934. Int8PtrTy, Int8PtrTy, IntTy, IntTy, NULL);
  3935. // struct _ivar_list_t {
  3936. // uint32 entsize; // sizeof(struct _ivar_t)
  3937. // uint32 count;
  3938. // struct _iver_t list[count];
  3939. // }
  3940. IvarListnfABITy =
  3941. llvm::StructType::create("struct._ivar_list_t", IntTy, IntTy,
  3942. llvm::ArrayType::get(IvarnfABITy, 0), NULL);
  3943. IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
  3944. // struct _class_ro_t {
  3945. // uint32_t const flags;
  3946. // uint32_t const instanceStart;
  3947. // uint32_t const instanceSize;
  3948. // uint32_t const reserved; // only when building for 64bit targets
  3949. // const uint8_t * const ivarLayout;
  3950. // const char *const name;
  3951. // const struct _method_list_t * const baseMethods;
  3952. // const struct _objc_protocol_list *const baseProtocols;
  3953. // const struct _ivar_list_t *const ivars;
  3954. // const uint8_t * const weakIvarLayout;
  3955. // const struct _prop_list_t * const properties;
  3956. // }
  3957. // FIXME. Add 'reserved' field in 64bit abi mode!
  3958. ClassRonfABITy = llvm::StructType::create("struct._class_ro_t",
  3959. IntTy, IntTy, IntTy, Int8PtrTy,
  3960. Int8PtrTy, MethodListnfABIPtrTy,
  3961. ProtocolListnfABIPtrTy,
  3962. IvarListnfABIPtrTy,
  3963. Int8PtrTy, PropertyListPtrTy, NULL);
  3964. // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
  3965. llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
  3966. ImpnfABITy = llvm::FunctionType::get(ObjectPtrTy, params, false)
  3967. ->getPointerTo();
  3968. // struct _class_t {
  3969. // struct _class_t *isa;
  3970. // struct _class_t * const superclass;
  3971. // void *cache;
  3972. // IMP *vtable;
  3973. // struct class_ro_t *ro;
  3974. // }
  3975. ClassnfABITy = llvm::StructType::create(VMContext, "struct._class_t");
  3976. ClassnfABITy->setBody(llvm::PointerType::getUnqual(ClassnfABITy),
  3977. llvm::PointerType::getUnqual(ClassnfABITy),
  3978. CachePtrTy,
  3979. llvm::PointerType::getUnqual(ImpnfABITy),
  3980. llvm::PointerType::getUnqual(ClassRonfABITy),
  3981. NULL);
  3982. // LLVM for struct _class_t *
  3983. ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
  3984. // struct _category_t {
  3985. // const char * const name;
  3986. // struct _class_t *const cls;
  3987. // const struct _method_list_t * const instance_methods;
  3988. // const struct _method_list_t * const class_methods;
  3989. // const struct _protocol_list_t * const protocols;
  3990. // const struct _prop_list_t * const properties;
  3991. // }
  3992. CategorynfABITy = llvm::StructType::create("struct._category_t",
  3993. Int8PtrTy, ClassnfABIPtrTy,
  3994. MethodListnfABIPtrTy,
  3995. MethodListnfABIPtrTy,
  3996. ProtocolListnfABIPtrTy,
  3997. PropertyListPtrTy,
  3998. NULL);
  3999. // New types for nonfragile abi messaging.
  4000. CodeGen::CodeGenTypes &Types = CGM.getTypes();
  4001. ASTContext &Ctx = CGM.getContext();
  4002. // MessageRefTy - LLVM for:
  4003. // struct _message_ref_t {
  4004. // IMP messenger;
  4005. // SEL name;
  4006. // };
  4007. // First the clang type for struct _message_ref_t
  4008. RecordDecl *RD = RecordDecl::Create(Ctx, TTK_Struct,
  4009. Ctx.getTranslationUnitDecl(),
  4010. SourceLocation(), SourceLocation(),
  4011. &Ctx.Idents.get("_message_ref_t"));
  4012. RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(), 0,
  4013. Ctx.VoidPtrTy, 0, 0, false, false));
  4014. RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(), 0,
  4015. Ctx.getObjCSelType(), 0, 0, false, false));
  4016. RD->completeDefinition();
  4017. MessageRefCTy = Ctx.getTagDeclType(RD);
  4018. MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
  4019. MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
  4020. // MessageRefPtrTy - LLVM for struct _message_ref_t*
  4021. MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
  4022. // SuperMessageRefTy - LLVM for:
  4023. // struct _super_message_ref_t {
  4024. // SUPER_IMP messenger;
  4025. // SEL name;
  4026. // };
  4027. SuperMessageRefTy =
  4028. llvm::StructType::create("struct._super_message_ref_t",
  4029. ImpnfABITy, SelectorPtrTy, NULL);
  4030. // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
  4031. SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
  4032. // struct objc_typeinfo {
  4033. // const void** vtable; // objc_ehtype_vtable + 2
  4034. // const char* name; // c++ typeinfo string
  4035. // Class cls;
  4036. // };
  4037. EHTypeTy =
  4038. llvm::StructType::create("struct._objc_typeinfo",
  4039. llvm::PointerType::getUnqual(Int8PtrTy),
  4040. Int8PtrTy, ClassnfABIPtrTy, NULL);
  4041. EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
  4042. }
  4043. llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
  4044. FinishNonFragileABIModule();
  4045. return NULL;
  4046. }
  4047. void CGObjCNonFragileABIMac::
  4048. AddModuleClassList(ArrayRef<llvm::GlobalValue*> Container,
  4049. const char *SymbolName,
  4050. const char *SectionName) {
  4051. unsigned NumClasses = Container.size();
  4052. if (!NumClasses)
  4053. return;
  4054. SmallVector<llvm::Constant*, 8> Symbols(NumClasses);
  4055. for (unsigned i=0; i<NumClasses; i++)
  4056. Symbols[i] = llvm::ConstantExpr::getBitCast(Container[i],
  4057. ObjCTypes.Int8PtrTy);
  4058. llvm::Constant *Init =
  4059. llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
  4060. Symbols.size()),
  4061. Symbols);
  4062. llvm::GlobalVariable *GV =
  4063. new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
  4064. llvm::GlobalValue::InternalLinkage,
  4065. Init,
  4066. SymbolName);
  4067. GV->setAlignment(CGM.getTargetData().getABITypeAlignment(Init->getType()));
  4068. GV->setSection(SectionName);
  4069. CGM.AddUsedGlobal(GV);
  4070. }
  4071. void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
  4072. // nonfragile abi has no module definition.
  4073. // Build list of all implemented class addresses in array
  4074. // L_OBJC_LABEL_CLASS_$.
  4075. AddModuleClassList(DefinedClasses,
  4076. "\01L_OBJC_LABEL_CLASS_$",
  4077. "__DATA, __objc_classlist, regular, no_dead_strip");
  4078. for (unsigned i = 0, e = DefinedClasses.size(); i < e; i++) {
  4079. llvm::GlobalValue *IMPLGV = DefinedClasses[i];
  4080. if (IMPLGV->getLinkage() != llvm::GlobalValue::ExternalWeakLinkage)
  4081. continue;
  4082. IMPLGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  4083. }
  4084. for (unsigned i = 0, e = DefinedMetaClasses.size(); i < e; i++) {
  4085. llvm::GlobalValue *IMPLGV = DefinedMetaClasses[i];
  4086. if (IMPLGV->getLinkage() != llvm::GlobalValue::ExternalWeakLinkage)
  4087. continue;
  4088. IMPLGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  4089. }
  4090. AddModuleClassList(DefinedNonLazyClasses,
  4091. "\01L_OBJC_LABEL_NONLAZY_CLASS_$",
  4092. "__DATA, __objc_nlclslist, regular, no_dead_strip");
  4093. // Build list of all implemented category addresses in array
  4094. // L_OBJC_LABEL_CATEGORY_$.
  4095. AddModuleClassList(DefinedCategories,
  4096. "\01L_OBJC_LABEL_CATEGORY_$",
  4097. "__DATA, __objc_catlist, regular, no_dead_strip");
  4098. AddModuleClassList(DefinedNonLazyCategories,
  4099. "\01L_OBJC_LABEL_NONLAZY_CATEGORY_$",
  4100. "__DATA, __objc_nlcatlist, regular, no_dead_strip");
  4101. EmitImageInfo();
  4102. }
  4103. /// isVTableDispatchedSelector - Returns true if SEL is not in the list of
  4104. /// VTableDispatchMethods; false otherwise. What this means is that
  4105. /// except for the 19 selectors in the list, we generate 32bit-style
  4106. /// message dispatch call for all the rest.
  4107. bool CGObjCNonFragileABIMac::isVTableDispatchedSelector(Selector Sel) {
  4108. // At various points we've experimented with using vtable-based
  4109. // dispatch for all methods.
  4110. switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
  4111. case CodeGenOptions::Legacy:
  4112. return false;
  4113. case CodeGenOptions::NonLegacy:
  4114. return true;
  4115. case CodeGenOptions::Mixed:
  4116. break;
  4117. }
  4118. // If so, see whether this selector is in the white-list of things which must
  4119. // use the new dispatch convention. We lazily build a dense set for this.
  4120. if (VTableDispatchMethods.empty()) {
  4121. VTableDispatchMethods.insert(GetNullarySelector("alloc"));
  4122. VTableDispatchMethods.insert(GetNullarySelector("class"));
  4123. VTableDispatchMethods.insert(GetNullarySelector("self"));
  4124. VTableDispatchMethods.insert(GetNullarySelector("isFlipped"));
  4125. VTableDispatchMethods.insert(GetNullarySelector("length"));
  4126. VTableDispatchMethods.insert(GetNullarySelector("count"));
  4127. // These are vtable-based if GC is disabled.
  4128. // Optimistically use vtable dispatch for hybrid compiles.
  4129. if (CGM.getLangOptions().getGC() != LangOptions::GCOnly) {
  4130. VTableDispatchMethods.insert(GetNullarySelector("retain"));
  4131. VTableDispatchMethods.insert(GetNullarySelector("release"));
  4132. VTableDispatchMethods.insert(GetNullarySelector("autorelease"));
  4133. }
  4134. VTableDispatchMethods.insert(GetUnarySelector("allocWithZone"));
  4135. VTableDispatchMethods.insert(GetUnarySelector("isKindOfClass"));
  4136. VTableDispatchMethods.insert(GetUnarySelector("respondsToSelector"));
  4137. VTableDispatchMethods.insert(GetUnarySelector("objectForKey"));
  4138. VTableDispatchMethods.insert(GetUnarySelector("objectAtIndex"));
  4139. VTableDispatchMethods.insert(GetUnarySelector("isEqualToString"));
  4140. VTableDispatchMethods.insert(GetUnarySelector("isEqual"));
  4141. // These are vtable-based if GC is enabled.
  4142. // Optimistically use vtable dispatch for hybrid compiles.
  4143. if (CGM.getLangOptions().getGC() != LangOptions::NonGC) {
  4144. VTableDispatchMethods.insert(GetNullarySelector("hash"));
  4145. VTableDispatchMethods.insert(GetUnarySelector("addObject"));
  4146. // "countByEnumeratingWithState:objects:count"
  4147. IdentifierInfo *KeyIdents[] = {
  4148. &CGM.getContext().Idents.get("countByEnumeratingWithState"),
  4149. &CGM.getContext().Idents.get("objects"),
  4150. &CGM.getContext().Idents.get("count")
  4151. };
  4152. VTableDispatchMethods.insert(
  4153. CGM.getContext().Selectors.getSelector(3, KeyIdents));
  4154. }
  4155. }
  4156. return VTableDispatchMethods.count(Sel);
  4157. }
  4158. // Metadata flags
  4159. enum MetaDataDlags {
  4160. CLS = 0x0,
  4161. CLS_META = 0x1,
  4162. CLS_ROOT = 0x2,
  4163. OBJC2_CLS_HIDDEN = 0x10,
  4164. CLS_EXCEPTION = 0x20,
  4165. /// (Obsolete) ARC-specific: this class has a .release_ivars method
  4166. CLS_HAS_IVAR_RELEASER = 0x40,
  4167. /// class was compiled with -fobjc-arr
  4168. CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
  4169. };
  4170. /// BuildClassRoTInitializer - generate meta-data for:
  4171. /// struct _class_ro_t {
  4172. /// uint32_t const flags;
  4173. /// uint32_t const instanceStart;
  4174. /// uint32_t const instanceSize;
  4175. /// uint32_t const reserved; // only when building for 64bit targets
  4176. /// const uint8_t * const ivarLayout;
  4177. /// const char *const name;
  4178. /// const struct _method_list_t * const baseMethods;
  4179. /// const struct _protocol_list_t *const baseProtocols;
  4180. /// const struct _ivar_list_t *const ivars;
  4181. /// const uint8_t * const weakIvarLayout;
  4182. /// const struct _prop_list_t * const properties;
  4183. /// }
  4184. ///
  4185. llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
  4186. unsigned flags,
  4187. unsigned InstanceStart,
  4188. unsigned InstanceSize,
  4189. const ObjCImplementationDecl *ID) {
  4190. std::string ClassName = ID->getNameAsString();
  4191. llvm::Constant *Values[10]; // 11 for 64bit targets!
  4192. if (CGM.getLangOptions().ObjCAutoRefCount)
  4193. flags |= CLS_COMPILED_BY_ARC;
  4194. Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
  4195. Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
  4196. Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
  4197. // FIXME. For 64bit targets add 0 here.
  4198. Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
  4199. : BuildIvarLayout(ID, true);
  4200. Values[ 4] = GetClassName(ID->getIdentifier());
  4201. // const struct _method_list_t * const baseMethods;
  4202. std::vector<llvm::Constant*> Methods;
  4203. std::string MethodListName("\01l_OBJC_$_");
  4204. if (flags & CLS_META) {
  4205. MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
  4206. for (ObjCImplementationDecl::classmeth_iterator
  4207. i = ID->classmeth_begin(), e = ID->classmeth_end(); i != e; ++i) {
  4208. // Class methods should always be defined.
  4209. Methods.push_back(GetMethodConstant(*i));
  4210. }
  4211. } else {
  4212. MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
  4213. for (ObjCImplementationDecl::instmeth_iterator
  4214. i = ID->instmeth_begin(), e = ID->instmeth_end(); i != e; ++i) {
  4215. // Instance methods should always be defined.
  4216. Methods.push_back(GetMethodConstant(*i));
  4217. }
  4218. for (ObjCImplementationDecl::propimpl_iterator
  4219. i = ID->propimpl_begin(), e = ID->propimpl_end(); i != e; ++i) {
  4220. ObjCPropertyImplDecl *PID = *i;
  4221. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
  4222. ObjCPropertyDecl *PD = PID->getPropertyDecl();
  4223. if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
  4224. if (llvm::Constant *C = GetMethodConstant(MD))
  4225. Methods.push_back(C);
  4226. if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
  4227. if (llvm::Constant *C = GetMethodConstant(MD))
  4228. Methods.push_back(C);
  4229. }
  4230. }
  4231. }
  4232. Values[ 5] = EmitMethodList(MethodListName,
  4233. "__DATA, __objc_const", Methods);
  4234. const ObjCInterfaceDecl *OID = ID->getClassInterface();
  4235. assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
  4236. Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
  4237. + OID->getName(),
  4238. OID->all_referenced_protocol_begin(),
  4239. OID->all_referenced_protocol_end());
  4240. if (flags & CLS_META)
  4241. Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
  4242. else
  4243. Values[ 7] = EmitIvarList(ID);
  4244. Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
  4245. : BuildIvarLayout(ID, false);
  4246. if (flags & CLS_META)
  4247. Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
  4248. else
  4249. Values[ 9] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getName(),
  4250. ID, ID->getClassInterface(), ObjCTypes);
  4251. llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
  4252. Values);
  4253. llvm::GlobalVariable *CLASS_RO_GV =
  4254. new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassRonfABITy, false,
  4255. llvm::GlobalValue::InternalLinkage,
  4256. Init,
  4257. (flags & CLS_META) ?
  4258. std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
  4259. std::string("\01l_OBJC_CLASS_RO_$_")+ClassName);
  4260. CLASS_RO_GV->setAlignment(
  4261. CGM.getTargetData().getABITypeAlignment(ObjCTypes.ClassRonfABITy));
  4262. CLASS_RO_GV->setSection("__DATA, __objc_const");
  4263. return CLASS_RO_GV;
  4264. }
  4265. /// BuildClassMetaData - This routine defines that to-level meta-data
  4266. /// for the given ClassName for:
  4267. /// struct _class_t {
  4268. /// struct _class_t *isa;
  4269. /// struct _class_t * const superclass;
  4270. /// void *cache;
  4271. /// IMP *vtable;
  4272. /// struct class_ro_t *ro;
  4273. /// }
  4274. ///
  4275. llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
  4276. std::string &ClassName,
  4277. llvm::Constant *IsAGV,
  4278. llvm::Constant *SuperClassGV,
  4279. llvm::Constant *ClassRoGV,
  4280. bool HiddenVisibility) {
  4281. llvm::Constant *Values[] = {
  4282. IsAGV,
  4283. SuperClassGV,
  4284. ObjCEmptyCacheVar, // &ObjCEmptyCacheVar
  4285. ObjCEmptyVtableVar, // &ObjCEmptyVtableVar
  4286. ClassRoGV // &CLASS_RO_GV
  4287. };
  4288. if (!Values[1])
  4289. Values[1] = llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
  4290. llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
  4291. Values);
  4292. llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
  4293. GV->setInitializer(Init);
  4294. GV->setSection("__DATA, __objc_data");
  4295. GV->setAlignment(
  4296. CGM.getTargetData().getABITypeAlignment(ObjCTypes.ClassnfABITy));
  4297. if (HiddenVisibility)
  4298. GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
  4299. return GV;
  4300. }
  4301. bool
  4302. CGObjCNonFragileABIMac::ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
  4303. return OD->getClassMethod(GetNullarySelector("load")) != 0;
  4304. }
  4305. void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCImplementationDecl *OID,
  4306. uint32_t &InstanceStart,
  4307. uint32_t &InstanceSize) {
  4308. const ASTRecordLayout &RL =
  4309. CGM.getContext().getASTObjCImplementationLayout(OID);
  4310. // InstanceSize is really instance end.
  4311. InstanceSize = RL.getDataSize().getQuantity();
  4312. // If there are no fields, the start is the same as the end.
  4313. if (!RL.getFieldCount())
  4314. InstanceStart = InstanceSize;
  4315. else
  4316. InstanceStart = RL.getFieldOffset(0) / CGM.getContext().getCharWidth();
  4317. }
  4318. void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
  4319. std::string ClassName = ID->getNameAsString();
  4320. if (!ObjCEmptyCacheVar) {
  4321. ObjCEmptyCacheVar = new llvm::GlobalVariable(
  4322. CGM.getModule(),
  4323. ObjCTypes.CacheTy,
  4324. false,
  4325. llvm::GlobalValue::ExternalLinkage,
  4326. 0,
  4327. "_objc_empty_cache");
  4328. ObjCEmptyVtableVar = new llvm::GlobalVariable(
  4329. CGM.getModule(),
  4330. ObjCTypes.ImpnfABITy,
  4331. false,
  4332. llvm::GlobalValue::ExternalLinkage,
  4333. 0,
  4334. "_objc_empty_vtable");
  4335. }
  4336. assert(ID->getClassInterface() &&
  4337. "CGObjCNonFragileABIMac::GenerateClass - class is 0");
  4338. // FIXME: Is this correct (that meta class size is never computed)?
  4339. uint32_t InstanceStart =
  4340. CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassnfABITy);
  4341. uint32_t InstanceSize = InstanceStart;
  4342. uint32_t flags = CLS_META;
  4343. std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
  4344. std::string ObjCClassName(getClassSymbolPrefix());
  4345. llvm::GlobalVariable *SuperClassGV, *IsAGV;
  4346. bool classIsHidden =
  4347. ID->getClassInterface()->getVisibility() == HiddenVisibility;
  4348. if (classIsHidden)
  4349. flags |= OBJC2_CLS_HIDDEN;
  4350. if (ID->hasCXXStructors())
  4351. flags |= eClassFlags_ABI2_HasCXXStructors;
  4352. if (!ID->getClassInterface()->getSuperClass()) {
  4353. // class is root
  4354. flags |= CLS_ROOT;
  4355. SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
  4356. IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
  4357. } else {
  4358. // Has a root. Current class is not a root.
  4359. const ObjCInterfaceDecl *Root = ID->getClassInterface();
  4360. while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
  4361. Root = Super;
  4362. IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
  4363. if (Root->isWeakImported())
  4364. IsAGV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  4365. // work on super class metadata symbol.
  4366. std::string SuperClassName =
  4367. ObjCMetaClassName +
  4368. ID->getClassInterface()->getSuperClass()->getNameAsString();
  4369. SuperClassGV = GetClassGlobal(SuperClassName);
  4370. if (ID->getClassInterface()->getSuperClass()->isWeakImported())
  4371. SuperClassGV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  4372. }
  4373. llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
  4374. InstanceStart,
  4375. InstanceSize,ID);
  4376. std::string TClassName = ObjCMetaClassName + ClassName;
  4377. llvm::GlobalVariable *MetaTClass =
  4378. BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
  4379. classIsHidden);
  4380. DefinedMetaClasses.push_back(MetaTClass);
  4381. // Metadata for the class
  4382. flags = CLS;
  4383. if (classIsHidden)
  4384. flags |= OBJC2_CLS_HIDDEN;
  4385. if (ID->hasCXXStructors())
  4386. flags |= eClassFlags_ABI2_HasCXXStructors;
  4387. if (hasObjCExceptionAttribute(CGM.getContext(), ID->getClassInterface()))
  4388. flags |= CLS_EXCEPTION;
  4389. if (!ID->getClassInterface()->getSuperClass()) {
  4390. flags |= CLS_ROOT;
  4391. SuperClassGV = 0;
  4392. } else {
  4393. // Has a root. Current class is not a root.
  4394. std::string RootClassName =
  4395. ID->getClassInterface()->getSuperClass()->getNameAsString();
  4396. SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
  4397. if (ID->getClassInterface()->getSuperClass()->isWeakImported())
  4398. SuperClassGV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  4399. }
  4400. GetClassSizeInfo(ID, InstanceStart, InstanceSize);
  4401. CLASS_RO_GV = BuildClassRoTInitializer(flags,
  4402. InstanceStart,
  4403. InstanceSize,
  4404. ID);
  4405. TClassName = ObjCClassName + ClassName;
  4406. llvm::GlobalVariable *ClassMD =
  4407. BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
  4408. classIsHidden);
  4409. DefinedClasses.push_back(ClassMD);
  4410. // Determine if this class is also "non-lazy".
  4411. if (ImplementationIsNonLazy(ID))
  4412. DefinedNonLazyClasses.push_back(ClassMD);
  4413. // Force the definition of the EHType if necessary.
  4414. if (flags & CLS_EXCEPTION)
  4415. GetInterfaceEHType(ID->getClassInterface(), true);
  4416. // Make sure method definition entries are all clear for next implementation.
  4417. MethodDefinitions.clear();
  4418. }
  4419. /// GenerateProtocolRef - This routine is called to generate code for
  4420. /// a protocol reference expression; as in:
  4421. /// @code
  4422. /// @protocol(Proto1);
  4423. /// @endcode
  4424. /// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
  4425. /// which will hold address of the protocol meta-data.
  4426. ///
  4427. llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
  4428. const ObjCProtocolDecl *PD) {
  4429. // This routine is called for @protocol only. So, we must build definition
  4430. // of protocol's meta-data (not a reference to it!)
  4431. //
  4432. llvm::Constant *Init =
  4433. llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
  4434. ObjCTypes.getExternalProtocolPtrTy());
  4435. std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
  4436. ProtocolName += PD->getName();
  4437. llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
  4438. if (PTGV)
  4439. return Builder.CreateLoad(PTGV);
  4440. PTGV = new llvm::GlobalVariable(
  4441. CGM.getModule(),
  4442. Init->getType(), false,
  4443. llvm::GlobalValue::WeakAnyLinkage,
  4444. Init,
  4445. ProtocolName);
  4446. PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
  4447. PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
  4448. CGM.AddUsedGlobal(PTGV);
  4449. return Builder.CreateLoad(PTGV);
  4450. }
  4451. /// GenerateCategory - Build metadata for a category implementation.
  4452. /// struct _category_t {
  4453. /// const char * const name;
  4454. /// struct _class_t *const cls;
  4455. /// const struct _method_list_t * const instance_methods;
  4456. /// const struct _method_list_t * const class_methods;
  4457. /// const struct _protocol_list_t * const protocols;
  4458. /// const struct _prop_list_t * const properties;
  4459. /// }
  4460. ///
  4461. void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
  4462. const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
  4463. const char *Prefix = "\01l_OBJC_$_CATEGORY_";
  4464. std::string ExtCatName(Prefix + Interface->getNameAsString()+
  4465. "_$_" + OCD->getNameAsString());
  4466. std::string ExtClassName(getClassSymbolPrefix() +
  4467. Interface->getNameAsString());
  4468. llvm::Constant *Values[6];
  4469. Values[0] = GetClassName(OCD->getIdentifier());
  4470. // meta-class entry symbol
  4471. llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
  4472. if (Interface->isWeakImported())
  4473. ClassGV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  4474. Values[1] = ClassGV;
  4475. std::vector<llvm::Constant*> Methods;
  4476. std::string MethodListName(Prefix);
  4477. MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
  4478. "_$_" + OCD->getNameAsString();
  4479. for (ObjCCategoryImplDecl::instmeth_iterator
  4480. i = OCD->instmeth_begin(), e = OCD->instmeth_end(); i != e; ++i) {
  4481. // Instance methods should always be defined.
  4482. Methods.push_back(GetMethodConstant(*i));
  4483. }
  4484. Values[2] = EmitMethodList(MethodListName,
  4485. "__DATA, __objc_const",
  4486. Methods);
  4487. MethodListName = Prefix;
  4488. MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
  4489. OCD->getNameAsString();
  4490. Methods.clear();
  4491. for (ObjCCategoryImplDecl::classmeth_iterator
  4492. i = OCD->classmeth_begin(), e = OCD->classmeth_end(); i != e; ++i) {
  4493. // Class methods should always be defined.
  4494. Methods.push_back(GetMethodConstant(*i));
  4495. }
  4496. Values[3] = EmitMethodList(MethodListName,
  4497. "__DATA, __objc_const",
  4498. Methods);
  4499. const ObjCCategoryDecl *Category =
  4500. Interface->FindCategoryDeclaration(OCD->getIdentifier());
  4501. if (Category) {
  4502. SmallString<256> ExtName;
  4503. llvm::raw_svector_ostream(ExtName) << Interface->getName() << "_$_"
  4504. << OCD->getName();
  4505. Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
  4506. + Interface->getName() + "_$_"
  4507. + Category->getName(),
  4508. Category->protocol_begin(),
  4509. Category->protocol_end());
  4510. Values[5] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ExtName.str(),
  4511. OCD, Category, ObjCTypes);
  4512. } else {
  4513. Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
  4514. Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
  4515. }
  4516. llvm::Constant *Init =
  4517. llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
  4518. Values);
  4519. llvm::GlobalVariable *GCATV
  4520. = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.CategorynfABITy,
  4521. false,
  4522. llvm::GlobalValue::InternalLinkage,
  4523. Init,
  4524. ExtCatName);
  4525. GCATV->setAlignment(
  4526. CGM.getTargetData().getABITypeAlignment(ObjCTypes.CategorynfABITy));
  4527. GCATV->setSection("__DATA, __objc_const");
  4528. CGM.AddUsedGlobal(GCATV);
  4529. DefinedCategories.push_back(GCATV);
  4530. // Determine if this category is also "non-lazy".
  4531. if (ImplementationIsNonLazy(OCD))
  4532. DefinedNonLazyCategories.push_back(GCATV);
  4533. // method definition entries must be clear for next implementation.
  4534. MethodDefinitions.clear();
  4535. }
  4536. /// GetMethodConstant - Return a struct objc_method constant for the
  4537. /// given method if it has been defined. The result is null if the
  4538. /// method has not been defined. The return value has type MethodPtrTy.
  4539. llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
  4540. const ObjCMethodDecl *MD) {
  4541. llvm::Function *Fn = GetMethodDefinition(MD);
  4542. if (!Fn)
  4543. return 0;
  4544. llvm::Constant *Method[] = {
  4545. llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
  4546. ObjCTypes.SelectorPtrTy),
  4547. GetMethodVarType(MD),
  4548. llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy)
  4549. };
  4550. return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
  4551. }
  4552. /// EmitMethodList - Build meta-data for method declarations
  4553. /// struct _method_list_t {
  4554. /// uint32_t entsize; // sizeof(struct _objc_method)
  4555. /// uint32_t method_count;
  4556. /// struct _objc_method method_list[method_count];
  4557. /// }
  4558. ///
  4559. llvm::Constant *
  4560. CGObjCNonFragileABIMac::EmitMethodList(Twine Name,
  4561. const char *Section,
  4562. ArrayRef<llvm::Constant*> Methods) {
  4563. // Return null for empty list.
  4564. if (Methods.empty())
  4565. return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
  4566. llvm::Constant *Values[3];
  4567. // sizeof(struct _objc_method)
  4568. unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.MethodTy);
  4569. Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
  4570. // method_count
  4571. Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
  4572. llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
  4573. Methods.size());
  4574. Values[2] = llvm::ConstantArray::get(AT, Methods);
  4575. llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
  4576. llvm::GlobalVariable *GV =
  4577. new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
  4578. llvm::GlobalValue::InternalLinkage, Init, Name);
  4579. GV->setAlignment(CGM.getTargetData().getABITypeAlignment(Init->getType()));
  4580. GV->setSection(Section);
  4581. CGM.AddUsedGlobal(GV);
  4582. return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodListnfABIPtrTy);
  4583. }
  4584. /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
  4585. /// the given ivar.
  4586. llvm::GlobalVariable *
  4587. CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
  4588. const ObjCIvarDecl *Ivar) {
  4589. const ObjCInterfaceDecl *Container = Ivar->getContainingInterface();
  4590. std::string Name = "OBJC_IVAR_$_" + Container->getNameAsString() +
  4591. '.' + Ivar->getNameAsString();
  4592. llvm::GlobalVariable *IvarOffsetGV =
  4593. CGM.getModule().getGlobalVariable(Name);
  4594. if (!IvarOffsetGV)
  4595. IvarOffsetGV =
  4596. new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.LongTy,
  4597. false,
  4598. llvm::GlobalValue::ExternalLinkage,
  4599. 0,
  4600. Name);
  4601. return IvarOffsetGV;
  4602. }
  4603. llvm::Constant *
  4604. CGObjCNonFragileABIMac::EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
  4605. const ObjCIvarDecl *Ivar,
  4606. unsigned long int Offset) {
  4607. llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
  4608. IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
  4609. Offset));
  4610. IvarOffsetGV->setAlignment(
  4611. CGM.getTargetData().getABITypeAlignment(ObjCTypes.LongTy));
  4612. // FIXME: This matches gcc, but shouldn't the visibility be set on the use as
  4613. // well (i.e., in ObjCIvarOffsetVariable).
  4614. if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
  4615. Ivar->getAccessControl() == ObjCIvarDecl::Package ||
  4616. ID->getVisibility() == HiddenVisibility)
  4617. IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
  4618. else
  4619. IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  4620. IvarOffsetGV->setSection("__DATA, __objc_ivar");
  4621. return IvarOffsetGV;
  4622. }
  4623. /// EmitIvarList - Emit the ivar list for the given
  4624. /// implementation. The return value has type
  4625. /// IvarListnfABIPtrTy.
  4626. /// struct _ivar_t {
  4627. /// unsigned long int *offset; // pointer to ivar offset location
  4628. /// char *name;
  4629. /// char *type;
  4630. /// uint32_t alignment;
  4631. /// uint32_t size;
  4632. /// }
  4633. /// struct _ivar_list_t {
  4634. /// uint32 entsize; // sizeof(struct _ivar_t)
  4635. /// uint32 count;
  4636. /// struct _iver_t list[count];
  4637. /// }
  4638. ///
  4639. llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
  4640. const ObjCImplementationDecl *ID) {
  4641. std::vector<llvm::Constant*> Ivars;
  4642. const ObjCInterfaceDecl *OID = ID->getClassInterface();
  4643. assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
  4644. // FIXME. Consolidate this with similar code in GenerateClass.
  4645. for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin();
  4646. IVD; IVD = IVD->getNextIvar()) {
  4647. // Ignore unnamed bit-fields.
  4648. if (!IVD->getDeclName())
  4649. continue;
  4650. llvm::Constant *Ivar[5];
  4651. Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
  4652. ComputeIvarBaseOffset(CGM, ID, IVD));
  4653. Ivar[1] = GetMethodVarName(IVD->getIdentifier());
  4654. Ivar[2] = GetMethodVarType(IVD);
  4655. llvm::Type *FieldTy =
  4656. CGM.getTypes().ConvertTypeForMem(IVD->getType());
  4657. unsigned Size = CGM.getTargetData().getTypeAllocSize(FieldTy);
  4658. unsigned Align = CGM.getContext().getPreferredTypeAlign(
  4659. IVD->getType().getTypePtr()) >> 3;
  4660. Align = llvm::Log2_32(Align);
  4661. Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
  4662. // NOTE. Size of a bitfield does not match gcc's, because of the
  4663. // way bitfields are treated special in each. But I am told that
  4664. // 'size' for bitfield ivars is ignored by the runtime so it does
  4665. // not matter. If it matters, there is enough info to get the
  4666. // bitfield right!
  4667. Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
  4668. Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
  4669. }
  4670. // Return null for empty list.
  4671. if (Ivars.empty())
  4672. return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
  4673. llvm::Constant *Values[3];
  4674. unsigned Size = CGM.getTargetData().getTypeAllocSize(ObjCTypes.IvarnfABITy);
  4675. Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
  4676. Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
  4677. llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
  4678. Ivars.size());
  4679. Values[2] = llvm::ConstantArray::get(AT, Ivars);
  4680. llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
  4681. const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
  4682. llvm::GlobalVariable *GV =
  4683. new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
  4684. llvm::GlobalValue::InternalLinkage,
  4685. Init,
  4686. Prefix + OID->getName());
  4687. GV->setAlignment(
  4688. CGM.getTargetData().getABITypeAlignment(Init->getType()));
  4689. GV->setSection("__DATA, __objc_const");
  4690. CGM.AddUsedGlobal(GV);
  4691. return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListnfABIPtrTy);
  4692. }
  4693. llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
  4694. const ObjCProtocolDecl *PD) {
  4695. llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
  4696. if (!Entry) {
  4697. // We use the initializer as a marker of whether this is a forward
  4698. // reference or not. At module finalization we add the empty
  4699. // contents for protocols which were referenced but never defined.
  4700. Entry =
  4701. new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy, false,
  4702. llvm::GlobalValue::ExternalLinkage,
  4703. 0,
  4704. "\01l_OBJC_PROTOCOL_$_" + PD->getName());
  4705. Entry->setSection("__DATA,__datacoal_nt,coalesced");
  4706. }
  4707. return Entry;
  4708. }
  4709. /// GetOrEmitProtocol - Generate the protocol meta-data:
  4710. /// @code
  4711. /// struct _protocol_t {
  4712. /// id isa; // NULL
  4713. /// const char * const protocol_name;
  4714. /// const struct _protocol_list_t * protocol_list; // super protocols
  4715. /// const struct method_list_t * const instance_methods;
  4716. /// const struct method_list_t * const class_methods;
  4717. /// const struct method_list_t *optionalInstanceMethods;
  4718. /// const struct method_list_t *optionalClassMethods;
  4719. /// const struct _prop_list_t * properties;
  4720. /// const uint32_t size; // sizeof(struct _protocol_t)
  4721. /// const uint32_t flags; // = 0
  4722. /// const char ** extendedMethodTypes;
  4723. /// }
  4724. /// @endcode
  4725. ///
  4726. llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
  4727. const ObjCProtocolDecl *PD) {
  4728. llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
  4729. // Early exit if a defining object has already been generated.
  4730. if (Entry && Entry->hasInitializer())
  4731. return Entry;
  4732. // Use the protocol definition, if there is one.
  4733. if (const ObjCProtocolDecl *Def = PD->getDefinition())
  4734. PD = Def;
  4735. // Construct method lists.
  4736. std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
  4737. std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
  4738. std::vector<llvm::Constant*> MethodTypesExt, OptMethodTypesExt;
  4739. for (ObjCProtocolDecl::instmeth_iterator
  4740. i = PD->instmeth_begin(), e = PD->instmeth_end(); i != e; ++i) {
  4741. ObjCMethodDecl *MD = *i;
  4742. llvm::Constant *C = GetMethodDescriptionConstant(MD);
  4743. if (!C)
  4744. return GetOrEmitProtocolRef(PD);
  4745. if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
  4746. OptInstanceMethods.push_back(C);
  4747. OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
  4748. } else {
  4749. InstanceMethods.push_back(C);
  4750. MethodTypesExt.push_back(GetMethodVarType(MD, true));
  4751. }
  4752. }
  4753. for (ObjCProtocolDecl::classmeth_iterator
  4754. i = PD->classmeth_begin(), e = PD->classmeth_end(); i != e; ++i) {
  4755. ObjCMethodDecl *MD = *i;
  4756. llvm::Constant *C = GetMethodDescriptionConstant(MD);
  4757. if (!C)
  4758. return GetOrEmitProtocolRef(PD);
  4759. if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
  4760. OptClassMethods.push_back(C);
  4761. OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
  4762. } else {
  4763. ClassMethods.push_back(C);
  4764. MethodTypesExt.push_back(GetMethodVarType(MD, true));
  4765. }
  4766. }
  4767. MethodTypesExt.insert(MethodTypesExt.end(),
  4768. OptMethodTypesExt.begin(), OptMethodTypesExt.end());
  4769. llvm::Constant *Values[11];
  4770. // isa is NULL
  4771. Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
  4772. Values[1] = GetClassName(PD->getIdentifier());
  4773. Values[2] = EmitProtocolList("\01l_OBJC_$_PROTOCOL_REFS_" + PD->getName(),
  4774. PD->protocol_begin(),
  4775. PD->protocol_end());
  4776. Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
  4777. + PD->getName(),
  4778. "__DATA, __objc_const",
  4779. InstanceMethods);
  4780. Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
  4781. + PD->getName(),
  4782. "__DATA, __objc_const",
  4783. ClassMethods);
  4784. Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
  4785. + PD->getName(),
  4786. "__DATA, __objc_const",
  4787. OptInstanceMethods);
  4788. Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
  4789. + PD->getName(),
  4790. "__DATA, __objc_const",
  4791. OptClassMethods);
  4792. Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getName(),
  4793. 0, PD, ObjCTypes);
  4794. uint32_t Size =
  4795. CGM.getTargetData().getTypeAllocSize(ObjCTypes.ProtocolnfABITy);
  4796. Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
  4797. Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
  4798. Values[10] = EmitProtocolMethodTypes("\01l_OBJC_$_PROTOCOL_METHOD_TYPES_"
  4799. + PD->getName(),
  4800. MethodTypesExt, ObjCTypes);
  4801. llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
  4802. Values);
  4803. if (Entry) {
  4804. // Already created, fix the linkage and update the initializer.
  4805. Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
  4806. Entry->setInitializer(Init);
  4807. } else {
  4808. Entry =
  4809. new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy,
  4810. false, llvm::GlobalValue::WeakAnyLinkage, Init,
  4811. "\01l_OBJC_PROTOCOL_$_" + PD->getName());
  4812. Entry->setAlignment(
  4813. CGM.getTargetData().getABITypeAlignment(ObjCTypes.ProtocolnfABITy));
  4814. Entry->setSection("__DATA,__datacoal_nt,coalesced");
  4815. }
  4816. Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
  4817. CGM.AddUsedGlobal(Entry);
  4818. // Use this protocol meta-data to build protocol list table in section
  4819. // __DATA, __objc_protolist
  4820. llvm::GlobalVariable *PTGV =
  4821. new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABIPtrTy,
  4822. false, llvm::GlobalValue::WeakAnyLinkage, Entry,
  4823. "\01l_OBJC_LABEL_PROTOCOL_$_" + PD->getName());
  4824. PTGV->setAlignment(
  4825. CGM.getTargetData().getABITypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
  4826. PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
  4827. PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
  4828. CGM.AddUsedGlobal(PTGV);
  4829. return Entry;
  4830. }
  4831. /// EmitProtocolList - Generate protocol list meta-data:
  4832. /// @code
  4833. /// struct _protocol_list_t {
  4834. /// long protocol_count; // Note, this is 32/64 bit
  4835. /// struct _protocol_t[protocol_count];
  4836. /// }
  4837. /// @endcode
  4838. ///
  4839. llvm::Constant *
  4840. CGObjCNonFragileABIMac::EmitProtocolList(Twine Name,
  4841. ObjCProtocolDecl::protocol_iterator begin,
  4842. ObjCProtocolDecl::protocol_iterator end) {
  4843. llvm::SmallVector<llvm::Constant*, 16> ProtocolRefs;
  4844. // Just return null for empty protocol lists
  4845. if (begin == end)
  4846. return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
  4847. // FIXME: We shouldn't need to do this lookup here, should we?
  4848. SmallString<256> TmpName;
  4849. Name.toVector(TmpName);
  4850. llvm::GlobalVariable *GV =
  4851. CGM.getModule().getGlobalVariable(TmpName.str(), true);
  4852. if (GV)
  4853. return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListnfABIPtrTy);
  4854. for (; begin != end; ++begin)
  4855. ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
  4856. // This list is null terminated.
  4857. ProtocolRefs.push_back(llvm::Constant::getNullValue(
  4858. ObjCTypes.ProtocolnfABIPtrTy));
  4859. llvm::Constant *Values[2];
  4860. Values[0] =
  4861. llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
  4862. Values[1] =
  4863. llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
  4864. ProtocolRefs.size()),
  4865. ProtocolRefs);
  4866. llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
  4867. GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
  4868. llvm::GlobalValue::InternalLinkage,
  4869. Init, Name);
  4870. GV->setSection("__DATA, __objc_const");
  4871. GV->setAlignment(
  4872. CGM.getTargetData().getABITypeAlignment(Init->getType()));
  4873. CGM.AddUsedGlobal(GV);
  4874. return llvm::ConstantExpr::getBitCast(GV,
  4875. ObjCTypes.ProtocolListnfABIPtrTy);
  4876. }
  4877. /// GetMethodDescriptionConstant - This routine build following meta-data:
  4878. /// struct _objc_method {
  4879. /// SEL _cmd;
  4880. /// char *method_type;
  4881. /// char *_imp;
  4882. /// }
  4883. llvm::Constant *
  4884. CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
  4885. llvm::Constant *Desc[3];
  4886. Desc[0] =
  4887. llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
  4888. ObjCTypes.SelectorPtrTy);
  4889. Desc[1] = GetMethodVarType(MD);
  4890. if (!Desc[1])
  4891. return 0;
  4892. // Protocol methods have no implementation. So, this entry is always NULL.
  4893. Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
  4894. return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
  4895. }
  4896. /// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
  4897. /// This code gen. amounts to generating code for:
  4898. /// @code
  4899. /// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
  4900. /// @encode
  4901. ///
  4902. LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
  4903. CodeGen::CodeGenFunction &CGF,
  4904. QualType ObjectTy,
  4905. llvm::Value *BaseValue,
  4906. const ObjCIvarDecl *Ivar,
  4907. unsigned CVRQualifiers) {
  4908. ObjCInterfaceDecl *ID = ObjectTy->getAs<ObjCObjectType>()->getInterface();
  4909. return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
  4910. EmitIvarOffset(CGF, ID, Ivar));
  4911. }
  4912. llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
  4913. CodeGen::CodeGenFunction &CGF,
  4914. const ObjCInterfaceDecl *Interface,
  4915. const ObjCIvarDecl *Ivar) {
  4916. return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),"ivar");
  4917. }
  4918. static void appendSelectorForMessageRefTable(std::string &buffer,
  4919. Selector selector) {
  4920. if (selector.isUnarySelector()) {
  4921. buffer += selector.getNameForSlot(0);
  4922. return;
  4923. }
  4924. for (unsigned i = 0, e = selector.getNumArgs(); i != e; ++i) {
  4925. buffer += selector.getNameForSlot(i);
  4926. buffer += '_';
  4927. }
  4928. }
  4929. /// Emit a "v-table" message send. We emit a weak hidden-visibility
  4930. /// struct, initially containing the selector pointer and a pointer to
  4931. /// a "fixup" variant of the appropriate objc_msgSend. To call, we
  4932. /// load and call the function pointer, passing the address of the
  4933. /// struct as the second parameter. The runtime determines whether
  4934. /// the selector is currently emitted using vtable dispatch; if so, it
  4935. /// substitutes a stub function which simply tail-calls through the
  4936. /// appropriate vtable slot, and if not, it substitues a stub function
  4937. /// which tail-calls objc_msgSend. Both stubs adjust the selector
  4938. /// argument to correctly point to the selector.
  4939. RValue
  4940. CGObjCNonFragileABIMac::EmitVTableMessageSend(CodeGenFunction &CGF,
  4941. ReturnValueSlot returnSlot,
  4942. QualType resultType,
  4943. Selector selector,
  4944. llvm::Value *arg0,
  4945. QualType arg0Type,
  4946. bool isSuper,
  4947. const CallArgList &formalArgs,
  4948. const ObjCMethodDecl *method) {
  4949. // Compute the actual arguments.
  4950. CallArgList args;
  4951. // First argument: the receiver / super-call structure.
  4952. if (!isSuper)
  4953. arg0 = CGF.Builder.CreateBitCast(arg0, ObjCTypes.ObjectPtrTy);
  4954. args.add(RValue::get(arg0), arg0Type);
  4955. // Second argument: a pointer to the message ref structure. Leave
  4956. // the actual argument value blank for now.
  4957. args.add(RValue::get(0), ObjCTypes.MessageRefCPtrTy);
  4958. args.insert(args.end(), formalArgs.begin(), formalArgs.end());
  4959. MessageSendInfo MSI = getMessageSendInfo(method, resultType, args);
  4960. NullReturnState nullReturn;
  4961. // Find the function to call and the mangled name for the message
  4962. // ref structure. Using a different mangled name wouldn't actually
  4963. // be a problem; it would just be a waste.
  4964. //
  4965. // The runtime currently never uses vtable dispatch for anything
  4966. // except normal, non-super message-sends.
  4967. // FIXME: don't use this for that.
  4968. llvm::Constant *fn = 0;
  4969. std::string messageRefName("\01l_");
  4970. if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
  4971. if (isSuper) {
  4972. fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
  4973. messageRefName += "objc_msgSendSuper2_stret_fixup";
  4974. } else {
  4975. nullReturn.init(CGF, arg0);
  4976. fn = ObjCTypes.getMessageSendStretFixupFn();
  4977. messageRefName += "objc_msgSend_stret_fixup";
  4978. }
  4979. } else if (!isSuper && CGM.ReturnTypeUsesFPRet(resultType)) {
  4980. fn = ObjCTypes.getMessageSendFpretFixupFn();
  4981. messageRefName += "objc_msgSend_fpret_fixup";
  4982. } else {
  4983. if (isSuper) {
  4984. fn = ObjCTypes.getMessageSendSuper2FixupFn();
  4985. messageRefName += "objc_msgSendSuper2_fixup";
  4986. } else {
  4987. fn = ObjCTypes.getMessageSendFixupFn();
  4988. messageRefName += "objc_msgSend_fixup";
  4989. }
  4990. }
  4991. assert(fn && "CGObjCNonFragileABIMac::EmitMessageSend");
  4992. messageRefName += '_';
  4993. // Append the selector name, except use underscores anywhere we
  4994. // would have used colons.
  4995. appendSelectorForMessageRefTable(messageRefName, selector);
  4996. llvm::GlobalVariable *messageRef
  4997. = CGM.getModule().getGlobalVariable(messageRefName);
  4998. if (!messageRef) {
  4999. // Build the message ref structure.
  5000. llvm::Constant *values[] = { fn, GetMethodVarName(selector) };
  5001. llvm::Constant *init = llvm::ConstantStruct::getAnon(values);
  5002. messageRef = new llvm::GlobalVariable(CGM.getModule(),
  5003. init->getType(),
  5004. /*constant*/ false,
  5005. llvm::GlobalValue::WeakAnyLinkage,
  5006. init,
  5007. messageRefName);
  5008. messageRef->setVisibility(llvm::GlobalValue::HiddenVisibility);
  5009. messageRef->setAlignment(16);
  5010. messageRef->setSection("__DATA, __objc_msgrefs, coalesced");
  5011. }
  5012. bool requiresnullCheck = false;
  5013. if (CGM.getLangOptions().ObjCAutoRefCount && method)
  5014. for (ObjCMethodDecl::param_const_iterator i = method->param_begin(),
  5015. e = method->param_end(); i != e; ++i) {
  5016. const ParmVarDecl *ParamDecl = (*i);
  5017. if (ParamDecl->hasAttr<NSConsumedAttr>()) {
  5018. if (!nullReturn.NullBB)
  5019. nullReturn.init(CGF, arg0);
  5020. requiresnullCheck = true;
  5021. break;
  5022. }
  5023. }
  5024. llvm::Value *mref =
  5025. CGF.Builder.CreateBitCast(messageRef, ObjCTypes.MessageRefPtrTy);
  5026. // Update the message ref argument.
  5027. args[1].RV = RValue::get(mref);
  5028. // Load the function to call from the message ref table.
  5029. llvm::Value *callee = CGF.Builder.CreateStructGEP(mref, 0);
  5030. callee = CGF.Builder.CreateLoad(callee, "msgSend_fn");
  5031. callee = CGF.Builder.CreateBitCast(callee, MSI.MessengerType);
  5032. RValue result = CGF.EmitCall(MSI.CallInfo, callee, returnSlot, args);
  5033. return nullReturn.complete(CGF, result, resultType, formalArgs,
  5034. requiresnullCheck ? method : 0);
  5035. }
  5036. /// Generate code for a message send expression in the nonfragile abi.
  5037. CodeGen::RValue
  5038. CGObjCNonFragileABIMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
  5039. ReturnValueSlot Return,
  5040. QualType ResultType,
  5041. Selector Sel,
  5042. llvm::Value *Receiver,
  5043. const CallArgList &CallArgs,
  5044. const ObjCInterfaceDecl *Class,
  5045. const ObjCMethodDecl *Method) {
  5046. return isVTableDispatchedSelector(Sel)
  5047. ? EmitVTableMessageSend(CGF, Return, ResultType, Sel,
  5048. Receiver, CGF.getContext().getObjCIdType(),
  5049. false, CallArgs, Method)
  5050. : EmitMessageSend(CGF, Return, ResultType,
  5051. EmitSelector(CGF.Builder, Sel),
  5052. Receiver, CGF.getContext().getObjCIdType(),
  5053. false, CallArgs, Method, ObjCTypes);
  5054. }
  5055. llvm::GlobalVariable *
  5056. CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
  5057. llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
  5058. if (!GV) {
  5059. GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABITy,
  5060. false, llvm::GlobalValue::ExternalLinkage,
  5061. 0, Name);
  5062. }
  5063. return GV;
  5064. }
  5065. llvm::Value *CGObjCNonFragileABIMac::EmitClassRefFromId(CGBuilderTy &Builder,
  5066. IdentifierInfo *II) {
  5067. llvm::GlobalVariable *&Entry = ClassReferences[II];
  5068. if (!Entry) {
  5069. std::string ClassName(getClassSymbolPrefix() + II->getName().str());
  5070. llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
  5071. Entry =
  5072. new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
  5073. false, llvm::GlobalValue::InternalLinkage,
  5074. ClassGV,
  5075. "\01L_OBJC_CLASSLIST_REFERENCES_$_");
  5076. Entry->setAlignment(
  5077. CGM.getTargetData().getABITypeAlignment(
  5078. ObjCTypes.ClassnfABIPtrTy));
  5079. Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
  5080. CGM.AddUsedGlobal(Entry);
  5081. }
  5082. return Builder.CreateLoad(Entry);
  5083. }
  5084. llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
  5085. const ObjCInterfaceDecl *ID) {
  5086. return EmitClassRefFromId(Builder, ID->getIdentifier());
  5087. }
  5088. llvm::Value *CGObjCNonFragileABIMac::EmitNSAutoreleasePoolClassRef(
  5089. CGBuilderTy &Builder) {
  5090. IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool");
  5091. return EmitClassRefFromId(Builder, II);
  5092. }
  5093. llvm::Value *
  5094. CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
  5095. const ObjCInterfaceDecl *ID) {
  5096. llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
  5097. if (!Entry) {
  5098. std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
  5099. llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
  5100. Entry =
  5101. new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
  5102. false, llvm::GlobalValue::InternalLinkage,
  5103. ClassGV,
  5104. "\01L_OBJC_CLASSLIST_SUP_REFS_$_");
  5105. Entry->setAlignment(
  5106. CGM.getTargetData().getABITypeAlignment(
  5107. ObjCTypes.ClassnfABIPtrTy));
  5108. Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
  5109. CGM.AddUsedGlobal(Entry);
  5110. }
  5111. return Builder.CreateLoad(Entry);
  5112. }
  5113. /// EmitMetaClassRef - Return a Value * of the address of _class_t
  5114. /// meta-data
  5115. ///
  5116. llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
  5117. const ObjCInterfaceDecl *ID) {
  5118. llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
  5119. if (Entry)
  5120. return Builder.CreateLoad(Entry);
  5121. std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
  5122. llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
  5123. Entry =
  5124. new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy, false,
  5125. llvm::GlobalValue::InternalLinkage,
  5126. MetaClassGV,
  5127. "\01L_OBJC_CLASSLIST_SUP_REFS_$_");
  5128. Entry->setAlignment(
  5129. CGM.getTargetData().getABITypeAlignment(
  5130. ObjCTypes.ClassnfABIPtrTy));
  5131. Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
  5132. CGM.AddUsedGlobal(Entry);
  5133. return Builder.CreateLoad(Entry);
  5134. }
  5135. /// GetClass - Return a reference to the class for the given interface
  5136. /// decl.
  5137. llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
  5138. const ObjCInterfaceDecl *ID) {
  5139. if (ID->isWeakImported()) {
  5140. std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
  5141. llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
  5142. ClassGV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  5143. }
  5144. return EmitClassRef(Builder, ID);
  5145. }
  5146. /// Generates a message send where the super is the receiver. This is
  5147. /// a message send to self with special delivery semantics indicating
  5148. /// which class's method should be called.
  5149. CodeGen::RValue
  5150. CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
  5151. ReturnValueSlot Return,
  5152. QualType ResultType,
  5153. Selector Sel,
  5154. const ObjCInterfaceDecl *Class,
  5155. bool isCategoryImpl,
  5156. llvm::Value *Receiver,
  5157. bool IsClassMessage,
  5158. const CodeGen::CallArgList &CallArgs,
  5159. const ObjCMethodDecl *Method) {
  5160. // ...
  5161. // Create and init a super structure; this is a (receiver, class)
  5162. // pair we will pass to objc_msgSendSuper.
  5163. llvm::Value *ObjCSuper =
  5164. CGF.CreateTempAlloca(ObjCTypes.SuperTy, "objc_super");
  5165. llvm::Value *ReceiverAsObject =
  5166. CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
  5167. CGF.Builder.CreateStore(ReceiverAsObject,
  5168. CGF.Builder.CreateStructGEP(ObjCSuper, 0));
  5169. // If this is a class message the metaclass is passed as the target.
  5170. llvm::Value *Target;
  5171. if (IsClassMessage) {
  5172. if (isCategoryImpl) {
  5173. // Message sent to "super' in a class method defined in
  5174. // a category implementation.
  5175. Target = EmitClassRef(CGF.Builder, Class);
  5176. Target = CGF.Builder.CreateStructGEP(Target, 0);
  5177. Target = CGF.Builder.CreateLoad(Target);
  5178. } else
  5179. Target = EmitMetaClassRef(CGF.Builder, Class);
  5180. } else
  5181. Target = EmitSuperClassRef(CGF.Builder, Class);
  5182. // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
  5183. // ObjCTypes types.
  5184. llvm::Type *ClassTy =
  5185. CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
  5186. Target = CGF.Builder.CreateBitCast(Target, ClassTy);
  5187. CGF.Builder.CreateStore(Target,
  5188. CGF.Builder.CreateStructGEP(ObjCSuper, 1));
  5189. return (isVTableDispatchedSelector(Sel))
  5190. ? EmitVTableMessageSend(CGF, Return, ResultType, Sel,
  5191. ObjCSuper, ObjCTypes.SuperPtrCTy,
  5192. true, CallArgs, Method)
  5193. : EmitMessageSend(CGF, Return, ResultType,
  5194. EmitSelector(CGF.Builder, Sel),
  5195. ObjCSuper, ObjCTypes.SuperPtrCTy,
  5196. true, CallArgs, Method, ObjCTypes);
  5197. }
  5198. llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
  5199. Selector Sel, bool lval) {
  5200. llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
  5201. if (!Entry) {
  5202. llvm::Constant *Casted =
  5203. llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
  5204. ObjCTypes.SelectorPtrTy);
  5205. Entry =
  5206. new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.SelectorPtrTy, false,
  5207. llvm::GlobalValue::InternalLinkage,
  5208. Casted, "\01L_OBJC_SELECTOR_REFERENCES_");
  5209. Entry->setSection("__DATA, __objc_selrefs, literal_pointers, no_dead_strip");
  5210. CGM.AddUsedGlobal(Entry);
  5211. }
  5212. if (lval)
  5213. return Entry;
  5214. llvm::LoadInst* LI = Builder.CreateLoad(Entry);
  5215. LI->setMetadata(CGM.getModule().getMDKindID("invariant.load"),
  5216. llvm::MDNode::get(VMContext,
  5217. ArrayRef<llvm::Value*>()));
  5218. return LI;
  5219. }
  5220. /// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
  5221. /// objc_assign_ivar (id src, id *dst, ptrdiff_t)
  5222. ///
  5223. void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
  5224. llvm::Value *src,
  5225. llvm::Value *dst,
  5226. llvm::Value *ivarOffset) {
  5227. llvm::Type * SrcTy = src->getType();
  5228. if (!isa<llvm::PointerType>(SrcTy)) {
  5229. unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
  5230. assert(Size <= 8 && "does not support size > 8");
  5231. src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
  5232. : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
  5233. src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
  5234. }
  5235. src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
  5236. dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
  5237. CGF.Builder.CreateCall3(ObjCTypes.getGcAssignIvarFn(),
  5238. src, dst, ivarOffset);
  5239. return;
  5240. }
  5241. /// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
  5242. /// objc_assign_strongCast (id src, id *dst)
  5243. ///
  5244. void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
  5245. CodeGen::CodeGenFunction &CGF,
  5246. llvm::Value *src, llvm::Value *dst) {
  5247. llvm::Type * SrcTy = src->getType();
  5248. if (!isa<llvm::PointerType>(SrcTy)) {
  5249. unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
  5250. assert(Size <= 8 && "does not support size > 8");
  5251. src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
  5252. : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
  5253. src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
  5254. }
  5255. src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
  5256. dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
  5257. CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
  5258. src, dst, "weakassign");
  5259. return;
  5260. }
  5261. void CGObjCNonFragileABIMac::EmitGCMemmoveCollectable(
  5262. CodeGen::CodeGenFunction &CGF,
  5263. llvm::Value *DestPtr,
  5264. llvm::Value *SrcPtr,
  5265. llvm::Value *Size) {
  5266. SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy);
  5267. DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy);
  5268. CGF.Builder.CreateCall3(ObjCTypes.GcMemmoveCollectableFn(),
  5269. DestPtr, SrcPtr, Size);
  5270. return;
  5271. }
  5272. /// EmitObjCWeakRead - Code gen for loading value of a __weak
  5273. /// object: objc_read_weak (id *src)
  5274. ///
  5275. llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
  5276. CodeGen::CodeGenFunction &CGF,
  5277. llvm::Value *AddrWeakObj) {
  5278. llvm::Type* DestTy =
  5279. cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
  5280. AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
  5281. llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
  5282. AddrWeakObj, "weakread");
  5283. read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
  5284. return read_weak;
  5285. }
  5286. /// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
  5287. /// objc_assign_weak (id src, id *dst)
  5288. ///
  5289. void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
  5290. llvm::Value *src, llvm::Value *dst) {
  5291. llvm::Type * SrcTy = src->getType();
  5292. if (!isa<llvm::PointerType>(SrcTy)) {
  5293. unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
  5294. assert(Size <= 8 && "does not support size > 8");
  5295. src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
  5296. : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
  5297. src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
  5298. }
  5299. src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
  5300. dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
  5301. CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
  5302. src, dst, "weakassign");
  5303. return;
  5304. }
  5305. /// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
  5306. /// objc_assign_global (id src, id *dst)
  5307. ///
  5308. void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
  5309. llvm::Value *src, llvm::Value *dst,
  5310. bool threadlocal) {
  5311. llvm::Type * SrcTy = src->getType();
  5312. if (!isa<llvm::PointerType>(SrcTy)) {
  5313. unsigned Size = CGM.getTargetData().getTypeAllocSize(SrcTy);
  5314. assert(Size <= 8 && "does not support size > 8");
  5315. src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
  5316. : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
  5317. src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
  5318. }
  5319. src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
  5320. dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
  5321. if (!threadlocal)
  5322. CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
  5323. src, dst, "globalassign");
  5324. else
  5325. CGF.Builder.CreateCall2(ObjCTypes.getGcAssignThreadLocalFn(),
  5326. src, dst, "threadlocalassign");
  5327. return;
  5328. }
  5329. void
  5330. CGObjCNonFragileABIMac::EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
  5331. const ObjCAtSynchronizedStmt &S) {
  5332. EmitAtSynchronizedStmt(CGF, S,
  5333. cast<llvm::Function>(ObjCTypes.getSyncEnterFn()),
  5334. cast<llvm::Function>(ObjCTypes.getSyncExitFn()));
  5335. }
  5336. llvm::Constant *
  5337. CGObjCNonFragileABIMac::GetEHType(QualType T) {
  5338. // There's a particular fixed type info for 'id'.
  5339. if (T->isObjCIdType() ||
  5340. T->isObjCQualifiedIdType()) {
  5341. llvm::Constant *IDEHType =
  5342. CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
  5343. if (!IDEHType)
  5344. IDEHType =
  5345. new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy,
  5346. false,
  5347. llvm::GlobalValue::ExternalLinkage,
  5348. 0, "OBJC_EHTYPE_id");
  5349. return IDEHType;
  5350. }
  5351. // All other types should be Objective-C interface pointer types.
  5352. const ObjCObjectPointerType *PT =
  5353. T->getAs<ObjCObjectPointerType>();
  5354. assert(PT && "Invalid @catch type.");
  5355. const ObjCInterfaceType *IT = PT->getInterfaceType();
  5356. assert(IT && "Invalid @catch type.");
  5357. return GetInterfaceEHType(IT->getDecl(), false);
  5358. }
  5359. void CGObjCNonFragileABIMac::EmitTryStmt(CodeGen::CodeGenFunction &CGF,
  5360. const ObjCAtTryStmt &S) {
  5361. EmitTryCatchStmt(CGF, S,
  5362. cast<llvm::Function>(ObjCTypes.getObjCBeginCatchFn()),
  5363. cast<llvm::Function>(ObjCTypes.getObjCEndCatchFn()),
  5364. cast<llvm::Function>(ObjCTypes.getExceptionRethrowFn()));
  5365. }
  5366. /// EmitThrowStmt - Generate code for a throw statement.
  5367. void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
  5368. const ObjCAtThrowStmt &S) {
  5369. if (const Expr *ThrowExpr = S.getThrowExpr()) {
  5370. llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
  5371. Exception = CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy);
  5372. CGF.EmitCallOrInvoke(ObjCTypes.getExceptionThrowFn(), Exception)
  5373. .setDoesNotReturn();
  5374. } else {
  5375. CGF.EmitCallOrInvoke(ObjCTypes.getExceptionRethrowFn())
  5376. .setDoesNotReturn();
  5377. }
  5378. CGF.Builder.CreateUnreachable();
  5379. CGF.Builder.ClearInsertionPoint();
  5380. }
  5381. llvm::Constant *
  5382. CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
  5383. bool ForDefinition) {
  5384. llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
  5385. // If we don't need a definition, return the entry if found or check
  5386. // if we use an external reference.
  5387. if (!ForDefinition) {
  5388. if (Entry)
  5389. return Entry;
  5390. // If this type (or a super class) has the __objc_exception__
  5391. // attribute, emit an external reference.
  5392. if (hasObjCExceptionAttribute(CGM.getContext(), ID))
  5393. return Entry =
  5394. new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false,
  5395. llvm::GlobalValue::ExternalLinkage,
  5396. 0,
  5397. ("OBJC_EHTYPE_$_" +
  5398. ID->getIdentifier()->getName()));
  5399. }
  5400. // Otherwise we need to either make a new entry or fill in the
  5401. // initializer.
  5402. assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
  5403. std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
  5404. std::string VTableName = "objc_ehtype_vtable";
  5405. llvm::GlobalVariable *VTableGV =
  5406. CGM.getModule().getGlobalVariable(VTableName);
  5407. if (!VTableGV)
  5408. VTableGV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.Int8PtrTy,
  5409. false,
  5410. llvm::GlobalValue::ExternalLinkage,
  5411. 0, VTableName);
  5412. llvm::Value *VTableIdx = llvm::ConstantInt::get(CGM.Int32Ty, 2);
  5413. llvm::Constant *Values[] = {
  5414. llvm::ConstantExpr::getGetElementPtr(VTableGV, VTableIdx),
  5415. GetClassName(ID->getIdentifier()),
  5416. GetClassGlobal(ClassName)
  5417. };
  5418. llvm::Constant *Init =
  5419. llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
  5420. if (Entry) {
  5421. Entry->setInitializer(Init);
  5422. } else {
  5423. Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false,
  5424. llvm::GlobalValue::WeakAnyLinkage,
  5425. Init,
  5426. ("OBJC_EHTYPE_$_" +
  5427. ID->getIdentifier()->getName()));
  5428. }
  5429. if (CGM.getLangOptions().getVisibilityMode() == HiddenVisibility)
  5430. Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
  5431. Entry->setAlignment(CGM.getTargetData().getABITypeAlignment(
  5432. ObjCTypes.EHTypeTy));
  5433. if (ForDefinition) {
  5434. Entry->setSection("__DATA,__objc_const");
  5435. Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
  5436. } else {
  5437. Entry->setSection("__DATA,__datacoal_nt,coalesced");
  5438. }
  5439. return Entry;
  5440. }
  5441. /* *** */
  5442. CodeGen::CGObjCRuntime *
  5443. CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
  5444. if (CGM.getLangOptions().ObjCNonFragileABI)
  5445. return new CGObjCNonFragileABIMac(CGM);
  5446. return new CGObjCMac(CGM);
  5447. }