TargetInfo.cpp 260 KB

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