TargetInfo.cpp 265 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438
  1. //===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
  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. // These classes wrap the information about a call or function
  11. // definition used to handle ABI compliancy.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "TargetInfo.h"
  15. #include "ABIInfo.h"
  16. #include "CGCXXABI.h"
  17. #include "CGValue.h"
  18. #include "CodeGenFunction.h"
  19. #include "clang/AST/RecordLayout.h"
  20. #include "clang/CodeGen/CGFunctionInfo.h"
  21. #include "clang/Frontend/CodeGenOptions.h"
  22. #include "llvm/ADT/StringExtras.h"
  23. #include "llvm/ADT/Triple.h"
  24. #include "llvm/IR/DataLayout.h"
  25. #include "llvm/IR/Type.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. #include <algorithm> // std::sort
  28. using namespace clang;
  29. using namespace CodeGen;
  30. static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
  31. llvm::Value *Array,
  32. llvm::Value *Value,
  33. unsigned FirstIndex,
  34. unsigned LastIndex) {
  35. // Alternatively, we could emit this as a loop in the source.
  36. for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
  37. llvm::Value *Cell =
  38. Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
  39. Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
  40. }
  41. }
  42. static bool isAggregateTypeForABI(QualType T) {
  43. return !CodeGenFunction::hasScalarEvaluationKind(T) ||
  44. T->isMemberFunctionPointerType();
  45. }
  46. ABIArgInfo
  47. ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByRef, bool Realign,
  48. llvm::Type *Padding) const {
  49. return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty),
  50. ByRef, Realign, Padding);
  51. }
  52. ABIArgInfo
  53. ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
  54. return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
  55. /*ByRef*/ false, Realign);
  56. }
  57. Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
  58. QualType Ty) const {
  59. return Address::invalid();
  60. }
  61. ABIInfo::~ABIInfo() {}
  62. static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
  63. CGCXXABI &CXXABI) {
  64. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
  65. if (!RD)
  66. return CGCXXABI::RAA_Default;
  67. return CXXABI.getRecordArgABI(RD);
  68. }
  69. static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
  70. CGCXXABI &CXXABI) {
  71. const RecordType *RT = T->getAs<RecordType>();
  72. if (!RT)
  73. return CGCXXABI::RAA_Default;
  74. return getRecordArgABI(RT, CXXABI);
  75. }
  76. /// Pass transparent unions as if they were the type of the first element. Sema
  77. /// should ensure that all elements of the union have the same "machine type".
  78. static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
  79. if (const RecordType *UT = Ty->getAsUnionType()) {
  80. const RecordDecl *UD = UT->getDecl();
  81. if (UD->hasAttr<TransparentUnionAttr>()) {
  82. assert(!UD->field_empty() && "sema created an empty transparent union");
  83. return UD->field_begin()->getType();
  84. }
  85. }
  86. return Ty;
  87. }
  88. CGCXXABI &ABIInfo::getCXXABI() const {
  89. return CGT.getCXXABI();
  90. }
  91. ASTContext &ABIInfo::getContext() const {
  92. return CGT.getContext();
  93. }
  94. llvm::LLVMContext &ABIInfo::getVMContext() const {
  95. return CGT.getLLVMContext();
  96. }
  97. const llvm::DataLayout &ABIInfo::getDataLayout() const {
  98. return CGT.getDataLayout();
  99. }
  100. const TargetInfo &ABIInfo::getTarget() const {
  101. return CGT.getTarget();
  102. }
  103. bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
  104. return false;
  105. }
  106. bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
  107. uint64_t Members) const {
  108. return false;
  109. }
  110. bool ABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
  111. return false;
  112. }
  113. void ABIArgInfo::dump() const {
  114. raw_ostream &OS = llvm::errs();
  115. OS << "(ABIArgInfo Kind=";
  116. switch (TheKind) {
  117. case Direct:
  118. OS << "Direct Type=";
  119. if (llvm::Type *Ty = getCoerceToType())
  120. Ty->print(OS);
  121. else
  122. OS << "null";
  123. break;
  124. case Extend:
  125. OS << "Extend";
  126. break;
  127. case Ignore:
  128. OS << "Ignore";
  129. break;
  130. case InAlloca:
  131. OS << "InAlloca Offset=" << getInAllocaFieldIndex();
  132. break;
  133. case Indirect:
  134. OS << "Indirect Align=" << getIndirectAlign().getQuantity()
  135. << " ByVal=" << getIndirectByVal()
  136. << " Realign=" << getIndirectRealign();
  137. break;
  138. case Expand:
  139. OS << "Expand";
  140. break;
  141. }
  142. OS << ")\n";
  143. }
  144. /// Emit va_arg for a platform using the common void* representation,
  145. /// where arguments are simply emitted in an array of slots on the stack.
  146. ///
  147. /// This version implements the core direct-value passing rules.
  148. ///
  149. /// \param SlotSize - The size and alignment of a stack slot.
  150. /// Each argument will be allocated to a multiple of this number of
  151. /// slots, and all the slots will be aligned to this value.
  152. /// \param AllowHigherAlign - The slot alignment is not a cap;
  153. /// an argument type with an alignment greater than the slot size
  154. /// will be emitted on a higher-alignment address, potentially
  155. /// leaving one or more empty slots behind as padding. If this
  156. /// is false, the returned address might be less-aligned than
  157. /// DirectAlign.
  158. static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
  159. Address VAListAddr,
  160. llvm::Type *DirectTy,
  161. CharUnits DirectSize,
  162. CharUnits DirectAlign,
  163. CharUnits SlotSize,
  164. bool AllowHigherAlign) {
  165. // Cast the element type to i8* if necessary. Some platforms define
  166. // va_list as a struct containing an i8* instead of just an i8*.
  167. if (VAListAddr.getElementType() != CGF.Int8PtrTy)
  168. VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
  169. llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
  170. // If the CC aligns values higher than the slot size, do so if needed.
  171. Address Addr = Address::invalid();
  172. if (AllowHigherAlign && DirectAlign > SlotSize) {
  173. llvm::Value *PtrAsInt = Ptr;
  174. PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
  175. PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
  176. llvm::ConstantInt::get(CGF.IntPtrTy, DirectAlign.getQuantity() - 1));
  177. PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
  178. llvm::ConstantInt::get(CGF.IntPtrTy, -DirectAlign.getQuantity()));
  179. Addr = Address(CGF.Builder.CreateIntToPtr(PtrAsInt, Ptr->getType(),
  180. "argp.cur.aligned"),
  181. DirectAlign);
  182. } else {
  183. Addr = Address(Ptr, SlotSize);
  184. }
  185. // Advance the pointer past the argument, then store that back.
  186. CharUnits FullDirectSize = DirectSize.RoundUpToAlignment(SlotSize);
  187. llvm::Value *NextPtr =
  188. CGF.Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), FullDirectSize,
  189. "argp.next");
  190. CGF.Builder.CreateStore(NextPtr, VAListAddr);
  191. // If the argument is smaller than a slot, and this is a big-endian
  192. // target, the argument will be right-adjusted in its slot.
  193. if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian()) {
  194. Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
  195. }
  196. Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
  197. return Addr;
  198. }
  199. /// Emit va_arg for a platform using the common void* representation,
  200. /// where arguments are simply emitted in an array of slots on the stack.
  201. ///
  202. /// \param IsIndirect - Values of this type are passed indirectly.
  203. /// \param ValueInfo - The size and alignment of this type, generally
  204. /// computed with getContext().getTypeInfoInChars(ValueTy).
  205. /// \param SlotSizeAndAlign - The size and alignment of a stack slot.
  206. /// Each argument will be allocated to a multiple of this number of
  207. /// slots, and all the slots will be aligned to this value.
  208. /// \param AllowHigherAlign - The slot alignment is not a cap;
  209. /// an argument type with an alignment greater than the slot size
  210. /// will be emitted on a higher-alignment address, potentially
  211. /// leaving one or more empty slots behind as padding.
  212. static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
  213. QualType ValueTy, bool IsIndirect,
  214. std::pair<CharUnits, CharUnits> ValueInfo,
  215. CharUnits SlotSizeAndAlign,
  216. bool AllowHigherAlign) {
  217. // The size and alignment of the value that was passed directly.
  218. CharUnits DirectSize, DirectAlign;
  219. if (IsIndirect) {
  220. DirectSize = CGF.getPointerSize();
  221. DirectAlign = CGF.getPointerAlign();
  222. } else {
  223. DirectSize = ValueInfo.first;
  224. DirectAlign = ValueInfo.second;
  225. }
  226. // Cast the address we've calculated to the right type.
  227. llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
  228. if (IsIndirect)
  229. DirectTy = DirectTy->getPointerTo(0);
  230. Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
  231. DirectSize, DirectAlign,
  232. SlotSizeAndAlign,
  233. AllowHigherAlign);
  234. if (IsIndirect) {
  235. Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second);
  236. }
  237. return Addr;
  238. }
  239. static Address emitMergePHI(CodeGenFunction &CGF,
  240. Address Addr1, llvm::BasicBlock *Block1,
  241. Address Addr2, llvm::BasicBlock *Block2,
  242. const llvm::Twine &Name = "") {
  243. assert(Addr1.getType() == Addr2.getType());
  244. llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
  245. PHI->addIncoming(Addr1.getPointer(), Block1);
  246. PHI->addIncoming(Addr2.getPointer(), Block2);
  247. CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
  248. return Address(PHI, Align);
  249. }
  250. TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
  251. // If someone can figure out a general rule for this, that would be great.
  252. // It's probably just doomed to be platform-dependent, though.
  253. unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
  254. // Verified for:
  255. // x86-64 FreeBSD, Linux, Darwin
  256. // x86-32 FreeBSD, Linux, Darwin
  257. // PowerPC Linux, Darwin
  258. // ARM Darwin (*not* EABI)
  259. // AArch64 Linux
  260. return 32;
  261. }
  262. bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
  263. const FunctionNoProtoType *fnType) const {
  264. // The following conventions are known to require this to be false:
  265. // x86_stdcall
  266. // MIPS
  267. // For everything else, we just prefer false unless we opt out.
  268. return false;
  269. }
  270. void
  271. TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
  272. llvm::SmallString<24> &Opt) const {
  273. // This assumes the user is passing a library name like "rt" instead of a
  274. // filename like "librt.a/so", and that they don't care whether it's static or
  275. // dynamic.
  276. Opt = "-l";
  277. Opt += Lib;
  278. }
  279. static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
  280. /// isEmptyField - Return true iff a the field is "empty", that is it
  281. /// is an unnamed bit-field or an (array of) empty record(s).
  282. static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
  283. bool AllowArrays) {
  284. if (FD->isUnnamedBitfield())
  285. return true;
  286. QualType FT = FD->getType();
  287. // Constant arrays of empty records count as empty, strip them off.
  288. // Constant arrays of zero length always count as empty.
  289. if (AllowArrays)
  290. while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
  291. if (AT->getSize() == 0)
  292. return true;
  293. FT = AT->getElementType();
  294. }
  295. const RecordType *RT = FT->getAs<RecordType>();
  296. if (!RT)
  297. return false;
  298. // C++ record fields are never empty, at least in the Itanium ABI.
  299. //
  300. // FIXME: We should use a predicate for whether this behavior is true in the
  301. // current ABI.
  302. if (isa<CXXRecordDecl>(RT->getDecl()))
  303. return false;
  304. return isEmptyRecord(Context, FT, AllowArrays);
  305. }
  306. /// isEmptyRecord - Return true iff a structure contains only empty
  307. /// fields. Note that a structure with a flexible array member is not
  308. /// considered empty.
  309. static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
  310. const RecordType *RT = T->getAs<RecordType>();
  311. if (!RT)
  312. return 0;
  313. const RecordDecl *RD = RT->getDecl();
  314. if (RD->hasFlexibleArrayMember())
  315. return false;
  316. // If this is a C++ record, check the bases first.
  317. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
  318. for (const auto &I : CXXRD->bases())
  319. if (!isEmptyRecord(Context, I.getType(), true))
  320. return false;
  321. for (const auto *I : RD->fields())
  322. if (!isEmptyField(Context, I, AllowArrays))
  323. return false;
  324. return true;
  325. }
  326. /// isSingleElementStruct - Determine if a structure is a "single
  327. /// element struct", i.e. it has exactly one non-empty field or
  328. /// exactly one field which is itself a single element
  329. /// struct. Structures with flexible array members are never
  330. /// considered single element structs.
  331. ///
  332. /// \return The field declaration for the single non-empty field, if
  333. /// it exists.
  334. static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
  335. const RecordType *RT = T->getAs<RecordType>();
  336. if (!RT)
  337. return nullptr;
  338. const RecordDecl *RD = RT->getDecl();
  339. if (RD->hasFlexibleArrayMember())
  340. return nullptr;
  341. const Type *Found = nullptr;
  342. // If this is a C++ record, check the bases first.
  343. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  344. for (const auto &I : CXXRD->bases()) {
  345. // Ignore empty records.
  346. if (isEmptyRecord(Context, I.getType(), true))
  347. continue;
  348. // If we already found an element then this isn't a single-element struct.
  349. if (Found)
  350. return nullptr;
  351. // If this is non-empty and not a single element struct, the composite
  352. // cannot be a single element struct.
  353. Found = isSingleElementStruct(I.getType(), Context);
  354. if (!Found)
  355. return nullptr;
  356. }
  357. }
  358. // Check for single element.
  359. for (const auto *FD : RD->fields()) {
  360. QualType FT = FD->getType();
  361. // Ignore empty fields.
  362. if (isEmptyField(Context, FD, true))
  363. continue;
  364. // If we already found an element then this isn't a single-element
  365. // struct.
  366. if (Found)
  367. return nullptr;
  368. // Treat single element arrays as the element.
  369. while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
  370. if (AT->getSize().getZExtValue() != 1)
  371. break;
  372. FT = AT->getElementType();
  373. }
  374. if (!isAggregateTypeForABI(FT)) {
  375. Found = FT.getTypePtr();
  376. } else {
  377. Found = isSingleElementStruct(FT, Context);
  378. if (!Found)
  379. return nullptr;
  380. }
  381. }
  382. // We don't consider a struct a single-element struct if it has
  383. // padding beyond the element type.
  384. if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
  385. return nullptr;
  386. return Found;
  387. }
  388. static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
  389. // Treat complex types as the element type.
  390. if (const ComplexType *CTy = Ty->getAs<ComplexType>())
  391. Ty = CTy->getElementType();
  392. // Check for a type which we know has a simple scalar argument-passing
  393. // convention without any padding. (We're specifically looking for 32
  394. // and 64-bit integer and integer-equivalents, float, and double.)
  395. if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
  396. !Ty->isEnumeralType() && !Ty->isBlockPointerType())
  397. return false;
  398. uint64_t Size = Context.getTypeSize(Ty);
  399. return Size == 32 || Size == 64;
  400. }
  401. /// canExpandIndirectArgument - Test whether an argument type which is to be
  402. /// passed indirectly (on the stack) would have the equivalent layout if it was
  403. /// expanded into separate arguments. If so, we prefer to do the latter to avoid
  404. /// inhibiting optimizations.
  405. ///
  406. // FIXME: This predicate is missing many cases, currently it just follows
  407. // llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
  408. // should probably make this smarter, or better yet make the LLVM backend
  409. // capable of handling it.
  410. static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
  411. // We can only expand structure types.
  412. const RecordType *RT = Ty->getAs<RecordType>();
  413. if (!RT)
  414. return false;
  415. // We can only expand (C) structures.
  416. //
  417. // FIXME: This needs to be generalized to handle classes as well.
  418. const RecordDecl *RD = RT->getDecl();
  419. if (!RD->isStruct())
  420. return false;
  421. // We try to expand CLike CXXRecordDecl.
  422. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  423. if (!CXXRD->isCLike())
  424. return false;
  425. }
  426. uint64_t Size = 0;
  427. for (const auto *FD : RD->fields()) {
  428. if (!is32Or64BitBasicType(FD->getType(), Context))
  429. return false;
  430. // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
  431. // how to expand them yet, and the predicate for telling if a bitfield still
  432. // counts as "basic" is more complicated than what we were doing previously.
  433. if (FD->isBitField())
  434. return false;
  435. Size += Context.getTypeSize(FD->getType());
  436. }
  437. // Make sure there are not any holes in the struct.
  438. if (Size != Context.getTypeSize(Ty))
  439. return false;
  440. return true;
  441. }
  442. namespace {
  443. /// DefaultABIInfo - The default implementation for ABI specific
  444. /// details. This implementation provides information which results in
  445. /// self-consistent and sensible LLVM IR generation, but does not
  446. /// conform to any particular ABI.
  447. class DefaultABIInfo : public ABIInfo {
  448. public:
  449. DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
  450. ABIArgInfo classifyReturnType(QualType RetTy) const;
  451. ABIArgInfo classifyArgumentType(QualType RetTy) const;
  452. void computeInfo(CGFunctionInfo &FI) const override {
  453. if (!getCXXABI().classifyReturnType(FI))
  454. FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
  455. for (auto &I : FI.arguments())
  456. I.info = classifyArgumentType(I.type);
  457. }
  458. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  459. QualType Ty) const override;
  460. };
  461. class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
  462. public:
  463. DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
  464. : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
  465. };
  466. Address DefaultABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  467. QualType Ty) const {
  468. return Address::invalid();
  469. }
  470. ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
  471. Ty = useFirstFieldIfTransparentUnion(Ty);
  472. if (isAggregateTypeForABI(Ty)) {
  473. // Records with non-trivial destructors/copy-constructors should not be
  474. // passed by value.
  475. if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
  476. return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
  477. return getNaturalAlignIndirect(Ty);
  478. }
  479. // Treat an enum type as its underlying type.
  480. if (const EnumType *EnumTy = Ty->getAs<EnumType>())
  481. Ty = EnumTy->getDecl()->getIntegerType();
  482. return (Ty->isPromotableIntegerType() ?
  483. ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
  484. }
  485. ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
  486. if (RetTy->isVoidType())
  487. return ABIArgInfo::getIgnore();
  488. if (isAggregateTypeForABI(RetTy))
  489. return getNaturalAlignIndirect(RetTy);
  490. // Treat an enum type as its underlying type.
  491. if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
  492. RetTy = EnumTy->getDecl()->getIntegerType();
  493. return (RetTy->isPromotableIntegerType() ?
  494. ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
  495. }
  496. //===----------------------------------------------------------------------===//
  497. // WebAssembly ABI Implementation
  498. //
  499. // This is a very simple ABI that relies a lot on DefaultABIInfo.
  500. //===----------------------------------------------------------------------===//
  501. class WebAssemblyABIInfo final : public DefaultABIInfo {
  502. public:
  503. explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
  504. : DefaultABIInfo(CGT) {}
  505. private:
  506. ABIArgInfo classifyReturnType(QualType RetTy) const;
  507. ABIArgInfo classifyArgumentType(QualType Ty) const;
  508. // DefaultABIInfo's classifyReturnType and classifyArgumentType are
  509. // non-virtual, but computeInfo is virtual, so we overload that.
  510. void computeInfo(CGFunctionInfo &FI) const override {
  511. if (!getCXXABI().classifyReturnType(FI))
  512. FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
  513. for (auto &Arg : FI.arguments())
  514. Arg.info = classifyArgumentType(Arg.type);
  515. }
  516. };
  517. class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
  518. public:
  519. explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
  520. : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
  521. };
  522. /// \brief Classify argument of given type \p Ty.
  523. ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
  524. Ty = useFirstFieldIfTransparentUnion(Ty);
  525. if (isAggregateTypeForABI(Ty)) {
  526. // Records with non-trivial destructors/copy-constructors should not be
  527. // passed by value.
  528. if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
  529. return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
  530. // Ignore empty structs/unions.
  531. if (isEmptyRecord(getContext(), Ty, true))
  532. return ABIArgInfo::getIgnore();
  533. // Lower single-element structs to just pass a regular value. TODO: We
  534. // could do reasonable-size multiple-element structs too, using getExpand(),
  535. // though watch out for things like bitfields.
  536. if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
  537. return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
  538. }
  539. // Otherwise just do the default thing.
  540. return DefaultABIInfo::classifyArgumentType(Ty);
  541. }
  542. ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
  543. if (isAggregateTypeForABI(RetTy)) {
  544. // Records with non-trivial destructors/copy-constructors should not be
  545. // returned by value.
  546. if (!getRecordArgABI(RetTy, getCXXABI())) {
  547. // Ignore empty structs/unions.
  548. if (isEmptyRecord(getContext(), RetTy, true))
  549. return ABIArgInfo::getIgnore();
  550. // Lower single-element structs to just return a regular value. TODO: We
  551. // could do reasonable-size multiple-element structs too, using
  552. // ABIArgInfo::getDirect().
  553. if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
  554. return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
  555. }
  556. }
  557. // Otherwise just do the default thing.
  558. return DefaultABIInfo::classifyReturnType(RetTy);
  559. }
  560. //===----------------------------------------------------------------------===//
  561. // le32/PNaCl bitcode ABI Implementation
  562. //
  563. // This is a simplified version of the x86_32 ABI. Arguments and return values
  564. // are always passed on the stack.
  565. //===----------------------------------------------------------------------===//
  566. class PNaClABIInfo : public ABIInfo {
  567. public:
  568. PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
  569. ABIArgInfo classifyReturnType(QualType RetTy) const;
  570. ABIArgInfo classifyArgumentType(QualType RetTy) const;
  571. void computeInfo(CGFunctionInfo &FI) const override;
  572. Address EmitVAArg(CodeGenFunction &CGF,
  573. Address VAListAddr, QualType Ty) const override;
  574. };
  575. class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
  576. public:
  577. PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
  578. : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
  579. };
  580. void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
  581. if (!getCXXABI().classifyReturnType(FI))
  582. FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
  583. for (auto &I : FI.arguments())
  584. I.info = classifyArgumentType(I.type);
  585. }
  586. Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  587. QualType Ty) const {
  588. return Address::invalid();
  589. }
  590. /// \brief Classify argument of given type \p Ty.
  591. ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
  592. if (isAggregateTypeForABI(Ty)) {
  593. if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
  594. return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
  595. return getNaturalAlignIndirect(Ty);
  596. } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
  597. // Treat an enum type as its underlying type.
  598. Ty = EnumTy->getDecl()->getIntegerType();
  599. } else if (Ty->isFloatingType()) {
  600. // Floating-point types don't go inreg.
  601. return ABIArgInfo::getDirect();
  602. }
  603. return (Ty->isPromotableIntegerType() ?
  604. ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
  605. }
  606. ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
  607. if (RetTy->isVoidType())
  608. return ABIArgInfo::getIgnore();
  609. // In the PNaCl ABI we always return records/structures on the stack.
  610. if (isAggregateTypeForABI(RetTy))
  611. return getNaturalAlignIndirect(RetTy);
  612. // Treat an enum type as its underlying type.
  613. if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
  614. RetTy = EnumTy->getDecl()->getIntegerType();
  615. return (RetTy->isPromotableIntegerType() ?
  616. ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
  617. }
  618. /// IsX86_MMXType - Return true if this is an MMX type.
  619. bool IsX86_MMXType(llvm::Type *IRType) {
  620. // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
  621. return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
  622. cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
  623. IRType->getScalarSizeInBits() != 64;
  624. }
  625. static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
  626. StringRef Constraint,
  627. llvm::Type* Ty) {
  628. if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
  629. if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
  630. // Invalid MMX constraint
  631. return nullptr;
  632. }
  633. return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
  634. }
  635. // No operation needed
  636. return Ty;
  637. }
  638. /// Returns true if this type can be passed in SSE registers with the
  639. /// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
  640. static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
  641. if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
  642. if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
  643. return true;
  644. } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
  645. // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
  646. // registers specially.
  647. unsigned VecSize = Context.getTypeSize(VT);
  648. if (VecSize == 128 || VecSize == 256 || VecSize == 512)
  649. return true;
  650. }
  651. return false;
  652. }
  653. /// Returns true if this aggregate is small enough to be passed in SSE registers
  654. /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
  655. static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
  656. return NumMembers <= 4;
  657. }
  658. //===----------------------------------------------------------------------===//
  659. // X86-32 ABI Implementation
  660. //===----------------------------------------------------------------------===//
  661. /// \brief Similar to llvm::CCState, but for Clang.
  662. struct CCState {
  663. CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
  664. unsigned CC;
  665. unsigned FreeRegs;
  666. unsigned FreeSSERegs;
  667. };
  668. /// X86_32ABIInfo - The X86-32 ABI information.
  669. class X86_32ABIInfo : public ABIInfo {
  670. enum Class {
  671. Integer,
  672. Float
  673. };
  674. static const unsigned MinABIStackAlignInBytes = 4;
  675. bool IsDarwinVectorABI;
  676. bool IsRetSmallStructInRegABI;
  677. bool IsWin32StructABI;
  678. bool IsSoftFloatABI;
  679. unsigned DefaultNumRegisterParameters;
  680. static bool isRegisterSize(unsigned Size) {
  681. return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
  682. }
  683. bool isHomogeneousAggregateBaseType(QualType Ty) const override {
  684. // FIXME: Assumes vectorcall is in use.
  685. return isX86VectorTypeForVectorCall(getContext(), Ty);
  686. }
  687. bool isHomogeneousAggregateSmallEnough(const Type *Ty,
  688. uint64_t NumMembers) const override {
  689. // FIXME: Assumes vectorcall is in use.
  690. return isX86VectorCallAggregateSmallEnough(NumMembers);
  691. }
  692. bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
  693. /// getIndirectResult - Give a source type \arg Ty, return a suitable result
  694. /// such that the argument will be passed in memory.
  695. ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
  696. ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
  697. /// \brief Return the alignment to use for the given type on the stack.
  698. unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
  699. Class classify(QualType Ty) const;
  700. ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
  701. ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
  702. bool shouldUseInReg(QualType Ty, CCState &State, bool &NeedsPadding) const;
  703. /// \brief Rewrite the function info so that all memory arguments use
  704. /// inalloca.
  705. void rewriteWithInAlloca(CGFunctionInfo &FI) const;
  706. void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
  707. CharUnits &StackOffset, ABIArgInfo &Info,
  708. QualType Type) const;
  709. public:
  710. void computeInfo(CGFunctionInfo &FI) const override;
  711. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  712. QualType Ty) const override;
  713. X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
  714. bool RetSmallStructInRegABI, bool Win32StructABI,
  715. unsigned NumRegisterParameters, bool SoftFloatABI)
  716. : ABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
  717. IsRetSmallStructInRegABI(RetSmallStructInRegABI),
  718. IsWin32StructABI(Win32StructABI),
  719. IsSoftFloatABI(SoftFloatABI),
  720. DefaultNumRegisterParameters(NumRegisterParameters) {}
  721. };
  722. class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
  723. public:
  724. X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
  725. bool RetSmallStructInRegABI, bool Win32StructABI,
  726. unsigned NumRegisterParameters, bool SoftFloatABI)
  727. : TargetCodeGenInfo(new X86_32ABIInfo(
  728. CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
  729. NumRegisterParameters, SoftFloatABI)) {}
  730. static bool isStructReturnInRegABI(
  731. const llvm::Triple &Triple, const CodeGenOptions &Opts);
  732. void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
  733. CodeGen::CodeGenModule &CGM) const override;
  734. int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
  735. // Darwin uses different dwarf register numbers for EH.
  736. if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
  737. return 4;
  738. }
  739. bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
  740. llvm::Value *Address) const override;
  741. llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
  742. StringRef Constraint,
  743. llvm::Type* Ty) const override {
  744. return X86AdjustInlineAsmType(CGF, Constraint, Ty);
  745. }
  746. void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
  747. std::string &Constraints,
  748. std::vector<llvm::Type *> &ResultRegTypes,
  749. std::vector<llvm::Type *> &ResultTruncRegTypes,
  750. std::vector<LValue> &ResultRegDests,
  751. std::string &AsmString,
  752. unsigned NumOutputs) const override;
  753. llvm::Constant *
  754. getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
  755. unsigned Sig = (0xeb << 0) | // jmp rel8
  756. (0x06 << 8) | // .+0x08
  757. ('F' << 16) |
  758. ('T' << 24);
  759. return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
  760. }
  761. };
  762. }
  763. /// Rewrite input constraint references after adding some output constraints.
  764. /// In the case where there is one output and one input and we add one output,
  765. /// we need to replace all operand references greater than or equal to 1:
  766. /// mov $0, $1
  767. /// mov eax, $1
  768. /// The result will be:
  769. /// mov $0, $2
  770. /// mov eax, $2
  771. static void rewriteInputConstraintReferences(unsigned FirstIn,
  772. unsigned NumNewOuts,
  773. std::string &AsmString) {
  774. std::string Buf;
  775. llvm::raw_string_ostream OS(Buf);
  776. size_t Pos = 0;
  777. while (Pos < AsmString.size()) {
  778. size_t DollarStart = AsmString.find('$', Pos);
  779. if (DollarStart == std::string::npos)
  780. DollarStart = AsmString.size();
  781. size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
  782. if (DollarEnd == std::string::npos)
  783. DollarEnd = AsmString.size();
  784. OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
  785. Pos = DollarEnd;
  786. size_t NumDollars = DollarEnd - DollarStart;
  787. if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
  788. // We have an operand reference.
  789. size_t DigitStart = Pos;
  790. size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
  791. if (DigitEnd == std::string::npos)
  792. DigitEnd = AsmString.size();
  793. StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
  794. unsigned OperandIndex;
  795. if (!OperandStr.getAsInteger(10, OperandIndex)) {
  796. if (OperandIndex >= FirstIn)
  797. OperandIndex += NumNewOuts;
  798. OS << OperandIndex;
  799. } else {
  800. OS << OperandStr;
  801. }
  802. Pos = DigitEnd;
  803. }
  804. }
  805. AsmString = std::move(OS.str());
  806. }
  807. /// Add output constraints for EAX:EDX because they are return registers.
  808. void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
  809. CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
  810. std::vector<llvm::Type *> &ResultRegTypes,
  811. std::vector<llvm::Type *> &ResultTruncRegTypes,
  812. std::vector<LValue> &ResultRegDests, std::string &AsmString,
  813. unsigned NumOutputs) const {
  814. uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
  815. // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
  816. // larger.
  817. if (!Constraints.empty())
  818. Constraints += ',';
  819. if (RetWidth <= 32) {
  820. Constraints += "={eax}";
  821. ResultRegTypes.push_back(CGF.Int32Ty);
  822. } else {
  823. // Use the 'A' constraint for EAX:EDX.
  824. Constraints += "=A";
  825. ResultRegTypes.push_back(CGF.Int64Ty);
  826. }
  827. // Truncate EAX or EAX:EDX to an integer of the appropriate size.
  828. llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
  829. ResultTruncRegTypes.push_back(CoerceTy);
  830. // Coerce the integer by bitcasting the return slot pointer.
  831. ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
  832. CoerceTy->getPointerTo()));
  833. ResultRegDests.push_back(ReturnSlot);
  834. rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
  835. }
  836. /// shouldReturnTypeInRegister - Determine if the given type should be
  837. /// returned in a register (for the Darwin ABI).
  838. bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
  839. ASTContext &Context) const {
  840. uint64_t Size = Context.getTypeSize(Ty);
  841. // Type must be register sized.
  842. if (!isRegisterSize(Size))
  843. return false;
  844. if (Ty->isVectorType()) {
  845. // 64- and 128- bit vectors inside structures are not returned in
  846. // registers.
  847. if (Size == 64 || Size == 128)
  848. return false;
  849. return true;
  850. }
  851. // If this is a builtin, pointer, enum, complex type, member pointer, or
  852. // member function pointer it is ok.
  853. if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
  854. Ty->isAnyComplexType() || Ty->isEnumeralType() ||
  855. Ty->isBlockPointerType() || Ty->isMemberPointerType())
  856. return true;
  857. // Arrays are treated like records.
  858. if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
  859. return shouldReturnTypeInRegister(AT->getElementType(), Context);
  860. // Otherwise, it must be a record type.
  861. const RecordType *RT = Ty->getAs<RecordType>();
  862. if (!RT) return false;
  863. // FIXME: Traverse bases here too.
  864. // Structure types are passed in register if all fields would be
  865. // passed in a register.
  866. for (const auto *FD : RT->getDecl()->fields()) {
  867. // Empty fields are ignored.
  868. if (isEmptyField(Context, FD, true))
  869. continue;
  870. // Check fields recursively.
  871. if (!shouldReturnTypeInRegister(FD->getType(), Context))
  872. return false;
  873. }
  874. return true;
  875. }
  876. ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
  877. // If the return value is indirect, then the hidden argument is consuming one
  878. // integer register.
  879. if (State.FreeRegs) {
  880. --State.FreeRegs;
  881. return getNaturalAlignIndirectInReg(RetTy);
  882. }
  883. return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
  884. }
  885. ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
  886. CCState &State) const {
  887. if (RetTy->isVoidType())
  888. return ABIArgInfo::getIgnore();
  889. const Type *Base = nullptr;
  890. uint64_t NumElts = 0;
  891. if (State.CC == llvm::CallingConv::X86_VectorCall &&
  892. isHomogeneousAggregate(RetTy, Base, NumElts)) {
  893. // The LLVM struct type for such an aggregate should lower properly.
  894. return ABIArgInfo::getDirect();
  895. }
  896. if (const VectorType *VT = RetTy->getAs<VectorType>()) {
  897. // On Darwin, some vectors are returned in registers.
  898. if (IsDarwinVectorABI) {
  899. uint64_t Size = getContext().getTypeSize(RetTy);
  900. // 128-bit vectors are a special case; they are returned in
  901. // registers and we need to make sure to pick a type the LLVM
  902. // backend will like.
  903. if (Size == 128)
  904. return ABIArgInfo::getDirect(llvm::VectorType::get(
  905. llvm::Type::getInt64Ty(getVMContext()), 2));
  906. // Always return in register if it fits in a general purpose
  907. // register, or if it is 64 bits and has a single element.
  908. if ((Size == 8 || Size == 16 || Size == 32) ||
  909. (Size == 64 && VT->getNumElements() == 1))
  910. return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
  911. Size));
  912. return getIndirectReturnResult(RetTy, State);
  913. }
  914. return ABIArgInfo::getDirect();
  915. }
  916. if (isAggregateTypeForABI(RetTy)) {
  917. if (const RecordType *RT = RetTy->getAs<RecordType>()) {
  918. // Structures with flexible arrays are always indirect.
  919. if (RT->getDecl()->hasFlexibleArrayMember())
  920. return getIndirectReturnResult(RetTy, State);
  921. }
  922. // If specified, structs and unions are always indirect.
  923. if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
  924. return getIndirectReturnResult(RetTy, State);
  925. // Small structures which are register sized are generally returned
  926. // in a register.
  927. if (shouldReturnTypeInRegister(RetTy, getContext())) {
  928. uint64_t Size = getContext().getTypeSize(RetTy);
  929. // As a special-case, if the struct is a "single-element" struct, and
  930. // the field is of type "float" or "double", return it in a
  931. // floating-point register. (MSVC does not apply this special case.)
  932. // We apply a similar transformation for pointer types to improve the
  933. // quality of the generated IR.
  934. if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
  935. if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
  936. || SeltTy->hasPointerRepresentation())
  937. return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
  938. // FIXME: We should be able to narrow this integer in cases with dead
  939. // padding.
  940. return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
  941. }
  942. return getIndirectReturnResult(RetTy, State);
  943. }
  944. // Treat an enum type as its underlying type.
  945. if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
  946. RetTy = EnumTy->getDecl()->getIntegerType();
  947. return (RetTy->isPromotableIntegerType() ?
  948. ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
  949. }
  950. static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
  951. return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
  952. }
  953. static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
  954. const RecordType *RT = Ty->getAs<RecordType>();
  955. if (!RT)
  956. return 0;
  957. const RecordDecl *RD = RT->getDecl();
  958. // If this is a C++ record, check the bases first.
  959. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
  960. for (const auto &I : CXXRD->bases())
  961. if (!isRecordWithSSEVectorType(Context, I.getType()))
  962. return false;
  963. for (const auto *i : RD->fields()) {
  964. QualType FT = i->getType();
  965. if (isSSEVectorType(Context, FT))
  966. return true;
  967. if (isRecordWithSSEVectorType(Context, FT))
  968. return true;
  969. }
  970. return false;
  971. }
  972. unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
  973. unsigned Align) const {
  974. // Otherwise, if the alignment is less than or equal to the minimum ABI
  975. // alignment, just use the default; the backend will handle this.
  976. if (Align <= MinABIStackAlignInBytes)
  977. return 0; // Use default alignment.
  978. // On non-Darwin, the stack type alignment is always 4.
  979. if (!IsDarwinVectorABI) {
  980. // Set explicit alignment, since we may need to realign the top.
  981. return MinABIStackAlignInBytes;
  982. }
  983. // Otherwise, if the type contains an SSE vector type, the alignment is 16.
  984. if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
  985. isRecordWithSSEVectorType(getContext(), Ty)))
  986. return 16;
  987. return MinABIStackAlignInBytes;
  988. }
  989. ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
  990. CCState &State) const {
  991. if (!ByVal) {
  992. if (State.FreeRegs) {
  993. --State.FreeRegs; // Non-byval indirects just use one pointer.
  994. return getNaturalAlignIndirectInReg(Ty);
  995. }
  996. return getNaturalAlignIndirect(Ty, false);
  997. }
  998. // Compute the byval alignment.
  999. unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
  1000. unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
  1001. if (StackAlign == 0)
  1002. return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
  1003. // If the stack alignment is less than the type alignment, realign the
  1004. // argument.
  1005. bool Realign = TypeAlign > StackAlign;
  1006. return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
  1007. /*ByVal=*/true, Realign);
  1008. }
  1009. X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
  1010. const Type *T = isSingleElementStruct(Ty, getContext());
  1011. if (!T)
  1012. T = Ty.getTypePtr();
  1013. if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
  1014. BuiltinType::Kind K = BT->getKind();
  1015. if (K == BuiltinType::Float || K == BuiltinType::Double)
  1016. return Float;
  1017. }
  1018. return Integer;
  1019. }
  1020. bool X86_32ABIInfo::shouldUseInReg(QualType Ty, CCState &State,
  1021. bool &NeedsPadding) const {
  1022. NeedsPadding = false;
  1023. if (!IsSoftFloatABI) {
  1024. Class C = classify(Ty);
  1025. if (C == Float)
  1026. return false;
  1027. }
  1028. unsigned Size = getContext().getTypeSize(Ty);
  1029. unsigned SizeInRegs = (Size + 31) / 32;
  1030. if (SizeInRegs == 0)
  1031. return false;
  1032. if (SizeInRegs > State.FreeRegs) {
  1033. State.FreeRegs = 0;
  1034. return false;
  1035. }
  1036. State.FreeRegs -= SizeInRegs;
  1037. if (State.CC == llvm::CallingConv::X86_FastCall ||
  1038. State.CC == llvm::CallingConv::X86_VectorCall) {
  1039. if (Size > 32)
  1040. return false;
  1041. if (Ty->isIntegralOrEnumerationType())
  1042. return true;
  1043. if (Ty->isPointerType())
  1044. return true;
  1045. if (Ty->isReferenceType())
  1046. return true;
  1047. if (State.FreeRegs)
  1048. NeedsPadding = true;
  1049. return false;
  1050. }
  1051. return true;
  1052. }
  1053. ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
  1054. CCState &State) const {
  1055. // FIXME: Set alignment on indirect arguments.
  1056. Ty = useFirstFieldIfTransparentUnion(Ty);
  1057. // Check with the C++ ABI first.
  1058. const RecordType *RT = Ty->getAs<RecordType>();
  1059. if (RT) {
  1060. CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
  1061. if (RAA == CGCXXABI::RAA_Indirect) {
  1062. return getIndirectResult(Ty, false, State);
  1063. } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
  1064. // The field index doesn't matter, we'll fix it up later.
  1065. return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
  1066. }
  1067. }
  1068. // vectorcall adds the concept of a homogenous vector aggregate, similar
  1069. // to other targets.
  1070. const Type *Base = nullptr;
  1071. uint64_t NumElts = 0;
  1072. if (State.CC == llvm::CallingConv::X86_VectorCall &&
  1073. isHomogeneousAggregate(Ty, Base, NumElts)) {
  1074. if (State.FreeSSERegs >= NumElts) {
  1075. State.FreeSSERegs -= NumElts;
  1076. if (Ty->isBuiltinType() || Ty->isVectorType())
  1077. return ABIArgInfo::getDirect();
  1078. return ABIArgInfo::getExpand();
  1079. }
  1080. return getIndirectResult(Ty, /*ByVal=*/false, State);
  1081. }
  1082. if (isAggregateTypeForABI(Ty)) {
  1083. if (RT) {
  1084. // Structs are always byval on win32, regardless of what they contain.
  1085. if (IsWin32StructABI)
  1086. return getIndirectResult(Ty, true, State);
  1087. // Structures with flexible arrays are always indirect.
  1088. if (RT->getDecl()->hasFlexibleArrayMember())
  1089. return getIndirectResult(Ty, true, State);
  1090. }
  1091. // Ignore empty structs/unions.
  1092. if (isEmptyRecord(getContext(), Ty, true))
  1093. return ABIArgInfo::getIgnore();
  1094. llvm::LLVMContext &LLVMContext = getVMContext();
  1095. llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
  1096. bool NeedsPadding;
  1097. if (shouldUseInReg(Ty, State, NeedsPadding)) {
  1098. unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
  1099. SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
  1100. llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
  1101. return ABIArgInfo::getDirectInReg(Result);
  1102. }
  1103. llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
  1104. // Expand small (<= 128-bit) record types when we know that the stack layout
  1105. // of those arguments will match the struct. This is important because the
  1106. // LLVM backend isn't smart enough to remove byval, which inhibits many
  1107. // optimizations.
  1108. if (getContext().getTypeSize(Ty) <= 4*32 &&
  1109. canExpandIndirectArgument(Ty, getContext()))
  1110. return ABIArgInfo::getExpandWithPadding(
  1111. State.CC == llvm::CallingConv::X86_FastCall ||
  1112. State.CC == llvm::CallingConv::X86_VectorCall,
  1113. PaddingType);
  1114. return getIndirectResult(Ty, true, State);
  1115. }
  1116. if (const VectorType *VT = Ty->getAs<VectorType>()) {
  1117. // On Darwin, some vectors are passed in memory, we handle this by passing
  1118. // it as an i8/i16/i32/i64.
  1119. if (IsDarwinVectorABI) {
  1120. uint64_t Size = getContext().getTypeSize(Ty);
  1121. if ((Size == 8 || Size == 16 || Size == 32) ||
  1122. (Size == 64 && VT->getNumElements() == 1))
  1123. return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
  1124. Size));
  1125. }
  1126. if (IsX86_MMXType(CGT.ConvertType(Ty)))
  1127. return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
  1128. return ABIArgInfo::getDirect();
  1129. }
  1130. if (const EnumType *EnumTy = Ty->getAs<EnumType>())
  1131. Ty = EnumTy->getDecl()->getIntegerType();
  1132. bool NeedsPadding;
  1133. bool InReg = shouldUseInReg(Ty, State, NeedsPadding);
  1134. if (Ty->isPromotableIntegerType()) {
  1135. if (InReg)
  1136. return ABIArgInfo::getExtendInReg();
  1137. return ABIArgInfo::getExtend();
  1138. }
  1139. if (InReg)
  1140. return ABIArgInfo::getDirectInReg();
  1141. return ABIArgInfo::getDirect();
  1142. }
  1143. void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
  1144. CCState State(FI.getCallingConvention());
  1145. if (State.CC == llvm::CallingConv::X86_FastCall)
  1146. State.FreeRegs = 2;
  1147. else if (State.CC == llvm::CallingConv::X86_VectorCall) {
  1148. State.FreeRegs = 2;
  1149. State.FreeSSERegs = 6;
  1150. } else if (FI.getHasRegParm())
  1151. State.FreeRegs = FI.getRegParm();
  1152. else
  1153. State.FreeRegs = DefaultNumRegisterParameters;
  1154. if (!getCXXABI().classifyReturnType(FI)) {
  1155. FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
  1156. } else if (FI.getReturnInfo().isIndirect()) {
  1157. // The C++ ABI is not aware of register usage, so we have to check if the
  1158. // return value was sret and put it in a register ourselves if appropriate.
  1159. if (State.FreeRegs) {
  1160. --State.FreeRegs; // The sret parameter consumes a register.
  1161. FI.getReturnInfo().setInReg(true);
  1162. }
  1163. }
  1164. // The chain argument effectively gives us another free register.
  1165. if (FI.isChainCall())
  1166. ++State.FreeRegs;
  1167. bool UsedInAlloca = false;
  1168. for (auto &I : FI.arguments()) {
  1169. I.info = classifyArgumentType(I.type, State);
  1170. UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
  1171. }
  1172. // If we needed to use inalloca for any argument, do a second pass and rewrite
  1173. // all the memory arguments to use inalloca.
  1174. if (UsedInAlloca)
  1175. rewriteWithInAlloca(FI);
  1176. }
  1177. void
  1178. X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
  1179. CharUnits &StackOffset, ABIArgInfo &Info,
  1180. QualType Type) const {
  1181. // Arguments are always 4-byte-aligned.
  1182. CharUnits FieldAlign = CharUnits::fromQuantity(4);
  1183. assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
  1184. Info = ABIArgInfo::getInAlloca(FrameFields.size());
  1185. FrameFields.push_back(CGT.ConvertTypeForMem(Type));
  1186. StackOffset += getContext().getTypeSizeInChars(Type);
  1187. // Insert padding bytes to respect alignment.
  1188. CharUnits FieldEnd = StackOffset;
  1189. StackOffset = FieldEnd.RoundUpToAlignment(FieldAlign);
  1190. if (StackOffset != FieldEnd) {
  1191. CharUnits NumBytes = StackOffset - FieldEnd;
  1192. llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
  1193. Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
  1194. FrameFields.push_back(Ty);
  1195. }
  1196. }
  1197. static bool isArgInAlloca(const ABIArgInfo &Info) {
  1198. // Leave ignored and inreg arguments alone.
  1199. switch (Info.getKind()) {
  1200. case ABIArgInfo::InAlloca:
  1201. return true;
  1202. case ABIArgInfo::Indirect:
  1203. assert(Info.getIndirectByVal());
  1204. return true;
  1205. case ABIArgInfo::Ignore:
  1206. return false;
  1207. case ABIArgInfo::Direct:
  1208. case ABIArgInfo::Extend:
  1209. case ABIArgInfo::Expand:
  1210. if (Info.getInReg())
  1211. return false;
  1212. return true;
  1213. }
  1214. llvm_unreachable("invalid enum");
  1215. }
  1216. void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
  1217. assert(IsWin32StructABI && "inalloca only supported on win32");
  1218. // Build a packed struct type for all of the arguments in memory.
  1219. SmallVector<llvm::Type *, 6> FrameFields;
  1220. // The stack alignment is always 4.
  1221. CharUnits StackAlign = CharUnits::fromQuantity(4);
  1222. CharUnits StackOffset;
  1223. CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
  1224. // Put 'this' into the struct before 'sret', if necessary.
  1225. bool IsThisCall =
  1226. FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
  1227. ABIArgInfo &Ret = FI.getReturnInfo();
  1228. if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
  1229. isArgInAlloca(I->info)) {
  1230. addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
  1231. ++I;
  1232. }
  1233. // Put the sret parameter into the inalloca struct if it's in memory.
  1234. if (Ret.isIndirect() && !Ret.getInReg()) {
  1235. CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
  1236. addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
  1237. // On Windows, the hidden sret parameter is always returned in eax.
  1238. Ret.setInAllocaSRet(IsWin32StructABI);
  1239. }
  1240. // Skip the 'this' parameter in ecx.
  1241. if (IsThisCall)
  1242. ++I;
  1243. // Put arguments passed in memory into the struct.
  1244. for (; I != E; ++I) {
  1245. if (isArgInAlloca(I->info))
  1246. addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
  1247. }
  1248. FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
  1249. /*isPacked=*/true),
  1250. StackAlign);
  1251. }
  1252. Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
  1253. Address VAListAddr, QualType Ty) const {
  1254. auto TypeInfo = getContext().getTypeInfoInChars(Ty);
  1255. // x86-32 changes the alignment of certain arguments on the stack.
  1256. //
  1257. // Just messing with TypeInfo like this works because we never pass
  1258. // anything indirectly.
  1259. TypeInfo.second = CharUnits::fromQuantity(
  1260. getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
  1261. return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
  1262. TypeInfo, CharUnits::fromQuantity(4),
  1263. /*AllowHigherAlign*/ true);
  1264. }
  1265. bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
  1266. const llvm::Triple &Triple, const CodeGenOptions &Opts) {
  1267. assert(Triple.getArch() == llvm::Triple::x86);
  1268. switch (Opts.getStructReturnConvention()) {
  1269. case CodeGenOptions::SRCK_Default:
  1270. break;
  1271. case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
  1272. return false;
  1273. case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
  1274. return true;
  1275. }
  1276. if (Triple.isOSDarwin())
  1277. return true;
  1278. switch (Triple.getOS()) {
  1279. case llvm::Triple::DragonFly:
  1280. case llvm::Triple::FreeBSD:
  1281. case llvm::Triple::OpenBSD:
  1282. case llvm::Triple::Bitrig:
  1283. case llvm::Triple::Win32:
  1284. return true;
  1285. default:
  1286. return false;
  1287. }
  1288. }
  1289. void X86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
  1290. llvm::GlobalValue *GV,
  1291. CodeGen::CodeGenModule &CGM) const {
  1292. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
  1293. if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
  1294. // Get the LLVM function.
  1295. llvm::Function *Fn = cast<llvm::Function>(GV);
  1296. // Now add the 'alignstack' attribute with a value of 16.
  1297. llvm::AttrBuilder B;
  1298. B.addStackAlignmentAttr(16);
  1299. Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
  1300. llvm::AttributeSet::get(CGM.getLLVMContext(),
  1301. llvm::AttributeSet::FunctionIndex,
  1302. B));
  1303. }
  1304. }
  1305. }
  1306. bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
  1307. CodeGen::CodeGenFunction &CGF,
  1308. llvm::Value *Address) const {
  1309. CodeGen::CGBuilderTy &Builder = CGF.Builder;
  1310. llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
  1311. // 0-7 are the eight integer registers; the order is different
  1312. // on Darwin (for EH), but the range is the same.
  1313. // 8 is %eip.
  1314. AssignToArrayRange(Builder, Address, Four8, 0, 8);
  1315. if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
  1316. // 12-16 are st(0..4). Not sure why we stop at 4.
  1317. // These have size 16, which is sizeof(long double) on
  1318. // platforms with 8-byte alignment for that type.
  1319. llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
  1320. AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
  1321. } else {
  1322. // 9 is %eflags, which doesn't get a size on Darwin for some
  1323. // reason.
  1324. Builder.CreateAlignedStore(
  1325. Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
  1326. CharUnits::One());
  1327. // 11-16 are st(0..5). Not sure why we stop at 5.
  1328. // These have size 12, which is sizeof(long double) on
  1329. // platforms with 4-byte alignment for that type.
  1330. llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
  1331. AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
  1332. }
  1333. return false;
  1334. }
  1335. //===----------------------------------------------------------------------===//
  1336. // X86-64 ABI Implementation
  1337. //===----------------------------------------------------------------------===//
  1338. namespace {
  1339. /// The AVX ABI level for X86 targets.
  1340. enum class X86AVXABILevel {
  1341. None,
  1342. AVX,
  1343. AVX512
  1344. };
  1345. /// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
  1346. static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
  1347. switch (AVXLevel) {
  1348. case X86AVXABILevel::AVX512:
  1349. return 512;
  1350. case X86AVXABILevel::AVX:
  1351. return 256;
  1352. case X86AVXABILevel::None:
  1353. return 128;
  1354. }
  1355. llvm_unreachable("Unknown AVXLevel");
  1356. }
  1357. /// X86_64ABIInfo - The X86_64 ABI information.
  1358. class X86_64ABIInfo : public ABIInfo {
  1359. enum Class {
  1360. Integer = 0,
  1361. SSE,
  1362. SSEUp,
  1363. X87,
  1364. X87Up,
  1365. ComplexX87,
  1366. NoClass,
  1367. Memory
  1368. };
  1369. /// merge - Implement the X86_64 ABI merging algorithm.
  1370. ///
  1371. /// Merge an accumulating classification \arg Accum with a field
  1372. /// classification \arg Field.
  1373. ///
  1374. /// \param Accum - The accumulating classification. This should
  1375. /// always be either NoClass or the result of a previous merge
  1376. /// call. In addition, this should never be Memory (the caller
  1377. /// should just return Memory for the aggregate).
  1378. static Class merge(Class Accum, Class Field);
  1379. /// postMerge - Implement the X86_64 ABI post merging algorithm.
  1380. ///
  1381. /// Post merger cleanup, reduces a malformed Hi and Lo pair to
  1382. /// final MEMORY or SSE classes when necessary.
  1383. ///
  1384. /// \param AggregateSize - The size of the current aggregate in
  1385. /// the classification process.
  1386. ///
  1387. /// \param Lo - The classification for the parts of the type
  1388. /// residing in the low word of the containing object.
  1389. ///
  1390. /// \param Hi - The classification for the parts of the type
  1391. /// residing in the higher words of the containing object.
  1392. ///
  1393. void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
  1394. /// classify - Determine the x86_64 register classes in which the
  1395. /// given type T should be passed.
  1396. ///
  1397. /// \param Lo - The classification for the parts of the type
  1398. /// residing in the low word of the containing object.
  1399. ///
  1400. /// \param Hi - The classification for the parts of the type
  1401. /// residing in the high word of the containing object.
  1402. ///
  1403. /// \param OffsetBase - The bit offset of this type in the
  1404. /// containing object. Some parameters are classified different
  1405. /// depending on whether they straddle an eightbyte boundary.
  1406. ///
  1407. /// \param isNamedArg - Whether the argument in question is a "named"
  1408. /// argument, as used in AMD64-ABI 3.5.7.
  1409. ///
  1410. /// If a word is unused its result will be NoClass; if a type should
  1411. /// be passed in Memory then at least the classification of \arg Lo
  1412. /// will be Memory.
  1413. ///
  1414. /// The \arg Lo class will be NoClass iff the argument is ignored.
  1415. ///
  1416. /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
  1417. /// also be ComplexX87.
  1418. void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
  1419. bool isNamedArg) const;
  1420. llvm::Type *GetByteVectorType(QualType Ty) const;
  1421. llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
  1422. unsigned IROffset, QualType SourceTy,
  1423. unsigned SourceOffset) const;
  1424. llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
  1425. unsigned IROffset, QualType SourceTy,
  1426. unsigned SourceOffset) const;
  1427. /// getIndirectResult - Give a source type \arg Ty, return a suitable result
  1428. /// such that the argument will be returned in memory.
  1429. ABIArgInfo getIndirectReturnResult(QualType Ty) const;
  1430. /// getIndirectResult - Give a source type \arg Ty, return a suitable result
  1431. /// such that the argument will be passed in memory.
  1432. ///
  1433. /// \param freeIntRegs - The number of free integer registers remaining
  1434. /// available.
  1435. ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
  1436. ABIArgInfo classifyReturnType(QualType RetTy) const;
  1437. ABIArgInfo classifyArgumentType(QualType Ty,
  1438. unsigned freeIntRegs,
  1439. unsigned &neededInt,
  1440. unsigned &neededSSE,
  1441. bool isNamedArg) const;
  1442. bool IsIllegalVectorType(QualType Ty) const;
  1443. /// The 0.98 ABI revision clarified a lot of ambiguities,
  1444. /// unfortunately in ways that were not always consistent with
  1445. /// certain previous compilers. In particular, platforms which
  1446. /// required strict binary compatibility with older versions of GCC
  1447. /// may need to exempt themselves.
  1448. bool honorsRevision0_98() const {
  1449. return !getTarget().getTriple().isOSDarwin();
  1450. }
  1451. X86AVXABILevel AVXLevel;
  1452. // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
  1453. // 64-bit hardware.
  1454. bool Has64BitPointers;
  1455. public:
  1456. X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
  1457. ABIInfo(CGT), AVXLevel(AVXLevel),
  1458. Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
  1459. }
  1460. bool isPassedUsingAVXType(QualType type) const {
  1461. unsigned neededInt, neededSSE;
  1462. // The freeIntRegs argument doesn't matter here.
  1463. ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
  1464. /*isNamedArg*/true);
  1465. if (info.isDirect()) {
  1466. llvm::Type *ty = info.getCoerceToType();
  1467. if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
  1468. return (vectorTy->getBitWidth() > 128);
  1469. }
  1470. return false;
  1471. }
  1472. void computeInfo(CGFunctionInfo &FI) const override;
  1473. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  1474. QualType Ty) const override;
  1475. Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
  1476. QualType Ty) const override;
  1477. bool has64BitPointers() const {
  1478. return Has64BitPointers;
  1479. }
  1480. };
  1481. /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
  1482. class WinX86_64ABIInfo : public ABIInfo {
  1483. ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
  1484. bool IsReturnType) const;
  1485. public:
  1486. WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
  1487. void computeInfo(CGFunctionInfo &FI) const override;
  1488. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  1489. QualType Ty) const override;
  1490. bool isHomogeneousAggregateBaseType(QualType Ty) const override {
  1491. // FIXME: Assumes vectorcall is in use.
  1492. return isX86VectorTypeForVectorCall(getContext(), Ty);
  1493. }
  1494. bool isHomogeneousAggregateSmallEnough(const Type *Ty,
  1495. uint64_t NumMembers) const override {
  1496. // FIXME: Assumes vectorcall is in use.
  1497. return isX86VectorCallAggregateSmallEnough(NumMembers);
  1498. }
  1499. };
  1500. class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
  1501. public:
  1502. X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
  1503. : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
  1504. const X86_64ABIInfo &getABIInfo() const {
  1505. return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
  1506. }
  1507. int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
  1508. return 7;
  1509. }
  1510. bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
  1511. llvm::Value *Address) const override {
  1512. llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
  1513. // 0-15 are the 16 integer registers.
  1514. // 16 is %rip.
  1515. AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
  1516. return false;
  1517. }
  1518. llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
  1519. StringRef Constraint,
  1520. llvm::Type* Ty) const override {
  1521. return X86AdjustInlineAsmType(CGF, Constraint, Ty);
  1522. }
  1523. bool isNoProtoCallVariadic(const CallArgList &args,
  1524. const FunctionNoProtoType *fnType) const override {
  1525. // The default CC on x86-64 sets %al to the number of SSA
  1526. // registers used, and GCC sets this when calling an unprototyped
  1527. // function, so we override the default behavior. However, don't do
  1528. // that when AVX types are involved: the ABI explicitly states it is
  1529. // undefined, and it doesn't work in practice because of how the ABI
  1530. // defines varargs anyway.
  1531. if (fnType->getCallConv() == CC_C) {
  1532. bool HasAVXType = false;
  1533. for (CallArgList::const_iterator
  1534. it = args.begin(), ie = args.end(); it != ie; ++it) {
  1535. if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
  1536. HasAVXType = true;
  1537. break;
  1538. }
  1539. }
  1540. if (!HasAVXType)
  1541. return true;
  1542. }
  1543. return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
  1544. }
  1545. llvm::Constant *
  1546. getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
  1547. unsigned Sig;
  1548. if (getABIInfo().has64BitPointers())
  1549. Sig = (0xeb << 0) | // jmp rel8
  1550. (0x0a << 8) | // .+0x0c
  1551. ('F' << 16) |
  1552. ('T' << 24);
  1553. else
  1554. Sig = (0xeb << 0) | // jmp rel8
  1555. (0x06 << 8) | // .+0x08
  1556. ('F' << 16) |
  1557. ('T' << 24);
  1558. return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
  1559. }
  1560. };
  1561. class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
  1562. public:
  1563. PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
  1564. : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
  1565. void getDependentLibraryOption(llvm::StringRef Lib,
  1566. llvm::SmallString<24> &Opt) const override {
  1567. Opt = "\01";
  1568. // If the argument contains a space, enclose it in quotes.
  1569. if (Lib.find(" ") != StringRef::npos)
  1570. Opt += "\"" + Lib.str() + "\"";
  1571. else
  1572. Opt += Lib;
  1573. }
  1574. };
  1575. static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
  1576. // If the argument does not end in .lib, automatically add the suffix.
  1577. // If the argument contains a space, enclose it in quotes.
  1578. // This matches the behavior of MSVC.
  1579. bool Quote = (Lib.find(" ") != StringRef::npos);
  1580. std::string ArgStr = Quote ? "\"" : "";
  1581. ArgStr += Lib;
  1582. if (!Lib.endswith_lower(".lib"))
  1583. ArgStr += ".lib";
  1584. ArgStr += Quote ? "\"" : "";
  1585. return ArgStr;
  1586. }
  1587. class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
  1588. public:
  1589. WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
  1590. bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
  1591. unsigned NumRegisterParameters)
  1592. : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
  1593. Win32StructABI, NumRegisterParameters, false) {}
  1594. void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
  1595. CodeGen::CodeGenModule &CGM) const override;
  1596. void getDependentLibraryOption(llvm::StringRef Lib,
  1597. llvm::SmallString<24> &Opt) const override {
  1598. Opt = "/DEFAULTLIB:";
  1599. Opt += qualifyWindowsLibrary(Lib);
  1600. }
  1601. void getDetectMismatchOption(llvm::StringRef Name,
  1602. llvm::StringRef Value,
  1603. llvm::SmallString<32> &Opt) const override {
  1604. Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
  1605. }
  1606. };
  1607. static void addStackProbeSizeTargetAttribute(const Decl *D,
  1608. llvm::GlobalValue *GV,
  1609. CodeGen::CodeGenModule &CGM) {
  1610. if (D && isa<FunctionDecl>(D)) {
  1611. if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
  1612. llvm::Function *Fn = cast<llvm::Function>(GV);
  1613. Fn->addFnAttr("stack-probe-size",
  1614. llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
  1615. }
  1616. }
  1617. }
  1618. void WinX86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
  1619. llvm::GlobalValue *GV,
  1620. CodeGen::CodeGenModule &CGM) const {
  1621. X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
  1622. addStackProbeSizeTargetAttribute(D, GV, CGM);
  1623. }
  1624. class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
  1625. public:
  1626. WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
  1627. X86AVXABILevel AVXLevel)
  1628. : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
  1629. void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
  1630. CodeGen::CodeGenModule &CGM) const override;
  1631. int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
  1632. return 7;
  1633. }
  1634. bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
  1635. llvm::Value *Address) const override {
  1636. llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
  1637. // 0-15 are the 16 integer registers.
  1638. // 16 is %rip.
  1639. AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
  1640. return false;
  1641. }
  1642. void getDependentLibraryOption(llvm::StringRef Lib,
  1643. llvm::SmallString<24> &Opt) const override {
  1644. Opt = "/DEFAULTLIB:";
  1645. Opt += qualifyWindowsLibrary(Lib);
  1646. }
  1647. void getDetectMismatchOption(llvm::StringRef Name,
  1648. llvm::StringRef Value,
  1649. llvm::SmallString<32> &Opt) const override {
  1650. Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
  1651. }
  1652. };
  1653. void WinX86_64TargetCodeGenInfo::setTargetAttributes(const Decl *D,
  1654. llvm::GlobalValue *GV,
  1655. CodeGen::CodeGenModule &CGM) const {
  1656. TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
  1657. addStackProbeSizeTargetAttribute(D, GV, CGM);
  1658. }
  1659. }
  1660. void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
  1661. Class &Hi) const {
  1662. // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
  1663. //
  1664. // (a) If one of the classes is Memory, the whole argument is passed in
  1665. // memory.
  1666. //
  1667. // (b) If X87UP is not preceded by X87, the whole argument is passed in
  1668. // memory.
  1669. //
  1670. // (c) If the size of the aggregate exceeds two eightbytes and the first
  1671. // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
  1672. // argument is passed in memory. NOTE: This is necessary to keep the
  1673. // ABI working for processors that don't support the __m256 type.
  1674. //
  1675. // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
  1676. //
  1677. // Some of these are enforced by the merging logic. Others can arise
  1678. // only with unions; for example:
  1679. // union { _Complex double; unsigned; }
  1680. //
  1681. // Note that clauses (b) and (c) were added in 0.98.
  1682. //
  1683. if (Hi == Memory)
  1684. Lo = Memory;
  1685. if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
  1686. Lo = Memory;
  1687. if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
  1688. Lo = Memory;
  1689. if (Hi == SSEUp && Lo != SSE)
  1690. Hi = SSE;
  1691. }
  1692. X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
  1693. // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
  1694. // classified recursively so that always two fields are
  1695. // considered. The resulting class is calculated according to
  1696. // the classes of the fields in the eightbyte:
  1697. //
  1698. // (a) If both classes are equal, this is the resulting class.
  1699. //
  1700. // (b) If one of the classes is NO_CLASS, the resulting class is
  1701. // the other class.
  1702. //
  1703. // (c) If one of the classes is MEMORY, the result is the MEMORY
  1704. // class.
  1705. //
  1706. // (d) If one of the classes is INTEGER, the result is the
  1707. // INTEGER.
  1708. //
  1709. // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
  1710. // MEMORY is used as class.
  1711. //
  1712. // (f) Otherwise class SSE is used.
  1713. // Accum should never be memory (we should have returned) or
  1714. // ComplexX87 (because this cannot be passed in a structure).
  1715. assert((Accum != Memory && Accum != ComplexX87) &&
  1716. "Invalid accumulated classification during merge.");
  1717. if (Accum == Field || Field == NoClass)
  1718. return Accum;
  1719. if (Field == Memory)
  1720. return Memory;
  1721. if (Accum == NoClass)
  1722. return Field;
  1723. if (Accum == Integer || Field == Integer)
  1724. return Integer;
  1725. if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
  1726. Accum == X87 || Accum == X87Up)
  1727. return Memory;
  1728. return SSE;
  1729. }
  1730. void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
  1731. Class &Lo, Class &Hi, bool isNamedArg) const {
  1732. // FIXME: This code can be simplified by introducing a simple value class for
  1733. // Class pairs with appropriate constructor methods for the various
  1734. // situations.
  1735. // FIXME: Some of the split computations are wrong; unaligned vectors
  1736. // shouldn't be passed in registers for example, so there is no chance they
  1737. // can straddle an eightbyte. Verify & simplify.
  1738. Lo = Hi = NoClass;
  1739. Class &Current = OffsetBase < 64 ? Lo : Hi;
  1740. Current = Memory;
  1741. if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
  1742. BuiltinType::Kind k = BT->getKind();
  1743. if (k == BuiltinType::Void) {
  1744. Current = NoClass;
  1745. } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
  1746. Lo = Integer;
  1747. Hi = Integer;
  1748. } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
  1749. Current = Integer;
  1750. } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
  1751. Current = SSE;
  1752. } else if (k == BuiltinType::LongDouble) {
  1753. const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
  1754. if (LDF == &llvm::APFloat::IEEEquad) {
  1755. Lo = SSE;
  1756. Hi = SSEUp;
  1757. } else if (LDF == &llvm::APFloat::x87DoubleExtended) {
  1758. Lo = X87;
  1759. Hi = X87Up;
  1760. } else if (LDF == &llvm::APFloat::IEEEdouble) {
  1761. Current = SSE;
  1762. } else
  1763. llvm_unreachable("unexpected long double representation!");
  1764. }
  1765. // FIXME: _Decimal32 and _Decimal64 are SSE.
  1766. // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
  1767. return;
  1768. }
  1769. if (const EnumType *ET = Ty->getAs<EnumType>()) {
  1770. // Classify the underlying integer type.
  1771. classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
  1772. return;
  1773. }
  1774. if (Ty->hasPointerRepresentation()) {
  1775. Current = Integer;
  1776. return;
  1777. }
  1778. if (Ty->isMemberPointerType()) {
  1779. if (Ty->isMemberFunctionPointerType()) {
  1780. if (Has64BitPointers) {
  1781. // If Has64BitPointers, this is an {i64, i64}, so classify both
  1782. // Lo and Hi now.
  1783. Lo = Hi = Integer;
  1784. } else {
  1785. // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
  1786. // straddles an eightbyte boundary, Hi should be classified as well.
  1787. uint64_t EB_FuncPtr = (OffsetBase) / 64;
  1788. uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
  1789. if (EB_FuncPtr != EB_ThisAdj) {
  1790. Lo = Hi = Integer;
  1791. } else {
  1792. Current = Integer;
  1793. }
  1794. }
  1795. } else {
  1796. Current = Integer;
  1797. }
  1798. return;
  1799. }
  1800. if (const VectorType *VT = Ty->getAs<VectorType>()) {
  1801. uint64_t Size = getContext().getTypeSize(VT);
  1802. if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
  1803. // gcc passes the following as integer:
  1804. // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
  1805. // 2 bytes - <2 x char>, <1 x short>
  1806. // 1 byte - <1 x char>
  1807. Current = Integer;
  1808. // If this type crosses an eightbyte boundary, it should be
  1809. // split.
  1810. uint64_t EB_Lo = (OffsetBase) / 64;
  1811. uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
  1812. if (EB_Lo != EB_Hi)
  1813. Hi = Lo;
  1814. } else if (Size == 64) {
  1815. // gcc passes <1 x double> in memory. :(
  1816. if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
  1817. return;
  1818. // gcc passes <1 x long long> as INTEGER.
  1819. if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
  1820. VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
  1821. VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
  1822. VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
  1823. Current = Integer;
  1824. else
  1825. Current = SSE;
  1826. // If this type crosses an eightbyte boundary, it should be
  1827. // split.
  1828. if (OffsetBase && OffsetBase != 64)
  1829. Hi = Lo;
  1830. } else if (Size == 128 ||
  1831. (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
  1832. // Arguments of 256-bits are split into four eightbyte chunks. The
  1833. // least significant one belongs to class SSE and all the others to class
  1834. // SSEUP. The original Lo and Hi design considers that types can't be
  1835. // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
  1836. // This design isn't correct for 256-bits, but since there're no cases
  1837. // where the upper parts would need to be inspected, avoid adding
  1838. // complexity and just consider Hi to match the 64-256 part.
  1839. //
  1840. // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
  1841. // registers if they are "named", i.e. not part of the "..." of a
  1842. // variadic function.
  1843. //
  1844. // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
  1845. // split into eight eightbyte chunks, one SSE and seven SSEUP.
  1846. Lo = SSE;
  1847. Hi = SSEUp;
  1848. }
  1849. return;
  1850. }
  1851. if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
  1852. QualType ET = getContext().getCanonicalType(CT->getElementType());
  1853. uint64_t Size = getContext().getTypeSize(Ty);
  1854. if (ET->isIntegralOrEnumerationType()) {
  1855. if (Size <= 64)
  1856. Current = Integer;
  1857. else if (Size <= 128)
  1858. Lo = Hi = Integer;
  1859. } else if (ET == getContext().FloatTy) {
  1860. Current = SSE;
  1861. } else if (ET == getContext().DoubleTy) {
  1862. Lo = Hi = SSE;
  1863. } else if (ET == getContext().LongDoubleTy) {
  1864. const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
  1865. if (LDF == &llvm::APFloat::IEEEquad)
  1866. Current = Memory;
  1867. else if (LDF == &llvm::APFloat::x87DoubleExtended)
  1868. Current = ComplexX87;
  1869. else if (LDF == &llvm::APFloat::IEEEdouble)
  1870. Lo = Hi = SSE;
  1871. else
  1872. llvm_unreachable("unexpected long double representation!");
  1873. }
  1874. // If this complex type crosses an eightbyte boundary then it
  1875. // should be split.
  1876. uint64_t EB_Real = (OffsetBase) / 64;
  1877. uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
  1878. if (Hi == NoClass && EB_Real != EB_Imag)
  1879. Hi = Lo;
  1880. return;
  1881. }
  1882. if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
  1883. // Arrays are treated like structures.
  1884. uint64_t Size = getContext().getTypeSize(Ty);
  1885. // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
  1886. // than four eightbytes, ..., it has class MEMORY.
  1887. if (Size > 256)
  1888. return;
  1889. // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
  1890. // fields, it has class MEMORY.
  1891. //
  1892. // Only need to check alignment of array base.
  1893. if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
  1894. return;
  1895. // Otherwise implement simplified merge. We could be smarter about
  1896. // this, but it isn't worth it and would be harder to verify.
  1897. Current = NoClass;
  1898. uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
  1899. uint64_t ArraySize = AT->getSize().getZExtValue();
  1900. // The only case a 256-bit wide vector could be used is when the array
  1901. // contains a single 256-bit element. Since Lo and Hi logic isn't extended
  1902. // to work for sizes wider than 128, early check and fallback to memory.
  1903. if (Size > 128 && EltSize != 256)
  1904. return;
  1905. for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
  1906. Class FieldLo, FieldHi;
  1907. classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
  1908. Lo = merge(Lo, FieldLo);
  1909. Hi = merge(Hi, FieldHi);
  1910. if (Lo == Memory || Hi == Memory)
  1911. break;
  1912. }
  1913. postMerge(Size, Lo, Hi);
  1914. assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
  1915. return;
  1916. }
  1917. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  1918. uint64_t Size = getContext().getTypeSize(Ty);
  1919. // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
  1920. // than four eightbytes, ..., it has class MEMORY.
  1921. if (Size > 256)
  1922. return;
  1923. // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
  1924. // copy constructor or a non-trivial destructor, it is passed by invisible
  1925. // reference.
  1926. if (getRecordArgABI(RT, getCXXABI()))
  1927. return;
  1928. const RecordDecl *RD = RT->getDecl();
  1929. // Assume variable sized types are passed in memory.
  1930. if (RD->hasFlexibleArrayMember())
  1931. return;
  1932. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
  1933. // Reset Lo class, this will be recomputed.
  1934. Current = NoClass;
  1935. // If this is a C++ record, classify the bases first.
  1936. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  1937. for (const auto &I : CXXRD->bases()) {
  1938. assert(!I.isVirtual() && !I.getType()->isDependentType() &&
  1939. "Unexpected base class!");
  1940. const CXXRecordDecl *Base =
  1941. cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
  1942. // Classify this field.
  1943. //
  1944. // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
  1945. // single eightbyte, each is classified separately. Each eightbyte gets
  1946. // initialized to class NO_CLASS.
  1947. Class FieldLo, FieldHi;
  1948. uint64_t Offset =
  1949. OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
  1950. classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
  1951. Lo = merge(Lo, FieldLo);
  1952. Hi = merge(Hi, FieldHi);
  1953. if (Lo == Memory || Hi == Memory) {
  1954. postMerge(Size, Lo, Hi);
  1955. return;
  1956. }
  1957. }
  1958. }
  1959. // Classify the fields one at a time, merging the results.
  1960. unsigned idx = 0;
  1961. for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
  1962. i != e; ++i, ++idx) {
  1963. uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
  1964. bool BitField = i->isBitField();
  1965. // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
  1966. // four eightbytes, or it contains unaligned fields, it has class MEMORY.
  1967. //
  1968. // The only case a 256-bit wide vector could be used is when the struct
  1969. // contains a single 256-bit element. Since Lo and Hi logic isn't extended
  1970. // to work for sizes wider than 128, early check and fallback to memory.
  1971. //
  1972. if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
  1973. Lo = Memory;
  1974. postMerge(Size, Lo, Hi);
  1975. return;
  1976. }
  1977. // Note, skip this test for bit-fields, see below.
  1978. if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
  1979. Lo = Memory;
  1980. postMerge(Size, Lo, Hi);
  1981. return;
  1982. }
  1983. // Classify this field.
  1984. //
  1985. // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
  1986. // exceeds a single eightbyte, each is classified
  1987. // separately. Each eightbyte gets initialized to class
  1988. // NO_CLASS.
  1989. Class FieldLo, FieldHi;
  1990. // Bit-fields require special handling, they do not force the
  1991. // structure to be passed in memory even if unaligned, and
  1992. // therefore they can straddle an eightbyte.
  1993. if (BitField) {
  1994. // Ignore padding bit-fields.
  1995. if (i->isUnnamedBitfield())
  1996. continue;
  1997. uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
  1998. uint64_t Size = i->getBitWidthValue(getContext());
  1999. uint64_t EB_Lo = Offset / 64;
  2000. uint64_t EB_Hi = (Offset + Size - 1) / 64;
  2001. if (EB_Lo) {
  2002. assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
  2003. FieldLo = NoClass;
  2004. FieldHi = Integer;
  2005. } else {
  2006. FieldLo = Integer;
  2007. FieldHi = EB_Hi ? Integer : NoClass;
  2008. }
  2009. } else
  2010. classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
  2011. Lo = merge(Lo, FieldLo);
  2012. Hi = merge(Hi, FieldHi);
  2013. if (Lo == Memory || Hi == Memory)
  2014. break;
  2015. }
  2016. postMerge(Size, Lo, Hi);
  2017. }
  2018. }
  2019. ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
  2020. // If this is a scalar LLVM value then assume LLVM will pass it in the right
  2021. // place naturally.
  2022. if (!isAggregateTypeForABI(Ty)) {
  2023. // Treat an enum type as its underlying type.
  2024. if (const EnumType *EnumTy = Ty->getAs<EnumType>())
  2025. Ty = EnumTy->getDecl()->getIntegerType();
  2026. return (Ty->isPromotableIntegerType() ?
  2027. ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
  2028. }
  2029. return getNaturalAlignIndirect(Ty);
  2030. }
  2031. bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
  2032. if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
  2033. uint64_t Size = getContext().getTypeSize(VecTy);
  2034. unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
  2035. if (Size <= 64 || Size > LargestVector)
  2036. return true;
  2037. }
  2038. return false;
  2039. }
  2040. ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
  2041. unsigned freeIntRegs) const {
  2042. // If this is a scalar LLVM value then assume LLVM will pass it in the right
  2043. // place naturally.
  2044. //
  2045. // This assumption is optimistic, as there could be free registers available
  2046. // when we need to pass this argument in memory, and LLVM could try to pass
  2047. // the argument in the free register. This does not seem to happen currently,
  2048. // but this code would be much safer if we could mark the argument with
  2049. // 'onstack'. See PR12193.
  2050. if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
  2051. // Treat an enum type as its underlying type.
  2052. if (const EnumType *EnumTy = Ty->getAs<EnumType>())
  2053. Ty = EnumTy->getDecl()->getIntegerType();
  2054. return (Ty->isPromotableIntegerType() ?
  2055. ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
  2056. }
  2057. if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
  2058. return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
  2059. // Compute the byval alignment. We specify the alignment of the byval in all
  2060. // cases so that the mid-level optimizer knows the alignment of the byval.
  2061. unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
  2062. // Attempt to avoid passing indirect results using byval when possible. This
  2063. // is important for good codegen.
  2064. //
  2065. // We do this by coercing the value into a scalar type which the backend can
  2066. // handle naturally (i.e., without using byval).
  2067. //
  2068. // For simplicity, we currently only do this when we have exhausted all of the
  2069. // free integer registers. Doing this when there are free integer registers
  2070. // would require more care, as we would have to ensure that the coerced value
  2071. // did not claim the unused register. That would require either reording the
  2072. // arguments to the function (so that any subsequent inreg values came first),
  2073. // or only doing this optimization when there were no following arguments that
  2074. // might be inreg.
  2075. //
  2076. // We currently expect it to be rare (particularly in well written code) for
  2077. // arguments to be passed on the stack when there are still free integer
  2078. // registers available (this would typically imply large structs being passed
  2079. // by value), so this seems like a fair tradeoff for now.
  2080. //
  2081. // We can revisit this if the backend grows support for 'onstack' parameter
  2082. // attributes. See PR12193.
  2083. if (freeIntRegs == 0) {
  2084. uint64_t Size = getContext().getTypeSize(Ty);
  2085. // If this type fits in an eightbyte, coerce it into the matching integral
  2086. // type, which will end up on the stack (with alignment 8).
  2087. if (Align == 8 && Size <= 64)
  2088. return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
  2089. Size));
  2090. }
  2091. return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
  2092. }
  2093. /// The ABI specifies that a value should be passed in a full vector XMM/YMM
  2094. /// register. Pick an LLVM IR type that will be passed as a vector register.
  2095. llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
  2096. // Wrapper structs/arrays that only contain vectors are passed just like
  2097. // vectors; strip them off if present.
  2098. if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
  2099. Ty = QualType(InnerTy, 0);
  2100. llvm::Type *IRType = CGT.ConvertType(Ty);
  2101. if (isa<llvm::VectorType>(IRType) ||
  2102. IRType->getTypeID() == llvm::Type::FP128TyID)
  2103. return IRType;
  2104. // We couldn't find the preferred IR vector type for 'Ty'.
  2105. uint64_t Size = getContext().getTypeSize(Ty);
  2106. assert((Size == 128 || Size == 256) && "Invalid type found!");
  2107. // Return a LLVM IR vector type based on the size of 'Ty'.
  2108. return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
  2109. Size / 64);
  2110. }
  2111. /// BitsContainNoUserData - Return true if the specified [start,end) bit range
  2112. /// is known to either be off the end of the specified type or being in
  2113. /// alignment padding. The user type specified is known to be at most 128 bits
  2114. /// in size, and have passed through X86_64ABIInfo::classify with a successful
  2115. /// classification that put one of the two halves in the INTEGER class.
  2116. ///
  2117. /// It is conservatively correct to return false.
  2118. static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
  2119. unsigned EndBit, ASTContext &Context) {
  2120. // If the bytes being queried are off the end of the type, there is no user
  2121. // data hiding here. This handles analysis of builtins, vectors and other
  2122. // types that don't contain interesting padding.
  2123. unsigned TySize = (unsigned)Context.getTypeSize(Ty);
  2124. if (TySize <= StartBit)
  2125. return true;
  2126. if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
  2127. unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
  2128. unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
  2129. // Check each element to see if the element overlaps with the queried range.
  2130. for (unsigned i = 0; i != NumElts; ++i) {
  2131. // If the element is after the span we care about, then we're done..
  2132. unsigned EltOffset = i*EltSize;
  2133. if (EltOffset >= EndBit) break;
  2134. unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
  2135. if (!BitsContainNoUserData(AT->getElementType(), EltStart,
  2136. EndBit-EltOffset, Context))
  2137. return false;
  2138. }
  2139. // If it overlaps no elements, then it is safe to process as padding.
  2140. return true;
  2141. }
  2142. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  2143. const RecordDecl *RD = RT->getDecl();
  2144. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  2145. // If this is a C++ record, check the bases first.
  2146. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  2147. for (const auto &I : CXXRD->bases()) {
  2148. assert(!I.isVirtual() && !I.getType()->isDependentType() &&
  2149. "Unexpected base class!");
  2150. const CXXRecordDecl *Base =
  2151. cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
  2152. // If the base is after the span we care about, ignore it.
  2153. unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
  2154. if (BaseOffset >= EndBit) continue;
  2155. unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
  2156. if (!BitsContainNoUserData(I.getType(), BaseStart,
  2157. EndBit-BaseOffset, Context))
  2158. return false;
  2159. }
  2160. }
  2161. // Verify that no field has data that overlaps the region of interest. Yes
  2162. // this could be sped up a lot by being smarter about queried fields,
  2163. // however we're only looking at structs up to 16 bytes, so we don't care
  2164. // much.
  2165. unsigned idx = 0;
  2166. for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
  2167. i != e; ++i, ++idx) {
  2168. unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
  2169. // If we found a field after the region we care about, then we're done.
  2170. if (FieldOffset >= EndBit) break;
  2171. unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
  2172. if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
  2173. Context))
  2174. return false;
  2175. }
  2176. // If nothing in this record overlapped the area of interest, then we're
  2177. // clean.
  2178. return true;
  2179. }
  2180. return false;
  2181. }
  2182. /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
  2183. /// float member at the specified offset. For example, {int,{float}} has a
  2184. /// float at offset 4. It is conservatively correct for this routine to return
  2185. /// false.
  2186. static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
  2187. const llvm::DataLayout &TD) {
  2188. // Base case if we find a float.
  2189. if (IROffset == 0 && IRType->isFloatTy())
  2190. return true;
  2191. // If this is a struct, recurse into the field at the specified offset.
  2192. if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
  2193. const llvm::StructLayout *SL = TD.getStructLayout(STy);
  2194. unsigned Elt = SL->getElementContainingOffset(IROffset);
  2195. IROffset -= SL->getElementOffset(Elt);
  2196. return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
  2197. }
  2198. // If this is an array, recurse into the field at the specified offset.
  2199. if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
  2200. llvm::Type *EltTy = ATy->getElementType();
  2201. unsigned EltSize = TD.getTypeAllocSize(EltTy);
  2202. IROffset -= IROffset/EltSize*EltSize;
  2203. return ContainsFloatAtOffset(EltTy, IROffset, TD);
  2204. }
  2205. return false;
  2206. }
  2207. /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
  2208. /// low 8 bytes of an XMM register, corresponding to the SSE class.
  2209. llvm::Type *X86_64ABIInfo::
  2210. GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
  2211. QualType SourceTy, unsigned SourceOffset) const {
  2212. // The only three choices we have are either double, <2 x float>, or float. We
  2213. // pass as float if the last 4 bytes is just padding. This happens for
  2214. // structs that contain 3 floats.
  2215. if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
  2216. SourceOffset*8+64, getContext()))
  2217. return llvm::Type::getFloatTy(getVMContext());
  2218. // We want to pass as <2 x float> if the LLVM IR type contains a float at
  2219. // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
  2220. // case.
  2221. if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
  2222. ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
  2223. return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
  2224. return llvm::Type::getDoubleTy(getVMContext());
  2225. }
  2226. /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
  2227. /// an 8-byte GPR. This means that we either have a scalar or we are talking
  2228. /// about the high or low part of an up-to-16-byte struct. This routine picks
  2229. /// the best LLVM IR type to represent this, which may be i64 or may be anything
  2230. /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
  2231. /// etc).
  2232. ///
  2233. /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
  2234. /// the source type. IROffset is an offset in bytes into the LLVM IR type that
  2235. /// the 8-byte value references. PrefType may be null.
  2236. ///
  2237. /// SourceTy is the source-level type for the entire argument. SourceOffset is
  2238. /// an offset into this that we're processing (which is always either 0 or 8).
  2239. ///
  2240. llvm::Type *X86_64ABIInfo::
  2241. GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
  2242. QualType SourceTy, unsigned SourceOffset) const {
  2243. // If we're dealing with an un-offset LLVM IR type, then it means that we're
  2244. // returning an 8-byte unit starting with it. See if we can safely use it.
  2245. if (IROffset == 0) {
  2246. // Pointers and int64's always fill the 8-byte unit.
  2247. if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
  2248. IRType->isIntegerTy(64))
  2249. return IRType;
  2250. // If we have a 1/2/4-byte integer, we can use it only if the rest of the
  2251. // goodness in the source type is just tail padding. This is allowed to
  2252. // kick in for struct {double,int} on the int, but not on
  2253. // struct{double,int,int} because we wouldn't return the second int. We
  2254. // have to do this analysis on the source type because we can't depend on
  2255. // unions being lowered a specific way etc.
  2256. if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
  2257. IRType->isIntegerTy(32) ||
  2258. (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
  2259. unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
  2260. cast<llvm::IntegerType>(IRType)->getBitWidth();
  2261. if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
  2262. SourceOffset*8+64, getContext()))
  2263. return IRType;
  2264. }
  2265. }
  2266. if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
  2267. // If this is a struct, recurse into the field at the specified offset.
  2268. const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
  2269. if (IROffset < SL->getSizeInBytes()) {
  2270. unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
  2271. IROffset -= SL->getElementOffset(FieldIdx);
  2272. return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
  2273. SourceTy, SourceOffset);
  2274. }
  2275. }
  2276. if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
  2277. llvm::Type *EltTy = ATy->getElementType();
  2278. unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
  2279. unsigned EltOffset = IROffset/EltSize*EltSize;
  2280. return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
  2281. SourceOffset);
  2282. }
  2283. // Okay, we don't have any better idea of what to pass, so we pass this in an
  2284. // integer register that isn't too big to fit the rest of the struct.
  2285. unsigned TySizeInBytes =
  2286. (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
  2287. assert(TySizeInBytes != SourceOffset && "Empty field?");
  2288. // It is always safe to classify this as an integer type up to i64 that
  2289. // isn't larger than the structure.
  2290. return llvm::IntegerType::get(getVMContext(),
  2291. std::min(TySizeInBytes-SourceOffset, 8U)*8);
  2292. }
  2293. /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
  2294. /// be used as elements of a two register pair to pass or return, return a
  2295. /// first class aggregate to represent them. For example, if the low part of
  2296. /// a by-value argument should be passed as i32* and the high part as float,
  2297. /// return {i32*, float}.
  2298. static llvm::Type *
  2299. GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
  2300. const llvm::DataLayout &TD) {
  2301. // In order to correctly satisfy the ABI, we need to the high part to start
  2302. // at offset 8. If the high and low parts we inferred are both 4-byte types
  2303. // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
  2304. // the second element at offset 8. Check for this:
  2305. unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
  2306. unsigned HiAlign = TD.getABITypeAlignment(Hi);
  2307. unsigned HiStart = llvm::RoundUpToAlignment(LoSize, HiAlign);
  2308. assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
  2309. // To handle this, we have to increase the size of the low part so that the
  2310. // second element will start at an 8 byte offset. We can't increase the size
  2311. // of the second element because it might make us access off the end of the
  2312. // struct.
  2313. if (HiStart != 8) {
  2314. // There are usually two sorts of types the ABI generation code can produce
  2315. // for the low part of a pair that aren't 8 bytes in size: float or
  2316. // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
  2317. // NaCl).
  2318. // Promote these to a larger type.
  2319. if (Lo->isFloatTy())
  2320. Lo = llvm::Type::getDoubleTy(Lo->getContext());
  2321. else {
  2322. assert((Lo->isIntegerTy() || Lo->isPointerTy())
  2323. && "Invalid/unknown lo type");
  2324. Lo = llvm::Type::getInt64Ty(Lo->getContext());
  2325. }
  2326. }
  2327. llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
  2328. // Verify that the second element is at an 8-byte offset.
  2329. assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
  2330. "Invalid x86-64 argument pair!");
  2331. return Result;
  2332. }
  2333. ABIArgInfo X86_64ABIInfo::
  2334. classifyReturnType(QualType RetTy) const {
  2335. // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
  2336. // classification algorithm.
  2337. X86_64ABIInfo::Class Lo, Hi;
  2338. classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
  2339. // Check some invariants.
  2340. assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
  2341. assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
  2342. llvm::Type *ResType = nullptr;
  2343. switch (Lo) {
  2344. case NoClass:
  2345. if (Hi == NoClass)
  2346. return ABIArgInfo::getIgnore();
  2347. // If the low part is just padding, it takes no register, leave ResType
  2348. // null.
  2349. assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
  2350. "Unknown missing lo part");
  2351. break;
  2352. case SSEUp:
  2353. case X87Up:
  2354. llvm_unreachable("Invalid classification for lo word.");
  2355. // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
  2356. // hidden argument.
  2357. case Memory:
  2358. return getIndirectReturnResult(RetTy);
  2359. // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
  2360. // available register of the sequence %rax, %rdx is used.
  2361. case Integer:
  2362. ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
  2363. // If we have a sign or zero extended integer, make sure to return Extend
  2364. // so that the parameter gets the right LLVM IR attributes.
  2365. if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
  2366. // Treat an enum type as its underlying type.
  2367. if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
  2368. RetTy = EnumTy->getDecl()->getIntegerType();
  2369. if (RetTy->isIntegralOrEnumerationType() &&
  2370. RetTy->isPromotableIntegerType())
  2371. return ABIArgInfo::getExtend();
  2372. }
  2373. break;
  2374. // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
  2375. // available SSE register of the sequence %xmm0, %xmm1 is used.
  2376. case SSE:
  2377. ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
  2378. break;
  2379. // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
  2380. // returned on the X87 stack in %st0 as 80-bit x87 number.
  2381. case X87:
  2382. ResType = llvm::Type::getX86_FP80Ty(getVMContext());
  2383. break;
  2384. // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
  2385. // part of the value is returned in %st0 and the imaginary part in
  2386. // %st1.
  2387. case ComplexX87:
  2388. assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
  2389. ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
  2390. llvm::Type::getX86_FP80Ty(getVMContext()),
  2391. nullptr);
  2392. break;
  2393. }
  2394. llvm::Type *HighPart = nullptr;
  2395. switch (Hi) {
  2396. // Memory was handled previously and X87 should
  2397. // never occur as a hi class.
  2398. case Memory:
  2399. case X87:
  2400. llvm_unreachable("Invalid classification for hi word.");
  2401. case ComplexX87: // Previously handled.
  2402. case NoClass:
  2403. break;
  2404. case Integer:
  2405. HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
  2406. if (Lo == NoClass) // Return HighPart at offset 8 in memory.
  2407. return ABIArgInfo::getDirect(HighPart, 8);
  2408. break;
  2409. case SSE:
  2410. HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
  2411. if (Lo == NoClass) // Return HighPart at offset 8 in memory.
  2412. return ABIArgInfo::getDirect(HighPart, 8);
  2413. break;
  2414. // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
  2415. // is passed in the next available eightbyte chunk if the last used
  2416. // vector register.
  2417. //
  2418. // SSEUP should always be preceded by SSE, just widen.
  2419. case SSEUp:
  2420. assert(Lo == SSE && "Unexpected SSEUp classification.");
  2421. ResType = GetByteVectorType(RetTy);
  2422. break;
  2423. // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
  2424. // returned together with the previous X87 value in %st0.
  2425. case X87Up:
  2426. // If X87Up is preceded by X87, we don't need to do
  2427. // anything. However, in some cases with unions it may not be
  2428. // preceded by X87. In such situations we follow gcc and pass the
  2429. // extra bits in an SSE reg.
  2430. if (Lo != X87) {
  2431. HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
  2432. if (Lo == NoClass) // Return HighPart at offset 8 in memory.
  2433. return ABIArgInfo::getDirect(HighPart, 8);
  2434. }
  2435. break;
  2436. }
  2437. // If a high part was specified, merge it together with the low part. It is
  2438. // known to pass in the high eightbyte of the result. We do this by forming a
  2439. // first class struct aggregate with the high and low part: {low, high}
  2440. if (HighPart)
  2441. ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
  2442. return ABIArgInfo::getDirect(ResType);
  2443. }
  2444. ABIArgInfo X86_64ABIInfo::classifyArgumentType(
  2445. QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
  2446. bool isNamedArg)
  2447. const
  2448. {
  2449. Ty = useFirstFieldIfTransparentUnion(Ty);
  2450. X86_64ABIInfo::Class Lo, Hi;
  2451. classify(Ty, 0, Lo, Hi, isNamedArg);
  2452. // Check some invariants.
  2453. // FIXME: Enforce these by construction.
  2454. assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
  2455. assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
  2456. neededInt = 0;
  2457. neededSSE = 0;
  2458. llvm::Type *ResType = nullptr;
  2459. switch (Lo) {
  2460. case NoClass:
  2461. if (Hi == NoClass)
  2462. return ABIArgInfo::getIgnore();
  2463. // If the low part is just padding, it takes no register, leave ResType
  2464. // null.
  2465. assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
  2466. "Unknown missing lo part");
  2467. break;
  2468. // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
  2469. // on the stack.
  2470. case Memory:
  2471. // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
  2472. // COMPLEX_X87, it is passed in memory.
  2473. case X87:
  2474. case ComplexX87:
  2475. if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
  2476. ++neededInt;
  2477. return getIndirectResult(Ty, freeIntRegs);
  2478. case SSEUp:
  2479. case X87Up:
  2480. llvm_unreachable("Invalid classification for lo word.");
  2481. // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
  2482. // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
  2483. // and %r9 is used.
  2484. case Integer:
  2485. ++neededInt;
  2486. // Pick an 8-byte type based on the preferred type.
  2487. ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
  2488. // If we have a sign or zero extended integer, make sure to return Extend
  2489. // so that the parameter gets the right LLVM IR attributes.
  2490. if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
  2491. // Treat an enum type as its underlying type.
  2492. if (const EnumType *EnumTy = Ty->getAs<EnumType>())
  2493. Ty = EnumTy->getDecl()->getIntegerType();
  2494. if (Ty->isIntegralOrEnumerationType() &&
  2495. Ty->isPromotableIntegerType())
  2496. return ABIArgInfo::getExtend();
  2497. }
  2498. break;
  2499. // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
  2500. // available SSE register is used, the registers are taken in the
  2501. // order from %xmm0 to %xmm7.
  2502. case SSE: {
  2503. llvm::Type *IRType = CGT.ConvertType(Ty);
  2504. ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
  2505. ++neededSSE;
  2506. break;
  2507. }
  2508. }
  2509. llvm::Type *HighPart = nullptr;
  2510. switch (Hi) {
  2511. // Memory was handled previously, ComplexX87 and X87 should
  2512. // never occur as hi classes, and X87Up must be preceded by X87,
  2513. // which is passed in memory.
  2514. case Memory:
  2515. case X87:
  2516. case ComplexX87:
  2517. llvm_unreachable("Invalid classification for hi word.");
  2518. case NoClass: break;
  2519. case Integer:
  2520. ++neededInt;
  2521. // Pick an 8-byte type based on the preferred type.
  2522. HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
  2523. if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
  2524. return ABIArgInfo::getDirect(HighPart, 8);
  2525. break;
  2526. // X87Up generally doesn't occur here (long double is passed in
  2527. // memory), except in situations involving unions.
  2528. case X87Up:
  2529. case SSE:
  2530. HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
  2531. if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
  2532. return ABIArgInfo::getDirect(HighPart, 8);
  2533. ++neededSSE;
  2534. break;
  2535. // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
  2536. // eightbyte is passed in the upper half of the last used SSE
  2537. // register. This only happens when 128-bit vectors are passed.
  2538. case SSEUp:
  2539. assert(Lo == SSE && "Unexpected SSEUp classification");
  2540. ResType = GetByteVectorType(Ty);
  2541. break;
  2542. }
  2543. // If a high part was specified, merge it together with the low part. It is
  2544. // known to pass in the high eightbyte of the result. We do this by forming a
  2545. // first class struct aggregate with the high and low part: {low, high}
  2546. if (HighPart)
  2547. ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
  2548. return ABIArgInfo::getDirect(ResType);
  2549. }
  2550. void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
  2551. if (!getCXXABI().classifyReturnType(FI))
  2552. FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
  2553. // Keep track of the number of assigned registers.
  2554. unsigned freeIntRegs = 6, freeSSERegs = 8;
  2555. // If the return value is indirect, then the hidden argument is consuming one
  2556. // integer register.
  2557. if (FI.getReturnInfo().isIndirect())
  2558. --freeIntRegs;
  2559. // The chain argument effectively gives us another free register.
  2560. if (FI.isChainCall())
  2561. ++freeIntRegs;
  2562. unsigned NumRequiredArgs = FI.getNumRequiredArgs();
  2563. // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
  2564. // get assigned (in left-to-right order) for passing as follows...
  2565. unsigned ArgNo = 0;
  2566. for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
  2567. it != ie; ++it, ++ArgNo) {
  2568. bool IsNamedArg = ArgNo < NumRequiredArgs;
  2569. unsigned neededInt, neededSSE;
  2570. it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
  2571. neededSSE, IsNamedArg);
  2572. // AMD64-ABI 3.2.3p3: If there are no registers available for any
  2573. // eightbyte of an argument, the whole argument is passed on the
  2574. // stack. If registers have already been assigned for some
  2575. // eightbytes of such an argument, the assignments get reverted.
  2576. if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
  2577. freeIntRegs -= neededInt;
  2578. freeSSERegs -= neededSSE;
  2579. } else {
  2580. it->info = getIndirectResult(it->type, freeIntRegs);
  2581. }
  2582. }
  2583. }
  2584. static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
  2585. Address VAListAddr, QualType Ty) {
  2586. Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
  2587. VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
  2588. llvm::Value *overflow_arg_area =
  2589. CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
  2590. // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
  2591. // byte boundary if alignment needed by type exceeds 8 byte boundary.
  2592. // It isn't stated explicitly in the standard, but in practice we use
  2593. // alignment greater than 16 where necessary.
  2594. uint64_t Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
  2595. if (Align > 8) {
  2596. // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
  2597. llvm::Value *Offset =
  2598. llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
  2599. overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
  2600. llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
  2601. CGF.Int64Ty);
  2602. llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
  2603. overflow_arg_area =
  2604. CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
  2605. overflow_arg_area->getType(),
  2606. "overflow_arg_area.align");
  2607. }
  2608. // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
  2609. llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
  2610. llvm::Value *Res =
  2611. CGF.Builder.CreateBitCast(overflow_arg_area,
  2612. llvm::PointerType::getUnqual(LTy));
  2613. // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
  2614. // l->overflow_arg_area + sizeof(type).
  2615. // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
  2616. // an 8 byte boundary.
  2617. uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
  2618. llvm::Value *Offset =
  2619. llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
  2620. overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
  2621. "overflow_arg_area.next");
  2622. CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
  2623. // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
  2624. return Address(Res, CharUnits::fromQuantity(Align));
  2625. }
  2626. Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  2627. QualType Ty) const {
  2628. // Assume that va_list type is correct; should be pointer to LLVM type:
  2629. // struct {
  2630. // i32 gp_offset;
  2631. // i32 fp_offset;
  2632. // i8* overflow_arg_area;
  2633. // i8* reg_save_area;
  2634. // };
  2635. unsigned neededInt, neededSSE;
  2636. Ty = getContext().getCanonicalType(Ty);
  2637. ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
  2638. /*isNamedArg*/false);
  2639. // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
  2640. // in the registers. If not go to step 7.
  2641. if (!neededInt && !neededSSE)
  2642. return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
  2643. // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
  2644. // general purpose registers needed to pass type and num_fp to hold
  2645. // the number of floating point registers needed.
  2646. // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
  2647. // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
  2648. // l->fp_offset > 304 - num_fp * 16 go to step 7.
  2649. //
  2650. // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
  2651. // register save space).
  2652. llvm::Value *InRegs = nullptr;
  2653. Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
  2654. llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
  2655. if (neededInt) {
  2656. gp_offset_p =
  2657. CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
  2658. "gp_offset_p");
  2659. gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
  2660. InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
  2661. InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
  2662. }
  2663. if (neededSSE) {
  2664. fp_offset_p =
  2665. CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
  2666. "fp_offset_p");
  2667. fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
  2668. llvm::Value *FitsInFP =
  2669. llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
  2670. FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
  2671. InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
  2672. }
  2673. llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
  2674. llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
  2675. llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
  2676. CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
  2677. // Emit code to load the value if it was passed in registers.
  2678. CGF.EmitBlock(InRegBlock);
  2679. // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
  2680. // an offset of l->gp_offset and/or l->fp_offset. This may require
  2681. // copying to a temporary location in case the parameter is passed
  2682. // in different register classes or requires an alignment greater
  2683. // than 8 for general purpose registers and 16 for XMM registers.
  2684. //
  2685. // FIXME: This really results in shameful code when we end up needing to
  2686. // collect arguments from different places; often what should result in a
  2687. // simple assembling of a structure from scattered addresses has many more
  2688. // loads than necessary. Can we clean this up?
  2689. llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
  2690. llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
  2691. CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
  2692. "reg_save_area");
  2693. Address RegAddr = Address::invalid();
  2694. if (neededInt && neededSSE) {
  2695. // FIXME: Cleanup.
  2696. assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
  2697. llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
  2698. Address Tmp = CGF.CreateMemTemp(Ty);
  2699. Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
  2700. assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
  2701. llvm::Type *TyLo = ST->getElementType(0);
  2702. llvm::Type *TyHi = ST->getElementType(1);
  2703. assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
  2704. "Unexpected ABI info for mixed regs");
  2705. llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
  2706. llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
  2707. llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
  2708. llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
  2709. llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
  2710. llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
  2711. // Copy the first element.
  2712. llvm::Value *V =
  2713. CGF.Builder.CreateDefaultAlignedLoad(
  2714. CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
  2715. CGF.Builder.CreateStore(V,
  2716. CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
  2717. // Copy the second element.
  2718. V = CGF.Builder.CreateDefaultAlignedLoad(
  2719. CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
  2720. CharUnits Offset = CharUnits::fromQuantity(
  2721. getDataLayout().getStructLayout(ST)->getElementOffset(1));
  2722. CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
  2723. RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
  2724. } else if (neededInt) {
  2725. RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
  2726. CharUnits::fromQuantity(8));
  2727. RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
  2728. // Copy to a temporary if necessary to ensure the appropriate alignment.
  2729. std::pair<CharUnits, CharUnits> SizeAlign =
  2730. getContext().getTypeInfoInChars(Ty);
  2731. uint64_t TySize = SizeAlign.first.getQuantity();
  2732. CharUnits TyAlign = SizeAlign.second;
  2733. // Copy into a temporary if the type is more aligned than the
  2734. // register save area.
  2735. if (TyAlign.getQuantity() > 8) {
  2736. Address Tmp = CGF.CreateMemTemp(Ty);
  2737. CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
  2738. RegAddr = Tmp;
  2739. }
  2740. } else if (neededSSE == 1) {
  2741. RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
  2742. CharUnits::fromQuantity(16));
  2743. RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
  2744. } else {
  2745. assert(neededSSE == 2 && "Invalid number of needed registers!");
  2746. // SSE registers are spaced 16 bytes apart in the register save
  2747. // area, we need to collect the two eightbytes together.
  2748. // The ABI isn't explicit about this, but it seems reasonable
  2749. // to assume that the slots are 16-byte aligned, since the stack is
  2750. // naturally 16-byte aligned and the prologue is expected to store
  2751. // all the SSE registers to the RSA.
  2752. Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
  2753. CharUnits::fromQuantity(16));
  2754. Address RegAddrHi =
  2755. CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
  2756. CharUnits::fromQuantity(16));
  2757. llvm::Type *DoubleTy = CGF.DoubleTy;
  2758. llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
  2759. llvm::Value *V;
  2760. Address Tmp = CGF.CreateMemTemp(Ty);
  2761. Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
  2762. V = CGF.Builder.CreateLoad(
  2763. CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
  2764. CGF.Builder.CreateStore(V,
  2765. CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
  2766. V = CGF.Builder.CreateLoad(
  2767. CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
  2768. CGF.Builder.CreateStore(V,
  2769. CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
  2770. RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
  2771. }
  2772. // AMD64-ABI 3.5.7p5: Step 5. Set:
  2773. // l->gp_offset = l->gp_offset + num_gp * 8
  2774. // l->fp_offset = l->fp_offset + num_fp * 16.
  2775. if (neededInt) {
  2776. llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
  2777. CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
  2778. gp_offset_p);
  2779. }
  2780. if (neededSSE) {
  2781. llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
  2782. CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
  2783. fp_offset_p);
  2784. }
  2785. CGF.EmitBranch(ContBlock);
  2786. // Emit code to load the value if it was passed in memory.
  2787. CGF.EmitBlock(InMemBlock);
  2788. Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
  2789. // Return the appropriate result.
  2790. CGF.EmitBlock(ContBlock);
  2791. Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
  2792. "vaarg.addr");
  2793. return ResAddr;
  2794. }
  2795. Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
  2796. QualType Ty) const {
  2797. return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
  2798. CGF.getContext().getTypeInfoInChars(Ty),
  2799. CharUnits::fromQuantity(8),
  2800. /*allowHigherAlign*/ false);
  2801. }
  2802. ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
  2803. bool IsReturnType) const {
  2804. if (Ty->isVoidType())
  2805. return ABIArgInfo::getIgnore();
  2806. if (const EnumType *EnumTy = Ty->getAs<EnumType>())
  2807. Ty = EnumTy->getDecl()->getIntegerType();
  2808. TypeInfo Info = getContext().getTypeInfo(Ty);
  2809. uint64_t Width = Info.Width;
  2810. unsigned Align = getContext().toCharUnitsFromBits(Info.Align).getQuantity();
  2811. const RecordType *RT = Ty->getAs<RecordType>();
  2812. if (RT) {
  2813. if (!IsReturnType) {
  2814. if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
  2815. return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
  2816. }
  2817. if (RT->getDecl()->hasFlexibleArrayMember())
  2818. return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
  2819. // FIXME: mingw-w64-gcc emits 128-bit struct as i128
  2820. if (Width == 128 && getTarget().getTriple().isWindowsGNUEnvironment())
  2821. return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
  2822. Width));
  2823. }
  2824. // vectorcall adds the concept of a homogenous vector aggregate, similar to
  2825. // other targets.
  2826. const Type *Base = nullptr;
  2827. uint64_t NumElts = 0;
  2828. if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
  2829. if (FreeSSERegs >= NumElts) {
  2830. FreeSSERegs -= NumElts;
  2831. if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
  2832. return ABIArgInfo::getDirect();
  2833. return ABIArgInfo::getExpand();
  2834. }
  2835. return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align),
  2836. /*ByVal=*/false);
  2837. }
  2838. if (Ty->isMemberPointerType()) {
  2839. // If the member pointer is represented by an LLVM int or ptr, pass it
  2840. // directly.
  2841. llvm::Type *LLTy = CGT.ConvertType(Ty);
  2842. if (LLTy->isPointerTy() || LLTy->isIntegerTy())
  2843. return ABIArgInfo::getDirect();
  2844. }
  2845. if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
  2846. // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
  2847. // not 1, 2, 4, or 8 bytes, must be passed by reference."
  2848. if (Width > 64 || !llvm::isPowerOf2_64(Width))
  2849. return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
  2850. // Otherwise, coerce it to a small integer.
  2851. return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
  2852. }
  2853. // Bool type is always extended to the ABI, other builtin types are not
  2854. // extended.
  2855. const BuiltinType *BT = Ty->getAs<BuiltinType>();
  2856. if (BT && BT->getKind() == BuiltinType::Bool)
  2857. return ABIArgInfo::getExtend();
  2858. return ABIArgInfo::getDirect();
  2859. }
  2860. void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
  2861. bool IsVectorCall =
  2862. FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
  2863. // We can use up to 4 SSE return registers with vectorcall.
  2864. unsigned FreeSSERegs = IsVectorCall ? 4 : 0;
  2865. if (!getCXXABI().classifyReturnType(FI))
  2866. FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
  2867. // We can use up to 6 SSE register parameters with vectorcall.
  2868. FreeSSERegs = IsVectorCall ? 6 : 0;
  2869. for (auto &I : FI.arguments())
  2870. I.info = classify(I.type, FreeSSERegs, false);
  2871. }
  2872. Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  2873. QualType Ty) const {
  2874. return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
  2875. CGF.getContext().getTypeInfoInChars(Ty),
  2876. CharUnits::fromQuantity(8),
  2877. /*allowHigherAlign*/ false);
  2878. }
  2879. // PowerPC-32
  2880. namespace {
  2881. /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
  2882. class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
  2883. public:
  2884. PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
  2885. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  2886. QualType Ty) const override;
  2887. };
  2888. class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
  2889. public:
  2890. PPC32TargetCodeGenInfo(CodeGenTypes &CGT)
  2891. : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT)) {}
  2892. int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
  2893. // This is recovered from gcc output.
  2894. return 1; // r1 is the dedicated stack pointer
  2895. }
  2896. bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
  2897. llvm::Value *Address) const override;
  2898. };
  2899. }
  2900. Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
  2901. QualType Ty) const {
  2902. if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
  2903. // TODO: Implement this. For now ignore.
  2904. (void)CTy;
  2905. return Address::invalid();
  2906. }
  2907. // struct __va_list_tag {
  2908. // unsigned char gpr;
  2909. // unsigned char fpr;
  2910. // unsigned short reserved;
  2911. // void *overflow_arg_area;
  2912. // void *reg_save_area;
  2913. // };
  2914. bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
  2915. bool isInt =
  2916. Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
  2917. // All aggregates are passed indirectly? That doesn't seem consistent
  2918. // with the argument-lowering code.
  2919. bool isIndirect = Ty->isAggregateType();
  2920. CGBuilderTy &Builder = CGF.Builder;
  2921. // The calling convention either uses 1-2 GPRs or 1 FPR.
  2922. Address NumRegsAddr = Address::invalid();
  2923. if (isInt) {
  2924. NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
  2925. } else {
  2926. NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
  2927. }
  2928. llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
  2929. // "Align" the register count when TY is i64.
  2930. if (isI64) {
  2931. NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
  2932. NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
  2933. }
  2934. llvm::Value *CC =
  2935. Builder.CreateICmpULT(NumRegs, Builder.getInt8(8), "cond");
  2936. llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
  2937. llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
  2938. llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
  2939. Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
  2940. llvm::Type *DirectTy = CGF.ConvertType(Ty);
  2941. if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
  2942. // Case 1: consume registers.
  2943. Address RegAddr = Address::invalid();
  2944. {
  2945. CGF.EmitBlock(UsingRegs);
  2946. Address RegSaveAreaPtr =
  2947. Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
  2948. RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
  2949. CharUnits::fromQuantity(8));
  2950. assert(RegAddr.getElementType() == CGF.Int8Ty);
  2951. // Floating-point registers start after the general-purpose registers.
  2952. if (!isInt) {
  2953. RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
  2954. CharUnits::fromQuantity(32));
  2955. }
  2956. // Get the address of the saved value by scaling the number of
  2957. // registers we've used by the number of
  2958. CharUnits RegSize = CharUnits::fromQuantity(isInt ? 4 : 8);
  2959. llvm::Value *RegOffset =
  2960. Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
  2961. RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
  2962. RegAddr.getPointer(), RegOffset),
  2963. RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
  2964. RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
  2965. // Increase the used-register count.
  2966. NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(isI64 ? 2 : 1));
  2967. Builder.CreateStore(NumRegs, NumRegsAddr);
  2968. CGF.EmitBranch(Cont);
  2969. }
  2970. // Case 2: consume space in the overflow area.
  2971. Address MemAddr = Address::invalid();
  2972. {
  2973. CGF.EmitBlock(UsingOverflow);
  2974. // Everything in the overflow area is rounded up to a size of at least 4.
  2975. CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
  2976. CharUnits Size;
  2977. if (!isIndirect) {
  2978. auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
  2979. Size = TypeInfo.first.RoundUpToAlignment(OverflowAreaAlign);
  2980. } else {
  2981. Size = CGF.getPointerSize();
  2982. }
  2983. Address OverflowAreaAddr =
  2984. Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
  2985. Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr),
  2986. OverflowAreaAlign);
  2987. // The current address is the address of the varargs element.
  2988. // FIXME: do we not need to round up to alignment?
  2989. MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
  2990. // Increase the overflow area.
  2991. OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
  2992. Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
  2993. CGF.EmitBranch(Cont);
  2994. }
  2995. CGF.EmitBlock(Cont);
  2996. // Merge the cases with a phi.
  2997. Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
  2998. "vaarg.addr");
  2999. // Load the pointer if the argument was passed indirectly.
  3000. if (isIndirect) {
  3001. Result = Address(Builder.CreateLoad(Result, "aggr"),
  3002. getContext().getTypeAlignInChars(Ty));
  3003. }
  3004. return Result;
  3005. }
  3006. bool
  3007. PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
  3008. llvm::Value *Address) const {
  3009. // This is calculated from the LLVM and GCC tables and verified
  3010. // against gcc output. AFAIK all ABIs use the same encoding.
  3011. CodeGen::CGBuilderTy &Builder = CGF.Builder;
  3012. llvm::IntegerType *i8 = CGF.Int8Ty;
  3013. llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
  3014. llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
  3015. llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
  3016. // 0-31: r0-31, the 4-byte general-purpose registers
  3017. AssignToArrayRange(Builder, Address, Four8, 0, 31);
  3018. // 32-63: fp0-31, the 8-byte floating-point registers
  3019. AssignToArrayRange(Builder, Address, Eight8, 32, 63);
  3020. // 64-76 are various 4-byte special-purpose registers:
  3021. // 64: mq
  3022. // 65: lr
  3023. // 66: ctr
  3024. // 67: ap
  3025. // 68-75 cr0-7
  3026. // 76: xer
  3027. AssignToArrayRange(Builder, Address, Four8, 64, 76);
  3028. // 77-108: v0-31, the 16-byte vector registers
  3029. AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
  3030. // 109: vrsave
  3031. // 110: vscr
  3032. // 111: spe_acc
  3033. // 112: spefscr
  3034. // 113: sfp
  3035. AssignToArrayRange(Builder, Address, Four8, 109, 113);
  3036. return false;
  3037. }
  3038. // PowerPC-64
  3039. namespace {
  3040. /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
  3041. class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
  3042. public:
  3043. enum ABIKind {
  3044. ELFv1 = 0,
  3045. ELFv2
  3046. };
  3047. private:
  3048. static const unsigned GPRBits = 64;
  3049. ABIKind Kind;
  3050. bool HasQPX;
  3051. // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
  3052. // will be passed in a QPX register.
  3053. bool IsQPXVectorTy(const Type *Ty) const {
  3054. if (!HasQPX)
  3055. return false;
  3056. if (const VectorType *VT = Ty->getAs<VectorType>()) {
  3057. unsigned NumElements = VT->getNumElements();
  3058. if (NumElements == 1)
  3059. return false;
  3060. if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
  3061. if (getContext().getTypeSize(Ty) <= 256)
  3062. return true;
  3063. } else if (VT->getElementType()->
  3064. isSpecificBuiltinType(BuiltinType::Float)) {
  3065. if (getContext().getTypeSize(Ty) <= 128)
  3066. return true;
  3067. }
  3068. }
  3069. return false;
  3070. }
  3071. bool IsQPXVectorTy(QualType Ty) const {
  3072. return IsQPXVectorTy(Ty.getTypePtr());
  3073. }
  3074. public:
  3075. PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX)
  3076. : DefaultABIInfo(CGT), Kind(Kind), HasQPX(HasQPX) {}
  3077. bool isPromotableTypeForABI(QualType Ty) const;
  3078. CharUnits getParamTypeAlignment(QualType Ty) const;
  3079. ABIArgInfo classifyReturnType(QualType RetTy) const;
  3080. ABIArgInfo classifyArgumentType(QualType Ty) const;
  3081. bool isHomogeneousAggregateBaseType(QualType Ty) const override;
  3082. bool isHomogeneousAggregateSmallEnough(const Type *Ty,
  3083. uint64_t Members) const override;
  3084. // TODO: We can add more logic to computeInfo to improve performance.
  3085. // Example: For aggregate arguments that fit in a register, we could
  3086. // use getDirectInReg (as is done below for structs containing a single
  3087. // floating-point value) to avoid pushing them to memory on function
  3088. // entry. This would require changing the logic in PPCISelLowering
  3089. // when lowering the parameters in the caller and args in the callee.
  3090. void computeInfo(CGFunctionInfo &FI) const override {
  3091. if (!getCXXABI().classifyReturnType(FI))
  3092. FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
  3093. for (auto &I : FI.arguments()) {
  3094. // We rely on the default argument classification for the most part.
  3095. // One exception: An aggregate containing a single floating-point
  3096. // or vector item must be passed in a register if one is available.
  3097. const Type *T = isSingleElementStruct(I.type, getContext());
  3098. if (T) {
  3099. const BuiltinType *BT = T->getAs<BuiltinType>();
  3100. if (IsQPXVectorTy(T) ||
  3101. (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
  3102. (BT && BT->isFloatingPoint())) {
  3103. QualType QT(T, 0);
  3104. I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
  3105. continue;
  3106. }
  3107. }
  3108. I.info = classifyArgumentType(I.type);
  3109. }
  3110. }
  3111. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  3112. QualType Ty) const override;
  3113. };
  3114. class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
  3115. public:
  3116. PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
  3117. PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX)
  3118. : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX)) {}
  3119. int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
  3120. // This is recovered from gcc output.
  3121. return 1; // r1 is the dedicated stack pointer
  3122. }
  3123. bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
  3124. llvm::Value *Address) const override;
  3125. };
  3126. class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
  3127. public:
  3128. PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
  3129. int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
  3130. // This is recovered from gcc output.
  3131. return 1; // r1 is the dedicated stack pointer
  3132. }
  3133. bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
  3134. llvm::Value *Address) const override;
  3135. };
  3136. }
  3137. // Return true if the ABI requires Ty to be passed sign- or zero-
  3138. // extended to 64 bits.
  3139. bool
  3140. PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
  3141. // Treat an enum type as its underlying type.
  3142. if (const EnumType *EnumTy = Ty->getAs<EnumType>())
  3143. Ty = EnumTy->getDecl()->getIntegerType();
  3144. // Promotable integer types are required to be promoted by the ABI.
  3145. if (Ty->isPromotableIntegerType())
  3146. return true;
  3147. // In addition to the usual promotable integer types, we also need to
  3148. // extend all 32-bit types, since the ABI requires promotion to 64 bits.
  3149. if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
  3150. switch (BT->getKind()) {
  3151. case BuiltinType::Int:
  3152. case BuiltinType::UInt:
  3153. return true;
  3154. default:
  3155. break;
  3156. }
  3157. return false;
  3158. }
  3159. /// isAlignedParamType - Determine whether a type requires 16-byte or
  3160. /// higher alignment in the parameter area. Always returns at least 8.
  3161. CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
  3162. // Complex types are passed just like their elements.
  3163. if (const ComplexType *CTy = Ty->getAs<ComplexType>())
  3164. Ty = CTy->getElementType();
  3165. // Only vector types of size 16 bytes need alignment (larger types are
  3166. // passed via reference, smaller types are not aligned).
  3167. if (IsQPXVectorTy(Ty)) {
  3168. if (getContext().getTypeSize(Ty) > 128)
  3169. return CharUnits::fromQuantity(32);
  3170. return CharUnits::fromQuantity(16);
  3171. } else if (Ty->isVectorType()) {
  3172. return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
  3173. }
  3174. // For single-element float/vector structs, we consider the whole type
  3175. // to have the same alignment requirements as its single element.
  3176. const Type *AlignAsType = nullptr;
  3177. const Type *EltType = isSingleElementStruct(Ty, getContext());
  3178. if (EltType) {
  3179. const BuiltinType *BT = EltType->getAs<BuiltinType>();
  3180. if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
  3181. getContext().getTypeSize(EltType) == 128) ||
  3182. (BT && BT->isFloatingPoint()))
  3183. AlignAsType = EltType;
  3184. }
  3185. // Likewise for ELFv2 homogeneous aggregates.
  3186. const Type *Base = nullptr;
  3187. uint64_t Members = 0;
  3188. if (!AlignAsType && Kind == ELFv2 &&
  3189. isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
  3190. AlignAsType = Base;
  3191. // With special case aggregates, only vector base types need alignment.
  3192. if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
  3193. if (getContext().getTypeSize(AlignAsType) > 128)
  3194. return CharUnits::fromQuantity(32);
  3195. return CharUnits::fromQuantity(16);
  3196. } else if (AlignAsType) {
  3197. return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
  3198. }
  3199. // Otherwise, we only need alignment for any aggregate type that
  3200. // has an alignment requirement of >= 16 bytes.
  3201. if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
  3202. if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
  3203. return CharUnits::fromQuantity(32);
  3204. return CharUnits::fromQuantity(16);
  3205. }
  3206. return CharUnits::fromQuantity(8);
  3207. }
  3208. /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
  3209. /// aggregate. Base is set to the base element type, and Members is set
  3210. /// to the number of base elements.
  3211. bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
  3212. uint64_t &Members) const {
  3213. if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
  3214. uint64_t NElements = AT->getSize().getZExtValue();
  3215. if (NElements == 0)
  3216. return false;
  3217. if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
  3218. return false;
  3219. Members *= NElements;
  3220. } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
  3221. const RecordDecl *RD = RT->getDecl();
  3222. if (RD->hasFlexibleArrayMember())
  3223. return false;
  3224. Members = 0;
  3225. // If this is a C++ record, check the bases first.
  3226. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  3227. for (const auto &I : CXXRD->bases()) {
  3228. // Ignore empty records.
  3229. if (isEmptyRecord(getContext(), I.getType(), true))
  3230. continue;
  3231. uint64_t FldMembers;
  3232. if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
  3233. return false;
  3234. Members += FldMembers;
  3235. }
  3236. }
  3237. for (const auto *FD : RD->fields()) {
  3238. // Ignore (non-zero arrays of) empty records.
  3239. QualType FT = FD->getType();
  3240. while (const ConstantArrayType *AT =
  3241. getContext().getAsConstantArrayType(FT)) {
  3242. if (AT->getSize().getZExtValue() == 0)
  3243. return false;
  3244. FT = AT->getElementType();
  3245. }
  3246. if (isEmptyRecord(getContext(), FT, true))
  3247. continue;
  3248. // For compatibility with GCC, ignore empty bitfields in C++ mode.
  3249. if (getContext().getLangOpts().CPlusPlus &&
  3250. FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
  3251. continue;
  3252. uint64_t FldMembers;
  3253. if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
  3254. return false;
  3255. Members = (RD->isUnion() ?
  3256. std::max(Members, FldMembers) : Members + FldMembers);
  3257. }
  3258. if (!Base)
  3259. return false;
  3260. // Ensure there is no padding.
  3261. if (getContext().getTypeSize(Base) * Members !=
  3262. getContext().getTypeSize(Ty))
  3263. return false;
  3264. } else {
  3265. Members = 1;
  3266. if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
  3267. Members = 2;
  3268. Ty = CT->getElementType();
  3269. }
  3270. // Most ABIs only support float, double, and some vector type widths.
  3271. if (!isHomogeneousAggregateBaseType(Ty))
  3272. return false;
  3273. // The base type must be the same for all members. Types that
  3274. // agree in both total size and mode (float vs. vector) are
  3275. // treated as being equivalent here.
  3276. const Type *TyPtr = Ty.getTypePtr();
  3277. if (!Base)
  3278. Base = TyPtr;
  3279. if (Base->isVectorType() != TyPtr->isVectorType() ||
  3280. getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
  3281. return false;
  3282. }
  3283. return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
  3284. }
  3285. bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
  3286. // Homogeneous aggregates for ELFv2 must have base types of float,
  3287. // double, long double, or 128-bit vectors.
  3288. if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
  3289. if (BT->getKind() == BuiltinType::Float ||
  3290. BT->getKind() == BuiltinType::Double ||
  3291. BT->getKind() == BuiltinType::LongDouble)
  3292. return true;
  3293. }
  3294. if (const VectorType *VT = Ty->getAs<VectorType>()) {
  3295. if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
  3296. return true;
  3297. }
  3298. return false;
  3299. }
  3300. bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
  3301. const Type *Base, uint64_t Members) const {
  3302. // Vector types require one register, floating point types require one
  3303. // or two registers depending on their size.
  3304. uint32_t NumRegs =
  3305. Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
  3306. // Homogeneous Aggregates may occupy at most 8 registers.
  3307. return Members * NumRegs <= 8;
  3308. }
  3309. ABIArgInfo
  3310. PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
  3311. Ty = useFirstFieldIfTransparentUnion(Ty);
  3312. if (Ty->isAnyComplexType())
  3313. return ABIArgInfo::getDirect();
  3314. // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
  3315. // or via reference (larger than 16 bytes).
  3316. if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
  3317. uint64_t Size = getContext().getTypeSize(Ty);
  3318. if (Size > 128)
  3319. return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
  3320. else if (Size < 128) {
  3321. llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
  3322. return ABIArgInfo::getDirect(CoerceTy);
  3323. }
  3324. }
  3325. if (isAggregateTypeForABI(Ty)) {
  3326. if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
  3327. return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
  3328. uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
  3329. uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
  3330. // ELFv2 homogeneous aggregates are passed as array types.
  3331. const Type *Base = nullptr;
  3332. uint64_t Members = 0;
  3333. if (Kind == ELFv2 &&
  3334. isHomogeneousAggregate(Ty, Base, Members)) {
  3335. llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
  3336. llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
  3337. return ABIArgInfo::getDirect(CoerceTy);
  3338. }
  3339. // If an aggregate may end up fully in registers, we do not
  3340. // use the ByVal method, but pass the aggregate as array.
  3341. // This is usually beneficial since we avoid forcing the
  3342. // back-end to store the argument to memory.
  3343. uint64_t Bits = getContext().getTypeSize(Ty);
  3344. if (Bits > 0 && Bits <= 8 * GPRBits) {
  3345. llvm::Type *CoerceTy;
  3346. // Types up to 8 bytes are passed as integer type (which will be
  3347. // properly aligned in the argument save area doubleword).
  3348. if (Bits <= GPRBits)
  3349. CoerceTy = llvm::IntegerType::get(getVMContext(),
  3350. llvm::RoundUpToAlignment(Bits, 8));
  3351. // Larger types are passed as arrays, with the base type selected
  3352. // according to the required alignment in the save area.
  3353. else {
  3354. uint64_t RegBits = ABIAlign * 8;
  3355. uint64_t NumRegs = llvm::RoundUpToAlignment(Bits, RegBits) / RegBits;
  3356. llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
  3357. CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
  3358. }
  3359. return ABIArgInfo::getDirect(CoerceTy);
  3360. }
  3361. // All other aggregates are passed ByVal.
  3362. return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
  3363. /*ByVal=*/true,
  3364. /*Realign=*/TyAlign > ABIAlign);
  3365. }
  3366. return (isPromotableTypeForABI(Ty) ?
  3367. ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
  3368. }
  3369. ABIArgInfo
  3370. PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
  3371. if (RetTy->isVoidType())
  3372. return ABIArgInfo::getIgnore();
  3373. if (RetTy->isAnyComplexType())
  3374. return ABIArgInfo::getDirect();
  3375. // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
  3376. // or via reference (larger than 16 bytes).
  3377. if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
  3378. uint64_t Size = getContext().getTypeSize(RetTy);
  3379. if (Size > 128)
  3380. return getNaturalAlignIndirect(RetTy);
  3381. else if (Size < 128) {
  3382. llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
  3383. return ABIArgInfo::getDirect(CoerceTy);
  3384. }
  3385. }
  3386. if (isAggregateTypeForABI(RetTy)) {
  3387. // ELFv2 homogeneous aggregates are returned as array types.
  3388. const Type *Base = nullptr;
  3389. uint64_t Members = 0;
  3390. if (Kind == ELFv2 &&
  3391. isHomogeneousAggregate(RetTy, Base, Members)) {
  3392. llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
  3393. llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
  3394. return ABIArgInfo::getDirect(CoerceTy);
  3395. }
  3396. // ELFv2 small aggregates are returned in up to two registers.
  3397. uint64_t Bits = getContext().getTypeSize(RetTy);
  3398. if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
  3399. if (Bits == 0)
  3400. return ABIArgInfo::getIgnore();
  3401. llvm::Type *CoerceTy;
  3402. if (Bits > GPRBits) {
  3403. CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
  3404. CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
  3405. } else
  3406. CoerceTy = llvm::IntegerType::get(getVMContext(),
  3407. llvm::RoundUpToAlignment(Bits, 8));
  3408. return ABIArgInfo::getDirect(CoerceTy);
  3409. }
  3410. // All other aggregates are returned indirectly.
  3411. return getNaturalAlignIndirect(RetTy);
  3412. }
  3413. return (isPromotableTypeForABI(RetTy) ?
  3414. ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
  3415. }
  3416. // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
  3417. Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  3418. QualType Ty) const {
  3419. auto TypeInfo = getContext().getTypeInfoInChars(Ty);
  3420. TypeInfo.second = getParamTypeAlignment(Ty);
  3421. CharUnits SlotSize = CharUnits::fromQuantity(8);
  3422. // If we have a complex type and the base type is smaller than 8 bytes,
  3423. // the ABI calls for the real and imaginary parts to be right-adjusted
  3424. // in separate doublewords. However, Clang expects us to produce a
  3425. // pointer to a structure with the two parts packed tightly. So generate
  3426. // loads of the real and imaginary parts relative to the va_list pointer,
  3427. // and store them to a temporary structure.
  3428. if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
  3429. CharUnits EltSize = TypeInfo.first / 2;
  3430. if (EltSize < SlotSize) {
  3431. Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
  3432. SlotSize * 2, SlotSize,
  3433. SlotSize, /*AllowHigher*/ true);
  3434. Address RealAddr = Addr;
  3435. Address ImagAddr = RealAddr;
  3436. if (CGF.CGM.getDataLayout().isBigEndian()) {
  3437. RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
  3438. SlotSize - EltSize);
  3439. ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
  3440. 2 * SlotSize - EltSize);
  3441. } else {
  3442. ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
  3443. }
  3444. llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
  3445. RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
  3446. ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
  3447. llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
  3448. llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
  3449. Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
  3450. CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
  3451. /*init*/ true);
  3452. return Temp;
  3453. }
  3454. }
  3455. // Otherwise, just use the general rule.
  3456. return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
  3457. TypeInfo, SlotSize, /*AllowHigher*/ true);
  3458. }
  3459. static bool
  3460. PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
  3461. llvm::Value *Address) {
  3462. // This is calculated from the LLVM and GCC tables and verified
  3463. // against gcc output. AFAIK all ABIs use the same encoding.
  3464. CodeGen::CGBuilderTy &Builder = CGF.Builder;
  3465. llvm::IntegerType *i8 = CGF.Int8Ty;
  3466. llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
  3467. llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
  3468. llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
  3469. // 0-31: r0-31, the 8-byte general-purpose registers
  3470. AssignToArrayRange(Builder, Address, Eight8, 0, 31);
  3471. // 32-63: fp0-31, the 8-byte floating-point registers
  3472. AssignToArrayRange(Builder, Address, Eight8, 32, 63);
  3473. // 64-76 are various 4-byte special-purpose registers:
  3474. // 64: mq
  3475. // 65: lr
  3476. // 66: ctr
  3477. // 67: ap
  3478. // 68-75 cr0-7
  3479. // 76: xer
  3480. AssignToArrayRange(Builder, Address, Four8, 64, 76);
  3481. // 77-108: v0-31, the 16-byte vector registers
  3482. AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
  3483. // 109: vrsave
  3484. // 110: vscr
  3485. // 111: spe_acc
  3486. // 112: spefscr
  3487. // 113: sfp
  3488. AssignToArrayRange(Builder, Address, Four8, 109, 113);
  3489. return false;
  3490. }
  3491. bool
  3492. PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
  3493. CodeGen::CodeGenFunction &CGF,
  3494. llvm::Value *Address) const {
  3495. return PPC64_initDwarfEHRegSizeTable(CGF, Address);
  3496. }
  3497. bool
  3498. PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
  3499. llvm::Value *Address) const {
  3500. return PPC64_initDwarfEHRegSizeTable(CGF, Address);
  3501. }
  3502. //===----------------------------------------------------------------------===//
  3503. // AArch64 ABI Implementation
  3504. //===----------------------------------------------------------------------===//
  3505. namespace {
  3506. class AArch64ABIInfo : public ABIInfo {
  3507. public:
  3508. enum ABIKind {
  3509. AAPCS = 0,
  3510. DarwinPCS
  3511. };
  3512. private:
  3513. ABIKind Kind;
  3514. public:
  3515. AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
  3516. private:
  3517. ABIKind getABIKind() const { return Kind; }
  3518. bool isDarwinPCS() const { return Kind == DarwinPCS; }
  3519. ABIArgInfo classifyReturnType(QualType RetTy) const;
  3520. ABIArgInfo classifyArgumentType(QualType RetTy) const;
  3521. bool isHomogeneousAggregateBaseType(QualType Ty) const override;
  3522. bool isHomogeneousAggregateSmallEnough(const Type *Ty,
  3523. uint64_t Members) const override;
  3524. bool isIllegalVectorType(QualType Ty) const;
  3525. void computeInfo(CGFunctionInfo &FI) const override {
  3526. if (!getCXXABI().classifyReturnType(FI))
  3527. FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
  3528. for (auto &it : FI.arguments())
  3529. it.info = classifyArgumentType(it.type);
  3530. }
  3531. Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
  3532. CodeGenFunction &CGF) const;
  3533. Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
  3534. CodeGenFunction &CGF) const;
  3535. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  3536. QualType Ty) const override {
  3537. return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
  3538. : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
  3539. }
  3540. };
  3541. class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
  3542. public:
  3543. AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
  3544. : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
  3545. StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
  3546. return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
  3547. }
  3548. int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
  3549. return 31;
  3550. }
  3551. bool doesReturnSlotInterfereWithArgs() const override { return false; }
  3552. };
  3553. }
  3554. ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
  3555. Ty = useFirstFieldIfTransparentUnion(Ty);
  3556. // Handle illegal vector types here.
  3557. if (isIllegalVectorType(Ty)) {
  3558. uint64_t Size = getContext().getTypeSize(Ty);
  3559. if (Size <= 32) {
  3560. llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
  3561. return ABIArgInfo::getDirect(ResType);
  3562. }
  3563. if (Size == 64) {
  3564. llvm::Type *ResType =
  3565. llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
  3566. return ABIArgInfo::getDirect(ResType);
  3567. }
  3568. if (Size == 128) {
  3569. llvm::Type *ResType =
  3570. llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
  3571. return ABIArgInfo::getDirect(ResType);
  3572. }
  3573. return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
  3574. }
  3575. if (!isAggregateTypeForABI(Ty)) {
  3576. // Treat an enum type as its underlying type.
  3577. if (const EnumType *EnumTy = Ty->getAs<EnumType>())
  3578. Ty = EnumTy->getDecl()->getIntegerType();
  3579. return (Ty->isPromotableIntegerType() && isDarwinPCS()
  3580. ? ABIArgInfo::getExtend()
  3581. : ABIArgInfo::getDirect());
  3582. }
  3583. // Structures with either a non-trivial destructor or a non-trivial
  3584. // copy constructor are always indirect.
  3585. if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
  3586. return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
  3587. CGCXXABI::RAA_DirectInMemory);
  3588. }
  3589. // Empty records are always ignored on Darwin, but actually passed in C++ mode
  3590. // elsewhere for GNU compatibility.
  3591. if (isEmptyRecord(getContext(), Ty, true)) {
  3592. if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
  3593. return ABIArgInfo::getIgnore();
  3594. return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
  3595. }
  3596. // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
  3597. const Type *Base = nullptr;
  3598. uint64_t Members = 0;
  3599. if (isHomogeneousAggregate(Ty, Base, Members)) {
  3600. return ABIArgInfo::getDirect(
  3601. llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
  3602. }
  3603. // Aggregates <= 16 bytes are passed directly in registers or on the stack.
  3604. uint64_t Size = getContext().getTypeSize(Ty);
  3605. if (Size <= 128) {
  3606. unsigned Alignment = getContext().getTypeAlign(Ty);
  3607. Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
  3608. // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
  3609. // For aggregates with 16-byte alignment, we use i128.
  3610. if (Alignment < 128 && Size == 128) {
  3611. llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
  3612. return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
  3613. }
  3614. return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
  3615. }
  3616. return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
  3617. }
  3618. ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
  3619. if (RetTy->isVoidType())
  3620. return ABIArgInfo::getIgnore();
  3621. // Large vector types should be returned via memory.
  3622. if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
  3623. return getNaturalAlignIndirect(RetTy);
  3624. if (!isAggregateTypeForABI(RetTy)) {
  3625. // Treat an enum type as its underlying type.
  3626. if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
  3627. RetTy = EnumTy->getDecl()->getIntegerType();
  3628. return (RetTy->isPromotableIntegerType() && isDarwinPCS()
  3629. ? ABIArgInfo::getExtend()
  3630. : ABIArgInfo::getDirect());
  3631. }
  3632. if (isEmptyRecord(getContext(), RetTy, true))
  3633. return ABIArgInfo::getIgnore();
  3634. const Type *Base = nullptr;
  3635. uint64_t Members = 0;
  3636. if (isHomogeneousAggregate(RetTy, Base, Members))
  3637. // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
  3638. return ABIArgInfo::getDirect();
  3639. // Aggregates <= 16 bytes are returned directly in registers or on the stack.
  3640. uint64_t Size = getContext().getTypeSize(RetTy);
  3641. if (Size <= 128) {
  3642. unsigned Alignment = getContext().getTypeAlign(RetTy);
  3643. Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
  3644. // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
  3645. // For aggregates with 16-byte alignment, we use i128.
  3646. if (Alignment < 128 && Size == 128) {
  3647. llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
  3648. return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
  3649. }
  3650. return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
  3651. }
  3652. return getNaturalAlignIndirect(RetTy);
  3653. }
  3654. /// isIllegalVectorType - check whether the vector type is legal for AArch64.
  3655. bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
  3656. if (const VectorType *VT = Ty->getAs<VectorType>()) {
  3657. // Check whether VT is legal.
  3658. unsigned NumElements = VT->getNumElements();
  3659. uint64_t Size = getContext().getTypeSize(VT);
  3660. // NumElements should be power of 2 between 1 and 16.
  3661. if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
  3662. return true;
  3663. return Size != 64 && (Size != 128 || NumElements == 1);
  3664. }
  3665. return false;
  3666. }
  3667. bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
  3668. // Homogeneous aggregates for AAPCS64 must have base types of a floating
  3669. // point type or a short-vector type. This is the same as the 32-bit ABI,
  3670. // but with the difference that any floating-point type is allowed,
  3671. // including __fp16.
  3672. if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
  3673. if (BT->isFloatingPoint())
  3674. return true;
  3675. } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
  3676. unsigned VecSize = getContext().getTypeSize(VT);
  3677. if (VecSize == 64 || VecSize == 128)
  3678. return true;
  3679. }
  3680. return false;
  3681. }
  3682. bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
  3683. uint64_t Members) const {
  3684. return Members <= 4;
  3685. }
  3686. Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
  3687. QualType Ty,
  3688. CodeGenFunction &CGF) const {
  3689. ABIArgInfo AI = classifyArgumentType(Ty);
  3690. bool IsIndirect = AI.isIndirect();
  3691. llvm::Type *BaseTy = CGF.ConvertType(Ty);
  3692. if (IsIndirect)
  3693. BaseTy = llvm::PointerType::getUnqual(BaseTy);
  3694. else if (AI.getCoerceToType())
  3695. BaseTy = AI.getCoerceToType();
  3696. unsigned NumRegs = 1;
  3697. if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
  3698. BaseTy = ArrTy->getElementType();
  3699. NumRegs = ArrTy->getNumElements();
  3700. }
  3701. bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
  3702. // The AArch64 va_list type and handling is specified in the Procedure Call
  3703. // Standard, section B.4:
  3704. //
  3705. // struct {
  3706. // void *__stack;
  3707. // void *__gr_top;
  3708. // void *__vr_top;
  3709. // int __gr_offs;
  3710. // int __vr_offs;
  3711. // };
  3712. llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
  3713. llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
  3714. llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
  3715. llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
  3716. auto TyInfo = getContext().getTypeInfoInChars(Ty);
  3717. CharUnits TyAlign = TyInfo.second;
  3718. Address reg_offs_p = Address::invalid();
  3719. llvm::Value *reg_offs = nullptr;
  3720. int reg_top_index;
  3721. CharUnits reg_top_offset;
  3722. int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
  3723. if (!IsFPR) {
  3724. // 3 is the field number of __gr_offs
  3725. reg_offs_p =
  3726. CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
  3727. "gr_offs_p");
  3728. reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
  3729. reg_top_index = 1; // field number for __gr_top
  3730. reg_top_offset = CharUnits::fromQuantity(8);
  3731. RegSize = llvm::RoundUpToAlignment(RegSize, 8);
  3732. } else {
  3733. // 4 is the field number of __vr_offs.
  3734. reg_offs_p =
  3735. CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
  3736. "vr_offs_p");
  3737. reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
  3738. reg_top_index = 2; // field number for __vr_top
  3739. reg_top_offset = CharUnits::fromQuantity(16);
  3740. RegSize = 16 * NumRegs;
  3741. }
  3742. //=======================================
  3743. // Find out where argument was passed
  3744. //=======================================
  3745. // If reg_offs >= 0 we're already using the stack for this type of
  3746. // argument. We don't want to keep updating reg_offs (in case it overflows,
  3747. // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
  3748. // whatever they get).
  3749. llvm::Value *UsingStack = nullptr;
  3750. UsingStack = CGF.Builder.CreateICmpSGE(
  3751. reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
  3752. CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
  3753. // Otherwise, at least some kind of argument could go in these registers, the
  3754. // question is whether this particular type is too big.
  3755. CGF.EmitBlock(MaybeRegBlock);
  3756. // Integer arguments may need to correct register alignment (for example a
  3757. // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
  3758. // align __gr_offs to calculate the potential address.
  3759. if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
  3760. int Align = TyAlign.getQuantity();
  3761. reg_offs = CGF.Builder.CreateAdd(
  3762. reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
  3763. "align_regoffs");
  3764. reg_offs = CGF.Builder.CreateAnd(
  3765. reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
  3766. "aligned_regoffs");
  3767. }
  3768. // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
  3769. // The fact that this is done unconditionally reflects the fact that
  3770. // allocating an argument to the stack also uses up all the remaining
  3771. // registers of the appropriate kind.
  3772. llvm::Value *NewOffset = nullptr;
  3773. NewOffset = CGF.Builder.CreateAdd(
  3774. reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
  3775. CGF.Builder.CreateStore(NewOffset, reg_offs_p);
  3776. // Now we're in a position to decide whether this argument really was in
  3777. // registers or not.
  3778. llvm::Value *InRegs = nullptr;
  3779. InRegs = CGF.Builder.CreateICmpSLE(
  3780. NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
  3781. CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
  3782. //=======================================
  3783. // Argument was in registers
  3784. //=======================================
  3785. // Now we emit the code for if the argument was originally passed in
  3786. // registers. First start the appropriate block:
  3787. CGF.EmitBlock(InRegBlock);
  3788. llvm::Value *reg_top = nullptr;
  3789. Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
  3790. reg_top_offset, "reg_top_p");
  3791. reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
  3792. Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
  3793. CharUnits::fromQuantity(IsFPR ? 16 : 8));
  3794. Address RegAddr = Address::invalid();
  3795. llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
  3796. if (IsIndirect) {
  3797. // If it's been passed indirectly (actually a struct), whatever we find from
  3798. // stored registers or on the stack will actually be a struct **.
  3799. MemTy = llvm::PointerType::getUnqual(MemTy);
  3800. }
  3801. const Type *Base = nullptr;
  3802. uint64_t NumMembers = 0;
  3803. bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
  3804. if (IsHFA && NumMembers > 1) {
  3805. // Homogeneous aggregates passed in registers will have their elements split
  3806. // and stored 16-bytes apart regardless of size (they're notionally in qN,
  3807. // qN+1, ...). We reload and store into a temporary local variable
  3808. // contiguously.
  3809. assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
  3810. auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
  3811. llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
  3812. llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
  3813. Address Tmp = CGF.CreateTempAlloca(HFATy,
  3814. std::max(TyAlign, BaseTyInfo.second));
  3815. // On big-endian platforms, the value will be right-aligned in its slot.
  3816. int Offset = 0;
  3817. if (CGF.CGM.getDataLayout().isBigEndian() &&
  3818. BaseTyInfo.first.getQuantity() < 16)
  3819. Offset = 16 - BaseTyInfo.first.getQuantity();
  3820. for (unsigned i = 0; i < NumMembers; ++i) {
  3821. CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
  3822. Address LoadAddr =
  3823. CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
  3824. LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
  3825. Address StoreAddr =
  3826. CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
  3827. llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
  3828. CGF.Builder.CreateStore(Elem, StoreAddr);
  3829. }
  3830. RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
  3831. } else {
  3832. // Otherwise the object is contiguous in memory.
  3833. // It might be right-aligned in its slot.
  3834. CharUnits SlotSize = BaseAddr.getAlignment();
  3835. if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
  3836. (IsHFA || !isAggregateTypeForABI(Ty)) &&
  3837. TyInfo.first < SlotSize) {
  3838. CharUnits Offset = SlotSize - TyInfo.first;
  3839. BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
  3840. }
  3841. RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
  3842. }
  3843. CGF.EmitBranch(ContBlock);
  3844. //=======================================
  3845. // Argument was on the stack
  3846. //=======================================
  3847. CGF.EmitBlock(OnStackBlock);
  3848. Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
  3849. CharUnits::Zero(), "stack_p");
  3850. llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
  3851. // Again, stack arguments may need realignment. In this case both integer and
  3852. // floating-point ones might be affected.
  3853. if (!IsIndirect && TyAlign.getQuantity() > 8) {
  3854. int Align = TyAlign.getQuantity();
  3855. OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
  3856. OnStackPtr = CGF.Builder.CreateAdd(
  3857. OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
  3858. "align_stack");
  3859. OnStackPtr = CGF.Builder.CreateAnd(
  3860. OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
  3861. "align_stack");
  3862. OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
  3863. }
  3864. Address OnStackAddr(OnStackPtr,
  3865. std::max(CharUnits::fromQuantity(8), TyAlign));
  3866. // All stack slots are multiples of 8 bytes.
  3867. CharUnits StackSlotSize = CharUnits::fromQuantity(8);
  3868. CharUnits StackSize;
  3869. if (IsIndirect)
  3870. StackSize = StackSlotSize;
  3871. else
  3872. StackSize = TyInfo.first.RoundUpToAlignment(StackSlotSize);
  3873. llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
  3874. llvm::Value *NewStack =
  3875. CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
  3876. // Write the new value of __stack for the next call to va_arg
  3877. CGF.Builder.CreateStore(NewStack, stack_p);
  3878. if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
  3879. TyInfo.first < StackSlotSize) {
  3880. CharUnits Offset = StackSlotSize - TyInfo.first;
  3881. OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
  3882. }
  3883. OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
  3884. CGF.EmitBranch(ContBlock);
  3885. //=======================================
  3886. // Tidy up
  3887. //=======================================
  3888. CGF.EmitBlock(ContBlock);
  3889. Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
  3890. OnStackAddr, OnStackBlock, "vaargs.addr");
  3891. if (IsIndirect)
  3892. return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
  3893. TyInfo.second);
  3894. return ResAddr;
  3895. }
  3896. Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
  3897. CodeGenFunction &CGF) const {
  3898. // The backend's lowering doesn't support va_arg for aggregates or
  3899. // illegal vector types. Lower VAArg here for these cases and use
  3900. // the LLVM va_arg instruction for everything else.
  3901. if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
  3902. return Address::invalid();
  3903. CharUnits SlotSize = CharUnits::fromQuantity(8);
  3904. // Empty records are ignored for parameter passing purposes.
  3905. if (isEmptyRecord(getContext(), Ty, true)) {
  3906. Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
  3907. Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
  3908. return Addr;
  3909. }
  3910. // The size of the actual thing passed, which might end up just
  3911. // being a pointer for indirect types.
  3912. auto TyInfo = getContext().getTypeInfoInChars(Ty);
  3913. // Arguments bigger than 16 bytes which aren't homogeneous
  3914. // aggregates should be passed indirectly.
  3915. bool IsIndirect = false;
  3916. if (TyInfo.first.getQuantity() > 16) {
  3917. const Type *Base = nullptr;
  3918. uint64_t Members = 0;
  3919. IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
  3920. }
  3921. return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
  3922. TyInfo, SlotSize, /*AllowHigherAlign*/ true);
  3923. }
  3924. //===----------------------------------------------------------------------===//
  3925. // ARM ABI Implementation
  3926. //===----------------------------------------------------------------------===//
  3927. namespace {
  3928. class ARMABIInfo : public ABIInfo {
  3929. public:
  3930. enum ABIKind {
  3931. APCS = 0,
  3932. AAPCS = 1,
  3933. AAPCS_VFP
  3934. };
  3935. private:
  3936. ABIKind Kind;
  3937. public:
  3938. ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {
  3939. setCCs();
  3940. }
  3941. bool isEABI() const {
  3942. switch (getTarget().getTriple().getEnvironment()) {
  3943. case llvm::Triple::Android:
  3944. case llvm::Triple::EABI:
  3945. case llvm::Triple::EABIHF:
  3946. case llvm::Triple::GNUEABI:
  3947. case llvm::Triple::GNUEABIHF:
  3948. return true;
  3949. default:
  3950. return false;
  3951. }
  3952. }
  3953. bool isEABIHF() const {
  3954. switch (getTarget().getTriple().getEnvironment()) {
  3955. case llvm::Triple::EABIHF:
  3956. case llvm::Triple::GNUEABIHF:
  3957. return true;
  3958. default:
  3959. return false;
  3960. }
  3961. }
  3962. ABIKind getABIKind() const { return Kind; }
  3963. private:
  3964. ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
  3965. ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
  3966. bool isIllegalVectorType(QualType Ty) const;
  3967. bool isHomogeneousAggregateBaseType(QualType Ty) const override;
  3968. bool isHomogeneousAggregateSmallEnough(const Type *Ty,
  3969. uint64_t Members) const override;
  3970. void computeInfo(CGFunctionInfo &FI) const override;
  3971. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  3972. QualType Ty) const override;
  3973. llvm::CallingConv::ID getLLVMDefaultCC() const;
  3974. llvm::CallingConv::ID getABIDefaultCC() const;
  3975. void setCCs();
  3976. };
  3977. class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
  3978. public:
  3979. ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
  3980. :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
  3981. const ARMABIInfo &getABIInfo() const {
  3982. return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
  3983. }
  3984. int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
  3985. return 13;
  3986. }
  3987. StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
  3988. return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
  3989. }
  3990. bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
  3991. llvm::Value *Address) const override {
  3992. llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
  3993. // 0-15 are the 16 integer registers.
  3994. AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
  3995. return false;
  3996. }
  3997. unsigned getSizeOfUnwindException() const override {
  3998. if (getABIInfo().isEABI()) return 88;
  3999. return TargetCodeGenInfo::getSizeOfUnwindException();
  4000. }
  4001. void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
  4002. CodeGen::CodeGenModule &CGM) const override {
  4003. const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
  4004. if (!FD)
  4005. return;
  4006. const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
  4007. if (!Attr)
  4008. return;
  4009. const char *Kind;
  4010. switch (Attr->getInterrupt()) {
  4011. case ARMInterruptAttr::Generic: Kind = ""; break;
  4012. case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
  4013. case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
  4014. case ARMInterruptAttr::SWI: Kind = "SWI"; break;
  4015. case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
  4016. case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
  4017. }
  4018. llvm::Function *Fn = cast<llvm::Function>(GV);
  4019. Fn->addFnAttr("interrupt", Kind);
  4020. if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
  4021. return;
  4022. // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
  4023. // however this is not necessarily true on taking any interrupt. Instruct
  4024. // the backend to perform a realignment as part of the function prologue.
  4025. llvm::AttrBuilder B;
  4026. B.addStackAlignmentAttr(8);
  4027. Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
  4028. llvm::AttributeSet::get(CGM.getLLVMContext(),
  4029. llvm::AttributeSet::FunctionIndex,
  4030. B));
  4031. }
  4032. };
  4033. class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
  4034. void addStackProbeSizeTargetAttribute(const Decl *D, llvm::GlobalValue *GV,
  4035. CodeGen::CodeGenModule &CGM) const;
  4036. public:
  4037. WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
  4038. : ARMTargetCodeGenInfo(CGT, K) {}
  4039. void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
  4040. CodeGen::CodeGenModule &CGM) const override;
  4041. };
  4042. void WindowsARMTargetCodeGenInfo::addStackProbeSizeTargetAttribute(
  4043. const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
  4044. if (!isa<FunctionDecl>(D))
  4045. return;
  4046. if (CGM.getCodeGenOpts().StackProbeSize == 4096)
  4047. return;
  4048. llvm::Function *F = cast<llvm::Function>(GV);
  4049. F->addFnAttr("stack-probe-size",
  4050. llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
  4051. }
  4052. void WindowsARMTargetCodeGenInfo::setTargetAttributes(
  4053. const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
  4054. ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
  4055. addStackProbeSizeTargetAttribute(D, GV, CGM);
  4056. }
  4057. }
  4058. void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
  4059. if (!getCXXABI().classifyReturnType(FI))
  4060. FI.getReturnInfo() =
  4061. classifyReturnType(FI.getReturnType(), FI.isVariadic());
  4062. for (auto &I : FI.arguments())
  4063. I.info = classifyArgumentType(I.type, FI.isVariadic());
  4064. // Always honor user-specified calling convention.
  4065. if (FI.getCallingConvention() != llvm::CallingConv::C)
  4066. return;
  4067. llvm::CallingConv::ID cc = getRuntimeCC();
  4068. if (cc != llvm::CallingConv::C)
  4069. FI.setEffectiveCallingConvention(cc);
  4070. }
  4071. /// Return the default calling convention that LLVM will use.
  4072. llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
  4073. // The default calling convention that LLVM will infer.
  4074. if (isEABIHF())
  4075. return llvm::CallingConv::ARM_AAPCS_VFP;
  4076. else if (isEABI())
  4077. return llvm::CallingConv::ARM_AAPCS;
  4078. else
  4079. return llvm::CallingConv::ARM_APCS;
  4080. }
  4081. /// Return the calling convention that our ABI would like us to use
  4082. /// as the C calling convention.
  4083. llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
  4084. switch (getABIKind()) {
  4085. case APCS: return llvm::CallingConv::ARM_APCS;
  4086. case AAPCS: return llvm::CallingConv::ARM_AAPCS;
  4087. case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
  4088. }
  4089. llvm_unreachable("bad ABI kind");
  4090. }
  4091. void ARMABIInfo::setCCs() {
  4092. assert(getRuntimeCC() == llvm::CallingConv::C);
  4093. // Don't muddy up the IR with a ton of explicit annotations if
  4094. // they'd just match what LLVM will infer from the triple.
  4095. llvm::CallingConv::ID abiCC = getABIDefaultCC();
  4096. if (abiCC != getLLVMDefaultCC())
  4097. RuntimeCC = abiCC;
  4098. BuiltinCC = (getABIKind() == APCS ?
  4099. llvm::CallingConv::ARM_APCS : llvm::CallingConv::ARM_AAPCS);
  4100. }
  4101. ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
  4102. bool isVariadic) const {
  4103. // 6.1.2.1 The following argument types are VFP CPRCs:
  4104. // A single-precision floating-point type (including promoted
  4105. // half-precision types); A double-precision floating-point type;
  4106. // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
  4107. // with a Base Type of a single- or double-precision floating-point type,
  4108. // 64-bit containerized vectors or 128-bit containerized vectors with one
  4109. // to four Elements.
  4110. bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
  4111. Ty = useFirstFieldIfTransparentUnion(Ty);
  4112. // Handle illegal vector types here.
  4113. if (isIllegalVectorType(Ty)) {
  4114. uint64_t Size = getContext().getTypeSize(Ty);
  4115. if (Size <= 32) {
  4116. llvm::Type *ResType =
  4117. llvm::Type::getInt32Ty(getVMContext());
  4118. return ABIArgInfo::getDirect(ResType);
  4119. }
  4120. if (Size == 64) {
  4121. llvm::Type *ResType = llvm::VectorType::get(
  4122. llvm::Type::getInt32Ty(getVMContext()), 2);
  4123. return ABIArgInfo::getDirect(ResType);
  4124. }
  4125. if (Size == 128) {
  4126. llvm::Type *ResType = llvm::VectorType::get(
  4127. llvm::Type::getInt32Ty(getVMContext()), 4);
  4128. return ABIArgInfo::getDirect(ResType);
  4129. }
  4130. return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
  4131. }
  4132. // __fp16 gets passed as if it were an int or float, but with the top 16 bits
  4133. // unspecified. This is not done for OpenCL as it handles the half type
  4134. // natively, and does not need to interwork with AAPCS code.
  4135. if (Ty->isHalfType() && !getContext().getLangOpts().OpenCL) {
  4136. llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
  4137. llvm::Type::getFloatTy(getVMContext()) :
  4138. llvm::Type::getInt32Ty(getVMContext());
  4139. return ABIArgInfo::getDirect(ResType);
  4140. }
  4141. if (!isAggregateTypeForABI(Ty)) {
  4142. // Treat an enum type as its underlying type.
  4143. if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
  4144. Ty = EnumTy->getDecl()->getIntegerType();
  4145. }
  4146. return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
  4147. : ABIArgInfo::getDirect());
  4148. }
  4149. if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
  4150. return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
  4151. }
  4152. // Ignore empty records.
  4153. if (isEmptyRecord(getContext(), Ty, true))
  4154. return ABIArgInfo::getIgnore();
  4155. if (IsEffectivelyAAPCS_VFP) {
  4156. // Homogeneous Aggregates need to be expanded when we can fit the aggregate
  4157. // into VFP registers.
  4158. const Type *Base = nullptr;
  4159. uint64_t Members = 0;
  4160. if (isHomogeneousAggregate(Ty, Base, Members)) {
  4161. assert(Base && "Base class should be set for homogeneous aggregate");
  4162. // Base can be a floating-point or a vector.
  4163. return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
  4164. }
  4165. }
  4166. // Support byval for ARM.
  4167. // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
  4168. // most 8-byte. We realign the indirect argument if type alignment is bigger
  4169. // than ABI alignment.
  4170. uint64_t ABIAlign = 4;
  4171. uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
  4172. if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
  4173. getABIKind() == ARMABIInfo::AAPCS)
  4174. ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
  4175. if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
  4176. return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
  4177. /*ByVal=*/true,
  4178. /*Realign=*/TyAlign > ABIAlign);
  4179. }
  4180. // Otherwise, pass by coercing to a structure of the appropriate size.
  4181. llvm::Type* ElemTy;
  4182. unsigned SizeRegs;
  4183. // FIXME: Try to match the types of the arguments more accurately where
  4184. // we can.
  4185. if (getContext().getTypeAlign(Ty) <= 32) {
  4186. ElemTy = llvm::Type::getInt32Ty(getVMContext());
  4187. SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
  4188. } else {
  4189. ElemTy = llvm::Type::getInt64Ty(getVMContext());
  4190. SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
  4191. }
  4192. return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
  4193. }
  4194. static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
  4195. llvm::LLVMContext &VMContext) {
  4196. // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
  4197. // is called integer-like if its size is less than or equal to one word, and
  4198. // the offset of each of its addressable sub-fields is zero.
  4199. uint64_t Size = Context.getTypeSize(Ty);
  4200. // Check that the type fits in a word.
  4201. if (Size > 32)
  4202. return false;
  4203. // FIXME: Handle vector types!
  4204. if (Ty->isVectorType())
  4205. return false;
  4206. // Float types are never treated as "integer like".
  4207. if (Ty->isRealFloatingType())
  4208. return false;
  4209. // If this is a builtin or pointer type then it is ok.
  4210. if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
  4211. return true;
  4212. // Small complex integer types are "integer like".
  4213. if (const ComplexType *CT = Ty->getAs<ComplexType>())
  4214. return isIntegerLikeType(CT->getElementType(), Context, VMContext);
  4215. // Single element and zero sized arrays should be allowed, by the definition
  4216. // above, but they are not.
  4217. // Otherwise, it must be a record type.
  4218. const RecordType *RT = Ty->getAs<RecordType>();
  4219. if (!RT) return false;
  4220. // Ignore records with flexible arrays.
  4221. const RecordDecl *RD = RT->getDecl();
  4222. if (RD->hasFlexibleArrayMember())
  4223. return false;
  4224. // Check that all sub-fields are at offset 0, and are themselves "integer
  4225. // like".
  4226. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  4227. bool HadField = false;
  4228. unsigned idx = 0;
  4229. for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
  4230. i != e; ++i, ++idx) {
  4231. const FieldDecl *FD = *i;
  4232. // Bit-fields are not addressable, we only need to verify they are "integer
  4233. // like". We still have to disallow a subsequent non-bitfield, for example:
  4234. // struct { int : 0; int x }
  4235. // is non-integer like according to gcc.
  4236. if (FD->isBitField()) {
  4237. if (!RD->isUnion())
  4238. HadField = true;
  4239. if (!isIntegerLikeType(FD->getType(), Context, VMContext))
  4240. return false;
  4241. continue;
  4242. }
  4243. // Check if this field is at offset 0.
  4244. if (Layout.getFieldOffset(idx) != 0)
  4245. return false;
  4246. if (!isIntegerLikeType(FD->getType(), Context, VMContext))
  4247. return false;
  4248. // Only allow at most one field in a structure. This doesn't match the
  4249. // wording above, but follows gcc in situations with a field following an
  4250. // empty structure.
  4251. if (!RD->isUnion()) {
  4252. if (HadField)
  4253. return false;
  4254. HadField = true;
  4255. }
  4256. }
  4257. return true;
  4258. }
  4259. ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
  4260. bool isVariadic) const {
  4261. bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
  4262. if (RetTy->isVoidType())
  4263. return ABIArgInfo::getIgnore();
  4264. // Large vector types should be returned via memory.
  4265. if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
  4266. return getNaturalAlignIndirect(RetTy);
  4267. }
  4268. // __fp16 gets returned as if it were an int or float, but with the top 16
  4269. // bits unspecified. This is not done for OpenCL as it handles the half type
  4270. // natively, and does not need to interwork with AAPCS code.
  4271. if (RetTy->isHalfType() && !getContext().getLangOpts().OpenCL) {
  4272. llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
  4273. llvm::Type::getFloatTy(getVMContext()) :
  4274. llvm::Type::getInt32Ty(getVMContext());
  4275. return ABIArgInfo::getDirect(ResType);
  4276. }
  4277. if (!isAggregateTypeForABI(RetTy)) {
  4278. // Treat an enum type as its underlying type.
  4279. if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
  4280. RetTy = EnumTy->getDecl()->getIntegerType();
  4281. return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
  4282. : ABIArgInfo::getDirect();
  4283. }
  4284. // Are we following APCS?
  4285. if (getABIKind() == APCS) {
  4286. if (isEmptyRecord(getContext(), RetTy, false))
  4287. return ABIArgInfo::getIgnore();
  4288. // Complex types are all returned as packed integers.
  4289. //
  4290. // FIXME: Consider using 2 x vector types if the back end handles them
  4291. // correctly.
  4292. if (RetTy->isAnyComplexType())
  4293. return ABIArgInfo::getDirect(llvm::IntegerType::get(
  4294. getVMContext(), getContext().getTypeSize(RetTy)));
  4295. // Integer like structures are returned in r0.
  4296. if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
  4297. // Return in the smallest viable integer type.
  4298. uint64_t Size = getContext().getTypeSize(RetTy);
  4299. if (Size <= 8)
  4300. return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
  4301. if (Size <= 16)
  4302. return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
  4303. return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
  4304. }
  4305. // Otherwise return in memory.
  4306. return getNaturalAlignIndirect(RetTy);
  4307. }
  4308. // Otherwise this is an AAPCS variant.
  4309. if (isEmptyRecord(getContext(), RetTy, true))
  4310. return ABIArgInfo::getIgnore();
  4311. // Check for homogeneous aggregates with AAPCS-VFP.
  4312. if (IsEffectivelyAAPCS_VFP) {
  4313. const Type *Base = nullptr;
  4314. uint64_t Members;
  4315. if (isHomogeneousAggregate(RetTy, Base, Members)) {
  4316. assert(Base && "Base class should be set for homogeneous aggregate");
  4317. // Homogeneous Aggregates are returned directly.
  4318. return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
  4319. }
  4320. }
  4321. // Aggregates <= 4 bytes are returned in r0; other aggregates
  4322. // are returned indirectly.
  4323. uint64_t Size = getContext().getTypeSize(RetTy);
  4324. if (Size <= 32) {
  4325. if (getDataLayout().isBigEndian())
  4326. // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
  4327. return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
  4328. // Return in the smallest viable integer type.
  4329. if (Size <= 8)
  4330. return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
  4331. if (Size <= 16)
  4332. return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
  4333. return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
  4334. }
  4335. return getNaturalAlignIndirect(RetTy);
  4336. }
  4337. /// isIllegalVector - check whether Ty is an illegal vector type.
  4338. bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
  4339. if (const VectorType *VT = Ty->getAs<VectorType>()) {
  4340. // Check whether VT is legal.
  4341. unsigned NumElements = VT->getNumElements();
  4342. uint64_t Size = getContext().getTypeSize(VT);
  4343. // NumElements should be power of 2.
  4344. if ((NumElements & (NumElements - 1)) != 0)
  4345. return true;
  4346. // Size should be greater than 32 bits.
  4347. return Size <= 32;
  4348. }
  4349. return false;
  4350. }
  4351. bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
  4352. // Homogeneous aggregates for AAPCS-VFP must have base types of float,
  4353. // double, or 64-bit or 128-bit vectors.
  4354. if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
  4355. if (BT->getKind() == BuiltinType::Float ||
  4356. BT->getKind() == BuiltinType::Double ||
  4357. BT->getKind() == BuiltinType::LongDouble)
  4358. return true;
  4359. } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
  4360. unsigned VecSize = getContext().getTypeSize(VT);
  4361. if (VecSize == 64 || VecSize == 128)
  4362. return true;
  4363. }
  4364. return false;
  4365. }
  4366. bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
  4367. uint64_t Members) const {
  4368. return Members <= 4;
  4369. }
  4370. Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  4371. QualType Ty) const {
  4372. CharUnits SlotSize = CharUnits::fromQuantity(4);
  4373. // Empty records are ignored for parameter passing purposes.
  4374. if (isEmptyRecord(getContext(), Ty, true)) {
  4375. Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
  4376. Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
  4377. return Addr;
  4378. }
  4379. auto TyInfo = getContext().getTypeInfoInChars(Ty);
  4380. CharUnits TyAlignForABI = TyInfo.second;
  4381. // Use indirect if size of the illegal vector is bigger than 16 bytes.
  4382. bool IsIndirect = false;
  4383. if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
  4384. IsIndirect = true;
  4385. // Otherwise, bound the type's ABI alignment.
  4386. // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
  4387. // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
  4388. // Our callers should be prepared to handle an under-aligned address.
  4389. } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
  4390. getABIKind() == ARMABIInfo::AAPCS) {
  4391. TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
  4392. TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
  4393. } else {
  4394. TyAlignForABI = CharUnits::fromQuantity(4);
  4395. }
  4396. TyInfo.second = TyAlignForABI;
  4397. return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
  4398. SlotSize, /*AllowHigherAlign*/ true);
  4399. }
  4400. //===----------------------------------------------------------------------===//
  4401. // NVPTX ABI Implementation
  4402. //===----------------------------------------------------------------------===//
  4403. namespace {
  4404. class NVPTXABIInfo : public ABIInfo {
  4405. public:
  4406. NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
  4407. ABIArgInfo classifyReturnType(QualType RetTy) const;
  4408. ABIArgInfo classifyArgumentType(QualType Ty) const;
  4409. void computeInfo(CGFunctionInfo &FI) const override;
  4410. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  4411. QualType Ty) const override;
  4412. };
  4413. class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
  4414. public:
  4415. NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
  4416. : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
  4417. void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
  4418. CodeGen::CodeGenModule &M) const override;
  4419. private:
  4420. // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
  4421. // resulting MDNode to the nvvm.annotations MDNode.
  4422. static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
  4423. };
  4424. ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
  4425. if (RetTy->isVoidType())
  4426. return ABIArgInfo::getIgnore();
  4427. // note: this is different from default ABI
  4428. if (!RetTy->isScalarType())
  4429. return ABIArgInfo::getDirect();
  4430. // Treat an enum type as its underlying type.
  4431. if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
  4432. RetTy = EnumTy->getDecl()->getIntegerType();
  4433. return (RetTy->isPromotableIntegerType() ?
  4434. ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
  4435. }
  4436. ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
  4437. // Treat an enum type as its underlying type.
  4438. if (const EnumType *EnumTy = Ty->getAs<EnumType>())
  4439. Ty = EnumTy->getDecl()->getIntegerType();
  4440. // Return aggregates type as indirect by value
  4441. if (isAggregateTypeForABI(Ty))
  4442. return getNaturalAlignIndirect(Ty, /* byval */ true);
  4443. return (Ty->isPromotableIntegerType() ?
  4444. ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
  4445. }
  4446. void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
  4447. if (!getCXXABI().classifyReturnType(FI))
  4448. FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
  4449. for (auto &I : FI.arguments())
  4450. I.info = classifyArgumentType(I.type);
  4451. // Always honor user-specified calling convention.
  4452. if (FI.getCallingConvention() != llvm::CallingConv::C)
  4453. return;
  4454. FI.setEffectiveCallingConvention(getRuntimeCC());
  4455. }
  4456. Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  4457. QualType Ty) const {
  4458. llvm_unreachable("NVPTX does not support varargs");
  4459. }
  4460. void NVPTXTargetCodeGenInfo::
  4461. setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
  4462. CodeGen::CodeGenModule &M) const{
  4463. const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
  4464. if (!FD) return;
  4465. llvm::Function *F = cast<llvm::Function>(GV);
  4466. // Perform special handling in OpenCL mode
  4467. if (M.getLangOpts().OpenCL) {
  4468. // Use OpenCL function attributes to check for kernel functions
  4469. // By default, all functions are device functions
  4470. if (FD->hasAttr<OpenCLKernelAttr>()) {
  4471. // OpenCL __kernel functions get kernel metadata
  4472. // Create !{<func-ref>, metadata !"kernel", i32 1} node
  4473. addNVVMMetadata(F, "kernel", 1);
  4474. // And kernel functions are not subject to inlining
  4475. F->addFnAttr(llvm::Attribute::NoInline);
  4476. }
  4477. }
  4478. // Perform special handling in CUDA mode.
  4479. if (M.getLangOpts().CUDA) {
  4480. // CUDA __global__ functions get a kernel metadata entry. Since
  4481. // __global__ functions cannot be called from the device, we do not
  4482. // need to set the noinline attribute.
  4483. if (FD->hasAttr<CUDAGlobalAttr>()) {
  4484. // Create !{<func-ref>, metadata !"kernel", i32 1} node
  4485. addNVVMMetadata(F, "kernel", 1);
  4486. }
  4487. if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
  4488. // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
  4489. llvm::APSInt MaxThreads(32);
  4490. MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
  4491. if (MaxThreads > 0)
  4492. addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
  4493. // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
  4494. // not specified in __launch_bounds__ or if the user specified a 0 value,
  4495. // we don't have to add a PTX directive.
  4496. if (Attr->getMinBlocks()) {
  4497. llvm::APSInt MinBlocks(32);
  4498. MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
  4499. if (MinBlocks > 0)
  4500. // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
  4501. addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
  4502. }
  4503. }
  4504. }
  4505. }
  4506. void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
  4507. int Operand) {
  4508. llvm::Module *M = F->getParent();
  4509. llvm::LLVMContext &Ctx = M->getContext();
  4510. // Get "nvvm.annotations" metadata node
  4511. llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
  4512. llvm::Metadata *MDVals[] = {
  4513. llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
  4514. llvm::ConstantAsMetadata::get(
  4515. llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
  4516. // Append metadata to nvvm.annotations
  4517. MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
  4518. }
  4519. }
  4520. //===----------------------------------------------------------------------===//
  4521. // SystemZ ABI Implementation
  4522. //===----------------------------------------------------------------------===//
  4523. namespace {
  4524. class SystemZABIInfo : public ABIInfo {
  4525. bool HasVector;
  4526. public:
  4527. SystemZABIInfo(CodeGenTypes &CGT, bool HV)
  4528. : ABIInfo(CGT), HasVector(HV) {}
  4529. bool isPromotableIntegerType(QualType Ty) const;
  4530. bool isCompoundType(QualType Ty) const;
  4531. bool isVectorArgumentType(QualType Ty) const;
  4532. bool isFPArgumentType(QualType Ty) const;
  4533. QualType GetSingleElementType(QualType Ty) const;
  4534. ABIArgInfo classifyReturnType(QualType RetTy) const;
  4535. ABIArgInfo classifyArgumentType(QualType ArgTy) const;
  4536. void computeInfo(CGFunctionInfo &FI) const override {
  4537. if (!getCXXABI().classifyReturnType(FI))
  4538. FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
  4539. for (auto &I : FI.arguments())
  4540. I.info = classifyArgumentType(I.type);
  4541. }
  4542. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  4543. QualType Ty) const override;
  4544. };
  4545. class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
  4546. public:
  4547. SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
  4548. : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
  4549. };
  4550. }
  4551. bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
  4552. // Treat an enum type as its underlying type.
  4553. if (const EnumType *EnumTy = Ty->getAs<EnumType>())
  4554. Ty = EnumTy->getDecl()->getIntegerType();
  4555. // Promotable integer types are required to be promoted by the ABI.
  4556. if (Ty->isPromotableIntegerType())
  4557. return true;
  4558. // 32-bit values must also be promoted.
  4559. if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
  4560. switch (BT->getKind()) {
  4561. case BuiltinType::Int:
  4562. case BuiltinType::UInt:
  4563. return true;
  4564. default:
  4565. return false;
  4566. }
  4567. return false;
  4568. }
  4569. bool SystemZABIInfo::isCompoundType(QualType Ty) const {
  4570. return (Ty->isAnyComplexType() ||
  4571. Ty->isVectorType() ||
  4572. isAggregateTypeForABI(Ty));
  4573. }
  4574. bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
  4575. return (HasVector &&
  4576. Ty->isVectorType() &&
  4577. getContext().getTypeSize(Ty) <= 128);
  4578. }
  4579. bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
  4580. if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
  4581. switch (BT->getKind()) {
  4582. case BuiltinType::Float:
  4583. case BuiltinType::Double:
  4584. return true;
  4585. default:
  4586. return false;
  4587. }
  4588. return false;
  4589. }
  4590. QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
  4591. if (const RecordType *RT = Ty->getAsStructureType()) {
  4592. const RecordDecl *RD = RT->getDecl();
  4593. QualType Found;
  4594. // If this is a C++ record, check the bases first.
  4595. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
  4596. for (const auto &I : CXXRD->bases()) {
  4597. QualType Base = I.getType();
  4598. // Empty bases don't affect things either way.
  4599. if (isEmptyRecord(getContext(), Base, true))
  4600. continue;
  4601. if (!Found.isNull())
  4602. return Ty;
  4603. Found = GetSingleElementType(Base);
  4604. }
  4605. // Check the fields.
  4606. for (const auto *FD : RD->fields()) {
  4607. // For compatibility with GCC, ignore empty bitfields in C++ mode.
  4608. // Unlike isSingleElementStruct(), empty structure and array fields
  4609. // do count. So do anonymous bitfields that aren't zero-sized.
  4610. if (getContext().getLangOpts().CPlusPlus &&
  4611. FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
  4612. continue;
  4613. // Unlike isSingleElementStruct(), arrays do not count.
  4614. // Nested structures still do though.
  4615. if (!Found.isNull())
  4616. return Ty;
  4617. Found = GetSingleElementType(FD->getType());
  4618. }
  4619. // Unlike isSingleElementStruct(), trailing padding is allowed.
  4620. // An 8-byte aligned struct s { float f; } is passed as a double.
  4621. if (!Found.isNull())
  4622. return Found;
  4623. }
  4624. return Ty;
  4625. }
  4626. Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  4627. QualType Ty) const {
  4628. // Assume that va_list type is correct; should be pointer to LLVM type:
  4629. // struct {
  4630. // i64 __gpr;
  4631. // i64 __fpr;
  4632. // i8 *__overflow_arg_area;
  4633. // i8 *__reg_save_area;
  4634. // };
  4635. // Every non-vector argument occupies 8 bytes and is passed by preference
  4636. // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
  4637. // always passed on the stack.
  4638. Ty = getContext().getCanonicalType(Ty);
  4639. auto TyInfo = getContext().getTypeInfoInChars(Ty);
  4640. llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
  4641. llvm::Type *DirectTy = ArgTy;
  4642. ABIArgInfo AI = classifyArgumentType(Ty);
  4643. bool IsIndirect = AI.isIndirect();
  4644. bool InFPRs = false;
  4645. bool IsVector = false;
  4646. CharUnits UnpaddedSize;
  4647. CharUnits DirectAlign;
  4648. if (IsIndirect) {
  4649. DirectTy = llvm::PointerType::getUnqual(DirectTy);
  4650. UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
  4651. } else {
  4652. if (AI.getCoerceToType())
  4653. ArgTy = AI.getCoerceToType();
  4654. InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
  4655. IsVector = ArgTy->isVectorTy();
  4656. UnpaddedSize = TyInfo.first;
  4657. DirectAlign = TyInfo.second;
  4658. }
  4659. CharUnits PaddedSize = CharUnits::fromQuantity(8);
  4660. if (IsVector && UnpaddedSize > PaddedSize)
  4661. PaddedSize = CharUnits::fromQuantity(16);
  4662. assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
  4663. CharUnits Padding = (PaddedSize - UnpaddedSize);
  4664. llvm::Type *IndexTy = CGF.Int64Ty;
  4665. llvm::Value *PaddedSizeV =
  4666. llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
  4667. if (IsVector) {
  4668. // Work out the address of a vector argument on the stack.
  4669. // Vector arguments are always passed in the high bits of a
  4670. // single (8 byte) or double (16 byte) stack slot.
  4671. Address OverflowArgAreaPtr =
  4672. CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
  4673. "overflow_arg_area_ptr");
  4674. Address OverflowArgArea =
  4675. Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
  4676. TyInfo.second);
  4677. Address MemAddr =
  4678. CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
  4679. // Update overflow_arg_area_ptr pointer
  4680. llvm::Value *NewOverflowArgArea =
  4681. CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
  4682. "overflow_arg_area");
  4683. CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
  4684. return MemAddr;
  4685. }
  4686. assert(PaddedSize.getQuantity() == 8);
  4687. unsigned MaxRegs, RegCountField, RegSaveIndex;
  4688. CharUnits RegPadding;
  4689. if (InFPRs) {
  4690. MaxRegs = 4; // Maximum of 4 FPR arguments
  4691. RegCountField = 1; // __fpr
  4692. RegSaveIndex = 16; // save offset for f0
  4693. RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
  4694. } else {
  4695. MaxRegs = 5; // Maximum of 5 GPR arguments
  4696. RegCountField = 0; // __gpr
  4697. RegSaveIndex = 2; // save offset for r2
  4698. RegPadding = Padding; // values are passed in the low bits of a GPR
  4699. }
  4700. Address RegCountPtr = CGF.Builder.CreateStructGEP(
  4701. VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
  4702. "reg_count_ptr");
  4703. llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
  4704. llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
  4705. llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
  4706. "fits_in_regs");
  4707. llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
  4708. llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
  4709. llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
  4710. CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
  4711. // Emit code to load the value if it was passed in registers.
  4712. CGF.EmitBlock(InRegBlock);
  4713. // Work out the address of an argument register.
  4714. llvm::Value *ScaledRegCount =
  4715. CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
  4716. llvm::Value *RegBase =
  4717. llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
  4718. + RegPadding.getQuantity());
  4719. llvm::Value *RegOffset =
  4720. CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
  4721. Address RegSaveAreaPtr =
  4722. CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
  4723. "reg_save_area_ptr");
  4724. llvm::Value *RegSaveArea =
  4725. CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
  4726. Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
  4727. "raw_reg_addr"),
  4728. PaddedSize);
  4729. Address RegAddr =
  4730. CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
  4731. // Update the register count
  4732. llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
  4733. llvm::Value *NewRegCount =
  4734. CGF.Builder.CreateAdd(RegCount, One, "reg_count");
  4735. CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
  4736. CGF.EmitBranch(ContBlock);
  4737. // Emit code to load the value if it was passed in memory.
  4738. CGF.EmitBlock(InMemBlock);
  4739. // Work out the address of a stack argument.
  4740. Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
  4741. VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
  4742. Address OverflowArgArea =
  4743. Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
  4744. PaddedSize);
  4745. Address RawMemAddr =
  4746. CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
  4747. Address MemAddr =
  4748. CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
  4749. // Update overflow_arg_area_ptr pointer
  4750. llvm::Value *NewOverflowArgArea =
  4751. CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
  4752. "overflow_arg_area");
  4753. CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
  4754. CGF.EmitBranch(ContBlock);
  4755. // Return the appropriate result.
  4756. CGF.EmitBlock(ContBlock);
  4757. Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
  4758. MemAddr, InMemBlock, "va_arg.addr");
  4759. if (IsIndirect)
  4760. ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
  4761. TyInfo.second);
  4762. return ResAddr;
  4763. }
  4764. ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
  4765. if (RetTy->isVoidType())
  4766. return ABIArgInfo::getIgnore();
  4767. if (isVectorArgumentType(RetTy))
  4768. return ABIArgInfo::getDirect();
  4769. if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
  4770. return getNaturalAlignIndirect(RetTy);
  4771. return (isPromotableIntegerType(RetTy) ?
  4772. ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
  4773. }
  4774. ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
  4775. // Handle the generic C++ ABI.
  4776. if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
  4777. return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
  4778. // Integers and enums are extended to full register width.
  4779. if (isPromotableIntegerType(Ty))
  4780. return ABIArgInfo::getExtend();
  4781. // Handle vector types and vector-like structure types. Note that
  4782. // as opposed to float-like structure types, we do not allow any
  4783. // padding for vector-like structures, so verify the sizes match.
  4784. uint64_t Size = getContext().getTypeSize(Ty);
  4785. QualType SingleElementTy = GetSingleElementType(Ty);
  4786. if (isVectorArgumentType(SingleElementTy) &&
  4787. getContext().getTypeSize(SingleElementTy) == Size)
  4788. return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
  4789. // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
  4790. if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
  4791. return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
  4792. // Handle small structures.
  4793. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  4794. // Structures with flexible arrays have variable length, so really
  4795. // fail the size test above.
  4796. const RecordDecl *RD = RT->getDecl();
  4797. if (RD->hasFlexibleArrayMember())
  4798. return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
  4799. // The structure is passed as an unextended integer, a float, or a double.
  4800. llvm::Type *PassTy;
  4801. if (isFPArgumentType(SingleElementTy)) {
  4802. assert(Size == 32 || Size == 64);
  4803. if (Size == 32)
  4804. PassTy = llvm::Type::getFloatTy(getVMContext());
  4805. else
  4806. PassTy = llvm::Type::getDoubleTy(getVMContext());
  4807. } else
  4808. PassTy = llvm::IntegerType::get(getVMContext(), Size);
  4809. return ABIArgInfo::getDirect(PassTy);
  4810. }
  4811. // Non-structure compounds are passed indirectly.
  4812. if (isCompoundType(Ty))
  4813. return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
  4814. return ABIArgInfo::getDirect(nullptr);
  4815. }
  4816. //===----------------------------------------------------------------------===//
  4817. // MSP430 ABI Implementation
  4818. //===----------------------------------------------------------------------===//
  4819. namespace {
  4820. class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
  4821. public:
  4822. MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
  4823. : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
  4824. void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
  4825. CodeGen::CodeGenModule &M) const override;
  4826. };
  4827. }
  4828. void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
  4829. llvm::GlobalValue *GV,
  4830. CodeGen::CodeGenModule &M) const {
  4831. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
  4832. if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
  4833. // Handle 'interrupt' attribute:
  4834. llvm::Function *F = cast<llvm::Function>(GV);
  4835. // Step 1: Set ISR calling convention.
  4836. F->setCallingConv(llvm::CallingConv::MSP430_INTR);
  4837. // Step 2: Add attributes goodness.
  4838. F->addFnAttr(llvm::Attribute::NoInline);
  4839. // Step 3: Emit ISR vector alias.
  4840. unsigned Num = attr->getNumber() / 2;
  4841. llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
  4842. "__isr_" + Twine(Num), F);
  4843. }
  4844. }
  4845. }
  4846. //===----------------------------------------------------------------------===//
  4847. // MIPS ABI Implementation. This works for both little-endian and
  4848. // big-endian variants.
  4849. //===----------------------------------------------------------------------===//
  4850. namespace {
  4851. class MipsABIInfo : public ABIInfo {
  4852. bool IsO32;
  4853. unsigned MinABIStackAlignInBytes, StackAlignInBytes;
  4854. void CoerceToIntArgs(uint64_t TySize,
  4855. SmallVectorImpl<llvm::Type *> &ArgList) const;
  4856. llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
  4857. llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
  4858. llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
  4859. public:
  4860. MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
  4861. ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
  4862. StackAlignInBytes(IsO32 ? 8 : 16) {}
  4863. ABIArgInfo classifyReturnType(QualType RetTy) const;
  4864. ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
  4865. void computeInfo(CGFunctionInfo &FI) const override;
  4866. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  4867. QualType Ty) const override;
  4868. bool shouldSignExtUnsignedType(QualType Ty) const override;
  4869. };
  4870. class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
  4871. unsigned SizeOfUnwindException;
  4872. public:
  4873. MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
  4874. : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
  4875. SizeOfUnwindException(IsO32 ? 24 : 32) {}
  4876. int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
  4877. return 29;
  4878. }
  4879. void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
  4880. CodeGen::CodeGenModule &CGM) const override {
  4881. const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
  4882. if (!FD) return;
  4883. llvm::Function *Fn = cast<llvm::Function>(GV);
  4884. if (FD->hasAttr<Mips16Attr>()) {
  4885. Fn->addFnAttr("mips16");
  4886. }
  4887. else if (FD->hasAttr<NoMips16Attr>()) {
  4888. Fn->addFnAttr("nomips16");
  4889. }
  4890. }
  4891. bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
  4892. llvm::Value *Address) const override;
  4893. unsigned getSizeOfUnwindException() const override {
  4894. return SizeOfUnwindException;
  4895. }
  4896. };
  4897. }
  4898. void MipsABIInfo::CoerceToIntArgs(
  4899. uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
  4900. llvm::IntegerType *IntTy =
  4901. llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
  4902. // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
  4903. for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
  4904. ArgList.push_back(IntTy);
  4905. // If necessary, add one more integer type to ArgList.
  4906. unsigned R = TySize % (MinABIStackAlignInBytes * 8);
  4907. if (R)
  4908. ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
  4909. }
  4910. // In N32/64, an aligned double precision floating point field is passed in
  4911. // a register.
  4912. llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
  4913. SmallVector<llvm::Type*, 8> ArgList, IntArgList;
  4914. if (IsO32) {
  4915. CoerceToIntArgs(TySize, ArgList);
  4916. return llvm::StructType::get(getVMContext(), ArgList);
  4917. }
  4918. if (Ty->isComplexType())
  4919. return CGT.ConvertType(Ty);
  4920. const RecordType *RT = Ty->getAs<RecordType>();
  4921. // Unions/vectors are passed in integer registers.
  4922. if (!RT || !RT->isStructureOrClassType()) {
  4923. CoerceToIntArgs(TySize, ArgList);
  4924. return llvm::StructType::get(getVMContext(), ArgList);
  4925. }
  4926. const RecordDecl *RD = RT->getDecl();
  4927. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
  4928. assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
  4929. uint64_t LastOffset = 0;
  4930. unsigned idx = 0;
  4931. llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
  4932. // Iterate over fields in the struct/class and check if there are any aligned
  4933. // double fields.
  4934. for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
  4935. i != e; ++i, ++idx) {
  4936. const QualType Ty = i->getType();
  4937. const BuiltinType *BT = Ty->getAs<BuiltinType>();
  4938. if (!BT || BT->getKind() != BuiltinType::Double)
  4939. continue;
  4940. uint64_t Offset = Layout.getFieldOffset(idx);
  4941. if (Offset % 64) // Ignore doubles that are not aligned.
  4942. continue;
  4943. // Add ((Offset - LastOffset) / 64) args of type i64.
  4944. for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
  4945. ArgList.push_back(I64);
  4946. // Add double type.
  4947. ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
  4948. LastOffset = Offset + 64;
  4949. }
  4950. CoerceToIntArgs(TySize - LastOffset, IntArgList);
  4951. ArgList.append(IntArgList.begin(), IntArgList.end());
  4952. return llvm::StructType::get(getVMContext(), ArgList);
  4953. }
  4954. llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
  4955. uint64_t Offset) const {
  4956. if (OrigOffset + MinABIStackAlignInBytes > Offset)
  4957. return nullptr;
  4958. return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
  4959. }
  4960. ABIArgInfo
  4961. MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
  4962. Ty = useFirstFieldIfTransparentUnion(Ty);
  4963. uint64_t OrigOffset = Offset;
  4964. uint64_t TySize = getContext().getTypeSize(Ty);
  4965. uint64_t Align = getContext().getTypeAlign(Ty) / 8;
  4966. Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
  4967. (uint64_t)StackAlignInBytes);
  4968. unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
  4969. Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
  4970. if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
  4971. // Ignore empty aggregates.
  4972. if (TySize == 0)
  4973. return ABIArgInfo::getIgnore();
  4974. if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
  4975. Offset = OrigOffset + MinABIStackAlignInBytes;
  4976. return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
  4977. }
  4978. // If we have reached here, aggregates are passed directly by coercing to
  4979. // another structure type. Padding is inserted if the offset of the
  4980. // aggregate is unaligned.
  4981. ABIArgInfo ArgInfo =
  4982. ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
  4983. getPaddingType(OrigOffset, CurrOffset));
  4984. ArgInfo.setInReg(true);
  4985. return ArgInfo;
  4986. }
  4987. // Treat an enum type as its underlying type.
  4988. if (const EnumType *EnumTy = Ty->getAs<EnumType>())
  4989. Ty = EnumTy->getDecl()->getIntegerType();
  4990. // All integral types are promoted to the GPR width.
  4991. if (Ty->isIntegralOrEnumerationType())
  4992. return ABIArgInfo::getExtend();
  4993. return ABIArgInfo::getDirect(
  4994. nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
  4995. }
  4996. llvm::Type*
  4997. MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
  4998. const RecordType *RT = RetTy->getAs<RecordType>();
  4999. SmallVector<llvm::Type*, 8> RTList;
  5000. if (RT && RT->isStructureOrClassType()) {
  5001. const RecordDecl *RD = RT->getDecl();
  5002. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
  5003. unsigned FieldCnt = Layout.getFieldCount();
  5004. // N32/64 returns struct/classes in floating point registers if the
  5005. // following conditions are met:
  5006. // 1. The size of the struct/class is no larger than 128-bit.
  5007. // 2. The struct/class has one or two fields all of which are floating
  5008. // point types.
  5009. // 3. The offset of the first field is zero (this follows what gcc does).
  5010. //
  5011. // Any other composite results are returned in integer registers.
  5012. //
  5013. if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
  5014. RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
  5015. for (; b != e; ++b) {
  5016. const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
  5017. if (!BT || !BT->isFloatingPoint())
  5018. break;
  5019. RTList.push_back(CGT.ConvertType(b->getType()));
  5020. }
  5021. if (b == e)
  5022. return llvm::StructType::get(getVMContext(), RTList,
  5023. RD->hasAttr<PackedAttr>());
  5024. RTList.clear();
  5025. }
  5026. }
  5027. CoerceToIntArgs(Size, RTList);
  5028. return llvm::StructType::get(getVMContext(), RTList);
  5029. }
  5030. ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
  5031. uint64_t Size = getContext().getTypeSize(RetTy);
  5032. if (RetTy->isVoidType())
  5033. return ABIArgInfo::getIgnore();
  5034. // O32 doesn't treat zero-sized structs differently from other structs.
  5035. // However, N32/N64 ignores zero sized return values.
  5036. if (!IsO32 && Size == 0)
  5037. return ABIArgInfo::getIgnore();
  5038. if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
  5039. if (Size <= 128) {
  5040. if (RetTy->isAnyComplexType())
  5041. return ABIArgInfo::getDirect();
  5042. // O32 returns integer vectors in registers and N32/N64 returns all small
  5043. // aggregates in registers.
  5044. if (!IsO32 ||
  5045. (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
  5046. ABIArgInfo ArgInfo =
  5047. ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
  5048. ArgInfo.setInReg(true);
  5049. return ArgInfo;
  5050. }
  5051. }
  5052. return getNaturalAlignIndirect(RetTy);
  5053. }
  5054. // Treat an enum type as its underlying type.
  5055. if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
  5056. RetTy = EnumTy->getDecl()->getIntegerType();
  5057. return (RetTy->isPromotableIntegerType() ?
  5058. ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
  5059. }
  5060. void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
  5061. ABIArgInfo &RetInfo = FI.getReturnInfo();
  5062. if (!getCXXABI().classifyReturnType(FI))
  5063. RetInfo = classifyReturnType(FI.getReturnType());
  5064. // Check if a pointer to an aggregate is passed as a hidden argument.
  5065. uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
  5066. for (auto &I : FI.arguments())
  5067. I.info = classifyArgumentType(I.type, Offset);
  5068. }
  5069. Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  5070. QualType OrigTy) const {
  5071. QualType Ty = OrigTy;
  5072. // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
  5073. // Pointers are also promoted in the same way but this only matters for N32.
  5074. unsigned SlotSizeInBits = IsO32 ? 32 : 64;
  5075. unsigned PtrWidth = getTarget().getPointerWidth(0);
  5076. bool DidPromote = false;
  5077. if ((Ty->isIntegerType() &&
  5078. getContext().getIntWidth(Ty) < SlotSizeInBits) ||
  5079. (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
  5080. DidPromote = true;
  5081. Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
  5082. Ty->isSignedIntegerType());
  5083. }
  5084. auto TyInfo = getContext().getTypeInfoInChars(Ty);
  5085. // The alignment of things in the argument area is never larger than
  5086. // StackAlignInBytes.
  5087. TyInfo.second =
  5088. std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
  5089. // MinABIStackAlignInBytes is the size of argument slots on the stack.
  5090. CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
  5091. Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
  5092. TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
  5093. // If there was a promotion, "unpromote" into a temporary.
  5094. // TODO: can we just use a pointer into a subset of the original slot?
  5095. if (DidPromote) {
  5096. Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
  5097. llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
  5098. // Truncate down to the right width.
  5099. llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
  5100. : CGF.IntPtrTy);
  5101. llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
  5102. if (OrigTy->isPointerType())
  5103. V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
  5104. CGF.Builder.CreateStore(V, Temp);
  5105. Addr = Temp;
  5106. }
  5107. return Addr;
  5108. }
  5109. bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
  5110. int TySize = getContext().getTypeSize(Ty);
  5111. // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
  5112. if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
  5113. return true;
  5114. return false;
  5115. }
  5116. bool
  5117. MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
  5118. llvm::Value *Address) const {
  5119. // This information comes from gcc's implementation, which seems to
  5120. // as canonical as it gets.
  5121. // Everything on MIPS is 4 bytes. Double-precision FP registers
  5122. // are aliased to pairs of single-precision FP registers.
  5123. llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
  5124. // 0-31 are the general purpose registers, $0 - $31.
  5125. // 32-63 are the floating-point registers, $f0 - $f31.
  5126. // 64 and 65 are the multiply/divide registers, $hi and $lo.
  5127. // 66 is the (notional, I think) register for signal-handler return.
  5128. AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
  5129. // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
  5130. // They are one bit wide and ignored here.
  5131. // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
  5132. // (coprocessor 1 is the FP unit)
  5133. // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
  5134. // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
  5135. // 176-181 are the DSP accumulator registers.
  5136. AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
  5137. return false;
  5138. }
  5139. //===----------------------------------------------------------------------===//
  5140. // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
  5141. // Currently subclassed only to implement custom OpenCL C function attribute
  5142. // handling.
  5143. //===----------------------------------------------------------------------===//
  5144. namespace {
  5145. class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
  5146. public:
  5147. TCETargetCodeGenInfo(CodeGenTypes &CGT)
  5148. : DefaultTargetCodeGenInfo(CGT) {}
  5149. void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
  5150. CodeGen::CodeGenModule &M) const override;
  5151. };
  5152. void TCETargetCodeGenInfo::setTargetAttributes(
  5153. const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
  5154. const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
  5155. if (!FD) return;
  5156. llvm::Function *F = cast<llvm::Function>(GV);
  5157. if (M.getLangOpts().OpenCL) {
  5158. if (FD->hasAttr<OpenCLKernelAttr>()) {
  5159. // OpenCL C Kernel functions are not subject to inlining
  5160. F->addFnAttr(llvm::Attribute::NoInline);
  5161. const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
  5162. if (Attr) {
  5163. // Convert the reqd_work_group_size() attributes to metadata.
  5164. llvm::LLVMContext &Context = F->getContext();
  5165. llvm::NamedMDNode *OpenCLMetadata =
  5166. M.getModule().getOrInsertNamedMetadata(
  5167. "opencl.kernel_wg_size_info");
  5168. SmallVector<llvm::Metadata *, 5> Operands;
  5169. Operands.push_back(llvm::ConstantAsMetadata::get(F));
  5170. Operands.push_back(
  5171. llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
  5172. M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
  5173. Operands.push_back(
  5174. llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
  5175. M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
  5176. Operands.push_back(
  5177. llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
  5178. M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
  5179. // Add a boolean constant operand for "required" (true) or "hint"
  5180. // (false) for implementing the work_group_size_hint attr later.
  5181. // Currently always true as the hint is not yet implemented.
  5182. Operands.push_back(
  5183. llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
  5184. OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
  5185. }
  5186. }
  5187. }
  5188. }
  5189. }
  5190. //===----------------------------------------------------------------------===//
  5191. // Hexagon ABI Implementation
  5192. //===----------------------------------------------------------------------===//
  5193. namespace {
  5194. class HexagonABIInfo : public ABIInfo {
  5195. public:
  5196. HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
  5197. private:
  5198. ABIArgInfo classifyReturnType(QualType RetTy) const;
  5199. ABIArgInfo classifyArgumentType(QualType RetTy) const;
  5200. void computeInfo(CGFunctionInfo &FI) const override;
  5201. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  5202. QualType Ty) const override;
  5203. };
  5204. class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
  5205. public:
  5206. HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
  5207. :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
  5208. int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
  5209. return 29;
  5210. }
  5211. };
  5212. }
  5213. void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
  5214. if (!getCXXABI().classifyReturnType(FI))
  5215. FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
  5216. for (auto &I : FI.arguments())
  5217. I.info = classifyArgumentType(I.type);
  5218. }
  5219. ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
  5220. if (!isAggregateTypeForABI(Ty)) {
  5221. // Treat an enum type as its underlying type.
  5222. if (const EnumType *EnumTy = Ty->getAs<EnumType>())
  5223. Ty = EnumTy->getDecl()->getIntegerType();
  5224. return (Ty->isPromotableIntegerType() ?
  5225. ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
  5226. }
  5227. // Ignore empty records.
  5228. if (isEmptyRecord(getContext(), Ty, true))
  5229. return ABIArgInfo::getIgnore();
  5230. if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
  5231. return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
  5232. uint64_t Size = getContext().getTypeSize(Ty);
  5233. if (Size > 64)
  5234. return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
  5235. // Pass in the smallest viable integer type.
  5236. else if (Size > 32)
  5237. return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
  5238. else if (Size > 16)
  5239. return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
  5240. else if (Size > 8)
  5241. return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
  5242. else
  5243. return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
  5244. }
  5245. ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
  5246. if (RetTy->isVoidType())
  5247. return ABIArgInfo::getIgnore();
  5248. // Large vector types should be returned via memory.
  5249. if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
  5250. return getNaturalAlignIndirect(RetTy);
  5251. if (!isAggregateTypeForABI(RetTy)) {
  5252. // Treat an enum type as its underlying type.
  5253. if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
  5254. RetTy = EnumTy->getDecl()->getIntegerType();
  5255. return (RetTy->isPromotableIntegerType() ?
  5256. ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
  5257. }
  5258. if (isEmptyRecord(getContext(), RetTy, true))
  5259. return ABIArgInfo::getIgnore();
  5260. // Aggregates <= 8 bytes are returned in r0; other aggregates
  5261. // are returned indirectly.
  5262. uint64_t Size = getContext().getTypeSize(RetTy);
  5263. if (Size <= 64) {
  5264. // Return in the smallest viable integer type.
  5265. if (Size <= 8)
  5266. return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
  5267. if (Size <= 16)
  5268. return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
  5269. if (Size <= 32)
  5270. return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
  5271. return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
  5272. }
  5273. return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
  5274. }
  5275. Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  5276. QualType Ty) const {
  5277. // FIXME: Someone needs to audit that this handle alignment correctly.
  5278. return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
  5279. getContext().getTypeInfoInChars(Ty),
  5280. CharUnits::fromQuantity(4),
  5281. /*AllowHigherAlign*/ true);
  5282. }
  5283. //===----------------------------------------------------------------------===//
  5284. // AMDGPU ABI Implementation
  5285. //===----------------------------------------------------------------------===//
  5286. namespace {
  5287. class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
  5288. public:
  5289. AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
  5290. : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
  5291. void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
  5292. CodeGen::CodeGenModule &M) const override;
  5293. };
  5294. }
  5295. void AMDGPUTargetCodeGenInfo::setTargetAttributes(
  5296. const Decl *D,
  5297. llvm::GlobalValue *GV,
  5298. CodeGen::CodeGenModule &M) const {
  5299. const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
  5300. if (!FD)
  5301. return;
  5302. if (const auto Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
  5303. llvm::Function *F = cast<llvm::Function>(GV);
  5304. uint32_t NumVGPR = Attr->getNumVGPR();
  5305. if (NumVGPR != 0)
  5306. F->addFnAttr("amdgpu_num_vgpr", llvm::utostr(NumVGPR));
  5307. }
  5308. if (const auto Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
  5309. llvm::Function *F = cast<llvm::Function>(GV);
  5310. unsigned NumSGPR = Attr->getNumSGPR();
  5311. if (NumSGPR != 0)
  5312. F->addFnAttr("amdgpu_num_sgpr", llvm::utostr(NumSGPR));
  5313. }
  5314. }
  5315. //===----------------------------------------------------------------------===//
  5316. // SPARC v9 ABI Implementation.
  5317. // Based on the SPARC Compliance Definition version 2.4.1.
  5318. //
  5319. // Function arguments a mapped to a nominal "parameter array" and promoted to
  5320. // registers depending on their type. Each argument occupies 8 or 16 bytes in
  5321. // the array, structs larger than 16 bytes are passed indirectly.
  5322. //
  5323. // One case requires special care:
  5324. //
  5325. // struct mixed {
  5326. // int i;
  5327. // float f;
  5328. // };
  5329. //
  5330. // When a struct mixed is passed by value, it only occupies 8 bytes in the
  5331. // parameter array, but the int is passed in an integer register, and the float
  5332. // is passed in a floating point register. This is represented as two arguments
  5333. // with the LLVM IR inreg attribute:
  5334. //
  5335. // declare void f(i32 inreg %i, float inreg %f)
  5336. //
  5337. // The code generator will only allocate 4 bytes from the parameter array for
  5338. // the inreg arguments. All other arguments are allocated a multiple of 8
  5339. // bytes.
  5340. //
  5341. namespace {
  5342. class SparcV9ABIInfo : public ABIInfo {
  5343. public:
  5344. SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
  5345. private:
  5346. ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
  5347. void computeInfo(CGFunctionInfo &FI) const override;
  5348. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  5349. QualType Ty) const override;
  5350. // Coercion type builder for structs passed in registers. The coercion type
  5351. // serves two purposes:
  5352. //
  5353. // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
  5354. // in registers.
  5355. // 2. Expose aligned floating point elements as first-level elements, so the
  5356. // code generator knows to pass them in floating point registers.
  5357. //
  5358. // We also compute the InReg flag which indicates that the struct contains
  5359. // aligned 32-bit floats.
  5360. //
  5361. struct CoerceBuilder {
  5362. llvm::LLVMContext &Context;
  5363. const llvm::DataLayout &DL;
  5364. SmallVector<llvm::Type*, 8> Elems;
  5365. uint64_t Size;
  5366. bool InReg;
  5367. CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
  5368. : Context(c), DL(dl), Size(0), InReg(false) {}
  5369. // Pad Elems with integers until Size is ToSize.
  5370. void pad(uint64_t ToSize) {
  5371. assert(ToSize >= Size && "Cannot remove elements");
  5372. if (ToSize == Size)
  5373. return;
  5374. // Finish the current 64-bit word.
  5375. uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
  5376. if (Aligned > Size && Aligned <= ToSize) {
  5377. Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
  5378. Size = Aligned;
  5379. }
  5380. // Add whole 64-bit words.
  5381. while (Size + 64 <= ToSize) {
  5382. Elems.push_back(llvm::Type::getInt64Ty(Context));
  5383. Size += 64;
  5384. }
  5385. // Final in-word padding.
  5386. if (Size < ToSize) {
  5387. Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
  5388. Size = ToSize;
  5389. }
  5390. }
  5391. // Add a floating point element at Offset.
  5392. void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
  5393. // Unaligned floats are treated as integers.
  5394. if (Offset % Bits)
  5395. return;
  5396. // The InReg flag is only required if there are any floats < 64 bits.
  5397. if (Bits < 64)
  5398. InReg = true;
  5399. pad(Offset);
  5400. Elems.push_back(Ty);
  5401. Size = Offset + Bits;
  5402. }
  5403. // Add a struct type to the coercion type, starting at Offset (in bits).
  5404. void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
  5405. const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
  5406. for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
  5407. llvm::Type *ElemTy = StrTy->getElementType(i);
  5408. uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
  5409. switch (ElemTy->getTypeID()) {
  5410. case llvm::Type::StructTyID:
  5411. addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
  5412. break;
  5413. case llvm::Type::FloatTyID:
  5414. addFloat(ElemOffset, ElemTy, 32);
  5415. break;
  5416. case llvm::Type::DoubleTyID:
  5417. addFloat(ElemOffset, ElemTy, 64);
  5418. break;
  5419. case llvm::Type::FP128TyID:
  5420. addFloat(ElemOffset, ElemTy, 128);
  5421. break;
  5422. case llvm::Type::PointerTyID:
  5423. if (ElemOffset % 64 == 0) {
  5424. pad(ElemOffset);
  5425. Elems.push_back(ElemTy);
  5426. Size += 64;
  5427. }
  5428. break;
  5429. default:
  5430. break;
  5431. }
  5432. }
  5433. }
  5434. // Check if Ty is a usable substitute for the coercion type.
  5435. bool isUsableType(llvm::StructType *Ty) const {
  5436. return llvm::makeArrayRef(Elems) == Ty->elements();
  5437. }
  5438. // Get the coercion type as a literal struct type.
  5439. llvm::Type *getType() const {
  5440. if (Elems.size() == 1)
  5441. return Elems.front();
  5442. else
  5443. return llvm::StructType::get(Context, Elems);
  5444. }
  5445. };
  5446. };
  5447. } // end anonymous namespace
  5448. ABIArgInfo
  5449. SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
  5450. if (Ty->isVoidType())
  5451. return ABIArgInfo::getIgnore();
  5452. uint64_t Size = getContext().getTypeSize(Ty);
  5453. // Anything too big to fit in registers is passed with an explicit indirect
  5454. // pointer / sret pointer.
  5455. if (Size > SizeLimit)
  5456. return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
  5457. // Treat an enum type as its underlying type.
  5458. if (const EnumType *EnumTy = Ty->getAs<EnumType>())
  5459. Ty = EnumTy->getDecl()->getIntegerType();
  5460. // Integer types smaller than a register are extended.
  5461. if (Size < 64 && Ty->isIntegerType())
  5462. return ABIArgInfo::getExtend();
  5463. // Other non-aggregates go in registers.
  5464. if (!isAggregateTypeForABI(Ty))
  5465. return ABIArgInfo::getDirect();
  5466. // If a C++ object has either a non-trivial copy constructor or a non-trivial
  5467. // destructor, it is passed with an explicit indirect pointer / sret pointer.
  5468. if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
  5469. return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
  5470. // This is a small aggregate type that should be passed in registers.
  5471. // Build a coercion type from the LLVM struct type.
  5472. llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
  5473. if (!StrTy)
  5474. return ABIArgInfo::getDirect();
  5475. CoerceBuilder CB(getVMContext(), getDataLayout());
  5476. CB.addStruct(0, StrTy);
  5477. CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
  5478. // Try to use the original type for coercion.
  5479. llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
  5480. if (CB.InReg)
  5481. return ABIArgInfo::getDirectInReg(CoerceTy);
  5482. else
  5483. return ABIArgInfo::getDirect(CoerceTy);
  5484. }
  5485. Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  5486. QualType Ty) const {
  5487. ABIArgInfo AI = classifyType(Ty, 16 * 8);
  5488. llvm::Type *ArgTy = CGT.ConvertType(Ty);
  5489. if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
  5490. AI.setCoerceToType(ArgTy);
  5491. CharUnits SlotSize = CharUnits::fromQuantity(8);
  5492. CGBuilderTy &Builder = CGF.Builder;
  5493. Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
  5494. llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
  5495. auto TypeInfo = getContext().getTypeInfoInChars(Ty);
  5496. Address ArgAddr = Address::invalid();
  5497. CharUnits Stride;
  5498. switch (AI.getKind()) {
  5499. case ABIArgInfo::Expand:
  5500. case ABIArgInfo::InAlloca:
  5501. llvm_unreachable("Unsupported ABI kind for va_arg");
  5502. case ABIArgInfo::Extend: {
  5503. Stride = SlotSize;
  5504. CharUnits Offset = SlotSize - TypeInfo.first;
  5505. ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
  5506. break;
  5507. }
  5508. case ABIArgInfo::Direct: {
  5509. auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
  5510. Stride = CharUnits::fromQuantity(AllocSize).RoundUpToAlignment(SlotSize);
  5511. ArgAddr = Addr;
  5512. break;
  5513. }
  5514. case ABIArgInfo::Indirect:
  5515. Stride = SlotSize;
  5516. ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
  5517. ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
  5518. TypeInfo.second);
  5519. break;
  5520. case ABIArgInfo::Ignore:
  5521. return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
  5522. }
  5523. // Update VAList.
  5524. llvm::Value *NextPtr =
  5525. Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
  5526. Builder.CreateStore(NextPtr, VAListAddr);
  5527. return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
  5528. }
  5529. void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
  5530. FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
  5531. for (auto &I : FI.arguments())
  5532. I.info = classifyType(I.type, 16 * 8);
  5533. }
  5534. namespace {
  5535. class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
  5536. public:
  5537. SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
  5538. : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
  5539. int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
  5540. return 14;
  5541. }
  5542. bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
  5543. llvm::Value *Address) const override;
  5544. };
  5545. } // end anonymous namespace
  5546. bool
  5547. SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
  5548. llvm::Value *Address) const {
  5549. // This is calculated from the LLVM and GCC tables and verified
  5550. // against gcc output. AFAIK all ABIs use the same encoding.
  5551. CodeGen::CGBuilderTy &Builder = CGF.Builder;
  5552. llvm::IntegerType *i8 = CGF.Int8Ty;
  5553. llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
  5554. llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
  5555. // 0-31: the 8-byte general-purpose registers
  5556. AssignToArrayRange(Builder, Address, Eight8, 0, 31);
  5557. // 32-63: f0-31, the 4-byte floating-point registers
  5558. AssignToArrayRange(Builder, Address, Four8, 32, 63);
  5559. // Y = 64
  5560. // PSR = 65
  5561. // WIM = 66
  5562. // TBR = 67
  5563. // PC = 68
  5564. // NPC = 69
  5565. // FSR = 70
  5566. // CSR = 71
  5567. AssignToArrayRange(Builder, Address, Eight8, 64, 71);
  5568. // 72-87: d0-15, the 8-byte floating-point registers
  5569. AssignToArrayRange(Builder, Address, Eight8, 72, 87);
  5570. return false;
  5571. }
  5572. //===----------------------------------------------------------------------===//
  5573. // XCore ABI Implementation
  5574. //===----------------------------------------------------------------------===//
  5575. namespace {
  5576. /// A SmallStringEnc instance is used to build up the TypeString by passing
  5577. /// it by reference between functions that append to it.
  5578. typedef llvm::SmallString<128> SmallStringEnc;
  5579. /// TypeStringCache caches the meta encodings of Types.
  5580. ///
  5581. /// The reason for caching TypeStrings is two fold:
  5582. /// 1. To cache a type's encoding for later uses;
  5583. /// 2. As a means to break recursive member type inclusion.
  5584. ///
  5585. /// A cache Entry can have a Status of:
  5586. /// NonRecursive: The type encoding is not recursive;
  5587. /// Recursive: The type encoding is recursive;
  5588. /// Incomplete: An incomplete TypeString;
  5589. /// IncompleteUsed: An incomplete TypeString that has been used in a
  5590. /// Recursive type encoding.
  5591. ///
  5592. /// A NonRecursive entry will have all of its sub-members expanded as fully
  5593. /// as possible. Whilst it may contain types which are recursive, the type
  5594. /// itself is not recursive and thus its encoding may be safely used whenever
  5595. /// the type is encountered.
  5596. ///
  5597. /// A Recursive entry will have all of its sub-members expanded as fully as
  5598. /// possible. The type itself is recursive and it may contain other types which
  5599. /// are recursive. The Recursive encoding must not be used during the expansion
  5600. /// of a recursive type's recursive branch. For simplicity the code uses
  5601. /// IncompleteCount to reject all usage of Recursive encodings for member types.
  5602. ///
  5603. /// An Incomplete entry is always a RecordType and only encodes its
  5604. /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
  5605. /// are placed into the cache during type expansion as a means to identify and
  5606. /// handle recursive inclusion of types as sub-members. If there is recursion
  5607. /// the entry becomes IncompleteUsed.
  5608. ///
  5609. /// During the expansion of a RecordType's members:
  5610. ///
  5611. /// If the cache contains a NonRecursive encoding for the member type, the
  5612. /// cached encoding is used;
  5613. ///
  5614. /// If the cache contains a Recursive encoding for the member type, the
  5615. /// cached encoding is 'Swapped' out, as it may be incorrect, and...
  5616. ///
  5617. /// If the member is a RecordType, an Incomplete encoding is placed into the
  5618. /// cache to break potential recursive inclusion of itself as a sub-member;
  5619. ///
  5620. /// Once a member RecordType has been expanded, its temporary incomplete
  5621. /// entry is removed from the cache. If a Recursive encoding was swapped out
  5622. /// it is swapped back in;
  5623. ///
  5624. /// If an incomplete entry is used to expand a sub-member, the incomplete
  5625. /// entry is marked as IncompleteUsed. The cache keeps count of how many
  5626. /// IncompleteUsed entries it currently contains in IncompleteUsedCount;
  5627. ///
  5628. /// If a member's encoding is found to be a NonRecursive or Recursive viz:
  5629. /// IncompleteUsedCount==0, the member's encoding is added to the cache.
  5630. /// Else the member is part of a recursive type and thus the recursion has
  5631. /// been exited too soon for the encoding to be correct for the member.
  5632. ///
  5633. class TypeStringCache {
  5634. enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
  5635. struct Entry {
  5636. std::string Str; // The encoded TypeString for the type.
  5637. enum Status State; // Information about the encoding in 'Str'.
  5638. std::string Swapped; // A temporary place holder for a Recursive encoding
  5639. // during the expansion of RecordType's members.
  5640. };
  5641. std::map<const IdentifierInfo *, struct Entry> Map;
  5642. unsigned IncompleteCount; // Number of Incomplete entries in the Map.
  5643. unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
  5644. public:
  5645. TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
  5646. void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
  5647. bool removeIncomplete(const IdentifierInfo *ID);
  5648. void addIfComplete(const IdentifierInfo *ID, StringRef Str,
  5649. bool IsRecursive);
  5650. StringRef lookupStr(const IdentifierInfo *ID);
  5651. };
  5652. /// TypeString encodings for enum & union fields must be order.
  5653. /// FieldEncoding is a helper for this ordering process.
  5654. class FieldEncoding {
  5655. bool HasName;
  5656. std::string Enc;
  5657. public:
  5658. FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
  5659. StringRef str() {return Enc.c_str();}
  5660. bool operator<(const FieldEncoding &rhs) const {
  5661. if (HasName != rhs.HasName) return HasName;
  5662. return Enc < rhs.Enc;
  5663. }
  5664. };
  5665. class XCoreABIInfo : public DefaultABIInfo {
  5666. public:
  5667. XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
  5668. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  5669. QualType Ty) const override;
  5670. };
  5671. class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
  5672. mutable TypeStringCache TSC;
  5673. public:
  5674. XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
  5675. :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
  5676. void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
  5677. CodeGen::CodeGenModule &M) const override;
  5678. };
  5679. } // End anonymous namespace.
  5680. Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  5681. QualType Ty) const {
  5682. CGBuilderTy &Builder = CGF.Builder;
  5683. // Get the VAList.
  5684. CharUnits SlotSize = CharUnits::fromQuantity(4);
  5685. Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
  5686. // Handle the argument.
  5687. ABIArgInfo AI = classifyArgumentType(Ty);
  5688. CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
  5689. llvm::Type *ArgTy = CGT.ConvertType(Ty);
  5690. if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
  5691. AI.setCoerceToType(ArgTy);
  5692. llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
  5693. Address Val = Address::invalid();
  5694. CharUnits ArgSize = CharUnits::Zero();
  5695. switch (AI.getKind()) {
  5696. case ABIArgInfo::Expand:
  5697. case ABIArgInfo::InAlloca:
  5698. llvm_unreachable("Unsupported ABI kind for va_arg");
  5699. case ABIArgInfo::Ignore:
  5700. Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
  5701. ArgSize = CharUnits::Zero();
  5702. break;
  5703. case ABIArgInfo::Extend:
  5704. case ABIArgInfo::Direct:
  5705. Val = Builder.CreateBitCast(AP, ArgPtrTy);
  5706. ArgSize = CharUnits::fromQuantity(
  5707. getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
  5708. ArgSize = ArgSize.RoundUpToAlignment(SlotSize);
  5709. break;
  5710. case ABIArgInfo::Indirect:
  5711. Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
  5712. Val = Address(Builder.CreateLoad(Val), TypeAlign);
  5713. ArgSize = SlotSize;
  5714. break;
  5715. }
  5716. // Increment the VAList.
  5717. if (!ArgSize.isZero()) {
  5718. llvm::Value *APN =
  5719. Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
  5720. Builder.CreateStore(APN, VAListAddr);
  5721. }
  5722. return Val;
  5723. }
  5724. /// During the expansion of a RecordType, an incomplete TypeString is placed
  5725. /// into the cache as a means to identify and break recursion.
  5726. /// If there is a Recursive encoding in the cache, it is swapped out and will
  5727. /// be reinserted by removeIncomplete().
  5728. /// All other types of encoding should have been used rather than arriving here.
  5729. void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
  5730. std::string StubEnc) {
  5731. if (!ID)
  5732. return;
  5733. Entry &E = Map[ID];
  5734. assert( (E.Str.empty() || E.State == Recursive) &&
  5735. "Incorrectly use of addIncomplete");
  5736. assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
  5737. E.Swapped.swap(E.Str); // swap out the Recursive
  5738. E.Str.swap(StubEnc);
  5739. E.State = Incomplete;
  5740. ++IncompleteCount;
  5741. }
  5742. /// Once the RecordType has been expanded, the temporary incomplete TypeString
  5743. /// must be removed from the cache.
  5744. /// If a Recursive was swapped out by addIncomplete(), it will be replaced.
  5745. /// Returns true if the RecordType was defined recursively.
  5746. bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
  5747. if (!ID)
  5748. return false;
  5749. auto I = Map.find(ID);
  5750. assert(I != Map.end() && "Entry not present");
  5751. Entry &E = I->second;
  5752. assert( (E.State == Incomplete ||
  5753. E.State == IncompleteUsed) &&
  5754. "Entry must be an incomplete type");
  5755. bool IsRecursive = false;
  5756. if (E.State == IncompleteUsed) {
  5757. // We made use of our Incomplete encoding, thus we are recursive.
  5758. IsRecursive = true;
  5759. --IncompleteUsedCount;
  5760. }
  5761. if (E.Swapped.empty())
  5762. Map.erase(I);
  5763. else {
  5764. // Swap the Recursive back.
  5765. E.Swapped.swap(E.Str);
  5766. E.Swapped.clear();
  5767. E.State = Recursive;
  5768. }
  5769. --IncompleteCount;
  5770. return IsRecursive;
  5771. }
  5772. /// Add the encoded TypeString to the cache only if it is NonRecursive or
  5773. /// Recursive (viz: all sub-members were expanded as fully as possible).
  5774. void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
  5775. bool IsRecursive) {
  5776. if (!ID || IncompleteUsedCount)
  5777. return; // No key or it is is an incomplete sub-type so don't add.
  5778. Entry &E = Map[ID];
  5779. if (IsRecursive && !E.Str.empty()) {
  5780. assert(E.State==Recursive && E.Str.size() == Str.size() &&
  5781. "This is not the same Recursive entry");
  5782. // The parent container was not recursive after all, so we could have used
  5783. // this Recursive sub-member entry after all, but we assumed the worse when
  5784. // we started viz: IncompleteCount!=0.
  5785. return;
  5786. }
  5787. assert(E.Str.empty() && "Entry already present");
  5788. E.Str = Str.str();
  5789. E.State = IsRecursive? Recursive : NonRecursive;
  5790. }
  5791. /// Return a cached TypeString encoding for the ID. If there isn't one, or we
  5792. /// are recursively expanding a type (IncompleteCount != 0) and the cached
  5793. /// encoding is Recursive, return an empty StringRef.
  5794. StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
  5795. if (!ID)
  5796. return StringRef(); // We have no key.
  5797. auto I = Map.find(ID);
  5798. if (I == Map.end())
  5799. return StringRef(); // We have no encoding.
  5800. Entry &E = I->second;
  5801. if (E.State == Recursive && IncompleteCount)
  5802. return StringRef(); // We don't use Recursive encodings for member types.
  5803. if (E.State == Incomplete) {
  5804. // The incomplete type is being used to break out of recursion.
  5805. E.State = IncompleteUsed;
  5806. ++IncompleteUsedCount;
  5807. }
  5808. return E.Str.c_str();
  5809. }
  5810. /// The XCore ABI includes a type information section that communicates symbol
  5811. /// type information to the linker. The linker uses this information to verify
  5812. /// safety/correctness of things such as array bound and pointers et al.
  5813. /// The ABI only requires C (and XC) language modules to emit TypeStrings.
  5814. /// This type information (TypeString) is emitted into meta data for all global
  5815. /// symbols: definitions, declarations, functions & variables.
  5816. ///
  5817. /// The TypeString carries type, qualifier, name, size & value details.
  5818. /// Please see 'Tools Development Guide' section 2.16.2 for format details:
  5819. /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
  5820. /// The output is tested by test/CodeGen/xcore-stringtype.c.
  5821. ///
  5822. static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
  5823. CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
  5824. /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
  5825. void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
  5826. CodeGen::CodeGenModule &CGM) const {
  5827. SmallStringEnc Enc;
  5828. if (getTypeString(Enc, D, CGM, TSC)) {
  5829. llvm::LLVMContext &Ctx = CGM.getModule().getContext();
  5830. llvm::SmallVector<llvm::Metadata *, 2> MDVals;
  5831. MDVals.push_back(llvm::ConstantAsMetadata::get(GV));
  5832. MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
  5833. llvm::NamedMDNode *MD =
  5834. CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
  5835. MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
  5836. }
  5837. }
  5838. static bool appendType(SmallStringEnc &Enc, QualType QType,
  5839. const CodeGen::CodeGenModule &CGM,
  5840. TypeStringCache &TSC);
  5841. /// Helper function for appendRecordType().
  5842. /// Builds a SmallVector containing the encoded field types in declaration
  5843. /// order.
  5844. static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
  5845. const RecordDecl *RD,
  5846. const CodeGen::CodeGenModule &CGM,
  5847. TypeStringCache &TSC) {
  5848. for (const auto *Field : RD->fields()) {
  5849. SmallStringEnc Enc;
  5850. Enc += "m(";
  5851. Enc += Field->getName();
  5852. Enc += "){";
  5853. if (Field->isBitField()) {
  5854. Enc += "b(";
  5855. llvm::raw_svector_ostream OS(Enc);
  5856. OS << Field->getBitWidthValue(CGM.getContext());
  5857. Enc += ':';
  5858. }
  5859. if (!appendType(Enc, Field->getType(), CGM, TSC))
  5860. return false;
  5861. if (Field->isBitField())
  5862. Enc += ')';
  5863. Enc += '}';
  5864. FE.emplace_back(!Field->getName().empty(), Enc);
  5865. }
  5866. return true;
  5867. }
  5868. /// Appends structure and union types to Enc and adds encoding to cache.
  5869. /// Recursively calls appendType (via extractFieldType) for each field.
  5870. /// Union types have their fields ordered according to the ABI.
  5871. static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
  5872. const CodeGen::CodeGenModule &CGM,
  5873. TypeStringCache &TSC, const IdentifierInfo *ID) {
  5874. // Append the cached TypeString if we have one.
  5875. StringRef TypeString = TSC.lookupStr(ID);
  5876. if (!TypeString.empty()) {
  5877. Enc += TypeString;
  5878. return true;
  5879. }
  5880. // Start to emit an incomplete TypeString.
  5881. size_t Start = Enc.size();
  5882. Enc += (RT->isUnionType()? 'u' : 's');
  5883. Enc += '(';
  5884. if (ID)
  5885. Enc += ID->getName();
  5886. Enc += "){";
  5887. // We collect all encoded fields and order as necessary.
  5888. bool IsRecursive = false;
  5889. const RecordDecl *RD = RT->getDecl()->getDefinition();
  5890. if (RD && !RD->field_empty()) {
  5891. // An incomplete TypeString stub is placed in the cache for this RecordType
  5892. // so that recursive calls to this RecordType will use it whilst building a
  5893. // complete TypeString for this RecordType.
  5894. SmallVector<FieldEncoding, 16> FE;
  5895. std::string StubEnc(Enc.substr(Start).str());
  5896. StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
  5897. TSC.addIncomplete(ID, std::move(StubEnc));
  5898. if (!extractFieldType(FE, RD, CGM, TSC)) {
  5899. (void) TSC.removeIncomplete(ID);
  5900. return false;
  5901. }
  5902. IsRecursive = TSC.removeIncomplete(ID);
  5903. // The ABI requires unions to be sorted but not structures.
  5904. // See FieldEncoding::operator< for sort algorithm.
  5905. if (RT->isUnionType())
  5906. std::sort(FE.begin(), FE.end());
  5907. // We can now complete the TypeString.
  5908. unsigned E = FE.size();
  5909. for (unsigned I = 0; I != E; ++I) {
  5910. if (I)
  5911. Enc += ',';
  5912. Enc += FE[I].str();
  5913. }
  5914. }
  5915. Enc += '}';
  5916. TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
  5917. return true;
  5918. }
  5919. /// Appends enum types to Enc and adds the encoding to the cache.
  5920. static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
  5921. TypeStringCache &TSC,
  5922. const IdentifierInfo *ID) {
  5923. // Append the cached TypeString if we have one.
  5924. StringRef TypeString = TSC.lookupStr(ID);
  5925. if (!TypeString.empty()) {
  5926. Enc += TypeString;
  5927. return true;
  5928. }
  5929. size_t Start = Enc.size();
  5930. Enc += "e(";
  5931. if (ID)
  5932. Enc += ID->getName();
  5933. Enc += "){";
  5934. // We collect all encoded enumerations and order them alphanumerically.
  5935. if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
  5936. SmallVector<FieldEncoding, 16> FE;
  5937. for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
  5938. ++I) {
  5939. SmallStringEnc EnumEnc;
  5940. EnumEnc += "m(";
  5941. EnumEnc += I->getName();
  5942. EnumEnc += "){";
  5943. I->getInitVal().toString(EnumEnc);
  5944. EnumEnc += '}';
  5945. FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
  5946. }
  5947. std::sort(FE.begin(), FE.end());
  5948. unsigned E = FE.size();
  5949. for (unsigned I = 0; I != E; ++I) {
  5950. if (I)
  5951. Enc += ',';
  5952. Enc += FE[I].str();
  5953. }
  5954. }
  5955. Enc += '}';
  5956. TSC.addIfComplete(ID, Enc.substr(Start), false);
  5957. return true;
  5958. }
  5959. /// Appends type's qualifier to Enc.
  5960. /// This is done prior to appending the type's encoding.
  5961. static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
  5962. // Qualifiers are emitted in alphabetical order.
  5963. static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
  5964. int Lookup = 0;
  5965. if (QT.isConstQualified())
  5966. Lookup += 1<<0;
  5967. if (QT.isRestrictQualified())
  5968. Lookup += 1<<1;
  5969. if (QT.isVolatileQualified())
  5970. Lookup += 1<<2;
  5971. Enc += Table[Lookup];
  5972. }
  5973. /// Appends built-in types to Enc.
  5974. static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
  5975. const char *EncType;
  5976. switch (BT->getKind()) {
  5977. case BuiltinType::Void:
  5978. EncType = "0";
  5979. break;
  5980. case BuiltinType::Bool:
  5981. EncType = "b";
  5982. break;
  5983. case BuiltinType::Char_U:
  5984. EncType = "uc";
  5985. break;
  5986. case BuiltinType::UChar:
  5987. EncType = "uc";
  5988. break;
  5989. case BuiltinType::SChar:
  5990. EncType = "sc";
  5991. break;
  5992. case BuiltinType::UShort:
  5993. EncType = "us";
  5994. break;
  5995. case BuiltinType::Short:
  5996. EncType = "ss";
  5997. break;
  5998. case BuiltinType::UInt:
  5999. EncType = "ui";
  6000. break;
  6001. case BuiltinType::Int:
  6002. EncType = "si";
  6003. break;
  6004. case BuiltinType::ULong:
  6005. EncType = "ul";
  6006. break;
  6007. case BuiltinType::Long:
  6008. EncType = "sl";
  6009. break;
  6010. case BuiltinType::ULongLong:
  6011. EncType = "ull";
  6012. break;
  6013. case BuiltinType::LongLong:
  6014. EncType = "sll";
  6015. break;
  6016. case BuiltinType::Float:
  6017. EncType = "ft";
  6018. break;
  6019. case BuiltinType::Double:
  6020. EncType = "d";
  6021. break;
  6022. case BuiltinType::LongDouble:
  6023. EncType = "ld";
  6024. break;
  6025. default:
  6026. return false;
  6027. }
  6028. Enc += EncType;
  6029. return true;
  6030. }
  6031. /// Appends a pointer encoding to Enc before calling appendType for the pointee.
  6032. static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
  6033. const CodeGen::CodeGenModule &CGM,
  6034. TypeStringCache &TSC) {
  6035. Enc += "p(";
  6036. if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
  6037. return false;
  6038. Enc += ')';
  6039. return true;
  6040. }
  6041. /// Appends array encoding to Enc before calling appendType for the element.
  6042. static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
  6043. const ArrayType *AT,
  6044. const CodeGen::CodeGenModule &CGM,
  6045. TypeStringCache &TSC, StringRef NoSizeEnc) {
  6046. if (AT->getSizeModifier() != ArrayType::Normal)
  6047. return false;
  6048. Enc += "a(";
  6049. if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
  6050. CAT->getSize().toStringUnsigned(Enc);
  6051. else
  6052. Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
  6053. Enc += ':';
  6054. // The Qualifiers should be attached to the type rather than the array.
  6055. appendQualifier(Enc, QT);
  6056. if (!appendType(Enc, AT->getElementType(), CGM, TSC))
  6057. return false;
  6058. Enc += ')';
  6059. return true;
  6060. }
  6061. /// Appends a function encoding to Enc, calling appendType for the return type
  6062. /// and the arguments.
  6063. static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
  6064. const CodeGen::CodeGenModule &CGM,
  6065. TypeStringCache &TSC) {
  6066. Enc += "f{";
  6067. if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
  6068. return false;
  6069. Enc += "}(";
  6070. if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
  6071. // N.B. we are only interested in the adjusted param types.
  6072. auto I = FPT->param_type_begin();
  6073. auto E = FPT->param_type_end();
  6074. if (I != E) {
  6075. do {
  6076. if (!appendType(Enc, *I, CGM, TSC))
  6077. return false;
  6078. ++I;
  6079. if (I != E)
  6080. Enc += ',';
  6081. } while (I != E);
  6082. if (FPT->isVariadic())
  6083. Enc += ",va";
  6084. } else {
  6085. if (FPT->isVariadic())
  6086. Enc += "va";
  6087. else
  6088. Enc += '0';
  6089. }
  6090. }
  6091. Enc += ')';
  6092. return true;
  6093. }
  6094. /// Handles the type's qualifier before dispatching a call to handle specific
  6095. /// type encodings.
  6096. static bool appendType(SmallStringEnc &Enc, QualType QType,
  6097. const CodeGen::CodeGenModule &CGM,
  6098. TypeStringCache &TSC) {
  6099. QualType QT = QType.getCanonicalType();
  6100. if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
  6101. // The Qualifiers should be attached to the type rather than the array.
  6102. // Thus we don't call appendQualifier() here.
  6103. return appendArrayType(Enc, QT, AT, CGM, TSC, "");
  6104. appendQualifier(Enc, QT);
  6105. if (const BuiltinType *BT = QT->getAs<BuiltinType>())
  6106. return appendBuiltinType(Enc, BT);
  6107. if (const PointerType *PT = QT->getAs<PointerType>())
  6108. return appendPointerType(Enc, PT, CGM, TSC);
  6109. if (const EnumType *ET = QT->getAs<EnumType>())
  6110. return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
  6111. if (const RecordType *RT = QT->getAsStructureType())
  6112. return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
  6113. if (const RecordType *RT = QT->getAsUnionType())
  6114. return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
  6115. if (const FunctionType *FT = QT->getAs<FunctionType>())
  6116. return appendFunctionType(Enc, FT, CGM, TSC);
  6117. return false;
  6118. }
  6119. static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
  6120. CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
  6121. if (!D)
  6122. return false;
  6123. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  6124. if (FD->getLanguageLinkage() != CLanguageLinkage)
  6125. return false;
  6126. return appendType(Enc, FD->getType(), CGM, TSC);
  6127. }
  6128. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  6129. if (VD->getLanguageLinkage() != CLanguageLinkage)
  6130. return false;
  6131. QualType QT = VD->getType().getCanonicalType();
  6132. if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
  6133. // Global ArrayTypes are given a size of '*' if the size is unknown.
  6134. // The Qualifiers should be attached to the type rather than the array.
  6135. // Thus we don't call appendQualifier() here.
  6136. return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
  6137. }
  6138. return appendType(Enc, QT, CGM, TSC);
  6139. }
  6140. return false;
  6141. }
  6142. //===----------------------------------------------------------------------===//
  6143. // Driver code
  6144. //===----------------------------------------------------------------------===//
  6145. const llvm::Triple &CodeGenModule::getTriple() const {
  6146. return getTarget().getTriple();
  6147. }
  6148. bool CodeGenModule::supportsCOMDAT() const {
  6149. return !getTriple().isOSBinFormatMachO();
  6150. }
  6151. const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
  6152. if (TheTargetCodeGenInfo)
  6153. return *TheTargetCodeGenInfo;
  6154. const llvm::Triple &Triple = getTarget().getTriple();
  6155. switch (Triple.getArch()) {
  6156. default:
  6157. return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
  6158. case llvm::Triple::le32:
  6159. return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
  6160. case llvm::Triple::mips:
  6161. case llvm::Triple::mipsel:
  6162. if (Triple.getOS() == llvm::Triple::NaCl)
  6163. return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
  6164. return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
  6165. case llvm::Triple::mips64:
  6166. case llvm::Triple::mips64el:
  6167. return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
  6168. case llvm::Triple::aarch64:
  6169. case llvm::Triple::aarch64_be: {
  6170. AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
  6171. if (getTarget().getABI() == "darwinpcs")
  6172. Kind = AArch64ABIInfo::DarwinPCS;
  6173. return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
  6174. }
  6175. case llvm::Triple::wasm32:
  6176. case llvm::Triple::wasm64:
  6177. return *(TheTargetCodeGenInfo = new WebAssemblyTargetCodeGenInfo(Types));
  6178. case llvm::Triple::arm:
  6179. case llvm::Triple::armeb:
  6180. case llvm::Triple::thumb:
  6181. case llvm::Triple::thumbeb:
  6182. {
  6183. if (Triple.getOS() == llvm::Triple::Win32) {
  6184. TheTargetCodeGenInfo =
  6185. new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP);
  6186. return *TheTargetCodeGenInfo;
  6187. }
  6188. ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
  6189. if (getTarget().getABI() == "apcs-gnu")
  6190. Kind = ARMABIInfo::APCS;
  6191. else if (CodeGenOpts.FloatABI == "hard" ||
  6192. (CodeGenOpts.FloatABI != "soft" &&
  6193. Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
  6194. Kind = ARMABIInfo::AAPCS_VFP;
  6195. return *(TheTargetCodeGenInfo = new ARMTargetCodeGenInfo(Types, Kind));
  6196. }
  6197. case llvm::Triple::ppc:
  6198. return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
  6199. case llvm::Triple::ppc64:
  6200. if (Triple.isOSBinFormatELF()) {
  6201. PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
  6202. if (getTarget().getABI() == "elfv2")
  6203. Kind = PPC64_SVR4_ABIInfo::ELFv2;
  6204. bool HasQPX = getTarget().getABI() == "elfv1-qpx";
  6205. return *(TheTargetCodeGenInfo =
  6206. new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
  6207. } else
  6208. return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
  6209. case llvm::Triple::ppc64le: {
  6210. assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
  6211. PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
  6212. if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
  6213. Kind = PPC64_SVR4_ABIInfo::ELFv1;
  6214. bool HasQPX = getTarget().getABI() == "elfv1-qpx";
  6215. return *(TheTargetCodeGenInfo =
  6216. new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
  6217. }
  6218. case llvm::Triple::nvptx:
  6219. case llvm::Triple::nvptx64:
  6220. return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
  6221. case llvm::Triple::msp430:
  6222. return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
  6223. case llvm::Triple::systemz: {
  6224. bool HasVector = getTarget().getABI() == "vector";
  6225. return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types,
  6226. HasVector));
  6227. }
  6228. case llvm::Triple::tce:
  6229. return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
  6230. case llvm::Triple::x86: {
  6231. bool IsDarwinVectorABI = Triple.isOSDarwin();
  6232. bool RetSmallStructInRegABI =
  6233. X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
  6234. bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
  6235. if (Triple.getOS() == llvm::Triple::Win32) {
  6236. return *(TheTargetCodeGenInfo = new WinX86_32TargetCodeGenInfo(
  6237. Types, IsDarwinVectorABI, RetSmallStructInRegABI,
  6238. IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
  6239. } else {
  6240. return *(TheTargetCodeGenInfo = new X86_32TargetCodeGenInfo(
  6241. Types, IsDarwinVectorABI, RetSmallStructInRegABI,
  6242. IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
  6243. CodeGenOpts.FloatABI == "soft"));
  6244. }
  6245. }
  6246. case llvm::Triple::x86_64: {
  6247. StringRef ABI = getTarget().getABI();
  6248. X86AVXABILevel AVXLevel = (ABI == "avx512" ? X86AVXABILevel::AVX512 :
  6249. ABI == "avx" ? X86AVXABILevel::AVX :
  6250. X86AVXABILevel::None);
  6251. switch (Triple.getOS()) {
  6252. case llvm::Triple::Win32:
  6253. return *(TheTargetCodeGenInfo =
  6254. new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
  6255. case llvm::Triple::PS4:
  6256. return *(TheTargetCodeGenInfo =
  6257. new PS4TargetCodeGenInfo(Types, AVXLevel));
  6258. default:
  6259. return *(TheTargetCodeGenInfo =
  6260. new X86_64TargetCodeGenInfo(Types, AVXLevel));
  6261. }
  6262. }
  6263. case llvm::Triple::hexagon:
  6264. return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
  6265. case llvm::Triple::r600:
  6266. return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
  6267. case llvm::Triple::amdgcn:
  6268. return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
  6269. case llvm::Triple::sparcv9:
  6270. return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
  6271. case llvm::Triple::xcore:
  6272. return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
  6273. }
  6274. }