TargetInfo.cpp 333 KB

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