HLOperationLower.cpp 259 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // HLOperationLower.cpp //
  4. // Copyright (C) Microsoft Corporation. All rights reserved. //
  5. // This file is distributed under the University of Illinois Open Source //
  6. // License. See LICENSE.TXT for details. //
  7. // //
  8. // Lower functions to lower HL operations to DXIL operations. //
  9. // //
  10. ///////////////////////////////////////////////////////////////////////////////
  11. #include "dxc/HLSL/DxilModule.h"
  12. #include "dxc/HLSL/DxilOperations.h"
  13. #include "dxc/HLSL/HLMatrixLowerHelper.h"
  14. #include "dxc/HLSL/HLModule.h"
  15. #include "dxc/HLSL/HLOperationLower.h"
  16. #include "dxc/HLSL/HLOperationLowerExtension.h"
  17. #include "dxc/HLSL/HLOperations.h"
  18. #include "dxc/HlslIntrinsicOp.h"
  19. #include "llvm/IR/GetElementPtrTypeIterator.h"
  20. #include "llvm/IR/IRBuilder.h"
  21. #include "llvm/IR/Instructions.h"
  22. #include "llvm/IR/Module.h"
  23. #include <unordered_set>
  24. using namespace llvm;
  25. using namespace hlsl;
  26. struct HLOperationLowerHelper {
  27. OP &hlslOP;
  28. Type *voidTy;
  29. Type *f32Ty;
  30. Type *i32Ty;
  31. llvm::Type *i1Ty;
  32. Type *i8Ty;
  33. DxilTypeSystem &dxilTypeSys;
  34. HLFunctionProps *functionProps;
  35. bool bLegacyCBufferLoad;
  36. DataLayout legacyDataLayout;
  37. HLOperationLowerHelper(HLModule &HLM);
  38. };
  39. HLOperationLowerHelper::HLOperationLowerHelper(HLModule &HLM)
  40. : hlslOP(*HLM.GetOP()), dxilTypeSys(HLM.GetTypeSystem()),
  41. legacyDataLayout(HLModule::GetLegacyDataLayoutDesc()) {
  42. llvm::LLVMContext &Ctx = HLM.GetCtx();
  43. voidTy = Type::getVoidTy(Ctx);
  44. f32Ty = Type::getFloatTy(Ctx);
  45. i32Ty = Type::getInt32Ty(Ctx);
  46. i1Ty = Type::getInt1Ty(Ctx);
  47. i8Ty = Type::getInt8Ty(Ctx);
  48. Function *EntryFunc = HLM.GetEntryFunction();
  49. functionProps = &HLM.GetHLFunctionProps(EntryFunc);
  50. bLegacyCBufferLoad = HLM.GetHLOptions().bLegacyCBufferLoad;
  51. }
  52. struct HLObjectOperationLowerHelper {
  53. private:
  54. // For object intrinsics.
  55. HLModule &HLM;
  56. struct ResAttribute {
  57. DXIL::ResourceClass RC;
  58. DXIL::ResourceKind RK;
  59. Type *ResourceType;
  60. };
  61. std::unordered_map<Value *, ResAttribute> HandleMetaMap;
  62. std::unordered_set<LoadInst *> &UpdateCounterSet;
  63. std::unordered_set<Value *> &NonUniformSet;
  64. // Map from pointer of cbuffer to pointer of resource.
  65. // For cbuffer like this:
  66. // cbuffer A {
  67. // Texture2D T;
  68. // };
  69. // A global resource Texture2D T2 will be created for Texture2D T.
  70. // CBPtrToResourceMap[T] will return T2.
  71. std::unordered_map<Value *, Value *> CBPtrToResourceMap;
  72. public:
  73. HLObjectOperationLowerHelper(HLModule &HLM,
  74. std::unordered_set<LoadInst *> &UpdateCounter,
  75. std::unordered_set<Value *> &NonUniform)
  76. : HLM(HLM), UpdateCounterSet(UpdateCounter), NonUniformSet(NonUniform) {}
  77. DXIL::ResourceClass GetRC(Value *Handle) {
  78. ResAttribute &Res = FindCreateHandleResourceBase(Handle);
  79. return Res.RC;
  80. }
  81. DXIL::ResourceKind GetRK(Value *Handle) {
  82. ResAttribute &Res = FindCreateHandleResourceBase(Handle);
  83. return Res.RK;
  84. }
  85. Type *GetResourceType(Value *Handle) {
  86. ResAttribute &Res = FindCreateHandleResourceBase(Handle);
  87. return Res.ResourceType;
  88. }
  89. void MarkHasCounter(Type *Ty, Value *handle) {
  90. DXIL::ResourceClass RC = GetRC(handle);
  91. DXASSERT_LOCALVAR(RC, RC == DXIL::ResourceClass::UAV,
  92. "must UAV for counter");
  93. std::unordered_set<Value *> resSet;
  94. MarkHasCounterOnCreateHandle(handle, resSet);
  95. }
  96. void MarkNonUniform(Value *V) { NonUniformSet.insert(V); }
  97. Value *GetOrCreateResourceForCbPtr(GetElementPtrInst *CbPtr,
  98. GlobalVariable *CbGV, MDNode *MD) {
  99. // Change array idx to 0 to make sure all array ptr share same key.
  100. Value *Key = UniformCbPtr(CbPtr, CbGV);
  101. if (CBPtrToResourceMap.count(Key))
  102. return CBPtrToResourceMap[Key];
  103. Value *Resource = CreateResourceForCbPtr(CbPtr, CbGV, MD);
  104. CBPtrToResourceMap[Key] = Resource;
  105. return Resource;
  106. }
  107. Value *LowerCbResourcePtr(GetElementPtrInst *CbPtr, Value *ResPtr) {
  108. // Simple case.
  109. if (ResPtr->getType() == CbPtr->getType())
  110. return ResPtr;
  111. // Array case.
  112. DXASSERT_NOMSG(ResPtr->getType()->getPointerElementType()->isArrayTy());
  113. IRBuilder<> Builder(CbPtr);
  114. gep_type_iterator GEPIt = gep_type_begin(CbPtr), E = gep_type_end(CbPtr);
  115. Value *arrayIdx = GEPIt.getOperand();
  116. // Only calc array idx and size.
  117. // Ignore struct type part.
  118. for (; GEPIt != E; ++GEPIt) {
  119. if (GEPIt->isArrayTy()) {
  120. arrayIdx = Builder.CreateMul(
  121. arrayIdx, Builder.getInt32(GEPIt->getArrayNumElements()));
  122. arrayIdx = Builder.CreateAdd(arrayIdx, GEPIt.getOperand());
  123. }
  124. }
  125. return Builder.CreateGEP(ResPtr, {Builder.getInt32(0), arrayIdx});
  126. }
  127. private:
  128. ResAttribute &FindCreateHandleResourceBase(Value *Handle) {
  129. if (HandleMetaMap.count(Handle))
  130. return HandleMetaMap[Handle];
  131. // Add invalid first to avoid dead loop.
  132. HandleMetaMap[Handle] = {DXIL::ResourceClass::Invalid,
  133. DXIL::ResourceKind::Invalid,
  134. StructType::get(Type::getVoidTy(HLM.GetCtx()))};
  135. if (Argument *Arg = dyn_cast<Argument>(Handle)) {
  136. MDNode *MD = HLM.GetDxilResourceAttrib(Arg);
  137. if (!MD) {
  138. Handle->getContext().emitError("cannot map resource to handle");
  139. return HandleMetaMap[Handle];
  140. }
  141. DxilResourceBase Res(DxilResource::Class::Invalid);
  142. HLM.LoadDxilResourceBaseFromMDNode(MD, Res);
  143. ResAttribute Attrib = {Res.GetClass(), Res.GetKind(),
  144. Res.GetGlobalSymbol()->getType()};
  145. HandleMetaMap[Handle] = Attrib;
  146. return HandleMetaMap[Handle];
  147. }
  148. if (CallInst *CI = dyn_cast<CallInst>(Handle)) {
  149. MDNode *MD = HLM.GetDxilResourceAttrib(CI->getCalledFunction());
  150. if (!MD) {
  151. Handle->getContext().emitError("cannot map resource to handle");
  152. return HandleMetaMap[Handle];
  153. }
  154. DxilResourceBase Res(DxilResource::Class::Invalid);
  155. HLM.LoadDxilResourceBaseFromMDNode(MD, Res);
  156. ResAttribute Attrib = {Res.GetClass(), Res.GetKind(),
  157. Res.GetGlobalSymbol()->getType()};
  158. HandleMetaMap[Handle] = Attrib;
  159. return HandleMetaMap[Handle];
  160. }
  161. if (SelectInst *Sel = dyn_cast<SelectInst>(Handle)) {
  162. ResAttribute &ResT = FindCreateHandleResourceBase(Sel->getTrueValue());
  163. // Use MDT here, ResourceClass, ResourceID match is done at
  164. // DxilGenerationPass::AddCreateHandleForPhiNodeAndSelect.
  165. HandleMetaMap[Handle] = ResT;
  166. FindCreateHandleResourceBase(Sel->getFalseValue());
  167. return ResT;
  168. }
  169. if (PHINode *Phi = dyn_cast<PHINode>(Handle)) {
  170. if (Phi->getNumOperands() == 0) {
  171. Handle->getContext().emitError("cannot map resource to handle");
  172. return HandleMetaMap[Handle];
  173. }
  174. ResAttribute &Res0 = FindCreateHandleResourceBase(Phi->getOperand(0));
  175. // Use Res0 here, ResourceClass, ResourceID match is done at
  176. // DxilGenerationPass::AddCreateHandleForPhiNodeAndSelect.
  177. HandleMetaMap[Handle] = Res0;
  178. for (unsigned i = 1; i < Phi->getNumOperands(); i++) {
  179. FindCreateHandleResourceBase(Phi->getOperand(i));
  180. }
  181. return Res0;
  182. }
  183. Handle->getContext().emitError("cannot map resource to handle");
  184. return HandleMetaMap[Handle];
  185. }
  186. CallInst *FindCreateHandle(Value *handle,
  187. std::unordered_set<Value *> &resSet) {
  188. // Already checked.
  189. if (resSet.count(handle))
  190. return nullptr;
  191. resSet.insert(handle);
  192. if (CallInst *CI = dyn_cast<CallInst>(handle))
  193. return CI;
  194. if (SelectInst *Sel = dyn_cast<SelectInst>(handle)) {
  195. if (CallInst *CI = FindCreateHandle(Sel->getTrueValue(), resSet))
  196. return CI;
  197. if (CallInst *CI = FindCreateHandle(Sel->getFalseValue(), resSet))
  198. return CI;
  199. return nullptr;
  200. }
  201. if (PHINode *Phi = dyn_cast<PHINode>(handle)) {
  202. for (unsigned i = 0; i < Phi->getNumOperands(); i++) {
  203. if (CallInst *CI = FindCreateHandle(Phi->getOperand(i), resSet))
  204. return CI;
  205. }
  206. return nullptr;
  207. }
  208. return nullptr;
  209. }
  210. void MarkHasCounterOnCreateHandle(Value *handle,
  211. std::unordered_set<Value *> &resSet) {
  212. // Already checked.
  213. if (resSet.count(handle))
  214. return;
  215. resSet.insert(handle);
  216. if (CallInst *CI = dyn_cast<CallInst>(handle)) {
  217. Value *Res =
  218. CI->getArgOperand(HLOperandIndex::kCreateHandleResourceOpIdx);
  219. LoadInst *LdRes = dyn_cast<LoadInst>(Res);
  220. if (!LdRes) {
  221. CI->getContext().emitError(CI, "cannot map resource to handle");
  222. return;
  223. }
  224. UpdateCounterSet.insert(LdRes);
  225. return;
  226. }
  227. if (SelectInst *Sel = dyn_cast<SelectInst>(handle)) {
  228. MarkHasCounterOnCreateHandle(Sel->getTrueValue(), resSet);
  229. MarkHasCounterOnCreateHandle(Sel->getFalseValue(), resSet);
  230. }
  231. if (PHINode *Phi = dyn_cast<PHINode>(handle)) {
  232. for (unsigned i = 0; i < Phi->getNumOperands(); i++) {
  233. MarkHasCounterOnCreateHandle(Phi->getOperand(i), resSet);
  234. }
  235. }
  236. }
  237. Value *UniformCbPtr(GetElementPtrInst *CbPtr, GlobalVariable *CbGV) {
  238. gep_type_iterator GEPIt = gep_type_begin(CbPtr), E = gep_type_end(CbPtr);
  239. std::vector<Value *> idxList(CbPtr->idx_begin(), CbPtr->idx_end());
  240. unsigned i = 0;
  241. IRBuilder<> Builder(HLM.GetCtx());
  242. Value *zero = Builder.getInt32(0);
  243. for (; GEPIt != E; ++GEPIt, ++i) {
  244. if (GEPIt->isArrayTy()) {
  245. // Change array idx to 0 to make sure all array ptr share same key.
  246. idxList[i] = zero;
  247. }
  248. }
  249. Value *Key = Builder.CreateInBoundsGEP(CbGV, idxList);
  250. return Key;
  251. }
  252. Value *CreateResourceForCbPtr(GetElementPtrInst *CbPtr, GlobalVariable *CbGV,
  253. MDNode *MD) {
  254. Type *CbTy = CbPtr->getPointerOperandType();
  255. DXASSERT_NOMSG(CbTy == CbGV->getType());
  256. gep_type_iterator GEPIt = gep_type_begin(CbPtr), E = gep_type_end(CbPtr);
  257. unsigned i = 0;
  258. IRBuilder<> Builder(HLM.GetCtx());
  259. unsigned arraySize = 1;
  260. DxilTypeSystem &typeSys = HLM.GetTypeSystem();
  261. std::string Name;
  262. for (; GEPIt != E; ++GEPIt, ++i) {
  263. if (GEPIt->isArrayTy()) {
  264. arraySize *= GEPIt->getArrayNumElements();
  265. } else if (GEPIt->isStructTy()) {
  266. DxilStructAnnotation *typeAnnot =
  267. typeSys.GetStructAnnotation(cast<StructType>(*GEPIt));
  268. DXASSERT_NOMSG(typeAnnot);
  269. unsigned idx = cast<ConstantInt>(GEPIt.getOperand())->getLimitedValue();
  270. DXASSERT_NOMSG(typeAnnot->GetNumFields() > idx);
  271. DxilFieldAnnotation &fieldAnnot = typeAnnot->GetFieldAnnotation(idx);
  272. if (!Name.empty())
  273. Name += ".";
  274. Name += fieldAnnot.GetFieldName();
  275. }
  276. }
  277. Type *Ty = CbPtr->getResultElementType();
  278. if (arraySize > 1) {
  279. Ty = ArrayType::get(Ty, arraySize);
  280. }
  281. return CreateResourceGV(Ty, Name, MD);
  282. }
  283. Value *CreateResourceGV(Type *Ty, StringRef Name, MDNode *MD) {
  284. Module &M = *HLM.GetModule();
  285. Constant *GV = M.getOrInsertGlobal(Name, Ty);
  286. // Create resource and set GV as globalSym.
  287. HLM.AddResourceWithGlobalVariableAndMDNode(GV, MD);
  288. return GV;
  289. }
  290. };
  291. using IntrinsicLowerFuncTy = Value *(CallInst *CI, IntrinsicOp IOP,
  292. DXIL::OpCode opcode,
  293. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated);
  294. struct IntrinsicLower {
  295. // Intrinsic opcode.
  296. IntrinsicOp IntriOpcode;
  297. // Lower function.
  298. IntrinsicLowerFuncTy &LowerFunc;
  299. // DXIL opcode if can direct map.
  300. DXIL::OpCode DxilOpcode;
  301. };
  302. // IOP intrinsics.
  303. namespace {
  304. Value *TrivialDxilOperation(Function *dxilFunc, OP::OpCode opcode, ArrayRef<Value *> refArgs,
  305. Type *Ty, Type *RetTy, OP *hlslOP,
  306. IRBuilder<> &Builder) {
  307. unsigned argNum = refArgs.size();
  308. std::vector<Value *> args = refArgs;
  309. if (Ty->isVectorTy()) {
  310. Value *retVal = llvm::UndefValue::get(RetTy);
  311. unsigned vecSize = Ty->getVectorNumElements();
  312. for (unsigned i = 0; i < vecSize; i++) {
  313. // Update vector args, skip known opcode arg.
  314. for (unsigned argIdx = HLOperandIndex::kUnaryOpSrc0Idx; argIdx < argNum;
  315. argIdx++) {
  316. if (refArgs[argIdx]->getType()->isVectorTy()) {
  317. Value *arg = refArgs[argIdx];
  318. args[argIdx] = Builder.CreateExtractElement(arg, i);
  319. }
  320. }
  321. Value *EltOP =
  322. Builder.CreateCall(dxilFunc, args, hlslOP->GetOpCodeName(opcode));
  323. retVal = Builder.CreateInsertElement(retVal, EltOP, i);
  324. }
  325. return retVal;
  326. } else {
  327. Value *retVal =
  328. Builder.CreateCall(dxilFunc, args, hlslOP->GetOpCodeName(opcode));
  329. return retVal;
  330. }
  331. }
  332. // Generates a DXIL operation over an overloaded type (Ty), returning a
  333. // RetTy value; when Ty is a vector, it will replicate per-element operations
  334. // into RetTy to rebuild it.
  335. Value *TrivialDxilOperation(OP::OpCode opcode, ArrayRef<Value *> refArgs,
  336. Type *Ty, Type *RetTy, OP *hlslOP,
  337. IRBuilder<> &Builder) {
  338. Type *EltTy = Ty->getScalarType();
  339. Function *dxilFunc = hlslOP->GetOpFunc(opcode, EltTy);
  340. return TrivialDxilOperation(dxilFunc, opcode, refArgs, Ty, RetTy, hlslOP, Builder);
  341. }
  342. Value *TrivialDxilOperation(OP::OpCode opcode, ArrayRef<Value *> refArgs,
  343. Type *Ty, Instruction *Inst, OP *hlslOP) {
  344. DXASSERT(refArgs.size() > 0, "else opcode isn't in signature");
  345. DXASSERT(refArgs[0] == nullptr,
  346. "else caller has already filled the value in");
  347. IRBuilder<> B(Inst);
  348. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  349. const_cast<llvm::Value **>(refArgs.data())[0] =
  350. opArg; // actually stack memory from caller
  351. return TrivialDxilOperation(opcode, refArgs, Ty, Inst->getType(), hlslOP, B);
  352. }
  353. Value *TrivialDxilUnaryOperationRet(OP::OpCode opcode, Value *src, Type *RetTy,
  354. hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  355. Type *Ty = src->getType();
  356. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  357. Value *args[] = {opArg, src};
  358. return TrivialDxilOperation(opcode, args, Ty, RetTy, hlslOP, Builder);
  359. }
  360. Value *TrivialDxilUnaryOperation(OP::OpCode opcode, Value *src,
  361. hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  362. return TrivialDxilUnaryOperationRet(opcode, src, src->getType(), hlslOP,
  363. Builder);
  364. }
  365. Value *TrivialDxilBinaryOperation(OP::OpCode opcode, Value *src0, Value *src1,
  366. hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  367. Type *Ty = src0->getType();
  368. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  369. Value *args[] = {opArg, src0, src1};
  370. return TrivialDxilOperation(opcode, args, Ty, Ty, hlslOP, Builder);
  371. }
  372. Value *TrivialDxilTrinaryOperation(OP::OpCode opcode, Value *src0, Value *src1,
  373. Value *src2, hlsl::OP *hlslOP,
  374. IRBuilder<> &Builder) {
  375. Type *Ty = src0->getType();
  376. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  377. Value *args[] = {opArg, src0, src1, src2};
  378. return TrivialDxilOperation(opcode, args, Ty, Ty, hlslOP, Builder);
  379. }
  380. Value *TrivialUnaryOperation(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  381. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  382. Value *src0 = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  383. IRBuilder<> Builder(CI);
  384. hlsl::OP *hlslOP = &helper.hlslOP;
  385. Value *retVal = TrivialDxilUnaryOperationRet(opcode, src0, CI->getType(), hlslOP, Builder);
  386. return retVal;
  387. }
  388. Value *TrivialBinaryOperation(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  389. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  390. hlsl::OP *hlslOP = &helper.hlslOP;
  391. Value *src0 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  392. Value *src1 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  393. IRBuilder<> Builder(CI);
  394. Value *binOp =
  395. TrivialDxilBinaryOperation(opcode, src0, src1, hlslOP, Builder);
  396. return binOp;
  397. }
  398. Value *TrivialTrinaryOperation(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  399. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  400. hlsl::OP *hlslOP = &helper.hlslOP;
  401. Value *src0 = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc0Idx);
  402. Value *src1 = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc1Idx);
  403. Value *src2 = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc2Idx);
  404. IRBuilder<> Builder(CI);
  405. Value *triOp =
  406. TrivialDxilTrinaryOperation(opcode, src0, src1, src2, hlslOP, Builder);
  407. return triOp;
  408. }
  409. Value *TrivialIsSpecialFloat(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  410. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  411. hlsl::OP *hlslOP = &helper.hlslOP;
  412. Value *src = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  413. IRBuilder<> Builder(CI);
  414. Type *Ty = src->getType();
  415. Type *RetTy = Type::getInt1Ty(CI->getContext());
  416. if (Ty->isVectorTy())
  417. RetTy = VectorType::get(RetTy, Ty->getVectorNumElements());
  418. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  419. Value *args[] = {opArg, src};
  420. return TrivialDxilOperation(opcode, args, Ty, RetTy, hlslOP, Builder);
  421. }
  422. Value *TranslateNonUniformResourceIndex(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  423. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  424. for (User *U : CI->users()) {
  425. if (CastInst *I = dyn_cast<CastInst>(U)) {
  426. pObjHelper->MarkNonUniform(I);
  427. }
  428. }
  429. Value *V = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  430. pObjHelper->MarkNonUniform(V);
  431. CI->replaceAllUsesWith(V);
  432. return nullptr;
  433. }
  434. Value *TrivialBarrier(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  435. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  436. hlsl::OP *OP = &helper.hlslOP;
  437. Function *dxilFunc = OP->GetOpFunc(OP::OpCode::Barrier, CI->getType());
  438. Constant *opArg = OP->GetU32Const((unsigned)OP::OpCode::Barrier);
  439. unsigned uglobal = static_cast<unsigned>(DXIL::BarrierMode::UAVFenceGlobal);
  440. unsigned g = static_cast<unsigned>(DXIL::BarrierMode::TGSMFence);
  441. unsigned t = static_cast<unsigned>(DXIL::BarrierMode::SyncThreadGroup);
  442. // unsigned ut = static_cast<unsigned>(DXIL::BarrierMode::UAVFenceThreadGroup);
  443. unsigned barrierMode;
  444. switch (IOP) {
  445. case IntrinsicOp::IOP_AllMemoryBarrier:
  446. barrierMode = uglobal | g;
  447. break;
  448. case IntrinsicOp::IOP_AllMemoryBarrierWithGroupSync:
  449. barrierMode = uglobal | g | t;
  450. break;
  451. case IntrinsicOp::IOP_GroupMemoryBarrier:
  452. barrierMode = g;
  453. break;
  454. case IntrinsicOp::IOP_GroupMemoryBarrierWithGroupSync:
  455. barrierMode = g | t;
  456. break;
  457. case IntrinsicOp::IOP_DeviceMemoryBarrier:
  458. barrierMode = uglobal;
  459. break;
  460. case IntrinsicOp::IOP_DeviceMemoryBarrierWithGroupSync:
  461. barrierMode = uglobal | t;
  462. break;
  463. default:
  464. DXASSERT(0, "invalid opcode for barrier");
  465. break;
  466. }
  467. Value *src0 = OP->GetU32Const(static_cast<unsigned>(barrierMode));
  468. Value *args[] = {opArg, src0};
  469. IRBuilder<> Builder(CI);
  470. Builder.CreateCall(dxilFunc, args);
  471. return nullptr;
  472. }
  473. Value *TranslateD3DColorToUByte4(CallInst *CI, IntrinsicOp IOP,
  474. OP::OpCode opcode,
  475. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  476. hlsl::OP *hlslOP = &helper.hlslOP;
  477. IRBuilder<> Builder(CI);
  478. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  479. Type *Ty = val->getType();
  480. Constant *toByteConst = ConstantFP::get(Ty->getScalarType(), 255);
  481. if (Ty != Ty->getScalarType()) {
  482. toByteConst =
  483. ConstantVector::getSplat(Ty->getVectorNumElements(), toByteConst);
  484. }
  485. Value *byte4 = Builder.CreateFMul(toByteConst, val);
  486. byte4 =
  487. TrivialDxilUnaryOperation(OP::OpCode::Round_z, byte4, hlslOP, Builder);
  488. return Builder.CreateBitCast(byte4, CI->getType());
  489. }
  490. Value *TranslateAddUint64(CallInst *CI, IntrinsicOp IOP,
  491. OP::OpCode opcode,
  492. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  493. hlsl::OP *hlslOP = &helper.hlslOP;
  494. IRBuilder<> Builder(CI);
  495. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  496. Type *Ty = val->getType();
  497. VectorType *VT = dyn_cast<VectorType>(Ty);
  498. if (!VT) {
  499. CI->getContext().emitError(
  500. CI, "AddUint64 can only be applied to uint2 and uint4 operands");
  501. return UndefValue::get(Ty);
  502. }
  503. unsigned size = VT->getNumElements();
  504. if (size != 2 && size != 4) {
  505. CI->getContext().emitError(
  506. CI, "AddUint64 can only be applied to uint2 and uint4 operands");
  507. return UndefValue::get(Ty);
  508. }
  509. Value *op0 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  510. Value *op1 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  511. Value *RetVal = UndefValue::get(Ty);
  512. Function *AddC = hlslOP->GetOpFunc(DXIL::OpCode::UAddc, helper.i32Ty);
  513. Value *opArg = Builder.getInt32(static_cast<unsigned>(DXIL::OpCode::UAddc));
  514. for (unsigned i=0; i<size; i+=2) {
  515. Value *low0 = Builder.CreateExtractElement(op0, i);
  516. Value *low1 = Builder.CreateExtractElement(op1, i);
  517. Value *lowWithC = Builder.CreateCall(AddC, { opArg, low0, low1});
  518. Value *low = Builder.CreateExtractValue(lowWithC, 0);
  519. RetVal = Builder.CreateInsertElement(RetVal, low, i);
  520. Value *carry = Builder.CreateExtractValue(lowWithC, 1);
  521. // Ext i1 to i32
  522. carry = Builder.CreateZExt(carry, helper.i32Ty);
  523. Value *hi0 = Builder.CreateExtractElement(op0, i+1);
  524. Value *hi1 = Builder.CreateExtractElement(op1, i+1);
  525. Value *hi = Builder.CreateAdd(hi0, hi1);
  526. hi = Builder.CreateAdd(hi, carry);
  527. RetVal = Builder.CreateInsertElement(RetVal, hi, i+1);
  528. }
  529. return RetVal;
  530. }
  531. bool IsValidLoadInput(Value *V) {
  532. // Must be load input.
  533. // TODO: report this error on front-end
  534. if (!isa<CallInst>(V)) {
  535. V->getContext().emitError("attribute evaluation can only be done on values "
  536. "taken directly from inputs");
  537. return false;
  538. }
  539. CallInst *CI = cast<CallInst>(V);
  540. // Must be immediate.
  541. ConstantInt *opArg =
  542. cast<ConstantInt>(CI->getArgOperand(DXIL::OperandIndex::kOpcodeIdx));
  543. DXIL::OpCode op = static_cast<DXIL::OpCode>(opArg->getLimitedValue());
  544. if (op != DXIL::OpCode::LoadInput) {
  545. V->getContext().emitError("attribute evaluation can only be done on values "
  546. "taken directly from inputs");
  547. return false;
  548. }
  549. return true;
  550. }
  551. // Apply current shuffle vector mask on top of previous shuffle mask.
  552. // For example, if previous mask is (12,11,10,13) and current mask is (3,1,0,2)
  553. // new mask would be (13,11,12,10)
  554. Constant *AccumulateMask(Constant *curMask, Constant *prevMask) {
  555. if (curMask == nullptr) {
  556. return prevMask;
  557. }
  558. unsigned size = cast<VectorType>(curMask->getType())->getNumElements();
  559. SmallVector<uint32_t, 16> Elts;
  560. for (unsigned i = 0; i != size; ++i) {
  561. ConstantInt *Index = cast<ConstantInt>(curMask->getAggregateElement(i));
  562. ConstantInt *IVal =
  563. cast<ConstantInt>(prevMask->getAggregateElement(Index->getSExtValue()));
  564. Elts.emplace_back(IVal->getSExtValue());
  565. }
  566. return ConstantDataVector::get(curMask->getContext(), Elts);
  567. }
  568. Constant *GetLoadInputsForEvaluate(Value *V, std::vector<CallInst*> &loadList) {
  569. Constant *shufMask = nullptr;
  570. if (V->getType()->isVectorTy()) {
  571. // Must be insert element inst. Keeping track of masks for shuffle vector
  572. Value *Vec = V;
  573. while (ShuffleVectorInst *shuf = dyn_cast<ShuffleVectorInst>(Vec)) {
  574. shufMask = AccumulateMask(shufMask, shuf->getMask());
  575. Vec = shuf->getOperand(0);
  576. }
  577. // TODO: We are assuming that the operand of insertelement is a LoadInput.
  578. // This will fail on the case where we pass in matrix member using array subscript.
  579. while (!isa<UndefValue>(Vec)) {
  580. InsertElementInst *insertInst = cast<InsertElementInst>(Vec);
  581. Vec = insertInst->getOperand(0);
  582. Value *Elt = insertInst->getOperand(1);
  583. if (IsValidLoadInput(Elt)) {
  584. loadList.emplace_back(cast<CallInst>(Elt));
  585. }
  586. }
  587. } else {
  588. if (IsValidLoadInput(V)) {
  589. loadList.emplace_back(cast<CallInst>(V));
  590. }
  591. }
  592. return shufMask;
  593. }
  594. // Swizzle could reduce the dimensionality of the Type, but
  595. // for temporary insertelement instructions should maintain the existing size of the loadinput.
  596. // So we have to analyze the type of src in order to determine the actual size required.
  597. Type *GetInsertElementTypeForEvaluate(Value *src) {
  598. if (InsertElementInst *IE = dyn_cast<InsertElementInst>(src)) {
  599. return src->getType();
  600. }
  601. else if (ShuffleVectorInst *SV = dyn_cast<ShuffleVectorInst>(src)) {
  602. return SV->getOperand(0)->getType();
  603. }
  604. src->getContext().emitError("Invalid type call for EvaluateAttribute function");
  605. return nullptr;
  606. }
  607. Value *TranslateEvalSample(CallInst *CI, IntrinsicOp IOP, OP::OpCode op,
  608. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  609. hlsl::OP *hlslOP = &helper.hlslOP;
  610. Value *val = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  611. Value *sampleIdx = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  612. IRBuilder<> Builder(CI);
  613. std::vector<CallInst*> loadList;
  614. Constant *shufMask = GetLoadInputsForEvaluate(val, loadList);
  615. unsigned size = loadList.size();
  616. OP::OpCode opcode = OP::OpCode::EvalSampleIndex;
  617. Value *opArg = hlslOP->GetU32Const((unsigned)opcode);
  618. Type *Ty = GetInsertElementTypeForEvaluate(val);
  619. Function *evalFunc = hlslOP->GetOpFunc(opcode, Ty->getScalarType());
  620. Value *result = UndefValue::get(Ty);
  621. for (unsigned i = 0; i < size; i++) {
  622. CallInst *loadInput = loadList[size-1-i];
  623. Value *inputElemID = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputIDOpIdx);
  624. Value *rowIdx = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputRowOpIdx);
  625. Value *colIdx = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputColOpIdx);
  626. Value *Elt = Builder.CreateCall(evalFunc, { opArg, inputElemID, rowIdx, colIdx, sampleIdx });
  627. result = Builder.CreateInsertElement(result, Elt, i);
  628. }
  629. if (shufMask)
  630. result = Builder.CreateShuffleVector(result, UndefValue::get(Ty), shufMask);
  631. return result;
  632. }
  633. Value *TranslateEvalSnapped(CallInst *CI, IntrinsicOp IOP, OP::OpCode op,
  634. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  635. hlsl::OP *hlslOP = &helper.hlslOP;
  636. Value *val = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  637. Value *offset = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  638. IRBuilder<> Builder(CI);
  639. Value *offsetX = Builder.CreateExtractElement(offset, (uint64_t)0);
  640. Value *offsetY = Builder.CreateExtractElement(offset, 1);
  641. std::vector<CallInst*> loadList;
  642. Constant *shufMask = GetLoadInputsForEvaluate(val, loadList);
  643. unsigned size = loadList.size();
  644. OP::OpCode opcode = OP::OpCode::EvalSnapped;
  645. Value *opArg = hlslOP->GetU32Const((unsigned)opcode);
  646. Type *Ty = GetInsertElementTypeForEvaluate(val);
  647. Function *evalFunc = hlslOP->GetOpFunc(opcode, Ty->getScalarType());
  648. Value *result = UndefValue::get(Ty);
  649. for (unsigned i = 0; i < size; i++) {
  650. CallInst *loadInput = loadList[size-1-i];
  651. Value *inputElemID = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputIDOpIdx);
  652. Value *rowIdx = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputRowOpIdx);
  653. Value *colIdx = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputColOpIdx);
  654. Value *Elt = Builder.CreateCall(evalFunc, { opArg, inputElemID, rowIdx, colIdx, offsetX, offsetY });
  655. result = Builder.CreateInsertElement(result, Elt, i);
  656. }
  657. if (shufMask)
  658. result = Builder.CreateShuffleVector(result, UndefValue::get(Ty), shufMask);
  659. return result;
  660. }
  661. Value *TranslateEvalCentroid(CallInst *CI, IntrinsicOp IOP, OP::OpCode op,
  662. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  663. hlsl::OP *hlslOP = &helper.hlslOP;
  664. Value *src = CI->getArgOperand(DXIL::OperandIndex::kUnarySrc0OpIdx);
  665. std::vector<CallInst*> loadList;
  666. Constant *shufMask = GetLoadInputsForEvaluate(src, loadList);
  667. unsigned size = loadList.size();
  668. IRBuilder<> Builder(CI);
  669. OP::OpCode opcode = OP::OpCode::EvalCentroid;
  670. Value *opArg = hlslOP->GetU32Const((unsigned)opcode);
  671. Type *Ty = GetInsertElementTypeForEvaluate(src);
  672. Function *evalFunc = hlslOP->GetOpFunc(opcode, Ty->getScalarType());
  673. Value *result = UndefValue::get(Ty);
  674. for (unsigned i = 0; i < size; i++) {
  675. CallInst *loadInput = loadList[size-1-i];
  676. Value *inputElemID = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputIDOpIdx);
  677. Value *rowIdx = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputRowOpIdx);
  678. Value *colIdx = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputColOpIdx);
  679. Value *Elt = Builder.CreateCall(evalFunc, { opArg, inputElemID, rowIdx, colIdx });
  680. result = Builder.CreateInsertElement(result, Elt, i);
  681. }
  682. if (shufMask)
  683. result = Builder.CreateShuffleVector(result, UndefValue::get(Ty), shufMask);
  684. return result;
  685. }
  686. Value *TranslateGetAttributeAtVertex(CallInst *CI, IntrinsicOp IOP, OP::OpCode op,
  687. HLOperationLowerHelper &helper,
  688. HLObjectOperationLowerHelper *pObjHelper,
  689. bool &Translated) {
  690. DXASSERT(op == OP::OpCode::AttributeAtVertex, "Wrong opcode to translate");
  691. hlsl::OP *hlslOP = &helper.hlslOP;
  692. IRBuilder<> Builder(CI);
  693. Type *Ty = CI->getType();
  694. Value *val = CI->getArgOperand(DXIL::OperandIndex::kBinarySrc0OpIdx);
  695. Value *vertexIdx = CI->getArgOperand(DXIL::OperandIndex::kBinarySrc1OpIdx);
  696. Value *vertexI8Idx = Builder.CreateTrunc(vertexIdx, Type::getInt8Ty(CI->getContext()));
  697. // Check the range of VertexID
  698. Value *vertex0 = Builder.getInt8(0);
  699. Value *vertex1 = Builder.getInt8(1);
  700. Value *vertex2 = Builder.getInt8(2);
  701. if (vertexI8Idx != vertex0 && vertexI8Idx != vertex1 && vertexI8Idx != vertex2) {
  702. CI->getContext().emitError(CI, "VertexID at GetAttributeAtVertex can only range from 0 to 2");
  703. return UndefValue::get(Ty);
  704. }
  705. std::vector<CallInst*> loadList;
  706. Constant *shufMask = GetLoadInputsForEvaluate(val, loadList);
  707. unsigned size = loadList.size();
  708. Value *opArg = hlslOP->GetU32Const((unsigned)op);
  709. Function *evalFunc = hlslOP->GetOpFunc(op, Ty->getScalarType());
  710. Value *result = UndefValue::get(Ty);
  711. for (unsigned i = 0; i < size; ++i) {
  712. CallInst *loadInput = loadList[size - 1 - i];
  713. Value *inputElemID = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputIDOpIdx);
  714. Value *rowIdx = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputRowOpIdx);
  715. Value *colIdx = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputColOpIdx);
  716. Value *Elt = Builder.CreateCall(evalFunc, { opArg, inputElemID, rowIdx, colIdx, vertexI8Idx });
  717. result = Builder.CreateInsertElement(result, Elt, i);
  718. }
  719. if (shufMask)
  720. result = Builder.CreateShuffleVector(result, UndefValue::get(Ty), shufMask);
  721. return result;
  722. }
  723. Value *TrivialNoArgOperation(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  724. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  725. hlsl::OP *hlslOP = &helper.hlslOP;
  726. Type *Ty = Type::getVoidTy(CI->getContext());
  727. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  728. Value *args[] = {opArg};
  729. IRBuilder<> Builder(CI);
  730. Value *dxilOp = TrivialDxilOperation(opcode, args, Ty, Ty, hlslOP, Builder);
  731. return dxilOp;
  732. }
  733. Value *TranslateGetRTSamplePos(CallInst *CI, IntrinsicOp IOP, OP::OpCode op,
  734. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  735. hlsl::OP *hlslOP = &helper.hlslOP;
  736. OP::OpCode opcode = OP::OpCode::RenderTargetGetSamplePosition;
  737. IRBuilder<> Builder(CI);
  738. Type *Ty = Type::getVoidTy(CI->getContext());
  739. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  740. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  741. Value *args[] = {opArg, val};
  742. Value *samplePos =
  743. TrivialDxilOperation(opcode, args, Ty, Ty, hlslOP, Builder);
  744. Value *result = UndefValue::get(CI->getType());
  745. Value *samplePosX = Builder.CreateExtractValue(samplePos, 0);
  746. Value *samplePosY = Builder.CreateExtractValue(samplePos, 1);
  747. result = Builder.CreateInsertElement(result, samplePosX, (uint64_t)0);
  748. result = Builder.CreateInsertElement(result, samplePosY, 1);
  749. return result;
  750. }
  751. // val QuadReadLaneAt(val, uint);
  752. Value *TranslateQuadReadLaneAt(CallInst *CI, IntrinsicOp IOP,
  753. OP::OpCode opcode,
  754. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  755. hlsl::OP *hlslOP = &helper.hlslOP;
  756. Value *refArgs[] = {nullptr, CI->getOperand(1), CI->getOperand(2)};
  757. return TrivialDxilOperation(DXIL::OpCode::QuadReadLaneAt, refArgs,
  758. CI->getOperand(1)->getType(), CI, hlslOP);
  759. }
  760. // Wave intrinsics of the form fn(val,QuadOpKind)->val
  761. Value *TranslateQuadReadAcross(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  762. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  763. hlsl::OP *hlslOP = &helper.hlslOP;
  764. DXIL::QuadOpKind opKind;
  765. switch (IOP) {
  766. case IntrinsicOp::IOP_QuadReadAcrossX: opKind = DXIL::QuadOpKind::ReadAcrossX; break;
  767. case IntrinsicOp::IOP_QuadReadAcrossY: opKind = DXIL::QuadOpKind::ReadAcrossY; break;
  768. default: DXASSERT_NOMSG(IOP == IntrinsicOp::IOP_QuadReadAcrossDiagonal);
  769. case IntrinsicOp::IOP_QuadReadAcrossDiagonal: opKind = DXIL::QuadOpKind::ReadAcrossDiagonal; break;
  770. }
  771. Constant *OpArg = hlslOP->GetI8Const((unsigned)opKind);
  772. Value *refArgs[] = {nullptr, CI->getOperand(1), OpArg};
  773. return TrivialDxilOperation(DXIL::OpCode::QuadOp, refArgs,
  774. CI->getOperand(1)->getType(), CI, hlslOP);
  775. }
  776. // WaveAllEqual(val<n>)->bool<n>
  777. Value *TranslateWaveAllEqual(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  778. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  779. hlsl::OP *hlslOP = &helper.hlslOP;
  780. Value *src = CI->getArgOperand(HLOperandIndex::kWaveAllEqualValueOpIdx);
  781. IRBuilder<> Builder(CI);
  782. Type *Ty = src->getType();
  783. Type *RetTy = Type::getInt1Ty(CI->getContext());
  784. if (Ty->isVectorTy())
  785. RetTy = VectorType::get(RetTy, Ty->getVectorNumElements());
  786. Constant *opArg = hlslOP->GetU32Const((unsigned)DXIL::OpCode::WaveActiveAllEqual);
  787. Value *args[] = {opArg, src};
  788. return TrivialDxilOperation(DXIL::OpCode::WaveActiveAllEqual, args, Ty, RetTy,
  789. hlslOP, Builder);
  790. }
  791. // Wave intrinsics of the form fn(valA)->valB, where no overloading takes place
  792. Value *TranslateWaveA2B(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  793. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  794. hlsl::OP *hlslOP = &helper.hlslOP;
  795. Value *refArgs[] = {nullptr, CI->getOperand(1)};
  796. return TrivialDxilOperation(opcode, refArgs, helper.voidTy, CI, hlslOP);
  797. }
  798. // Wave ballot intrinsic.
  799. Value *TranslateWaveBallot(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  800. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  801. // The high-level operation is uint4 ballot(i1).
  802. // The DXIL operation is struct.u4 ballot(i1).
  803. // To avoid updating users with more than a simple replace, we translate into
  804. // a call into struct.u4, then reassemble the vector.
  805. // Scalarization and constant propagation take care of cleanup.
  806. IRBuilder<> B(CI);
  807. // Make the DXIL call itself.
  808. hlsl::OP *hlslOP = &helper.hlslOP;
  809. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  810. Value *refArgs[] = { opArg, CI->getOperand(1) };
  811. Function *dxilFunc = hlslOP->GetOpFunc(opcode, Type::getVoidTy(CI->getContext()));
  812. Value *dxilVal = B.CreateCall(dxilFunc, refArgs, hlslOP->GetOpCodeName(opcode));
  813. // Assign from the call results into a vector.
  814. Type *ResTy = CI->getType();
  815. DXASSERT_NOMSG(ResTy->isVectorTy() && ResTy->getVectorNumElements() == 4);
  816. DXASSERT_NOMSG(dxilVal->getType()->isStructTy() &&
  817. dxilVal->getType()->getNumContainedTypes() == 4);
  818. // 'x' component is the first vector element, highest bits.
  819. Value *ResVal = llvm::UndefValue::get(ResTy);
  820. for (unsigned Idx = 0; Idx < 4; ++Idx) {
  821. ResVal = B.CreateInsertElement(
  822. ResVal, B.CreateExtractValue(dxilVal, ArrayRef<unsigned>(Idx)), Idx);
  823. }
  824. return ResVal;
  825. }
  826. static bool WaveIntrinsicNeedsSign(OP::OpCode opcode) {
  827. return opcode == OP::OpCode::WaveActiveOp ||
  828. opcode == OP::OpCode::WavePrefixOp;
  829. }
  830. static unsigned WaveIntrinsicToSignedOpKind(IntrinsicOp IOP) {
  831. if (IOP == IntrinsicOp::IOP_WaveActiveUMax ||
  832. IOP == IntrinsicOp::IOP_WaveActiveUMin ||
  833. IOP == IntrinsicOp::IOP_WaveActiveUSum ||
  834. IOP == IntrinsicOp::IOP_WaveActiveUProduct ||
  835. IOP == IntrinsicOp::IOP_WavePrefixUSum ||
  836. IOP == IntrinsicOp::IOP_WavePrefixUProduct)
  837. return (unsigned)DXIL::SignedOpKind::Unsigned;
  838. return (unsigned)DXIL::SignedOpKind::Signed;
  839. }
  840. static unsigned WaveIntrinsicToOpKind(IntrinsicOp IOP) {
  841. switch (IOP) {
  842. // Bit operations.
  843. case IntrinsicOp::IOP_WaveActiveBitOr:
  844. return (unsigned)DXIL::WaveBitOpKind::Or;
  845. case IntrinsicOp::IOP_WaveActiveBitAnd:
  846. return (unsigned)DXIL::WaveBitOpKind::And;
  847. case IntrinsicOp::IOP_WaveActiveBitXor:
  848. return (unsigned)DXIL::WaveBitOpKind::Xor;
  849. // Prefix operations.
  850. case IntrinsicOp::IOP_WavePrefixSum:
  851. case IntrinsicOp::IOP_WavePrefixUSum:
  852. return (unsigned)DXIL::WaveOpKind::Sum;
  853. case IntrinsicOp::IOP_WavePrefixProduct:
  854. case IntrinsicOp::IOP_WavePrefixUProduct:
  855. return (unsigned)DXIL::WaveOpKind::Product;
  856. // Numeric operations.
  857. case IntrinsicOp::IOP_WaveActiveMax:
  858. case IntrinsicOp::IOP_WaveActiveUMax:
  859. return (unsigned)DXIL::WaveOpKind::Max;
  860. case IntrinsicOp::IOP_WaveActiveMin:
  861. case IntrinsicOp::IOP_WaveActiveUMin:
  862. return (unsigned)DXIL::WaveOpKind::Min;
  863. case IntrinsicOp::IOP_WaveActiveSum:
  864. case IntrinsicOp::IOP_WaveActiveUSum:
  865. return (unsigned)DXIL::WaveOpKind::Sum;
  866. case IntrinsicOp::IOP_WaveActiveProduct:
  867. case IntrinsicOp::IOP_WaveActiveUProduct:
  868. default:
  869. DXASSERT(IOP == IntrinsicOp::IOP_WaveActiveProduct ||
  870. IOP == IntrinsicOp::IOP_WaveActiveUProduct,
  871. "else caller passed incorrect value");
  872. return (unsigned)DXIL::WaveOpKind::Product;
  873. }
  874. }
  875. // Wave intrinsics of the form fn(valA)->valA
  876. Value *TranslateWaveA2A(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  877. HLOperationLowerHelper &helper,
  878. HLObjectOperationLowerHelper *pObjHelper,
  879. bool &Translated) {
  880. hlsl::OP *hlslOP = &helper.hlslOP;
  881. Constant *kindValInt = hlslOP->GetI8Const(WaveIntrinsicToOpKind(IOP));
  882. Constant *signValInt = hlslOP->GetI8Const(WaveIntrinsicToSignedOpKind(IOP));
  883. Value *refArgs[] = {nullptr, CI->getOperand(1), kindValInt, signValInt};
  884. unsigned refArgCount = _countof(refArgs);
  885. if (!WaveIntrinsicNeedsSign(opcode))
  886. refArgCount--;
  887. return TrivialDxilOperation(opcode,
  888. llvm::ArrayRef<Value *>(refArgs, refArgCount),
  889. CI->getOperand(1)->getType(), CI, hlslOP);
  890. }
  891. // Wave intrinsics of the form fn()->val
  892. Value *TranslateWaveToVal(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  893. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  894. hlsl::OP *hlslOP = &helper.hlslOP;
  895. Value *refArgs[] = {nullptr};
  896. return TrivialDxilOperation(opcode, refArgs, helper.voidTy, CI, hlslOP);
  897. }
  898. // Wave intrinsics of the form fn(val,lane)->val
  899. Value *TranslateWaveReadLaneAt(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  900. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  901. hlsl::OP *hlslOP = &helper.hlslOP;
  902. Value *refArgs[] = {nullptr, CI->getOperand(1), CI->getOperand(2)};
  903. return TrivialDxilOperation(DXIL::OpCode::WaveReadLaneAt, refArgs,
  904. CI->getOperand(1)->getType(), CI, hlslOP);
  905. }
  906. // Wave intrinsics of the form fn(val)->val
  907. Value *TranslateWaveReadLaneFirst(CallInst *CI, IntrinsicOp IOP,
  908. OP::OpCode opcode,
  909. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  910. hlsl::OP *hlslOP = &helper.hlslOP;
  911. Value *refArgs[] = {nullptr, CI->getOperand(1)};
  912. return TrivialDxilOperation(DXIL::OpCode::WaveReadLaneFirst, refArgs,
  913. CI->getOperand(1)->getType(), CI, hlslOP);
  914. }
  915. Value *TranslateIAbs(CallInst *CI) {
  916. Type *Ty = CI->getType();
  917. Type *EltTy = Ty->getScalarType();
  918. unsigned bitWidth = EltTy->getIntegerBitWidth();
  919. uint64_t mask = ((uint64_t)1) << (bitWidth - 1);
  920. Constant *opMask = ConstantInt::get(EltTy, mask);
  921. if (Ty != EltTy) {
  922. unsigned size = Ty->getVectorNumElements();
  923. opMask = llvm::ConstantVector::getSplat(size, opMask);
  924. }
  925. IRBuilder<> Builder(CI);
  926. return Builder.CreateXor(CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx),
  927. opMask);
  928. }
  929. Value *TransalteAbs(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  930. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  931. hlsl::OP *hlslOP = &helper.hlslOP;
  932. Type *pOverloadTy = CI->getType()->getScalarType();
  933. if (pOverloadTy->isFloatingPointTy()) {
  934. Value *refArgs[] = {nullptr, CI->getOperand(1)};
  935. return TrivialDxilOperation(DXIL::OpCode::FAbs, refArgs, CI->getType(), CI,
  936. hlslOP);
  937. } else
  938. return TranslateIAbs(CI);
  939. }
  940. Value *GenerateCmpNEZero(Value *val, IRBuilder<> Builder) {
  941. Type *Ty = val->getType();
  942. Type *EltTy = Ty->getScalarType();
  943. Constant *zero = nullptr;
  944. if (EltTy->isFloatingPointTy())
  945. zero = ConstantFP::get(EltTy, 0);
  946. else
  947. zero = ConstantInt::get(EltTy, 0);
  948. if (Ty != EltTy) {
  949. zero = ConstantVector::getSplat(Ty->getVectorNumElements(), zero);
  950. }
  951. if (EltTy->isFloatingPointTy())
  952. return Builder.CreateFCmpUNE(val, zero);
  953. else
  954. return Builder.CreateICmpNE(val, zero);
  955. }
  956. Value *TranslateAllForValue(Value *val, IRBuilder<> &Builder) {
  957. Value *cond = GenerateCmpNEZero(val, Builder);
  958. Type *Ty = val->getType();
  959. Type *EltTy = Ty->getScalarType();
  960. if (Ty != EltTy) {
  961. Value *Result = Builder.CreateExtractElement(cond, (uint64_t)0);
  962. for (unsigned i = 1; i < Ty->getVectorNumElements(); i++) {
  963. Value *Elt = Builder.CreateExtractElement(cond, i);
  964. Result = Builder.CreateAnd(Result, Elt);
  965. }
  966. return Result;
  967. } else
  968. return cond;
  969. }
  970. Value *TranslateAll(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  971. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  972. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  973. IRBuilder<> Builder(CI);
  974. return TranslateAllForValue(val, Builder);
  975. }
  976. Value *TranslateAny(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  977. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  978. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  979. IRBuilder<> Builder(CI);
  980. Value *cond = GenerateCmpNEZero(val, Builder);
  981. Type *Ty = val->getType();
  982. Type *EltTy = Ty->getScalarType();
  983. if (Ty != EltTy) {
  984. Value *Result = Builder.CreateExtractElement(cond, (uint64_t)0);
  985. for (unsigned i = 1; i < Ty->getVectorNumElements(); i++) {
  986. Value *Elt = Builder.CreateExtractElement(cond, i);
  987. Result = Builder.CreateOr(Result, Elt);
  988. }
  989. return Result;
  990. } else
  991. return cond;
  992. }
  993. Value *TranslateBitcast(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  994. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  995. Type *Ty = CI->getType();
  996. Value *op = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  997. IRBuilder<> Builder(CI);
  998. return Builder.CreateBitCast(op, Ty);
  999. }
  1000. Value *TranslateDoubleAsUint(Value *x, Value *lo, Value *hi,
  1001. IRBuilder<> &Builder, hlsl::OP *hlslOP) {
  1002. Type *Ty = x->getType();
  1003. Type *outTy = lo->getType()->getPointerElementType();
  1004. DXIL::OpCode opcode = DXIL::OpCode::SplitDouble;
  1005. Function *dxilFunc = hlslOP->GetOpFunc(opcode, Ty->getScalarType());
  1006. Value *opArg = hlslOP->GetU32Const(static_cast<unsigned>(opcode));
  1007. if (Ty->isVectorTy()) {
  1008. Value *retValLo = llvm::UndefValue::get(outTy);
  1009. Value *retValHi = llvm::UndefValue::get(outTy);
  1010. unsigned vecSize = Ty->getVectorNumElements();
  1011. for (unsigned i = 0; i < vecSize; i++) {
  1012. Value *Elt = Builder.CreateExtractElement(x, i);
  1013. Value *EltOP = Builder.CreateCall(dxilFunc, {opArg, Elt},
  1014. hlslOP->GetOpCodeName(opcode));
  1015. Value *EltLo = Builder.CreateExtractValue(EltOP, 0);
  1016. retValLo = Builder.CreateInsertElement(retValLo, EltLo, i);
  1017. Value *EltHi = Builder.CreateExtractValue(EltOP, 1);
  1018. retValHi = Builder.CreateInsertElement(retValHi, EltHi, i);
  1019. }
  1020. Builder.CreateStore(retValLo, lo);
  1021. Builder.CreateStore(retValHi, hi);
  1022. } else {
  1023. Value *retVal =
  1024. Builder.CreateCall(dxilFunc, {opArg, x}, hlslOP->GetOpCodeName(opcode));
  1025. Value *retValLo = Builder.CreateExtractValue(retVal, 0);
  1026. Value *retValHi = Builder.CreateExtractValue(retVal, 1);
  1027. Builder.CreateStore(retValLo, lo);
  1028. Builder.CreateStore(retValHi, hi);
  1029. }
  1030. return nullptr;
  1031. }
  1032. Value *TranslateAsUint(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1033. HLOperationLowerHelper &helper,
  1034. HLObjectOperationLowerHelper *pObjHelper,
  1035. bool &Translated) {
  1036. if (CI->getNumArgOperands() == 2) {
  1037. return TranslateBitcast(CI, IOP, opcode, helper, pObjHelper, Translated);
  1038. } else {
  1039. DXASSERT_NOMSG(CI->getNumArgOperands() == 4);
  1040. hlsl::OP *hlslOP = &helper.hlslOP;
  1041. Value *x = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc0Idx);
  1042. DXASSERT_NOMSG(x->getType()->getScalarType()->isDoubleTy());
  1043. Value *lo = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc1Idx);
  1044. Value *hi = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc2Idx);
  1045. IRBuilder<> Builder(CI);
  1046. return TranslateDoubleAsUint(x, lo, hi, Builder, hlslOP);
  1047. }
  1048. }
  1049. Value *TranslateAsDouble(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1050. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1051. hlsl::OP *hlslOP = &helper.hlslOP;
  1052. Value *x = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1053. Value *y = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1054. Value *opArg = hlslOP->GetU32Const(static_cast<unsigned>(opcode));
  1055. IRBuilder<> Builder(CI);
  1056. return TrivialDxilOperation(opcode, { opArg, x, y }, CI->getType(), CI->getType(), hlslOP, Builder);
  1057. }
  1058. Value *TranslateAtan2(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1059. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1060. hlsl::OP *hlslOP = &helper.hlslOP;
  1061. Value *y = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1062. Value *x = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1063. IRBuilder<> Builder(CI);
  1064. Value *tan = Builder.CreateFDiv(y, x);
  1065. return TrivialDxilUnaryOperation(OP::OpCode::Atan, tan, hlslOP, Builder);
  1066. }
  1067. Value *TranslateClamp(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1068. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1069. hlsl::OP *hlslOP = &helper.hlslOP;
  1070. Type *Ty = CI->getType();
  1071. Type *EltTy = Ty->getScalarType();
  1072. DXIL::OpCode maxOp = DXIL::OpCode::FMax;
  1073. DXIL::OpCode minOp = DXIL::OpCode::FMin;
  1074. if (IOP == IntrinsicOp::IOP_uclamp) {
  1075. maxOp = DXIL::OpCode::UMax;
  1076. minOp = DXIL::OpCode::UMin;
  1077. } else if (EltTy->isIntegerTy()) {
  1078. maxOp = DXIL::OpCode::IMax;
  1079. minOp = DXIL::OpCode::IMin;
  1080. }
  1081. Value *x = CI->getArgOperand(HLOperandIndex::kClampOpXIdx);
  1082. Value *maxVal = CI->getArgOperand(HLOperandIndex::kClampOpMaxIdx);
  1083. Value *minVal = CI->getArgOperand(HLOperandIndex::kClampOpMinIdx);
  1084. IRBuilder<> Builder(CI);
  1085. // min(max(x, minVal), maxVal).
  1086. Value *maxXMinVal =
  1087. TrivialDxilBinaryOperation(maxOp, x, minVal, hlslOP, Builder);
  1088. return TrivialDxilBinaryOperation(minOp, maxXMinVal, maxVal, hlslOP, Builder);
  1089. }
  1090. Value *TranslateClip(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1091. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1092. hlsl::OP *hlslOP = &helper.hlslOP;
  1093. Function *discard =
  1094. hlslOP->GetOpFunc(OP::OpCode::Discard, Type::getVoidTy(CI->getContext()));
  1095. IRBuilder<> Builder(CI);
  1096. Value *cond = nullptr;
  1097. Value *arg = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1098. if (VectorType *VT = dyn_cast<VectorType>(arg->getType())) {
  1099. Value *elt = Builder.CreateExtractElement(arg, (uint64_t)0);
  1100. cond = Builder.CreateFCmpOLT(elt, hlslOP->GetFloatConst(0));
  1101. for (unsigned i = 1; i < VT->getNumElements(); i++) {
  1102. Value *elt = Builder.CreateExtractElement(arg, i);
  1103. Value *eltCond = Builder.CreateFCmpOLT(elt, hlslOP->GetFloatConst(0));
  1104. cond = Builder.CreateOr(cond, eltCond);
  1105. }
  1106. } else
  1107. cond = Builder.CreateFCmpOLT(arg, hlslOP->GetFloatConst(0));
  1108. Constant *opArg = hlslOP->GetU32Const((unsigned)OP::OpCode::Discard);
  1109. Builder.CreateCall(discard, {opArg, cond});
  1110. return nullptr;
  1111. }
  1112. Value *TranslateCross(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1113. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1114. VectorType *VT = cast<VectorType>(CI->getType());
  1115. DXASSERT_NOMSG(VT->getNumElements() == 3);
  1116. Value *op0 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1117. Value *op1 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1118. IRBuilder<> Builder(CI);
  1119. Value *op0_x = Builder.CreateExtractElement(op0, (uint64_t)0);
  1120. Value *op0_y = Builder.CreateExtractElement(op0, 1);
  1121. Value *op0_z = Builder.CreateExtractElement(op0, 2);
  1122. Value *op1_x = Builder.CreateExtractElement(op1, (uint64_t)0);
  1123. Value *op1_y = Builder.CreateExtractElement(op1, 1);
  1124. Value *op1_z = Builder.CreateExtractElement(op1, 2);
  1125. auto MulSub = [&](Value *x0, Value *y0, Value *x1, Value *y1) -> Value * {
  1126. Value *xy = Builder.CreateFMul(x0, y1);
  1127. Value *yx = Builder.CreateFMul(y0, x1);
  1128. return Builder.CreateFSub(xy, yx);
  1129. };
  1130. Value *yz_zy = MulSub(op0_y, op0_z, op1_y, op1_z);
  1131. Value *zx_xz = MulSub(op0_z, op0_x, op1_z, op1_x);
  1132. Value *xy_yx = MulSub(op0_x, op0_y, op1_x, op1_y);
  1133. Value *cross = UndefValue::get(VT);
  1134. cross = Builder.CreateInsertElement(cross, yz_zy, (uint64_t)0);
  1135. cross = Builder.CreateInsertElement(cross, zx_xz, 1);
  1136. cross = Builder.CreateInsertElement(cross, xy_yx, 2);
  1137. return cross;
  1138. }
  1139. Value *TranslateDegrees(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1140. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1141. IRBuilder<> Builder(CI);
  1142. Type *Ty = CI->getType();
  1143. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1144. // 180/pi.
  1145. // TODO: include M_PI from math.h.
  1146. const double M_PI = 3.14159265358979323846;
  1147. Constant *toDegreeConst = ConstantFP::get(Ty->getScalarType(), 180 / M_PI);
  1148. if (Ty != Ty->getScalarType()) {
  1149. toDegreeConst =
  1150. ConstantVector::getSplat(Ty->getVectorNumElements(), toDegreeConst);
  1151. }
  1152. return Builder.CreateFMul(toDegreeConst, val);
  1153. }
  1154. Value *TranslateDst(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1155. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1156. Value *src0 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1157. Value *src1 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1158. Type *Ty = src1->getType();
  1159. IRBuilder<> Builder(CI);
  1160. Value *Result = UndefValue::get(Ty);
  1161. Constant *oneConst = ConstantFP::get(Ty->getScalarType(), 1);
  1162. // dest.x = 1;
  1163. Result = Builder.CreateInsertElement(Result, oneConst, (uint64_t)0);
  1164. // dest.y = src0.y * src1.y;
  1165. Value *src0_y = Builder.CreateExtractElement(src0, 1);
  1166. Value *src1_y = Builder.CreateExtractElement(src1, 1);
  1167. Value *yMuly = Builder.CreateFMul(src0_y, src1_y);
  1168. Result = Builder.CreateInsertElement(Result, yMuly, 1);
  1169. // dest.z = src0.z;
  1170. Value *src0_z = Builder.CreateExtractElement(src0, 2);
  1171. Result = Builder.CreateInsertElement(Result, src0_z, 2);
  1172. // dest.w = src1.w;
  1173. Value *src1_w = Builder.CreateExtractElement(src1, 3);
  1174. Result = Builder.CreateInsertElement(Result, src1_w, 3);
  1175. return Result;
  1176. }
  1177. Value *TranslateFirstbitHi(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1178. HLOperationLowerHelper &helper,
  1179. HLObjectOperationLowerHelper *pObjHelper,
  1180. bool &Translated) {
  1181. Value *firstbitHi =
  1182. TrivialUnaryOperation(CI, IOP, opcode, helper, pObjHelper, Translated);
  1183. // firstbitHi == -1? -1 : (bitWidth-1 -firstbitHi);
  1184. IRBuilder<> Builder(CI);
  1185. Constant *neg1 = Builder.getInt32(-1);
  1186. Value *src = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1187. Type *Ty = src->getType();
  1188. IntegerType *EltTy = cast<IntegerType>(Ty->getScalarType());
  1189. Constant *bitWidth = Builder.getInt32(EltTy->getBitWidth()-1);
  1190. if (Ty == Ty->getScalarType()) {
  1191. Value *sub = Builder.CreateSub(bitWidth, firstbitHi);
  1192. Value *cond = Builder.CreateICmpEQ(neg1, firstbitHi);
  1193. return Builder.CreateSelect(cond, neg1, sub);
  1194. } else {
  1195. Value *result = UndefValue::get(CI->getType());
  1196. unsigned vecSize = Ty->getVectorNumElements();
  1197. for (unsigned i = 0; i < vecSize; i++) {
  1198. Value *EltFirstBit = Builder.CreateExtractElement(firstbitHi, i);
  1199. Value *sub = Builder.CreateSub(bitWidth, EltFirstBit);
  1200. Value *cond = Builder.CreateICmpEQ(neg1, EltFirstBit);
  1201. Value *Elt = Builder.CreateSelect(cond, neg1, sub);
  1202. result = Builder.CreateInsertElement(result, Elt, i);
  1203. }
  1204. return result;
  1205. }
  1206. }
  1207. Value *TranslateFirstbitLo(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1208. HLOperationLowerHelper &helper,
  1209. HLObjectOperationLowerHelper *pObjHelper,
  1210. bool &Translated) {
  1211. Value *firstbitLo =
  1212. TrivialUnaryOperation(CI, IOP, opcode, helper, pObjHelper, Translated);
  1213. return firstbitLo;
  1214. }
  1215. Value *TranslateLit(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1216. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1217. Value *n_dot_l = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc0Idx);
  1218. Value *n_dot_h = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc1Idx);
  1219. Value *m = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc2Idx);
  1220. IRBuilder<> Builder(CI);
  1221. Type *Ty = m->getType();
  1222. Value *Result = UndefValue::get(VectorType::get(Ty, 4));
  1223. // Result = (ambient, diffuse, specular, 1)
  1224. // ambient = 1.
  1225. Constant *oneConst = ConstantFP::get(Ty, 1);
  1226. Result = Builder.CreateInsertElement(Result, oneConst, (uint64_t)0);
  1227. // Result.w = 1.
  1228. Result = Builder.CreateInsertElement(Result, oneConst, 3);
  1229. // diffuse = (n_dot_l < 0) ? 0 : n_dot_l.
  1230. Constant *zeroConst = ConstantFP::get(Ty, 0);
  1231. Value *nlCmp = Builder.CreateFCmpOLT(n_dot_l, zeroConst);
  1232. Value *diffuse = Builder.CreateSelect(nlCmp, zeroConst, n_dot_l);
  1233. Result = Builder.CreateInsertElement(Result, diffuse, 1);
  1234. // specular = ((n_dot_l < 0) || (n_dot_h < 0)) ? 0: (n_dot_h * m).
  1235. Value *nhCmp = Builder.CreateFCmpOLT(n_dot_h, zeroConst);
  1236. Value *specCond = Builder.CreateOr(nlCmp, nhCmp);
  1237. Value *nhMulM = Builder.CreateFMul(n_dot_h, m);
  1238. Value *spec = Builder.CreateSelect(specCond, zeroConst, nhMulM);
  1239. Result = Builder.CreateInsertElement(Result, spec, 2);
  1240. return Result;
  1241. }
  1242. Value *TranslateRadians(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1243. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1244. IRBuilder<> Builder(CI);
  1245. Type *Ty = CI->getType();
  1246. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1247. // pi/180.
  1248. // TODO: include M_PI from math.h.
  1249. const double M_PI = 3.14159265358979323846;
  1250. Constant *toRadianConst = ConstantFP::get(Ty->getScalarType(), M_PI / 180);
  1251. if (Ty != Ty->getScalarType()) {
  1252. toRadianConst =
  1253. ConstantVector::getSplat(Ty->getVectorNumElements(), toRadianConst);
  1254. }
  1255. return Builder.CreateFMul(toRadianConst, val);
  1256. }
  1257. Value *TranslateF16ToF32(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1258. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1259. IRBuilder<> Builder(CI);
  1260. Value *x = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1261. Type *Ty = CI->getType();
  1262. Function *f16tof32 =
  1263. helper.hlslOP.GetOpFunc(opcode, helper.voidTy);
  1264. return TrivialDxilOperation(
  1265. f16tof32, opcode, {Builder.getInt32(static_cast<unsigned>(opcode)), x},
  1266. x->getType(), Ty, &helper.hlslOP, Builder);
  1267. }
  1268. Value *TranslateF32ToF16(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1269. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1270. IRBuilder<> Builder(CI);
  1271. Value *x = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1272. Type *Ty = CI->getType();
  1273. Function *f32tof16 =
  1274. helper.hlslOP.GetOpFunc(opcode, helper.voidTy);
  1275. return TrivialDxilOperation(
  1276. f32tof16, opcode, {Builder.getInt32(static_cast<unsigned>(opcode)), x},
  1277. x->getType(), Ty, &helper.hlslOP, Builder);
  1278. }
  1279. Value *TranslateLength(CallInst *CI, Value *val, hlsl::OP *hlslOP) {
  1280. IRBuilder<> Builder(CI);
  1281. if (VectorType *VT = dyn_cast<VectorType>(val->getType())) {
  1282. Value *Elt = Builder.CreateExtractElement(val, (uint64_t)0);
  1283. unsigned size = VT->getNumElements();
  1284. if (size > 1) {
  1285. Value *Sum = Builder.CreateFMul(Elt, Elt);
  1286. for (unsigned i = 1; i < size; i++) {
  1287. Elt = Builder.CreateExtractElement(val, i);
  1288. Value *Mul = Builder.CreateFMul(Elt, Elt);
  1289. Sum = Builder.CreateFAdd(Sum, Mul);
  1290. }
  1291. DXIL::OpCode sqrt = DXIL::OpCode::Sqrt;
  1292. Function *dxilSqrt = hlslOP->GetOpFunc(sqrt, VT->getElementType());
  1293. Value *opArg = hlslOP->GetI32Const((unsigned)sqrt);
  1294. return Builder.CreateCall(dxilSqrt, {opArg, Sum},
  1295. hlslOP->GetOpCodeName(sqrt));
  1296. } else {
  1297. val = Elt;
  1298. }
  1299. }
  1300. DXIL::OpCode fabs = DXIL::OpCode::FAbs;
  1301. Function *dxilFAbs = hlslOP->GetOpFunc(fabs, val->getType());
  1302. Value *opArg = hlslOP->GetI32Const((unsigned)fabs);
  1303. return Builder.CreateCall(dxilFAbs, {opArg, val},
  1304. hlslOP->GetOpCodeName(fabs));
  1305. }
  1306. Value *TranslateLength(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1307. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1308. hlsl::OP *hlslOP = &helper.hlslOP;
  1309. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1310. return TranslateLength(CI, val, hlslOP);
  1311. }
  1312. Value *TranslateModF(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1313. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1314. hlsl::OP *hlslOP = &helper.hlslOP;
  1315. Value *val = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1316. Value *outIntPtr = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1317. IRBuilder<> Builder(CI);
  1318. Value *Result =
  1319. TrivialDxilUnaryOperation(OP::OpCode::Round_z, val, hlslOP, Builder);
  1320. Value *intPortion = Builder.CreateFSub(val, Result);
  1321. Builder.CreateStore(intPortion, outIntPtr);
  1322. return Result;
  1323. }
  1324. Value *TranslateDistance(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1325. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1326. hlsl::OP *hlslOP = &helper.hlslOP;
  1327. Value *src0 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1328. Value *src1 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1329. IRBuilder<> Builder(CI);
  1330. Value *sub = Builder.CreateFSub(src0, src1);
  1331. return TranslateLength(CI, sub, hlslOP);
  1332. }
  1333. Value *TranslateExp(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1334. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1335. hlsl::OP *hlslOP = &helper.hlslOP;
  1336. IRBuilder<> Builder(CI);
  1337. Type *Ty = CI->getType();
  1338. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1339. // TODO: include M_LOG2E from math.h.
  1340. const double M_LOG2E = 1.44269504088896340736;
  1341. Constant *log2eConst = ConstantFP::get(Ty->getScalarType(), M_LOG2E);
  1342. if (Ty != Ty->getScalarType()) {
  1343. log2eConst =
  1344. ConstantVector::getSplat(Ty->getVectorNumElements(), log2eConst);
  1345. }
  1346. val = Builder.CreateFMul(log2eConst, val);
  1347. Value *exp = TrivialDxilUnaryOperation(OP::OpCode::Exp, val, hlslOP, Builder);
  1348. return exp;
  1349. }
  1350. Value *TranslateLog(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1351. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1352. hlsl::OP *hlslOP = &helper.hlslOP;
  1353. IRBuilder<> Builder(CI);
  1354. Type *Ty = CI->getType();
  1355. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1356. // TODO: include M_LN2 from math.h.
  1357. const double M_LN2 = 0.693147180559945309417;
  1358. Constant *ln2Const = ConstantFP::get(Ty->getScalarType(), M_LN2);
  1359. if (Ty != Ty->getScalarType()) {
  1360. ln2Const = ConstantVector::getSplat(Ty->getVectorNumElements(), ln2Const);
  1361. }
  1362. Value *log = TrivialDxilUnaryOperation(OP::OpCode::Log, val, hlslOP, Builder);
  1363. return Builder.CreateFMul(ln2Const, log);
  1364. }
  1365. Value *TranslateLog10(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1366. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1367. hlsl::OP *hlslOP = &helper.hlslOP;
  1368. IRBuilder<> Builder(CI);
  1369. Type *Ty = CI->getType();
  1370. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1371. // TODO: include M_LN2 from math.h.
  1372. const double M_LN2 = 0.693147180559945309417;
  1373. const double M_LN10 = 2.30258509299404568402;
  1374. Constant *log2_10Const = ConstantFP::get(Ty->getScalarType(), M_LN2 / M_LN10);
  1375. if (Ty != Ty->getScalarType()) {
  1376. log2_10Const =
  1377. ConstantVector::getSplat(Ty->getVectorNumElements(), log2_10Const);
  1378. }
  1379. Value *log = TrivialDxilUnaryOperation(OP::OpCode::Log, val, hlslOP, Builder);
  1380. return Builder.CreateFMul(log2_10Const, log);
  1381. }
  1382. Value *TranslateFMod(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1383. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1384. hlsl::OP *hlslOP = &helper.hlslOP;
  1385. Value *src0 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1386. Value *src1 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1387. IRBuilder<> Builder(CI);
  1388. Value *div = Builder.CreateFDiv(src0, src1);
  1389. Value *negDiv = Builder.CreateFNeg(div);
  1390. Value *ge = Builder.CreateFCmpOGE(div, negDiv);
  1391. Value *absDiv =
  1392. TrivialDxilUnaryOperation(OP::OpCode::FAbs, div, hlslOP, Builder);
  1393. Value *frc =
  1394. TrivialDxilUnaryOperation(OP::OpCode::Frc, absDiv, hlslOP, Builder);
  1395. Value *negFrc = Builder.CreateFNeg(frc);
  1396. Value *realFrc = Builder.CreateSelect(ge, frc, negFrc);
  1397. return Builder.CreateFMul(realFrc, src1);
  1398. }
  1399. Value *TranslateFUIBinary(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1400. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1401. bool isFloat = CI->getType()->getScalarType()->isFloatingPointTy();
  1402. if (isFloat) {
  1403. switch (IOP) {
  1404. case IntrinsicOp::IOP_max:
  1405. opcode = OP::OpCode::FMax;
  1406. break;
  1407. case IntrinsicOp::IOP_min:
  1408. default:
  1409. DXASSERT(IOP == IntrinsicOp::IOP_min, "");
  1410. opcode = OP::OpCode::FMin;
  1411. break;
  1412. }
  1413. }
  1414. return TrivialBinaryOperation(CI, IOP, opcode, helper, pObjHelper, Translated);
  1415. }
  1416. Value *TranslateFUITrinary(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1417. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1418. bool isFloat = CI->getType()->getScalarType()->isFloatingPointTy();
  1419. if (isFloat) {
  1420. switch (IOP) {
  1421. case IntrinsicOp::IOP_mad:
  1422. default:
  1423. DXASSERT(IOP == IntrinsicOp::IOP_mad, "");
  1424. opcode = OP::OpCode::FMad;
  1425. break;
  1426. }
  1427. }
  1428. return TrivialTrinaryOperation(CI, IOP, opcode, helper, pObjHelper, Translated);
  1429. }
  1430. Value *TranslateFrexp(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1431. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1432. hlsl::OP *hlslOP = &helper.hlslOP;
  1433. Value *val = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1434. Value *expPtr = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1435. IRBuilder<> Builder(CI);
  1436. Type *i32Ty = Type::getInt32Ty(CI->getContext());
  1437. Constant *exponentMaskConst = ConstantInt::get(i32Ty, 0x7f800000);
  1438. Constant *mantisaMaskConst = ConstantInt::get(i32Ty, 0x007fffff);
  1439. Constant *exponentShiftConst = ConstantInt::get(i32Ty, 23);
  1440. Constant *mantisaOrConst = ConstantInt::get(i32Ty, 0x3f000000);
  1441. Constant *exponentBiasConst = ConstantInt::get(i32Ty, -(int)0x3f000000);
  1442. // bool ne = val != 0;
  1443. Value *notZero = Builder.CreateFCmpUNE(val, hlslOP->GetFloatConst(0));
  1444. notZero = Builder.CreateZExt(notZero, i32Ty);
  1445. // int iVal = asint(val);
  1446. Type *dstTy = i32Ty;
  1447. Type *Ty = val->getType();
  1448. if (Ty->isVectorTy()) {
  1449. unsigned vecSize = Ty->getVectorNumElements();
  1450. dstTy = VectorType::get(i32Ty, vecSize);
  1451. exponentMaskConst = ConstantVector::getSplat(vecSize, exponentMaskConst);
  1452. mantisaMaskConst = ConstantVector::getSplat(vecSize, mantisaMaskConst);
  1453. exponentShiftConst = ConstantVector::getSplat(vecSize, exponentShiftConst);
  1454. mantisaOrConst = ConstantVector::getSplat(vecSize, mantisaOrConst);
  1455. exponentBiasConst = ConstantVector::getSplat(vecSize, exponentBiasConst);
  1456. }
  1457. Value *intVal = Builder.CreateBitCast(val, i32Ty);
  1458. // temp = intVal & exponentMask;
  1459. Value *temp = Builder.CreateAnd(intVal, exponentMaskConst);
  1460. // temp = temp + exponentBias;
  1461. temp = Builder.CreateAdd(temp, exponentBiasConst);
  1462. // temp = temp & ne;
  1463. temp = Builder.CreateAnd(temp, notZero);
  1464. // temp = temp >> exponentShift;
  1465. temp = Builder.CreateAShr(temp, exponentShiftConst);
  1466. // exp = float(temp);
  1467. Value *exp = Builder.CreateSIToFP(temp, Ty);
  1468. Builder.CreateStore(exp, expPtr);
  1469. // temp = iVal & mantisaMask;
  1470. temp = Builder.CreateAnd(intVal, mantisaMaskConst);
  1471. // temp = temp | mantisaOr;
  1472. temp = Builder.CreateOr(temp, mantisaOrConst);
  1473. // mantisa = temp & ne;
  1474. Value *mantisa = Builder.CreateAnd(temp, notZero);
  1475. return Builder.CreateBitCast(mantisa, Ty);
  1476. }
  1477. Value *TranslateLdExp(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1478. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1479. hlsl::OP *hlslOP = &helper.hlslOP;
  1480. Value *src0 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1481. Value *src1 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1482. IRBuilder<> Builder(CI);
  1483. Value *exp =
  1484. TrivialDxilUnaryOperation(OP::OpCode::Exp, src1, hlslOP, Builder);
  1485. return Builder.CreateFMul(exp, src0);
  1486. }
  1487. Value *TranslateFWidth(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1488. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1489. hlsl::OP *hlslOP = &helper.hlslOP;
  1490. Value *src = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1491. IRBuilder<> Builder(CI);
  1492. Value *ddx =
  1493. TrivialDxilUnaryOperation(OP::OpCode::DerivCoarseX, src, hlslOP, Builder);
  1494. Value *absDdx =
  1495. TrivialDxilUnaryOperation(OP::OpCode::FAbs, ddx, hlslOP, Builder);
  1496. Value *ddy =
  1497. TrivialDxilUnaryOperation(OP::OpCode::DerivCoarseY, src, hlslOP, Builder);
  1498. Value *absDdy =
  1499. TrivialDxilUnaryOperation(OP::OpCode::FAbs, ddy, hlslOP, Builder);
  1500. return Builder.CreateFAdd(absDdx, absDdy);
  1501. }
  1502. Value *TranslateNormalize(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1503. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1504. hlsl::OP *hlslOP = &helper.hlslOP;
  1505. Type *Ty = CI->getType();
  1506. Value *op = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1507. IRBuilder<> Builder(CI);
  1508. Value *length = TranslateLength(CI, op, hlslOP);
  1509. if (Ty != length->getType()) {
  1510. VectorType *VT = cast<VectorType>(Ty);
  1511. Value *vecLength = UndefValue::get(VT);
  1512. for (unsigned i = 0; i < VT->getNumElements(); i++)
  1513. vecLength = Builder.CreateInsertElement(vecLength, length, i);
  1514. length = vecLength;
  1515. }
  1516. return Builder.CreateFDiv(op, length);
  1517. }
  1518. Value *TranslateLerp(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1519. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1520. // x + s(y-x)
  1521. Value *x = CI->getArgOperand(HLOperandIndex::kLerpOpXIdx);
  1522. Value *y = CI->getArgOperand(HLOperandIndex::kLerpOpYIdx);
  1523. IRBuilder<> Builder(CI);
  1524. Value *ySubx = Builder.CreateFSub(y, x);
  1525. Value *s = CI->getArgOperand(HLOperandIndex::kLerpOpSIdx);
  1526. Value *sMulSub = Builder.CreateFMul(s, ySubx);
  1527. return Builder.CreateFAdd(x, sMulSub);
  1528. }
  1529. Value *TrivialDotOperation(OP::OpCode opcode, Value *src0,
  1530. Value *src1, hlsl::OP *hlslOP,
  1531. IRBuilder<> &Builder) {
  1532. Type *Ty = src0->getType()->getScalarType();
  1533. Function *dxilFunc = hlslOP->GetOpFunc(opcode, Ty);
  1534. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  1535. SmallVector<Value *, 9> args;
  1536. args.emplace_back(opArg);
  1537. unsigned vecSize = src0->getType()->getVectorNumElements();
  1538. for (unsigned i = 0; i < vecSize; i++)
  1539. args.emplace_back(Builder.CreateExtractElement(src0, i));
  1540. for (unsigned i = 0; i < vecSize; i++)
  1541. args.emplace_back(Builder.CreateExtractElement(src1, i));
  1542. Value *dotOP = Builder.CreateCall(dxilFunc, args);
  1543. return dotOP;
  1544. }
  1545. Value *TranslateIDot(Value *arg0, Value *arg1, unsigned vecSize, hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  1546. Value *Elt0 = Builder.CreateExtractElement(arg0, (uint64_t)0);
  1547. Value *Elt1 = Builder.CreateExtractElement(arg1, (uint64_t)0);
  1548. Value *Result = Builder.CreateMul(Elt0, Elt1);
  1549. switch (vecSize) {
  1550. case 4:
  1551. Elt0 = Builder.CreateExtractElement(arg0, 3);
  1552. Elt1 = Builder.CreateExtractElement(arg1, 3);
  1553. Result = TrivialDxilTrinaryOperation(DXIL::OpCode::IMad, Elt0, Elt1, Result, hlslOP, Builder);
  1554. // Pass thru.
  1555. case 3:
  1556. Elt0 = Builder.CreateExtractElement(arg0, 2);
  1557. Elt1 = Builder.CreateExtractElement(arg1, 2);
  1558. Result = TrivialDxilTrinaryOperation(DXIL::OpCode::IMad, Elt0, Elt1, Result, hlslOP, Builder);
  1559. // Pass thru.
  1560. case 2:
  1561. Elt0 = Builder.CreateExtractElement(arg0, 1);
  1562. Elt1 = Builder.CreateExtractElement(arg1, 1);
  1563. Result = TrivialDxilTrinaryOperation(DXIL::OpCode::IMad, Elt0, Elt1, Result, hlslOP, Builder);
  1564. break;
  1565. default:
  1566. case 1:
  1567. DXASSERT(vecSize == 1, "invalid vector size.");
  1568. }
  1569. return Result;
  1570. }
  1571. Value *TranslateFDot(Value *arg0, Value *arg1, unsigned vecSize,
  1572. hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  1573. switch (vecSize) {
  1574. case 2:
  1575. return TrivialDotOperation(OP::OpCode::Dot2, arg0, arg1, hlslOP, Builder);
  1576. break;
  1577. case 3:
  1578. return TrivialDotOperation(OP::OpCode::Dot3, arg0, arg1, hlslOP, Builder);
  1579. break;
  1580. case 4:
  1581. return TrivialDotOperation(OP::OpCode::Dot4, arg0, arg1, hlslOP, Builder);
  1582. break;
  1583. default:
  1584. DXASSERT(vecSize == 1, "wrong vector size");
  1585. {
  1586. Value *vecMul = Builder.CreateFMul(arg0, arg1);
  1587. return Builder.CreateExtractElement(vecMul, (uint64_t)0);
  1588. }
  1589. break;
  1590. }
  1591. }
  1592. Value *TranslateDot(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1593. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1594. hlsl::OP *hlslOP = &helper.hlslOP;
  1595. Value *arg0 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1596. Type *Ty = arg0->getType();
  1597. unsigned vecSize = Ty->getVectorNumElements();
  1598. Value *arg1 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1599. IRBuilder<> Builder(CI);
  1600. if (Ty->getScalarType()->isFloatingPointTy()) {
  1601. return TranslateFDot(arg0, arg1, vecSize, hlslOP, Builder);
  1602. } else {
  1603. return TranslateIDot(arg0, arg1, vecSize, hlslOP, Builder);
  1604. }
  1605. }
  1606. Value *TranslateReflect(CallInst *CI, IntrinsicOp IOP, OP::OpCode op,
  1607. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1608. hlsl::OP *hlslOP = &helper.hlslOP;
  1609. // v = i - 2 * n * dot(i•n).
  1610. IRBuilder<> Builder(CI);
  1611. Value *i = CI->getArgOperand(HLOperandIndex::kReflectOpIIdx);
  1612. Value *n = CI->getArgOperand(HLOperandIndex::kReflectOpNIdx);
  1613. VectorType *VT = cast<VectorType>(i->getType());
  1614. unsigned vecSize = VT->getNumElements();
  1615. Value *dot = TranslateFDot(i, n, vecSize, hlslOP, Builder);
  1616. // 2 * dot (i, n).
  1617. dot = Builder.CreateFMul(hlslOP->GetFloatConst(2), dot);
  1618. // 2 * n * dot(i, n).
  1619. Value *vecDot = Builder.CreateVectorSplat(vecSize, dot);
  1620. Value *nMulDot = Builder.CreateFMul(vecDot, n);
  1621. // i - 2 * n * dot(i, n).
  1622. return Builder.CreateFSub(i, nMulDot);
  1623. }
  1624. Value *TranslateRefract(CallInst *CI, IntrinsicOp IOP, OP::OpCode op,
  1625. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1626. hlsl::OP *hlslOP = &helper.hlslOP;
  1627. // d = dot(i•n);
  1628. // t = 1 - eta * eta * ( 1 - d*d);
  1629. // cond = t >= 1;
  1630. // r = eta * i - (eta * d + sqrt(t)) * n;
  1631. // return cond ? r : 0;
  1632. IRBuilder<> Builder(CI);
  1633. Value *i = CI->getArgOperand(HLOperandIndex::kRefractOpIIdx);
  1634. Value *n = CI->getArgOperand(HLOperandIndex::kRefractOpNIdx);
  1635. Value *eta = CI->getArgOperand(HLOperandIndex::kRefractOpEtaIdx);
  1636. VectorType *VT = cast<VectorType>(i->getType());
  1637. unsigned vecSize = VT->getNumElements();
  1638. Value *dot = TranslateFDot(i, n, vecSize, hlslOP, Builder);
  1639. // eta * eta;
  1640. Value *eta2 = Builder.CreateFMul(eta, eta);
  1641. // d*d;
  1642. Value *dot2 = Builder.CreateFMul(dot, dot);
  1643. Constant *one = hlslOP->GetFloatConst(1);
  1644. Constant *zero = hlslOP->GetFloatConst(0);
  1645. // 1- d*d;
  1646. dot2 = Builder.CreateFSub(one, dot2);
  1647. // eta * eta * (1-d*d);
  1648. eta2 = Builder.CreateFMul(dot2, eta2);
  1649. // t = 1 - eta * eta * ( 1 - d*d);
  1650. Value *t = Builder.CreateFSub(one, eta2);
  1651. // cond = t >= 0;
  1652. Value *cond = Builder.CreateFCmpOGE(t, zero);
  1653. // eta * i;
  1654. Value *vecEta = UndefValue::get(VT);
  1655. for (unsigned i = 0; i < vecSize; i++)
  1656. vecEta = Builder.CreateInsertElement(vecEta, eta, i);
  1657. Value *etaMulI = Builder.CreateFMul(i, vecEta);
  1658. // sqrt(t);
  1659. Value *sqrt = TrivialDxilUnaryOperation(OP::OpCode::Sqrt, t, hlslOP, Builder);
  1660. // eta * d;
  1661. Value *etaMulD = Builder.CreateFMul(eta, dot);
  1662. // eta * d + sqrt(t);
  1663. Value *etaSqrt = Builder.CreateFAdd(etaMulD, sqrt);
  1664. // (eta * d + sqrt(t)) * n;
  1665. Value *vecEtaSqrt = Builder.CreateVectorSplat(vecSize, etaSqrt);
  1666. Value *r = Builder.CreateFMul(vecEtaSqrt, n);
  1667. // r = eta * i - (eta * d + sqrt(t)) * n;
  1668. r = Builder.CreateFSub(etaMulI, r);
  1669. Value *refract =
  1670. Builder.CreateSelect(cond, r, ConstantVector::getSplat(vecSize, zero));
  1671. return refract;
  1672. }
  1673. Value *TranslateSmoothStep(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1674. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1675. hlsl::OP *hlslOP = &helper.hlslOP;
  1676. // s = saturate((x-min)/(max-min)).
  1677. IRBuilder<> Builder(CI);
  1678. Value *minVal = CI->getArgOperand(HLOperandIndex::kSmoothStepOpMinIdx);
  1679. Value *maxVal = CI->getArgOperand(HLOperandIndex::kSmoothStepOpMaxIdx);
  1680. Value *maxSubMin = Builder.CreateFSub(maxVal, minVal);
  1681. Value *x = CI->getArgOperand(HLOperandIndex::kSmoothStepOpXIdx);
  1682. Value *xSubMin = Builder.CreateFSub(x, minVal);
  1683. Value *satVal = Builder.CreateFDiv(xSubMin, maxSubMin);
  1684. Value *s = TrivialDxilUnaryOperation(DXIL::OpCode::Saturate, satVal, hlslOP,
  1685. Builder);
  1686. // return s * s *(3-2*s).
  1687. Constant *c2 = hlslOP->GetFloatConst(2);
  1688. Constant *c3 = hlslOP->GetFloatConst(3);
  1689. if (s->getType()->isVectorTy()) {
  1690. unsigned vecSize = s->getType()->getVectorNumElements();
  1691. c2 = ConstantVector::getSplat(vecSize, c2);
  1692. c3 = ConstantVector::getSplat(vecSize, c3);
  1693. }
  1694. Value *sMul2 = Builder.CreateFMul(s, c2);
  1695. Value *result = Builder.CreateFSub(c3, sMul2);
  1696. result = Builder.CreateFMul(s, result);
  1697. result = Builder.CreateFMul(s, result);
  1698. return result;
  1699. }
  1700. Value *TranslateMSad4(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1701. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1702. hlsl::OP *hlslOP = &helper.hlslOP;
  1703. Value *ref = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc0Idx);
  1704. Value *src = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc1Idx);
  1705. Value *accum = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc2Idx);
  1706. Type *Ty = CI->getType();
  1707. IRBuilder<> Builder(CI);
  1708. Value *vecRef = UndefValue::get(Ty);
  1709. for (unsigned i = 0; i < 4; i++)
  1710. vecRef = Builder.CreateInsertElement(vecRef, ref, i);
  1711. Value *srcX = Builder.CreateExtractElement(src, (uint64_t)0);
  1712. Value *srcY = Builder.CreateExtractElement(src, 1);
  1713. Value *byteSrc = UndefValue::get(Ty);
  1714. byteSrc = Builder.CreateInsertElement(byteSrc, srcX, (uint64_t)0);
  1715. // ushr r0.yzw, srcX, l(0, 8, 16, 24)
  1716. // bfi r1.yzw, l(0, 8, 16, 24), l(0, 24, 16, 8), srcX, r0.yyzw
  1717. Value *bfiOpArg =
  1718. hlslOP->GetU32Const(static_cast<unsigned>(DXIL::OpCode::Bfi));
  1719. Value *imm8 = hlslOP->GetU32Const(8);
  1720. Value *imm16 = hlslOP->GetU32Const(16);
  1721. Value *imm24 = hlslOP->GetU32Const(24);
  1722. Ty = ref->getType();
  1723. // Get x[31:8].
  1724. Value *srcXShift = Builder.CreateLShr(srcX, imm8);
  1725. // y[0~7] x[31:8].
  1726. Value *byteSrcElt = TrivialDxilOperation(
  1727. DXIL::OpCode::Bfi, {bfiOpArg, imm8, imm24, srcY, srcXShift}, Ty, Ty,
  1728. hlslOP, Builder);
  1729. byteSrc = Builder.CreateInsertElement(byteSrc, byteSrcElt, 1);
  1730. // Get x[31:16].
  1731. srcXShift = Builder.CreateLShr(srcXShift, imm8);
  1732. // y[0~15] x[31:16].
  1733. byteSrcElt = TrivialDxilOperation(DXIL::OpCode::Bfi,
  1734. {bfiOpArg, imm16, imm16, srcY, srcXShift},
  1735. Ty, Ty, hlslOP, Builder);
  1736. byteSrc = Builder.CreateInsertElement(byteSrc, byteSrcElt, 2);
  1737. // Get x[31:24].
  1738. srcXShift = Builder.CreateLShr(srcXShift, imm8);
  1739. // y[0~23] x[31:24].
  1740. byteSrcElt = TrivialDxilOperation(DXIL::OpCode::Bfi,
  1741. {bfiOpArg, imm24, imm8, srcY, srcXShift},
  1742. Ty, Ty, hlslOP, Builder);
  1743. byteSrc = Builder.CreateInsertElement(byteSrc, byteSrcElt, 3);
  1744. // Msad on vecref and byteSrc.
  1745. return TrivialDxilTrinaryOperation(DXIL::OpCode::Msad, vecRef, byteSrc, accum,
  1746. hlslOP, Builder);
  1747. }
  1748. Value *TranslateRCP(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1749. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1750. Type *Ty = CI->getType();
  1751. Value *op = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1752. IRBuilder<> Builder(CI);
  1753. Constant *one = ConstantFP::get(Ty->getScalarType(), 1.0);
  1754. if (Ty != Ty->getScalarType()) {
  1755. one = ConstantVector::getSplat(Ty->getVectorNumElements(), one);
  1756. }
  1757. return Builder.CreateFDiv(one, op);
  1758. }
  1759. Value *TranslateSign(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1760. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1761. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1762. Type *Ty = val->getType();
  1763. Type *EltTy = Ty->getScalarType();
  1764. IRBuilder<> Builder(CI);
  1765. if (EltTy->isIntegerTy()) {
  1766. Constant *zero = ConstantInt::get(Ty->getScalarType(), 0);
  1767. if (Ty != EltTy) {
  1768. zero = ConstantVector::getSplat(Ty->getVectorNumElements(), zero);
  1769. }
  1770. Value *zeroLtVal = Builder.CreateICmpSLT(zero, val);
  1771. zeroLtVal = Builder.CreateZExt(zeroLtVal, CI->getType());
  1772. Value *valLtZero = Builder.CreateICmpSLT(val, zero);
  1773. valLtZero = Builder.CreateZExt(valLtZero, CI->getType());
  1774. return Builder.CreateSub(zeroLtVal, valLtZero);
  1775. } else {
  1776. Constant *zero = ConstantFP::get(Ty->getScalarType(), 0.0);
  1777. if (Ty != EltTy) {
  1778. zero = ConstantVector::getSplat(Ty->getVectorNumElements(), zero);
  1779. }
  1780. Value *zeroLtVal = Builder.CreateFCmpOLT(zero, val);
  1781. zeroLtVal = Builder.CreateZExt(zeroLtVal, CI->getType());
  1782. Value *valLtZero = Builder.CreateFCmpOLT(val, zero);
  1783. valLtZero = Builder.CreateZExt(valLtZero, CI->getType());
  1784. return Builder.CreateSub(zeroLtVal, valLtZero);
  1785. }
  1786. }
  1787. Value *TranslateStep(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1788. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1789. Value *edge = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1790. Value *x = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1791. Type *Ty = CI->getType();
  1792. IRBuilder<> Builder(CI);
  1793. Constant *one = ConstantFP::get(Ty->getScalarType(), 1.0);
  1794. Constant *zero = ConstantFP::get(Ty->getScalarType(), 0);
  1795. Value *cond = Builder.CreateFCmpOLT(x, edge);
  1796. if (Ty != Ty->getScalarType()) {
  1797. one = ConstantVector::getSplat(Ty->getVectorNumElements(), one);
  1798. zero = ConstantVector::getSplat(Ty->getVectorNumElements(), zero);
  1799. }
  1800. return Builder.CreateSelect(cond, zero, one);
  1801. }
  1802. Value *TranslatePow(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1803. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1804. hlsl::OP *hlslOP = &helper.hlslOP;
  1805. Value *x = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1806. Value *y = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1807. IRBuilder<> Builder(CI);
  1808. // t = log(x);
  1809. Value *logX =
  1810. TrivialDxilUnaryOperation(DXIL::OpCode::Log, x, hlslOP, Builder);
  1811. // t = y * t;
  1812. Value *mulY = Builder.CreateFMul(logX, y);
  1813. // pow = exp(t);
  1814. return TrivialDxilUnaryOperation(DXIL::OpCode::Exp, mulY, hlslOP, Builder);
  1815. }
  1816. Value *TranslateFaceforward(CallInst *CI, IntrinsicOp IOP, OP::OpCode op,
  1817. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1818. hlsl::OP *hlslOP = &helper.hlslOP;
  1819. Type *Ty = CI->getType();
  1820. Value *n = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc0Idx);
  1821. Value *i = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc1Idx);
  1822. Value *ng = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc2Idx);
  1823. IRBuilder<> Builder(CI);
  1824. unsigned vecSize = Ty->getVectorNumElements();
  1825. // -n x sign(dot(i, ng)).
  1826. Value *dotOp = TranslateFDot(i, ng, vecSize, hlslOP, Builder);
  1827. Constant *zero = ConstantFP::get(Ty->getScalarType(), 0);
  1828. Value *dotLtZero = Builder.CreateFCmpOLT(dotOp, zero);
  1829. Value *negN = Builder.CreateFNeg(n);
  1830. Value *faceforward = Builder.CreateSelect(dotLtZero, n, negN);
  1831. return faceforward;
  1832. }
  1833. }
  1834. // MOP intrinsics
  1835. namespace {
  1836. Value *TranslateGetSamplePosition(CallInst *CI, IntrinsicOp IOP, OP::OpCode op,
  1837. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1838. hlsl::OP *hlslOP = &helper.hlslOP;
  1839. Value *handle = CI->getArgOperand(HLOperandIndex::kHandleOpIdx);
  1840. IRBuilder<> Builder(CI);
  1841. Value *sampleIdx =
  1842. CI->getArgOperand(HLOperandIndex::kGetSamplePositionSampleIdxOpIndex);
  1843. OP::OpCode opcode = OP::OpCode::Texture2DMSGetSamplePosition;
  1844. llvm::Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  1845. Function *dxilFunc =
  1846. hlslOP->GetOpFunc(opcode, Type::getVoidTy(CI->getContext()));
  1847. Value *args[] = {opArg, handle, sampleIdx};
  1848. Value *samplePos = Builder.CreateCall(dxilFunc, args);
  1849. Value *result = UndefValue::get(CI->getType());
  1850. Value *samplePosX = Builder.CreateExtractValue(samplePos, 0);
  1851. Value *samplePosY = Builder.CreateExtractValue(samplePos, 1);
  1852. result = Builder.CreateInsertElement(result, samplePosX, (uint64_t)0);
  1853. result = Builder.CreateInsertElement(result, samplePosY, 1);
  1854. return result;
  1855. }
  1856. Value *TranslateGetDimensions(CallInst *CI, IntrinsicOp IOP, OP::OpCode op,
  1857. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1858. hlsl::OP *hlslOP = &helper.hlslOP;
  1859. Value *handle = CI->getArgOperand(HLOperandIndex::kHandleOpIdx);
  1860. DxilResource::Kind RK = pObjHelper->GetRK(handle);
  1861. IRBuilder<> Builder(CI);
  1862. OP::OpCode opcode = OP::OpCode::GetDimensions;
  1863. llvm::Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  1864. Function *dxilFunc =
  1865. hlslOP->GetOpFunc(opcode, Type::getVoidTy(CI->getContext()));
  1866. Type *i32Ty = Type::getInt32Ty(CI->getContext());
  1867. Value *mipLevel = UndefValue::get(i32Ty);
  1868. unsigned widthOpIdx = HLOperandIndex::kGetDimensionsMipWidthOpIndex;
  1869. switch (RK) {
  1870. case DxilResource::Kind::Texture1D:
  1871. case DxilResource::Kind::Texture1DArray:
  1872. case DxilResource::Kind::Texture2D:
  1873. case DxilResource::Kind::Texture2DArray:
  1874. case DxilResource::Kind::TextureCube:
  1875. case DxilResource::Kind::TextureCubeArray:
  1876. case DxilResource::Kind::Texture3D: {
  1877. Value *opMipLevel =
  1878. CI->getArgOperand(HLOperandIndex::kGetDimensionsMipLevelOpIndex);
  1879. // mipLevel is in parameter, should not be pointer.
  1880. if (!opMipLevel->getType()->isPointerTy())
  1881. mipLevel = opMipLevel;
  1882. else {
  1883. // No mip level.
  1884. widthOpIdx = HLOperandIndex::kGetDimensionsNoMipWidthOpIndex;
  1885. mipLevel = ConstantInt::get(i32Ty, 0);
  1886. }
  1887. } break;
  1888. default:
  1889. widthOpIdx = HLOperandIndex::kGetDimensionsNoMipWidthOpIndex;
  1890. break;
  1891. }
  1892. Value *args[] = {opArg, handle, mipLevel};
  1893. Value *dims = Builder.CreateCall(dxilFunc, args);
  1894. unsigned dimensionIdx = 0;
  1895. Value *width = Builder.CreateExtractValue(dims, dimensionIdx++);
  1896. Value *widthPtr = CI->getArgOperand(widthOpIdx);
  1897. if (widthPtr->getType()->getPointerElementType()->isFloatTy())
  1898. width = Builder.CreateSIToFP(width,
  1899. widthPtr->getType()->getPointerElementType());
  1900. Builder.CreateStore(width, widthPtr);
  1901. if (RK == DxilResource::Kind::StructuredBuffer) {
  1902. // Set stride.
  1903. Value *stridePtr = CI->getArgOperand(widthOpIdx + 1);
  1904. const DataLayout &DL = helper.legacyDataLayout;
  1905. Value *buf = CI->getArgOperand(HLOperandIndex::kHandleOpIdx);
  1906. Type *bufTy = buf->getType();
  1907. Type *bufRetTy = bufTy->getStructElementType(0);
  1908. unsigned stride = DL.getTypeAllocSize(bufRetTy);
  1909. Builder.CreateStore(hlslOP->GetU32Const(stride), stridePtr);
  1910. } else {
  1911. if (widthOpIdx == HLOperandIndex::kGetDimensionsMipWidthOpIndex ||
  1912. // Samples is in w channel too.
  1913. RK == DXIL::ResourceKind::Texture2DMS) {
  1914. // Has mip.
  1915. for (unsigned argIdx = widthOpIdx + 1;
  1916. argIdx < CI->getNumArgOperands() - 1; argIdx++) {
  1917. Value *dim = Builder.CreateExtractValue(dims, dimensionIdx++);
  1918. Value *ptr = CI->getArgOperand(argIdx);
  1919. if (ptr->getType()->getPointerElementType()->isFloatTy())
  1920. dim = Builder.CreateSIToFP(dim,
  1921. ptr->getType()->getPointerElementType());
  1922. Builder.CreateStore(dim, ptr);
  1923. }
  1924. // NumOfLevel is in w channel.
  1925. dimensionIdx = 3;
  1926. Value *dim = Builder.CreateExtractValue(dims, dimensionIdx);
  1927. Value *ptr = CI->getArgOperand(CI->getNumArgOperands() - 1);
  1928. if (ptr->getType()->getPointerElementType()->isFloatTy())
  1929. dim =
  1930. Builder.CreateSIToFP(dim, ptr->getType()->getPointerElementType());
  1931. Builder.CreateStore(dim, ptr);
  1932. } else {
  1933. for (unsigned argIdx = widthOpIdx + 1; argIdx < CI->getNumArgOperands();
  1934. argIdx++) {
  1935. Value *dim = Builder.CreateExtractValue(dims, dimensionIdx++);
  1936. Value *ptr = CI->getArgOperand(argIdx);
  1937. if (ptr->getType()->getPointerElementType()->isFloatTy())
  1938. dim = Builder.CreateSIToFP(dim,
  1939. ptr->getType()->getPointerElementType());
  1940. Builder.CreateStore(dim, ptr);
  1941. }
  1942. }
  1943. }
  1944. return nullptr;
  1945. }
  1946. Value *GenerateUpdateCounter(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1947. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1948. hlsl::OP *hlslOP = &helper.hlslOP;
  1949. Value *handle = CI->getArgOperand(HLOperandIndex::kHandleOpIdx);
  1950. pObjHelper->MarkHasCounter(handle->getType(), handle);
  1951. bool bInc = IOP == IntrinsicOp::MOP_IncrementCounter;
  1952. IRBuilder<> Builder(CI);
  1953. OP::OpCode OpCode = OP::OpCode::BufferUpdateCounter;
  1954. Value *OpCodeArg = hlslOP->GetU32Const((unsigned)OpCode);
  1955. Value *IncVal = hlslOP->GetI8Const(bInc ? 1 : -1);
  1956. // Create BufferUpdateCounter call.
  1957. Value *Args[] = {OpCodeArg, handle, IncVal};
  1958. Function *F =
  1959. hlslOP->GetOpFunc(OpCode, Type::getVoidTy(handle->getContext()));
  1960. return Builder.CreateCall(F, Args);
  1961. }
  1962. Value *ScalarizeResRet(Type *RetTy, Value *ResRet, IRBuilder<> &Builder) {
  1963. // Extract value part.
  1964. Value *retVal = llvm::UndefValue::get(RetTy);
  1965. if (RetTy->isVectorTy()) {
  1966. for (unsigned i = 0; i < RetTy->getVectorNumElements(); i++) {
  1967. Value *retComp = Builder.CreateExtractValue(ResRet, i);
  1968. retVal = Builder.CreateInsertElement(retVal, retComp, i);
  1969. }
  1970. } else {
  1971. retVal = Builder.CreateExtractValue(ResRet, 0);
  1972. }
  1973. return retVal;
  1974. }
  1975. Value *ScalarizeElements(Type *RetTy, ArrayRef<Value*> Elts, IRBuilder<> &Builder) {
  1976. // Extract value part.
  1977. Value *retVal = llvm::UndefValue::get(RetTy);
  1978. if (RetTy->isVectorTy()) {
  1979. unsigned vecSize = RetTy->getVectorNumElements();
  1980. DXASSERT(vecSize <= Elts.size(), "vector size mismatch");
  1981. for (unsigned i = 0; i < vecSize; i++) {
  1982. Value *retComp = Elts[i];
  1983. retVal = Builder.CreateInsertElement(retVal, retComp, i);
  1984. }
  1985. } else {
  1986. retVal = Elts[0];
  1987. }
  1988. return retVal;
  1989. }
  1990. void UpdateStatus(Value *ResRet, Value *status, IRBuilder<> &Builder) {
  1991. if (status && !isa<UndefValue>(status)) {
  1992. Value *statusVal = Builder.CreateExtractValue(ResRet, 4);
  1993. Builder.CreateStore(statusVal, status);
  1994. }
  1995. }
  1996. Value *SplatToVector(Value *Elt, Type *DstTy, IRBuilder<> &Builder) {
  1997. Value *Result = UndefValue::get(DstTy);
  1998. for (unsigned i = 0; i < DstTy->getVectorNumElements(); i++)
  1999. Result = Builder.CreateInsertElement(Result, Elt, i);
  2000. return Result;
  2001. }
  2002. // Sample intrinsics.
  2003. struct SampleHelper {
  2004. SampleHelper(CallInst *CI, OP::OpCode op, HLObjectOperationLowerHelper *pObjHelper);
  2005. OP::OpCode opcode;
  2006. Value *texHandle;
  2007. Value *samplerHandle;
  2008. static const unsigned kMaxCoordDimensions = 4;
  2009. Value *coord[kMaxCoordDimensions];
  2010. Value *special; // For CompareValue, Bias, LOD.
  2011. // SampleGrad only.
  2012. static const unsigned kMaxDDXYDimensions = 3;
  2013. Value *ddx[kMaxDDXYDimensions];
  2014. Value *ddy[kMaxDDXYDimensions];
  2015. // Optional.
  2016. static const unsigned kMaxOffsetDimensions = 3;
  2017. Value *offset[kMaxOffsetDimensions];
  2018. Value *clamp;
  2019. Value *status;
  2020. void TranslateCoord(CallInst *CI, unsigned coordIdx,
  2021. unsigned coordDimensions) {
  2022. Value *coordArg = CI->getArgOperand(coordIdx);
  2023. IRBuilder<> Builder(CI);
  2024. for (unsigned i = 0; i < coordDimensions; i++)
  2025. coord[i] = Builder.CreateExtractElement(coordArg, i);
  2026. Value *undefF = UndefValue::get(Type::getFloatTy(CI->getContext()));
  2027. for (unsigned i = coordDimensions; i < kMaxCoordDimensions; i++)
  2028. coord[i] = undefF;
  2029. }
  2030. void TranslateOffset(CallInst *CI, unsigned offsetIdx,
  2031. unsigned offsetDimensions) {
  2032. Value *undefI = UndefValue::get(Type::getInt32Ty(CI->getContext()));
  2033. if (CI->getNumArgOperands() > offsetIdx) {
  2034. Value *offsetArg = CI->getArgOperand(offsetIdx);
  2035. IRBuilder<> Builder(CI);
  2036. for (unsigned i = 0; i < offsetDimensions; i++)
  2037. offset[i] = Builder.CreateExtractElement(offsetArg, i);
  2038. for (unsigned i = offsetDimensions; i < kMaxOffsetDimensions; i++)
  2039. offset[i] = undefI;
  2040. } else {
  2041. for (unsigned i = 0; i < kMaxOffsetDimensions; i++)
  2042. offset[i] = undefI;
  2043. }
  2044. }
  2045. void SetClamp(CallInst *CI, unsigned clampIdx) {
  2046. if (CI->getNumArgOperands() > clampIdx) {
  2047. clamp = CI->getArgOperand(clampIdx);
  2048. if (clamp->getType()->isVectorTy()) {
  2049. IRBuilder<> Builder(CI);
  2050. clamp = Builder.CreateExtractElement(clamp, (uint64_t)0);
  2051. }
  2052. } else
  2053. clamp = UndefValue::get(Type::getFloatTy(CI->getContext()));
  2054. }
  2055. void SetStatus(CallInst *CI, unsigned statusIdx) {
  2056. if (CI->getNumArgOperands() == (statusIdx + 1))
  2057. status = CI->getArgOperand(statusIdx);
  2058. else
  2059. status = nullptr;
  2060. }
  2061. void SetDDXY(CallInst *CI, MutableArrayRef<Value *> ddxy, Value *ddxyArg,
  2062. unsigned ddxySize) {
  2063. IRBuilder<> Builder(CI);
  2064. for (unsigned i = 0; i < ddxySize; i++)
  2065. ddxy[i] = Builder.CreateExtractElement(ddxyArg, i);
  2066. Value *undefF = UndefValue::get(Type::getFloatTy(CI->getContext()));
  2067. for (unsigned i = ddxySize; i < kMaxDDXYDimensions; i++)
  2068. ddxy[i] = undefF;
  2069. }
  2070. };
  2071. SampleHelper::SampleHelper(
  2072. CallInst *CI, OP::OpCode op, HLObjectOperationLowerHelper *pObjHelper)
  2073. : opcode(op) {
  2074. const unsigned thisIdx =
  2075. HLOperandIndex::kHandleOpIdx; // opcode takes arg0, this pointer is arg1.
  2076. const unsigned kSamplerArgIndex = HLOperandIndex::kSampleSamplerArgIndex;
  2077. IRBuilder<> Builder(CI);
  2078. texHandle = CI->getArgOperand(thisIdx);
  2079. samplerHandle = CI->getArgOperand(kSamplerArgIndex);
  2080. DXIL::ResourceKind RK = pObjHelper->GetRK(texHandle);
  2081. if (RK == DXIL::ResourceKind::Invalid) {
  2082. opcode = DXIL::OpCode::NumOpCodes;
  2083. return;
  2084. }
  2085. unsigned coordDimensions = DxilResource::GetNumCoords(RK);
  2086. unsigned offsetDimensions = DxilResource::GetNumOffsets(RK);
  2087. const unsigned kCoordArgIdx = HLOperandIndex::kSampleCoordArgIndex;
  2088. TranslateCoord(CI, kCoordArgIdx, coordDimensions);
  2089. special = nullptr;
  2090. switch (op) {
  2091. case OP::OpCode::Sample:
  2092. TranslateOffset(CI, HLOperandIndex::kSampleOffsetArgIndex,
  2093. offsetDimensions);
  2094. SetClamp(CI, HLOperandIndex::kSampleClampArgIndex);
  2095. SetStatus(CI, HLOperandIndex::kSampleStatusArgIndex);
  2096. break;
  2097. case OP::OpCode::SampleLevel:
  2098. special = CI->getArgOperand(HLOperandIndex::kSampleLLevelArgIndex);
  2099. TranslateOffset(CI, HLOperandIndex::kSampleLOffsetArgIndex,
  2100. offsetDimensions);
  2101. SetStatus(CI, HLOperandIndex::kSampleLStatusArgIndex);
  2102. break;
  2103. case OP::OpCode::SampleBias:
  2104. special = CI->getArgOperand(HLOperandIndex::kSampleBBiasArgIndex);
  2105. TranslateOffset(CI, HLOperandIndex::kSampleBOffsetArgIndex,
  2106. offsetDimensions);
  2107. SetClamp(CI, HLOperandIndex::kSampleBClampArgIndex);
  2108. SetStatus(CI, HLOperandIndex::kSampleBStatusArgIndex);
  2109. break;
  2110. case OP::OpCode::SampleCmp:
  2111. special = CI->getArgOperand(HLOperandIndex::kSampleCmpCmpValArgIndex);
  2112. TranslateOffset(CI, HLOperandIndex::kSampleCmpOffsetArgIndex,
  2113. offsetDimensions);
  2114. SetClamp(CI, HLOperandIndex::kSampleCmpClampArgIndex);
  2115. SetStatus(CI, HLOperandIndex::kSampleCmpStatusArgIndex);
  2116. break;
  2117. case OP::OpCode::SampleCmpLevelZero:
  2118. special = CI->getArgOperand(HLOperandIndex::kSampleCmpLZCmpValArgIndex);
  2119. TranslateOffset(CI, HLOperandIndex::kSampleCmpLZOffsetArgIndex,
  2120. offsetDimensions);
  2121. SetStatus(CI, HLOperandIndex::kSampleCmpLZStatusArgIndex);
  2122. break;
  2123. case OP::OpCode::SampleGrad:
  2124. SetDDXY(CI, ddx, CI->getArgOperand(HLOperandIndex::kSampleGDDXArgIndex),
  2125. offsetDimensions);
  2126. SetDDXY(CI, ddy, CI->getArgOperand(HLOperandIndex::kSampleGDDYArgIndex),
  2127. offsetDimensions);
  2128. TranslateOffset(CI, HLOperandIndex::kSampleGOffsetArgIndex,
  2129. offsetDimensions);
  2130. SetClamp(CI, HLOperandIndex::kSampleGClampArgIndex);
  2131. SetStatus(CI, HLOperandIndex::kSampleGStatusArgIndex);
  2132. break;
  2133. case OP::OpCode::CalculateLOD:
  2134. // Only need coord for LOD calculation.
  2135. break;
  2136. default:
  2137. DXASSERT(0, "invalid opcode for Sample");
  2138. break;
  2139. }
  2140. }
  2141. Value *TranslateCalculateLOD(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  2142. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  2143. hlsl::OP *hlslOP = &helper.hlslOP;
  2144. SampleHelper sampleHelper(CI, OP::OpCode::CalculateLOD, pObjHelper);
  2145. if (sampleHelper.opcode == DXIL::OpCode::NumOpCodes) {
  2146. Translated = false;
  2147. return nullptr;
  2148. }
  2149. bool bClamped = IOP == IntrinsicOp::MOP_CalculateLevelOfDetail;
  2150. IRBuilder<> Builder(CI);
  2151. Value *opArg =
  2152. hlslOP->GetU32Const(static_cast<unsigned>(OP::OpCode::CalculateLOD));
  2153. Value *clamped = hlslOP->GetI1Const(bClamped);
  2154. Value *args[] = {opArg,
  2155. sampleHelper.texHandle,
  2156. sampleHelper.samplerHandle,
  2157. sampleHelper.coord[0],
  2158. sampleHelper.coord[1],
  2159. sampleHelper.coord[2],
  2160. clamped};
  2161. Function *dxilFunc = hlslOP->GetOpFunc(OP::OpCode::CalculateLOD,
  2162. Type::getFloatTy(opArg->getContext()));
  2163. Value *LOD = Builder.CreateCall(dxilFunc, args);
  2164. return LOD;
  2165. }
  2166. void GenerateDxilSample(CallInst *CI, Function *F, ArrayRef<Value *> sampleArgs,
  2167. Value *status) {
  2168. IRBuilder<> Builder(CI);
  2169. CallInst *call = Builder.CreateCall(F, sampleArgs);
  2170. // extract value part
  2171. Value *retVal = ScalarizeResRet(CI->getType(), call, Builder);
  2172. // Replace ret val.
  2173. CI->replaceAllUsesWith(retVal);
  2174. // get status
  2175. if (status) {
  2176. UpdateStatus(call, status, Builder);
  2177. }
  2178. }
  2179. Value *TranslateSample(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  2180. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  2181. hlsl::OP *hlslOP = &helper.hlslOP;
  2182. SampleHelper sampleHelper(CI, opcode, pObjHelper);
  2183. if (sampleHelper.opcode == DXIL::OpCode::NumOpCodes) {
  2184. Translated = false;
  2185. return nullptr;
  2186. }
  2187. Type *Ty = CI->getType();
  2188. Function *F = hlslOP->GetOpFunc(opcode, Ty->getScalarType());
  2189. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  2190. switch (opcode) {
  2191. case OP::OpCode::Sample: {
  2192. Value *sampleArgs[] = {
  2193. opArg, sampleHelper.texHandle, sampleHelper.samplerHandle,
  2194. // Coord.
  2195. sampleHelper.coord[0], sampleHelper.coord[1], sampleHelper.coord[2],
  2196. sampleHelper.coord[3],
  2197. // Offset.
  2198. sampleHelper.offset[0], sampleHelper.offset[1], sampleHelper.offset[2],
  2199. // Clamp.
  2200. sampleHelper.clamp};
  2201. GenerateDxilSample(CI, F, sampleArgs, sampleHelper.status);
  2202. } break;
  2203. case OP::OpCode::SampleLevel: {
  2204. Value *sampleArgs[] = {
  2205. opArg, sampleHelper.texHandle, sampleHelper.samplerHandle,
  2206. // Coord.
  2207. sampleHelper.coord[0], sampleHelper.coord[1], sampleHelper.coord[2],
  2208. sampleHelper.coord[3],
  2209. // Offset.
  2210. sampleHelper.offset[0], sampleHelper.offset[1], sampleHelper.offset[2],
  2211. // LOD.
  2212. sampleHelper.special};
  2213. GenerateDxilSample(CI, F, sampleArgs, sampleHelper.status);
  2214. } break;
  2215. case OP::OpCode::SampleGrad: {
  2216. Value *sampleArgs[] = {
  2217. opArg, sampleHelper.texHandle, sampleHelper.samplerHandle,
  2218. // Coord.
  2219. sampleHelper.coord[0], sampleHelper.coord[1], sampleHelper.coord[2],
  2220. sampleHelper.coord[3],
  2221. // Offset.
  2222. sampleHelper.offset[0], sampleHelper.offset[1], sampleHelper.offset[2],
  2223. // Ddx.
  2224. sampleHelper.ddx[0], sampleHelper.ddx[1], sampleHelper.ddx[2],
  2225. // Ddy.
  2226. sampleHelper.ddy[0], sampleHelper.ddy[1], sampleHelper.ddy[2],
  2227. // Clamp.
  2228. sampleHelper.clamp};
  2229. GenerateDxilSample(CI, F, sampleArgs, sampleHelper.status);
  2230. } break;
  2231. case OP::OpCode::SampleBias: {
  2232. // Clamp bias for immediate.
  2233. Value *bias = sampleHelper.special;
  2234. if (ConstantFP *FP = dyn_cast<ConstantFP>(bias)) {
  2235. float v = FP->getValueAPF().convertToFloat();
  2236. if (v > DXIL::kMaxMipLodBias)
  2237. bias = ConstantFP::get(FP->getType(), DXIL::kMaxMipLodBias);
  2238. if (v < DXIL::kMinMipLodBias)
  2239. bias = ConstantFP::get(FP->getType(), DXIL::kMinMipLodBias);
  2240. }
  2241. Value *sampleArgs[] = {
  2242. opArg, sampleHelper.texHandle, sampleHelper.samplerHandle,
  2243. // Coord.
  2244. sampleHelper.coord[0], sampleHelper.coord[1], sampleHelper.coord[2],
  2245. sampleHelper.coord[3],
  2246. // Offset.
  2247. sampleHelper.offset[0], sampleHelper.offset[1], sampleHelper.offset[2],
  2248. // Bias.
  2249. bias,
  2250. // Clamp.
  2251. sampleHelper.clamp};
  2252. GenerateDxilSample(CI, F, sampleArgs, sampleHelper.status);
  2253. } break;
  2254. case OP::OpCode::SampleCmp: {
  2255. Value *sampleArgs[] = {
  2256. opArg, sampleHelper.texHandle, sampleHelper.samplerHandle,
  2257. // Coord.
  2258. sampleHelper.coord[0], sampleHelper.coord[1], sampleHelper.coord[2],
  2259. sampleHelper.coord[3],
  2260. // Offset.
  2261. sampleHelper.offset[0], sampleHelper.offset[1], sampleHelper.offset[2],
  2262. // CmpVal.
  2263. sampleHelper.special,
  2264. // Clamp.
  2265. sampleHelper.clamp};
  2266. GenerateDxilSample(CI, F, sampleArgs, sampleHelper.status);
  2267. } break;
  2268. case OP::OpCode::SampleCmpLevelZero:
  2269. default: {
  2270. DXASSERT(opcode == OP::OpCode::SampleCmpLevelZero, "invalid sample opcode");
  2271. Value *sampleArgs[] = {
  2272. opArg, sampleHelper.texHandle, sampleHelper.samplerHandle,
  2273. // Coord.
  2274. sampleHelper.coord[0], sampleHelper.coord[1], sampleHelper.coord[2],
  2275. sampleHelper.coord[3],
  2276. // Offset.
  2277. sampleHelper.offset[0], sampleHelper.offset[1], sampleHelper.offset[2],
  2278. // CmpVal.
  2279. sampleHelper.special};
  2280. GenerateDxilSample(CI, F, sampleArgs, sampleHelper.status);
  2281. } break;
  2282. }
  2283. // CI is replaced in GenerateDxilSample.
  2284. return nullptr;
  2285. }
  2286. // Gather intrinsics.
  2287. struct GatherHelper {
  2288. enum class GatherChannel {
  2289. GatherAll,
  2290. GatherRed,
  2291. GatherGreen,
  2292. GatherBlue,
  2293. GatherAlpha,
  2294. };
  2295. GatherHelper(CallInst *CI, OP::OpCode op, HLObjectOperationLowerHelper *pObjHelper,
  2296. GatherHelper::GatherChannel ch);
  2297. OP::OpCode opcode;
  2298. Value *texHandle;
  2299. Value *samplerHandle;
  2300. static const unsigned kMaxCoordDimensions = 4;
  2301. Value *coord[kMaxCoordDimensions];
  2302. unsigned channel;
  2303. Value *special; // For CompareValue, Bias, LOD.
  2304. // Optional.
  2305. static const unsigned kMaxOffsetDimensions = 2;
  2306. Value *offset[kMaxOffsetDimensions];
  2307. // For the overload send different offset for each sample.
  2308. // Only save 3 sampleOffsets because use offset for normal overload as first
  2309. // sample offset.
  2310. static const unsigned kSampleOffsetDimensions = 3;
  2311. Value *sampleOffsets[kSampleOffsetDimensions][kMaxOffsetDimensions];
  2312. Value *status;
  2313. bool hasSampleOffsets;
  2314. void TranslateCoord(CallInst *CI, unsigned coordIdx,
  2315. unsigned coordDimensions) {
  2316. Value *coordArg = CI->getArgOperand(coordIdx);
  2317. IRBuilder<> Builder(CI);
  2318. for (unsigned i = 0; i < coordDimensions; i++)
  2319. coord[i] = Builder.CreateExtractElement(coordArg, i);
  2320. Value *undefF = UndefValue::get(Type::getFloatTy(CI->getContext()));
  2321. for (unsigned i = coordDimensions; i < kMaxCoordDimensions; i++)
  2322. coord[i] = undefF;
  2323. }
  2324. void SetStatus(CallInst *CI, unsigned statusIdx) {
  2325. if (CI->getNumArgOperands() == (statusIdx + 1))
  2326. status = CI->getArgOperand(statusIdx);
  2327. else
  2328. status = nullptr;
  2329. }
  2330. void TranslateOffset(CallInst *CI, unsigned offsetIdx,
  2331. unsigned offsetDimensions) {
  2332. Value *undefI = UndefValue::get(Type::getInt32Ty(CI->getContext()));
  2333. if (CI->getNumArgOperands() > offsetIdx) {
  2334. Value *offsetArg = CI->getArgOperand(offsetIdx);
  2335. IRBuilder<> Builder(CI);
  2336. for (unsigned i = 0; i < offsetDimensions; i++)
  2337. offset[i] = Builder.CreateExtractElement(offsetArg, i);
  2338. for (unsigned i = offsetDimensions; i < kMaxOffsetDimensions; i++)
  2339. offset[i] = undefI;
  2340. } else {
  2341. for (unsigned i = 0; i < kMaxOffsetDimensions; i++)
  2342. offset[i] = undefI;
  2343. }
  2344. }
  2345. void TranslateSampleOffset(CallInst *CI, unsigned offsetIdx,
  2346. unsigned offsetDimensions) {
  2347. Value *undefI = UndefValue::get(Type::getInt32Ty(CI->getContext()));
  2348. if (CI->getNumArgOperands() >= (offsetIdx + kSampleOffsetDimensions)) {
  2349. hasSampleOffsets = true;
  2350. IRBuilder<> Builder(CI);
  2351. for (unsigned ch = 0; ch < kSampleOffsetDimensions; ch++) {
  2352. Value *offsetArg = CI->getArgOperand(offsetIdx + ch);
  2353. for (unsigned i = 0; i < offsetDimensions; i++)
  2354. sampleOffsets[ch][i] = Builder.CreateExtractElement(offsetArg, i);
  2355. for (unsigned i = offsetDimensions; i < kMaxOffsetDimensions; i++)
  2356. sampleOffsets[ch][i] = undefI;
  2357. }
  2358. }
  2359. }
  2360. // Update the offset args for gather with sample offset at sampleIdx.
  2361. void UpdateOffsetInGatherArgs(MutableArrayRef<Value *> gatherArgs,
  2362. unsigned sampleIdx) {
  2363. unsigned offsetBase = DXIL::OperandIndex::kTextureGatherOffset0OpIdx;
  2364. for (unsigned i = 0; i < kMaxOffsetDimensions; i++)
  2365. // -1 because offset for sample 0 is in GatherHelper::offset.
  2366. gatherArgs[offsetBase + i] = sampleOffsets[sampleIdx - 1][i];
  2367. }
  2368. };
  2369. GatherHelper::GatherHelper(
  2370. CallInst *CI, OP::OpCode op, HLObjectOperationLowerHelper *pObjHelper,
  2371. GatherHelper::GatherChannel ch)
  2372. : opcode(op), special(nullptr), hasSampleOffsets(false) {
  2373. const unsigned thisIdx =
  2374. HLOperandIndex::kHandleOpIdx; // opcode takes arg0, this pointer is arg1.
  2375. const unsigned kSamplerArgIndex = HLOperandIndex::kSampleSamplerArgIndex;
  2376. switch (ch) {
  2377. case GatherChannel::GatherAll:
  2378. channel = 0;
  2379. break;
  2380. case GatherChannel::GatherRed:
  2381. channel = 0;
  2382. break;
  2383. case GatherChannel::GatherGreen:
  2384. channel = 1;
  2385. break;
  2386. case GatherChannel::GatherBlue:
  2387. channel = 2;
  2388. break;
  2389. case GatherChannel::GatherAlpha:
  2390. channel = 3;
  2391. break;
  2392. }
  2393. IRBuilder<> Builder(CI);
  2394. texHandle = CI->getArgOperand(thisIdx);
  2395. samplerHandle = CI->getArgOperand(kSamplerArgIndex);
  2396. DXIL::ResourceKind RK = pObjHelper->GetRK(texHandle);
  2397. if (RK == DXIL::ResourceKind::Invalid) {
  2398. opcode = DXIL::OpCode::NumOpCodes;
  2399. return;
  2400. }
  2401. unsigned coordSize = DxilResource::GetNumCoords(RK);
  2402. unsigned offsetSize = DxilResource::GetNumOffsets(RK);
  2403. const unsigned kCoordArgIdx = HLOperandIndex::kSampleCoordArgIndex;
  2404. TranslateCoord(CI, kCoordArgIdx, coordSize);
  2405. switch (op) {
  2406. case OP::OpCode::TextureGather: {
  2407. TranslateOffset(CI, HLOperandIndex::kGatherOffsetArgIndex, offsetSize);
  2408. // Gather all don't have sample offset version overload.
  2409. if (ch != GatherChannel::GatherAll)
  2410. TranslateSampleOffset(CI, HLOperandIndex::kGatherSampleOffsetArgIndex,
  2411. offsetSize);
  2412. unsigned statusIdx =
  2413. hasSampleOffsets ? HLOperandIndex::kGatherStatusWithSampleOffsetArgIndex
  2414. : HLOperandIndex::kGatherStatusArgIndex;
  2415. SetStatus(CI, statusIdx);
  2416. } break;
  2417. case OP::OpCode::TextureGatherCmp: {
  2418. special = CI->getArgOperand(HLOperandIndex::kGatherCmpCmpValArgIndex);
  2419. TranslateOffset(CI, HLOperandIndex::kGatherCmpOffsetArgIndex, offsetSize);
  2420. // Gather all don't have sample offset version overload.
  2421. if (ch != GatherChannel::GatherAll)
  2422. TranslateSampleOffset(CI, HLOperandIndex::kGatherCmpSampleOffsetArgIndex,
  2423. offsetSize);
  2424. unsigned statusIdx =
  2425. hasSampleOffsets
  2426. ? HLOperandIndex::kGatherCmpStatusWithSampleOffsetArgIndex
  2427. : HLOperandIndex::kGatherCmpStatusArgIndex;
  2428. SetStatus(CI, statusIdx);
  2429. } break;
  2430. default:
  2431. DXASSERT(0, "invalid opcode for Gather");
  2432. break;
  2433. }
  2434. }
  2435. void GenerateDxilGather(CallInst *CI, Function *F,
  2436. MutableArrayRef<Value *> gatherArgs,
  2437. GatherHelper &helper) {
  2438. IRBuilder<> Builder(CI);
  2439. CallInst *call = Builder.CreateCall(F, gatherArgs);
  2440. if (!helper.hasSampleOffsets) {
  2441. // extract value part
  2442. Value *retVal = ScalarizeResRet(CI->getType(), call, Builder);
  2443. // Replace ret val.
  2444. CI->replaceAllUsesWith(retVal);
  2445. } else {
  2446. Value *retVal = UndefValue::get(CI->getType());
  2447. Value *elt = Builder.CreateExtractValue(call, (uint64_t)0);
  2448. retVal = Builder.CreateInsertElement(retVal, elt, (uint64_t)0);
  2449. helper.UpdateOffsetInGatherArgs(gatherArgs, /*sampleIdx*/ 1);
  2450. CallInst *callY = Builder.CreateCall(F, gatherArgs);
  2451. elt = Builder.CreateExtractValue(callY, (uint64_t)0);
  2452. retVal = Builder.CreateInsertElement(retVal, elt, 1);
  2453. helper.UpdateOffsetInGatherArgs(gatherArgs, /*sampleIdx*/ 2);
  2454. CallInst *callZ = Builder.CreateCall(F, gatherArgs);
  2455. elt = Builder.CreateExtractValue(callZ, (uint64_t)0);
  2456. retVal = Builder.CreateInsertElement(retVal, elt, 2);
  2457. helper.UpdateOffsetInGatherArgs(gatherArgs, /*sampleIdx*/ 3);
  2458. CallInst *callW = Builder.CreateCall(F, gatherArgs);
  2459. elt = Builder.CreateExtractValue(callW, (uint64_t)0);
  2460. retVal = Builder.CreateInsertElement(retVal, elt, 3);
  2461. // Replace ret val.
  2462. CI->replaceAllUsesWith(retVal);
  2463. // TODO: UpdateStatus for each gather call.
  2464. }
  2465. // Get status
  2466. if (helper.status) {
  2467. UpdateStatus(call, helper.status, Builder);
  2468. }
  2469. }
  2470. Value *TranslateGather(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  2471. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  2472. hlsl::OP *hlslOP = &helper.hlslOP;
  2473. GatherHelper::GatherChannel ch = GatherHelper::GatherChannel::GatherAll;
  2474. switch (IOP) {
  2475. case IntrinsicOp::MOP_Gather:
  2476. case IntrinsicOp::MOP_GatherCmp:
  2477. ch = GatherHelper::GatherChannel::GatherAll;
  2478. break;
  2479. case IntrinsicOp::MOP_GatherRed:
  2480. case IntrinsicOp::MOP_GatherCmpRed:
  2481. ch = GatherHelper::GatherChannel::GatherRed;
  2482. break;
  2483. case IntrinsicOp::MOP_GatherGreen:
  2484. case IntrinsicOp::MOP_GatherCmpGreen:
  2485. ch = GatherHelper::GatherChannel::GatherGreen;
  2486. break;
  2487. case IntrinsicOp::MOP_GatherBlue:
  2488. case IntrinsicOp::MOP_GatherCmpBlue:
  2489. ch = GatherHelper::GatherChannel::GatherBlue;
  2490. break;
  2491. case IntrinsicOp::MOP_GatherAlpha:
  2492. case IntrinsicOp::MOP_GatherCmpAlpha:
  2493. ch = GatherHelper::GatherChannel::GatherAlpha;
  2494. break;
  2495. default:
  2496. DXASSERT(0, "invalid gather intrinsic");
  2497. break;
  2498. }
  2499. GatherHelper gatherHelper(CI, opcode, pObjHelper, ch);
  2500. if (gatherHelper.opcode == DXIL::OpCode::NumOpCodes) {
  2501. Translated = false;
  2502. return nullptr;
  2503. }
  2504. Type *Ty = CI->getType();
  2505. Function *F = hlslOP->GetOpFunc(opcode, Ty->getScalarType());
  2506. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  2507. Value *channelArg = hlslOP->GetU32Const(gatherHelper.channel);
  2508. switch (opcode) {
  2509. case OP::OpCode::TextureGather: {
  2510. Value *gatherArgs[] = {
  2511. opArg, gatherHelper.texHandle, gatherHelper.samplerHandle,
  2512. // Coord.
  2513. gatherHelper.coord[0], gatherHelper.coord[1], gatherHelper.coord[2],
  2514. gatherHelper.coord[3],
  2515. // Offset.
  2516. gatherHelper.offset[0], gatherHelper.offset[1],
  2517. // Channel.
  2518. channelArg};
  2519. GenerateDxilGather(CI, F, gatherArgs, gatherHelper);
  2520. } break;
  2521. case OP::OpCode::TextureGatherCmp: {
  2522. Value *gatherArgs[] = {
  2523. opArg, gatherHelper.texHandle, gatherHelper.samplerHandle,
  2524. // Coord.
  2525. gatherHelper.coord[0], gatherHelper.coord[1], gatherHelper.coord[2],
  2526. gatherHelper.coord[3],
  2527. // Offset.
  2528. gatherHelper.offset[0], gatherHelper.offset[1],
  2529. // Channel.
  2530. channelArg,
  2531. // CmpVal.
  2532. gatherHelper.special};
  2533. GenerateDxilGather(CI, F, gatherArgs, gatherHelper);
  2534. } break;
  2535. default:
  2536. DXASSERT(0, "invalid opcode for Gather");
  2537. break;
  2538. }
  2539. // CI is replaced in GenerateDxilGather.
  2540. return nullptr;
  2541. }
  2542. // Load/Store intrinsics.
  2543. struct ResLoadHelper {
  2544. ResLoadHelper(CallInst *CI, DxilResource::Kind RK, DxilResourceBase::Class RC,
  2545. Value *h, bool bForSubscript=false);
  2546. ResLoadHelper(CallInst *CI, DxilResource::Kind RK, DxilResourceBase::Class RC,
  2547. Value *h, Value *mip);
  2548. // For double subscript.
  2549. ResLoadHelper(Instruction *ldInst, Value *h, Value *idx, Value *mip)
  2550. : opcode(OP::OpCode::TextureLoad), handle(h), retVal(ldInst), addr(idx),
  2551. offset(nullptr), status(nullptr), mipLevel(mip) {}
  2552. OP::OpCode opcode;
  2553. Value *handle;
  2554. Value *retVal;
  2555. Value *addr;
  2556. Value *offset;
  2557. Value *status;
  2558. Value *mipLevel;
  2559. };
  2560. ResLoadHelper::ResLoadHelper(CallInst *CI, DxilResource::Kind RK,
  2561. DxilResourceBase::Class RC, Value *hdl, bool bForSubscript)
  2562. : handle(hdl), offset(nullptr), status(nullptr) {
  2563. switch (RK) {
  2564. case DxilResource::Kind::RawBuffer:
  2565. case DxilResource::Kind::TypedBuffer:
  2566. case DxilResource::Kind::StructuredBuffer:
  2567. opcode = OP::OpCode::BufferLoad;
  2568. break;
  2569. case DxilResource::Kind::Invalid:
  2570. DXASSERT(0, "invalid resource kind");
  2571. break;
  2572. default:
  2573. opcode = OP::OpCode::TextureLoad;
  2574. break;
  2575. }
  2576. retVal = CI;
  2577. const unsigned kAddrIdx = HLOperandIndex::kBufLoadAddrOpIdx;
  2578. addr = CI->getArgOperand(kAddrIdx);
  2579. unsigned argc = CI->getNumArgOperands();
  2580. if (opcode == OP::OpCode::TextureLoad) {
  2581. // mip at last channel
  2582. unsigned coordSize = DxilResource::GetNumCoords(RK);
  2583. if (RC == DxilResourceBase::Class::SRV) {
  2584. if (bForSubscript) {
  2585. // Use 0 when access by [].
  2586. mipLevel = IRBuilder<>(CI).getInt32(0);
  2587. } else {
  2588. if (coordSize == 1 && !addr->getType()->isVectorTy()) {
  2589. // Use addr when access by Load.
  2590. mipLevel = addr;
  2591. } else {
  2592. mipLevel = IRBuilder<>(CI).CreateExtractElement(addr, coordSize);
  2593. }
  2594. }
  2595. } else {
  2596. // Set mip level to undef for UAV.
  2597. mipLevel = UndefValue::get(Type::getInt32Ty(addr->getContext()));
  2598. }
  2599. if (RC == DxilResourceBase::Class::SRV) {
  2600. unsigned offsetIdx = HLOperandIndex::kTexLoadOffsetOpIdx;
  2601. unsigned statusIdx = HLOperandIndex::kTexLoadStatusOpIdx;
  2602. if (RK == DxilResource::Kind::Texture2DMS ||
  2603. RK == DxilResource::Kind::Texture2DMSArray) {
  2604. offsetIdx = HLOperandIndex::kTex2DMSLoadOffsetOpIdx;
  2605. statusIdx = HLOperandIndex::kTex2DMSLoadStatusOpIdx;
  2606. mipLevel =
  2607. CI->getArgOperand(HLOperandIndex::kTex2DMSLoadSampleIdxOpIdx);
  2608. }
  2609. if (argc > offsetIdx)
  2610. offset = CI->getArgOperand(offsetIdx);
  2611. if (argc > statusIdx)
  2612. status = CI->getArgOperand(statusIdx);
  2613. } else {
  2614. const unsigned kStatusIdx = HLOperandIndex::kRWTexLoadStatusOpIdx;
  2615. if (argc > kStatusIdx)
  2616. status = CI->getArgOperand(kStatusIdx);
  2617. }
  2618. } else {
  2619. const unsigned kStatusIdx = HLOperandIndex::kBufLoadStatusOpIdx;
  2620. if (argc > kStatusIdx)
  2621. status = CI->getArgOperand(kStatusIdx);
  2622. }
  2623. }
  2624. ResLoadHelper::ResLoadHelper(CallInst *CI, DxilResource::Kind RK,
  2625. DxilResourceBase::Class RC, Value *hdl, Value *mip)
  2626. : handle(hdl), offset(nullptr), status(nullptr) {
  2627. DXASSERT(RK != DxilResource::Kind::RawBuffer &&
  2628. RK != DxilResource::Kind::TypedBuffer &&
  2629. RK != DxilResource::Kind::Invalid,
  2630. "invalid resource kind");
  2631. opcode = OP::OpCode::TextureLoad;
  2632. retVal = CI;
  2633. mipLevel = mip;
  2634. const unsigned kAddrIdx = HLOperandIndex::kMipLoadAddrOpIdx;
  2635. addr = CI->getArgOperand(kAddrIdx);
  2636. unsigned argc = CI->getNumArgOperands();
  2637. const unsigned kOffsetIdx = HLOperandIndex::kMipLoadOffsetOpIdx;
  2638. const unsigned kStatusIdx = HLOperandIndex::kMipLoadStatusOpIdx;
  2639. if (argc > kOffsetIdx)
  2640. offset = CI->getArgOperand(kOffsetIdx);
  2641. if (argc > kStatusIdx)
  2642. status = CI->getArgOperand(kStatusIdx);
  2643. }
  2644. void TranslateStructBufSubscript(CallInst *CI, Value *handle, Value *status,
  2645. hlsl::OP *OP, const DataLayout &DL);
  2646. // Create { v0, v1 } from { v0.lo, v0.hi, v1.lo, v1.hi }
  2647. void Make64bitResultForLoad(Type *EltTy, ArrayRef<Value *> resultElts32,
  2648. unsigned size, MutableArrayRef<Value *> resultElts,
  2649. hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  2650. Type *i64Ty = Builder.getInt64Ty();
  2651. Type *doubleTy = Builder.getDoubleTy();
  2652. if (EltTy == doubleTy) {
  2653. Function *makeDouble =
  2654. hlslOP->GetOpFunc(DXIL::OpCode::MakeDouble, doubleTy);
  2655. Value *makeDoubleOpArg =
  2656. Builder.getInt32((unsigned)DXIL::OpCode::MakeDouble);
  2657. for (unsigned i = 0; i < size; i++) {
  2658. Value *lo = resultElts32[2 * i];
  2659. Value *hi = resultElts32[2 * i + 1];
  2660. Value *V = Builder.CreateCall(makeDouble, {makeDoubleOpArg, lo, hi});
  2661. resultElts[i] = V;
  2662. }
  2663. } else {
  2664. for (unsigned i = 0; i < size; i++) {
  2665. Value *lo = resultElts32[2 * i];
  2666. Value *hi = resultElts32[2 * i + 1];
  2667. lo = Builder.CreateZExt(lo, i64Ty);
  2668. hi = Builder.CreateZExt(hi, i64Ty);
  2669. hi = Builder.CreateShl(hi, 32);
  2670. resultElts[i] = Builder.CreateOr(lo, hi);
  2671. }
  2672. }
  2673. }
  2674. void TranslateLoad(ResLoadHelper &helper, HLResource::Kind RK,
  2675. IRBuilder<> &Builder, hlsl::OP *OP, const DataLayout &DL) {
  2676. Type *Ty = helper.retVal->getType();
  2677. if (Ty->isPointerTy()) {
  2678. TranslateStructBufSubscript(cast<CallInst>(helper.retVal), helper.handle,
  2679. helper.status, OP, DL);
  2680. return;
  2681. }
  2682. OP::OpCode opcode = helper.opcode;
  2683. Type *i32Ty = Builder.getInt32Ty();
  2684. Type *i64Ty = Builder.getInt64Ty();
  2685. Type *doubleTy = Builder.getDoubleTy();
  2686. Type *EltTy = Ty->getScalarType();
  2687. bool is64 = EltTy == i64Ty || EltTy == doubleTy;
  2688. if (is64) {
  2689. EltTy = i32Ty;
  2690. }
  2691. Function *F = OP->GetOpFunc(opcode, EltTy);
  2692. llvm::Constant *opArg = OP->GetU32Const((unsigned)opcode);
  2693. llvm::Value *undefI = llvm::UndefValue::get(i32Ty);
  2694. SmallVector<Value *, 12> loadArgs;
  2695. loadArgs.emplace_back(opArg); // opcode
  2696. loadArgs.emplace_back(helper.handle); // resource handle
  2697. if (opcode == OP::OpCode::TextureLoad) {
  2698. // set mip level
  2699. loadArgs.emplace_back(helper.mipLevel);
  2700. }
  2701. if (opcode == OP::OpCode::TextureLoad) {
  2702. // texture coord
  2703. unsigned coordSize = DxilResource::GetNumCoords(RK);
  2704. bool isVectorAddr = helper.addr->getType()->isVectorTy();
  2705. for (unsigned i = 0; i < 3; i++) {
  2706. if (i < coordSize) {
  2707. loadArgs.emplace_back(
  2708. isVectorAddr ? Builder.CreateExtractElement(helper.addr, i) : helper.addr);
  2709. }
  2710. else
  2711. loadArgs.emplace_back(undefI);
  2712. }
  2713. } else {
  2714. if (helper.addr->getType()->isVectorTy()) {
  2715. Value *scalarOffset =
  2716. Builder.CreateExtractElement(helper.addr, (uint64_t)0);
  2717. // TODO: calculate the real address based on opcode
  2718. loadArgs.emplace_back(scalarOffset); // offset
  2719. } else {
  2720. // TODO: calculate the real address based on opcode
  2721. loadArgs.emplace_back(helper.addr); // offset
  2722. }
  2723. }
  2724. // offset 0
  2725. if (opcode == OP::OpCode::TextureLoad) {
  2726. if (helper.offset && !isa<llvm::UndefValue>(helper.offset)) {
  2727. unsigned offsetSize = DxilResource::GetNumOffsets(RK);
  2728. for (unsigned i = 0; i < 3; i++) {
  2729. if (i < offsetSize)
  2730. loadArgs.emplace_back(Builder.CreateExtractElement(helper.offset, i));
  2731. else
  2732. loadArgs.emplace_back(undefI);
  2733. }
  2734. } else {
  2735. loadArgs.emplace_back(undefI);
  2736. loadArgs.emplace_back(undefI);
  2737. loadArgs.emplace_back(undefI);
  2738. }
  2739. }
  2740. // Offset 1
  2741. if (RK == DxilResource::Kind::RawBuffer ||
  2742. RK == DxilResource::Kind::TypedBuffer) {
  2743. loadArgs.emplace_back(undefI);
  2744. } else if (RK == DxilResource::Kind::StructuredBuffer)
  2745. loadArgs.emplace_back(
  2746. OP->GetU32Const(0)); // For case use built-in types in structure buffer.
  2747. Value *ResRet =
  2748. Builder.CreateCall(F, loadArgs, OP->GetOpCodeName(opcode));
  2749. Value *retValNew = nullptr;
  2750. if (!is64) {
  2751. retValNew = ScalarizeResRet(Ty, ResRet, Builder);
  2752. } else {
  2753. unsigned size = 1;
  2754. if (Ty->isVectorTy()) {
  2755. size = Ty->getVectorNumElements();
  2756. }
  2757. DXASSERT(size <= 2, "typed buffer only allow 4 dwords");
  2758. EltTy = Ty->getScalarType();
  2759. Value *Elts[2];
  2760. Make64bitResultForLoad(Ty->getScalarType(),
  2761. {
  2762. Builder.CreateExtractValue(ResRet, 0),
  2763. Builder.CreateExtractValue(ResRet, 1),
  2764. Builder.CreateExtractValue(ResRet, 2),
  2765. Builder.CreateExtractValue(ResRet, 3),
  2766. },
  2767. size, Elts, OP, Builder);
  2768. retValNew = ScalarizeElements(Ty, Elts, Builder);
  2769. }
  2770. // replace
  2771. helper.retVal->replaceAllUsesWith(retValNew);
  2772. // Save new ret val.
  2773. helper.retVal = retValNew;
  2774. // get status
  2775. UpdateStatus(ResRet, helper.status, Builder);
  2776. }
  2777. Value *TranslateResourceLoad(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  2778. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  2779. hlsl::OP *hlslOP = &helper.hlslOP;
  2780. Value *handle = CI->getArgOperand(HLOperandIndex::kHandleOpIdx);
  2781. IRBuilder<> Builder(CI);
  2782. DXIL::ResourceClass RC = pObjHelper->GetRC(handle);
  2783. DXIL::ResourceKind RK = pObjHelper->GetRK(handle);
  2784. ResLoadHelper loadHelper(CI, RK, RC, handle);
  2785. TranslateLoad(loadHelper, RK, Builder, hlslOP, helper.legacyDataLayout);
  2786. // CI is replaced in TranslateLoad.
  2787. return nullptr;
  2788. }
  2789. // Split { v0, v1 } to { v0.lo, v0.hi, v1.lo, v1.hi }
  2790. void Split64bitValForStore(Type *EltTy, ArrayRef<Value *> vals, unsigned size,
  2791. MutableArrayRef<Value *> vals32, hlsl::OP *hlslOP,
  2792. IRBuilder<> &Builder) {
  2793. Type *i32Ty = Builder.getInt32Ty();
  2794. Type *doubleTy = Builder.getDoubleTy();
  2795. Value *undefI32 = UndefValue::get(i32Ty);
  2796. if (EltTy == doubleTy) {
  2797. Function *dToU = hlslOP->GetOpFunc(DXIL::OpCode::SplitDouble, doubleTy);
  2798. Value *dToUOpArg = Builder.getInt32((unsigned)DXIL::OpCode::SplitDouble);
  2799. for (unsigned i = 0; i < size; i++) {
  2800. if (isa<UndefValue>(vals[i])) {
  2801. vals32[2 * i] = undefI32;
  2802. vals32[2 * i + 1] = undefI32;
  2803. } else {
  2804. Value *retVal = Builder.CreateCall(dToU, {dToUOpArg, vals[i]});
  2805. Value *lo = Builder.CreateExtractValue(retVal, 0);
  2806. Value *hi = Builder.CreateExtractValue(retVal, 1);
  2807. vals32[2 * i] = lo;
  2808. vals32[2 * i + 1] = hi;
  2809. }
  2810. }
  2811. } else {
  2812. for (unsigned i = 0; i < size; i++) {
  2813. if (isa<UndefValue>(vals[i])) {
  2814. vals32[2 * i] = undefI32;
  2815. vals32[2 * i + 1] = undefI32;
  2816. } else {
  2817. Value *lo = Builder.CreateTrunc(vals[i], i32Ty);
  2818. Value *hi = Builder.CreateLShr(vals[i], 32);
  2819. hi = Builder.CreateTrunc(hi, i32Ty);
  2820. vals32[2 * i] = lo;
  2821. vals32[2 * i + 1] = hi;
  2822. }
  2823. }
  2824. }
  2825. }
  2826. void TranslateStore(DxilResource::Kind RK, Value *handle, Value *val,
  2827. Value *offset, IRBuilder<> &Builder, hlsl::OP *OP) {
  2828. Type *Ty = val->getType();
  2829. OP::OpCode opcode;
  2830. switch (RK) {
  2831. case DxilResource::Kind::RawBuffer:
  2832. case DxilResource::Kind::TypedBuffer:
  2833. opcode = OP::OpCode::BufferStore;
  2834. break;
  2835. case DxilResource::Kind::Invalid:
  2836. DXASSERT(0, "invalid resource kind");
  2837. break;
  2838. default:
  2839. opcode = OP::OpCode::TextureStore;
  2840. break;
  2841. }
  2842. Type *i32Ty = Builder.getInt32Ty();
  2843. Type *i64Ty = Builder.getInt64Ty();
  2844. Type *doubleTy = Builder.getDoubleTy();
  2845. Type *EltTy = Ty->getScalarType();
  2846. bool is64 = EltTy == i64Ty || EltTy == doubleTy;
  2847. if (is64) {
  2848. EltTy = i32Ty;
  2849. }
  2850. Function *F = OP->GetOpFunc(opcode, EltTy);
  2851. llvm::Constant *opArg = OP->GetU32Const((unsigned)opcode);
  2852. llvm::Value *undefI =
  2853. llvm::UndefValue::get(llvm::Type::getInt32Ty(Ty->getContext()));
  2854. llvm::Value *undefVal = llvm::UndefValue::get(Ty->getScalarType());
  2855. SmallVector<Value *, 13> storeArgs;
  2856. storeArgs.emplace_back(opArg); // opcode
  2857. storeArgs.emplace_back(handle); // resource handle
  2858. if (RK == DxilResource::Kind::RawBuffer ||
  2859. RK == DxilResource::Kind::TypedBuffer) {
  2860. // Offset 0
  2861. if (offset->getType()->isVectorTy()) {
  2862. Value *scalarOffset = Builder.CreateExtractElement(offset, (uint64_t)0);
  2863. storeArgs.emplace_back(scalarOffset); // offset
  2864. } else {
  2865. storeArgs.emplace_back(offset); // offset
  2866. }
  2867. // Offset 1
  2868. storeArgs.emplace_back(undefI);
  2869. } else {
  2870. // texture store
  2871. unsigned coordSize = DxilResource::GetNumCoords(RK);
  2872. // Set x first.
  2873. if (offset->getType()->isVectorTy())
  2874. storeArgs.emplace_back(Builder.CreateExtractElement(offset, (uint64_t)0));
  2875. else
  2876. storeArgs.emplace_back(offset);
  2877. for (unsigned i = 1; i < 3; i++) {
  2878. if (i < coordSize)
  2879. storeArgs.emplace_back(Builder.CreateExtractElement(offset, i));
  2880. else
  2881. storeArgs.emplace_back(undefI);
  2882. }
  2883. // TODO: support mip for texture ST
  2884. }
  2885. // values
  2886. bool isTyped = opcode == OP::OpCode::TextureStore ||
  2887. RK == DxilResource::Kind::TypedBuffer;
  2888. uint8_t mask = 0;
  2889. if (Ty->isVectorTy()) {
  2890. unsigned vecSize = Ty->getVectorNumElements();
  2891. Value *emptyVal = undefVal;
  2892. if (isTyped) {
  2893. mask = DXIL::kCompMask_All;
  2894. emptyVal = Builder.CreateExtractElement(val, (uint64_t)0);
  2895. }
  2896. for (unsigned i = 0; i < 4; i++) {
  2897. if (i < vecSize) {
  2898. storeArgs.emplace_back(Builder.CreateExtractElement(val, i));
  2899. mask |= (1<<i);
  2900. } else {
  2901. storeArgs.emplace_back(emptyVal);
  2902. }
  2903. }
  2904. } else {
  2905. if (isTyped) {
  2906. mask = DXIL::kCompMask_All;
  2907. storeArgs.emplace_back(val);
  2908. storeArgs.emplace_back(val);
  2909. storeArgs.emplace_back(val);
  2910. storeArgs.emplace_back(val);
  2911. } else {
  2912. storeArgs.emplace_back(val);
  2913. storeArgs.emplace_back(undefVal);
  2914. storeArgs.emplace_back(undefVal);
  2915. storeArgs.emplace_back(undefVal);
  2916. mask = DXIL::kCompMask_X;
  2917. }
  2918. }
  2919. if (is64) {
  2920. DXASSERT(mask == DXIL::kCompMask_All, "only typed buffer could have 64bit");
  2921. unsigned size = 1;
  2922. if (Ty->isVectorTy()) {
  2923. size = Ty->getVectorNumElements();
  2924. }
  2925. DXASSERT(size <= 2, "typed buffer only allow 4 dwords");
  2926. unsigned val0OpIdx = opcode == DXIL::OpCode::TextureStore
  2927. ? DXIL::OperandIndex::kTextureStoreVal0OpIdx
  2928. : DXIL::OperandIndex::kBufferStoreVal0OpIdx;
  2929. Value *V0 = storeArgs[val0OpIdx];
  2930. Value *V1 = storeArgs[val0OpIdx+1];
  2931. Value *vals32[4];
  2932. EltTy = Ty->getScalarType();
  2933. Split64bitValForStore(EltTy, {V0, V1}, size, vals32, OP, Builder);
  2934. // Fill the uninit vals.
  2935. if (size == 1) {
  2936. vals32[2] = vals32[0];
  2937. vals32[3] = vals32[1];
  2938. }
  2939. // Change valOp to 32 version.
  2940. for (unsigned i = 0; i < 4; i++) {
  2941. storeArgs[val0OpIdx + i] = vals32[i];
  2942. }
  2943. }
  2944. storeArgs.emplace_back(OP->GetU8Const(mask));
  2945. Builder.CreateCall(F, storeArgs);
  2946. }
  2947. Value *TranslateResourceStore(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  2948. HLOperationLowerHelper &helper,
  2949. HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  2950. hlsl::OP *hlslOP = &helper.hlslOP;
  2951. Value *handle = CI->getArgOperand(HLOperandIndex::kHandleOpIdx);
  2952. IRBuilder<> Builder(CI);
  2953. DXIL::ResourceKind RK = pObjHelper->GetRK(handle);
  2954. Value *val = CI->getArgOperand(HLOperandIndex::kStoreValOpIdx);
  2955. Value *offset = CI->getArgOperand(HLOperandIndex::kStoreOffsetOpIdx);
  2956. TranslateStore(RK, handle, val, offset, Builder, hlslOP);
  2957. return nullptr;
  2958. }
  2959. }
  2960. // Atomic intrinsics.
  2961. namespace {
  2962. // Atomic intrinsics.
  2963. struct AtomicHelper {
  2964. AtomicHelper(CallInst *CI, OP::OpCode op, Value *h);
  2965. AtomicHelper(CallInst *CI, OP::OpCode op, Value *h, Value *bufIdx,
  2966. Value *baseOffset);
  2967. OP::OpCode opcode;
  2968. Value *handle;
  2969. Value *addr;
  2970. Value *offset; // Offset for structrued buffer.
  2971. Value *value;
  2972. Value *originalValue;
  2973. Value *compareValue;
  2974. };
  2975. // For MOP version of Interlocked*.
  2976. AtomicHelper::AtomicHelper(CallInst *CI, OP::OpCode op, Value *h)
  2977. : opcode(op), handle(h), offset(nullptr), originalValue(nullptr) {
  2978. addr = CI->getArgOperand(HLOperandIndex::kObjectInterlockedDestOpIndex);
  2979. if (op == OP::OpCode::AtomicCompareExchange) {
  2980. compareValue = CI->getArgOperand(
  2981. HLOperandIndex::kObjectInterlockedCmpCompareValueOpIndex);
  2982. value =
  2983. CI->getArgOperand(HLOperandIndex::kObjectInterlockedCmpValueOpIndex);
  2984. if (CI->getNumArgOperands() ==
  2985. (HLOperandIndex::kObjectInterlockedCmpOriginalValueOpIndex + 1))
  2986. originalValue = CI->getArgOperand(
  2987. HLOperandIndex::kObjectInterlockedCmpOriginalValueOpIndex);
  2988. } else {
  2989. value = CI->getArgOperand(HLOperandIndex::kObjectInterlockedValueOpIndex);
  2990. if (CI->getNumArgOperands() ==
  2991. (HLOperandIndex::kObjectInterlockedOriginalValueOpIndex + 1))
  2992. originalValue = CI->getArgOperand(
  2993. HLOperandIndex::kObjectInterlockedOriginalValueOpIndex);
  2994. }
  2995. }
  2996. // For IOP version of Interlocked*.
  2997. AtomicHelper::AtomicHelper(CallInst *CI, OP::OpCode op, Value *h, Value *bufIdx,
  2998. Value *baseOffset)
  2999. : opcode(op), handle(h), addr(bufIdx),
  3000. offset(baseOffset), originalValue(nullptr) {
  3001. if (op == OP::OpCode::AtomicCompareExchange) {
  3002. compareValue =
  3003. CI->getArgOperand(HLOperandIndex::kInterlockedCmpCompareValueOpIndex);
  3004. value = CI->getArgOperand(HLOperandIndex::kInterlockedCmpValueOpIndex);
  3005. if (CI->getNumArgOperands() ==
  3006. (HLOperandIndex::kInterlockedCmpOriginalValueOpIndex + 1))
  3007. originalValue = CI->getArgOperand(
  3008. HLOperandIndex::kInterlockedCmpOriginalValueOpIndex);
  3009. } else {
  3010. value = CI->getArgOperand(HLOperandIndex::kInterlockedValueOpIndex);
  3011. if (CI->getNumArgOperands() ==
  3012. (HLOperandIndex::kInterlockedOriginalValueOpIndex + 1))
  3013. originalValue =
  3014. CI->getArgOperand(HLOperandIndex::kInterlockedOriginalValueOpIndex);
  3015. }
  3016. }
  3017. void TranslateAtomicBinaryOperation(AtomicHelper &helper,
  3018. DXIL::AtomicBinOpCode atomicOp,
  3019. IRBuilder<> &Builder, hlsl::OP *hlslOP) {
  3020. Value *handle = helper.handle;
  3021. Value *addr = helper.addr;
  3022. Value *val = helper.value;
  3023. Type *Ty = val->getType();
  3024. Value *undefI = UndefValue::get(Type::getInt32Ty(Ty->getContext()));
  3025. Function *dxilAtomic = hlslOP->GetOpFunc(helper.opcode, Ty->getScalarType());
  3026. Value *opArg = hlslOP->GetU32Const(static_cast<unsigned>(helper.opcode));
  3027. Value *atomicOpArg = hlslOP->GetU32Const(static_cast<unsigned>(atomicOp));
  3028. Value *args[] = {opArg, handle, atomicOpArg,
  3029. undefI, undefI, undefI, // coordinates
  3030. val};
  3031. // Setup coordinates.
  3032. if (addr->getType()->isVectorTy()) {
  3033. unsigned vectorNumElements = addr->getType()->getVectorNumElements();
  3034. DXASSERT(vectorNumElements <= 3, "up to 3 elements for atomic binary op");
  3035. _Analysis_assume_(vectorNumElements <= 3);
  3036. for (unsigned i = 0; i < vectorNumElements; i++) {
  3037. Value *Elt = Builder.CreateExtractElement(addr, i);
  3038. args[DXIL::OperandIndex::kAtomicBinOpCoord0OpIdx + i] = Elt;
  3039. }
  3040. } else
  3041. args[DXIL::OperandIndex::kAtomicBinOpCoord0OpIdx] = addr;
  3042. // Set offset for structured buffer.
  3043. if (helper.offset)
  3044. args[DXIL::OperandIndex::kAtomicBinOpCoord1OpIdx] = helper.offset;
  3045. Value *origVal =
  3046. Builder.CreateCall(dxilAtomic, args, hlslOP->GetAtomicOpName(atomicOp));
  3047. if (helper.originalValue) {
  3048. Builder.CreateStore(origVal, helper.originalValue);
  3049. }
  3050. }
  3051. Value *TranslateMopAtomicBinaryOperation(CallInst *CI, IntrinsicOp IOP,
  3052. OP::OpCode opcode,
  3053. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  3054. hlsl::OP *hlslOP = &helper.hlslOP;
  3055. Value *handle = CI->getArgOperand(HLOperandIndex::kHandleOpIdx);
  3056. IRBuilder<> Builder(CI);
  3057. switch (IOP) {
  3058. case IntrinsicOp::MOP_InterlockedAdd: {
  3059. AtomicHelper helper(CI, DXIL::OpCode::AtomicBinOp, handle);
  3060. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::Add, Builder,
  3061. hlslOP);
  3062. } break;
  3063. case IntrinsicOp::MOP_InterlockedAnd: {
  3064. AtomicHelper helper(CI, DXIL::OpCode::AtomicBinOp, handle);
  3065. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::And, Builder,
  3066. hlslOP);
  3067. } break;
  3068. case IntrinsicOp::MOP_InterlockedExchange: {
  3069. AtomicHelper helper(CI, DXIL::OpCode::AtomicBinOp, handle);
  3070. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::Exchange,
  3071. Builder, hlslOP);
  3072. } break;
  3073. case IntrinsicOp::MOP_InterlockedMax: {
  3074. AtomicHelper helper(CI, DXIL::OpCode::AtomicBinOp, handle);
  3075. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::IMax, Builder,
  3076. hlslOP);
  3077. } break;
  3078. case IntrinsicOp::MOP_InterlockedMin: {
  3079. AtomicHelper helper(CI, DXIL::OpCode::AtomicBinOp, handle);
  3080. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::IMin, Builder,
  3081. hlslOP);
  3082. } break;
  3083. case IntrinsicOp::MOP_InterlockedUMax: {
  3084. AtomicHelper helper(CI, DXIL::OpCode::AtomicBinOp, handle);
  3085. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::UMax, Builder,
  3086. hlslOP);
  3087. } break;
  3088. case IntrinsicOp::MOP_InterlockedUMin: {
  3089. AtomicHelper helper(CI, DXIL::OpCode::AtomicBinOp, handle);
  3090. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::UMin, Builder,
  3091. hlslOP);
  3092. } break;
  3093. case IntrinsicOp::MOP_InterlockedOr: {
  3094. AtomicHelper helper(CI, DXIL::OpCode::AtomicBinOp, handle);
  3095. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::Or, Builder,
  3096. hlslOP);
  3097. } break;
  3098. case IntrinsicOp::MOP_InterlockedXor: {
  3099. default:
  3100. DXASSERT(IOP == IntrinsicOp::MOP_InterlockedXor,
  3101. "invalid MOP atomic intrinsic");
  3102. AtomicHelper helper(CI, DXIL::OpCode::AtomicBinOp, handle);
  3103. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::Xor, Builder,
  3104. hlslOP);
  3105. } break;
  3106. }
  3107. return nullptr;
  3108. }
  3109. void TranslateAtomicCmpXChg(AtomicHelper &helper, IRBuilder<> &Builder,
  3110. hlsl::OP *hlslOP) {
  3111. Value *handle = helper.handle;
  3112. Value *addr = helper.addr;
  3113. Value *val = helper.value;
  3114. Value *cmpVal = helper.compareValue;
  3115. Type *Ty = val->getType();
  3116. Value *undefI = UndefValue::get(Type::getInt32Ty(Ty->getContext()));
  3117. Function *dxilAtomic = hlslOP->GetOpFunc(helper.opcode, Ty->getScalarType());
  3118. Value *opArg = hlslOP->GetU32Const(static_cast<unsigned>(helper.opcode));
  3119. Value *args[] = {opArg, handle, undefI, undefI, undefI, // coordinates
  3120. cmpVal, val};
  3121. // Setup coordinates.
  3122. if (addr->getType()->isVectorTy()) {
  3123. unsigned vectorNumElements = addr->getType()->getVectorNumElements();
  3124. DXASSERT(vectorNumElements <= 3, "up to 3 elements in atomic op");
  3125. _Analysis_assume_(vectorNumElements <= 3);
  3126. for (unsigned i = 0; i < vectorNumElements; i++) {
  3127. Value *Elt = Builder.CreateExtractElement(addr, i);
  3128. args[DXIL::OperandIndex::kAtomicCmpExchangeCoord0OpIdx + i] = Elt;
  3129. }
  3130. } else
  3131. args[DXIL::OperandIndex::kAtomicCmpExchangeCoord0OpIdx] = addr;
  3132. // Set offset for structured buffer.
  3133. if (helper.offset)
  3134. args[DXIL::OperandIndex::kAtomicCmpExchangeCoord1OpIdx] = helper.offset;
  3135. Value *origVal = Builder.CreateCall(dxilAtomic, args);
  3136. if (helper.originalValue) {
  3137. Builder.CreateStore(origVal, helper.originalValue);
  3138. }
  3139. }
  3140. Value *TranslateMopAtomicCmpXChg(CallInst *CI, IntrinsicOp IOP,
  3141. OP::OpCode opcode,
  3142. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  3143. hlsl::OP *hlslOP = &helper.hlslOP;
  3144. Value *handle = CI->getArgOperand(HLOperandIndex::kHandleOpIdx);
  3145. IRBuilder<> Builder(CI);
  3146. AtomicHelper atomicHelper(CI, OP::OpCode::AtomicCompareExchange, handle);
  3147. TranslateAtomicCmpXChg(atomicHelper, Builder, hlslOP);
  3148. return nullptr;
  3149. }
  3150. void TranslateSharedMemAtomicBinOp(CallInst *CI, IntrinsicOp IOP, Value *addr) {
  3151. AtomicRMWInst::BinOp Op;
  3152. switch (IOP) {
  3153. case IntrinsicOp::IOP_InterlockedAdd:
  3154. Op = AtomicRMWInst::BinOp::Add;
  3155. break;
  3156. case IntrinsicOp::IOP_InterlockedAnd:
  3157. Op = AtomicRMWInst::BinOp::And;
  3158. break;
  3159. case IntrinsicOp::IOP_InterlockedExchange:
  3160. Op = AtomicRMWInst::BinOp::Xchg;
  3161. break;
  3162. case IntrinsicOp::IOP_InterlockedMax:
  3163. Op = AtomicRMWInst::BinOp::Max;
  3164. break;
  3165. case IntrinsicOp::IOP_InterlockedUMax:
  3166. Op = AtomicRMWInst::BinOp::UMax;
  3167. break;
  3168. case IntrinsicOp::IOP_InterlockedMin:
  3169. Op = AtomicRMWInst::BinOp::Min;
  3170. break;
  3171. case IntrinsicOp::IOP_InterlockedUMin:
  3172. Op = AtomicRMWInst::BinOp::UMin;
  3173. break;
  3174. case IntrinsicOp::IOP_InterlockedOr:
  3175. Op = AtomicRMWInst::BinOp::Or;
  3176. break;
  3177. case IntrinsicOp::IOP_InterlockedXor:
  3178. default:
  3179. DXASSERT(IOP == IntrinsicOp::IOP_InterlockedXor, "Invalid Intrinsic");
  3180. Op = AtomicRMWInst::BinOp::Xor;
  3181. break;
  3182. }
  3183. Value *val = CI->getArgOperand(HLOperandIndex::kInterlockedValueOpIndex);
  3184. IRBuilder<> Builder(CI);
  3185. Value *Result = Builder.CreateAtomicRMW(
  3186. Op, addr, val, AtomicOrdering::SequentiallyConsistent);
  3187. if (CI->getNumArgOperands() >
  3188. HLOperandIndex::kInterlockedOriginalValueOpIndex)
  3189. Builder.CreateStore(
  3190. Result,
  3191. CI->getArgOperand(HLOperandIndex::kInterlockedOriginalValueOpIndex));
  3192. }
  3193. Value *TranslateIopAtomicBinaryOperation(CallInst *CI, IntrinsicOp IOP,
  3194. DXIL::OpCode opcode,
  3195. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  3196. Value *addr = CI->getArgOperand(HLOperandIndex::kInterlockedDestOpIndex);
  3197. // Get the original addr from cast.
  3198. if (CastInst *castInst = dyn_cast<CastInst>(addr))
  3199. addr = castInst->getOperand(0);
  3200. else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(addr)) {
  3201. if (CE->getOpcode() == Instruction::AddrSpaceCast) {
  3202. addr = CE->getOperand(0);
  3203. }
  3204. }
  3205. unsigned addressSpace = addr->getType()->getPointerAddressSpace();
  3206. if (addressSpace == DXIL::kTGSMAddrSpace)
  3207. TranslateSharedMemAtomicBinOp(CI, IOP, addr);
  3208. else {
  3209. // buffer atomic translated in TranslateSubscript.
  3210. // Do nothing here.
  3211. // Mark not translated.
  3212. Translated = false;
  3213. }
  3214. return nullptr;
  3215. }
  3216. void TranslateSharedMemAtomicCmpXChg(CallInst *CI, Value *addr) {
  3217. Value *val = CI->getArgOperand(HLOperandIndex::kInterlockedCmpValueOpIndex);
  3218. Value *cmpVal =
  3219. CI->getArgOperand(HLOperandIndex::kInterlockedCmpCompareValueOpIndex);
  3220. IRBuilder<> Builder(CI);
  3221. Value *Result = Builder.CreateAtomicCmpXchg(
  3222. addr, cmpVal, val, AtomicOrdering::SequentiallyConsistent,
  3223. AtomicOrdering::SequentiallyConsistent);
  3224. if (CI->getNumArgOperands() >
  3225. HLOperandIndex::kInterlockedCmpOriginalValueOpIndex) {
  3226. Value *originVal = Builder.CreateExtractValue(Result, 0);
  3227. Builder.CreateStore(
  3228. originVal,
  3229. CI->getArgOperand(HLOperandIndex::kInterlockedCmpOriginalValueOpIndex));
  3230. }
  3231. }
  3232. Value *TranslateIopAtomicCmpXChg(CallInst *CI, IntrinsicOp IOP,
  3233. DXIL::OpCode opcode,
  3234. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  3235. Value *addr = CI->getArgOperand(HLOperandIndex::kInterlockedDestOpIndex);
  3236. // Get the original addr from cast.
  3237. if (CastInst *castInst = dyn_cast<CastInst>(addr))
  3238. addr = castInst->getOperand(0);
  3239. unsigned addressSpace = addr->getType()->getPointerAddressSpace();
  3240. if (addressSpace == DXIL::kTGSMAddrSpace)
  3241. TranslateSharedMemAtomicCmpXChg(CI, addr);
  3242. else {
  3243. // buffer atomic translated in TranslateSubscript.
  3244. // Do nothing here.
  3245. // Mark not translated.
  3246. Translated = false;
  3247. }
  3248. return nullptr;
  3249. }
  3250. }
  3251. // Process Tess Factor.
  3252. namespace {
  3253. // Clamp to [0.0f..1.0f], NaN->0.0f.
  3254. Value *CleanupTessFactorScale(Value *input, hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  3255. float fMin = 0;
  3256. float fMax = 1;
  3257. Type *f32Ty = input->getType()->getScalarType();
  3258. Value *minFactor = ConstantFP::get(f32Ty, fMin);
  3259. Value *maxFactor = ConstantFP::get(f32Ty, fMax);
  3260. Type *Ty = input->getType();
  3261. if (Ty->isVectorTy())
  3262. minFactor = SplatToVector(minFactor, input->getType(), Builder);
  3263. Value *temp = TrivialDxilBinaryOperation(DXIL::OpCode::FMax, input, minFactor, hlslOP, Builder);
  3264. if (Ty->isVectorTy())
  3265. maxFactor = SplatToVector(maxFactor, input->getType(), Builder);
  3266. return TrivialDxilBinaryOperation(DXIL::OpCode::FMin, temp, maxFactor, hlslOP, Builder);
  3267. }
  3268. // Clamp to [1.0f..Inf], NaN->1.0f.
  3269. Value *CleanupTessFactor(Value *input, hlsl::OP *hlslOP, IRBuilder<> &Builder)
  3270. {
  3271. float fMin = 1.0;
  3272. Type *f32Ty = input->getType()->getScalarType();
  3273. Value *minFactor = ConstantFP::get(f32Ty, fMin);
  3274. minFactor = SplatToVector(minFactor, input->getType(), Builder);
  3275. return TrivialDxilBinaryOperation(DXIL::OpCode::FMax, input, minFactor, hlslOP, Builder);
  3276. }
  3277. // Do partitioning-specific clamping.
  3278. Value *ClampTessFactor(Value *input, DXIL::TessellatorPartitioning partitionMode,
  3279. hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  3280. const unsigned kTESSELLATOR_MAX_EVEN_TESSELLATION_FACTOR = 64;
  3281. const unsigned kTESSELLATOR_MAX_ODD_TESSELLATION_FACTOR = 63;
  3282. const unsigned kTESSELLATOR_MIN_EVEN_TESSELLATION_FACTOR = 2;
  3283. const unsigned kTESSELLATOR_MIN_ODD_TESSELLATION_FACTOR = 1;
  3284. const unsigned kTESSELLATOR_MAX_TESSELLATION_FACTOR = 64;
  3285. float fMin;
  3286. float fMax;
  3287. switch (partitionMode) {
  3288. case DXIL::TessellatorPartitioning::Integer:
  3289. fMin = kTESSELLATOR_MIN_ODD_TESSELLATION_FACTOR;
  3290. fMax = kTESSELLATOR_MAX_TESSELLATION_FACTOR;
  3291. break;
  3292. case DXIL::TessellatorPartitioning::Pow2:
  3293. fMin = kTESSELLATOR_MIN_ODD_TESSELLATION_FACTOR;
  3294. fMax = kTESSELLATOR_MAX_EVEN_TESSELLATION_FACTOR;
  3295. break;
  3296. case DXIL::TessellatorPartitioning::FractionalOdd:
  3297. fMin = kTESSELLATOR_MIN_ODD_TESSELLATION_FACTOR;
  3298. fMax = kTESSELLATOR_MAX_ODD_TESSELLATION_FACTOR;
  3299. break;
  3300. case DXIL::TessellatorPartitioning::FractionalEven:
  3301. default:
  3302. DXASSERT(partitionMode == DXIL::TessellatorPartitioning::FractionalEven,
  3303. "invalid partition mode");
  3304. fMin = kTESSELLATOR_MIN_EVEN_TESSELLATION_FACTOR;
  3305. fMax = kTESSELLATOR_MAX_EVEN_TESSELLATION_FACTOR;
  3306. break;
  3307. }
  3308. Type *f32Ty = input->getType()->getScalarType();
  3309. Value *minFactor = ConstantFP::get(f32Ty, fMin);
  3310. Value *maxFactor = ConstantFP::get(f32Ty, fMax);
  3311. Type *Ty = input->getType();
  3312. if (Ty->isVectorTy())
  3313. minFactor = SplatToVector(minFactor, input->getType(), Builder);
  3314. Value *temp = TrivialDxilBinaryOperation(DXIL::OpCode::FMax, input, minFactor, hlslOP, Builder);
  3315. if (Ty->isVectorTy())
  3316. maxFactor = SplatToVector(maxFactor, input->getType(), Builder);
  3317. return TrivialDxilBinaryOperation(DXIL::OpCode::FMin, temp, maxFactor, hlslOP, Builder);
  3318. }
  3319. // round up for integer/pow2 partitioning
  3320. // note that this code assumes the inputs should be in the range [1, inf),
  3321. // which should be enforced by the clamp above.
  3322. Value *RoundUpTessFactor(Value *input, DXIL::TessellatorPartitioning partitionMode,
  3323. hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  3324. switch (partitionMode) {
  3325. case DXIL::TessellatorPartitioning::Integer:
  3326. return TrivialDxilUnaryOperation(DXIL::OpCode::Round_pi, input, hlslOP, Builder);
  3327. case DXIL::TessellatorPartitioning::Pow2: {
  3328. const unsigned kExponentMask = 0x7f800000;
  3329. const unsigned kExponentLSB = 0x00800000;
  3330. const unsigned kMantissaMask = 0x007fffff;
  3331. Type *Ty = input->getType();
  3332. // (val = (asuint(val) & mantissamask) ?
  3333. // (asuint(val) & exponentmask) + exponentbump :
  3334. // asuint(val) & exponentmask;
  3335. Type *uintTy = Type::getInt32Ty(Ty->getContext());
  3336. if (Ty->isVectorTy())
  3337. uintTy = VectorType::get(uintTy, Ty->getVectorNumElements());
  3338. Value *uintVal = Builder.CreateCast(Instruction::CastOps::FPToUI, input, uintTy);
  3339. Value *mantMask = ConstantInt::get(uintTy->getScalarType(), kMantissaMask);
  3340. mantMask = SplatToVector(mantMask, uintTy, Builder);
  3341. Value *manVal = Builder.CreateAnd(uintVal, mantMask);
  3342. Value *expMask = ConstantInt::get(uintTy->getScalarType(), kExponentMask);
  3343. expMask = SplatToVector(expMask, uintTy, Builder);
  3344. Value *expVal = Builder.CreateAnd(uintVal, expMask);
  3345. Value *expLSB = ConstantInt::get(uintTy->getScalarType(), kExponentLSB);
  3346. expLSB = SplatToVector(expLSB, uintTy, Builder);
  3347. Value *newExpVal = Builder.CreateAdd(expVal, expLSB);
  3348. Value *manValNotZero = Builder.CreateICmpEQ(manVal, ConstantAggregateZero::get(uintTy));
  3349. Value *factors = Builder.CreateSelect(manValNotZero, newExpVal, expVal);
  3350. return Builder.CreateUIToFP(factors, Ty);
  3351. } break;
  3352. case DXIL::TessellatorPartitioning::FractionalEven:
  3353. case DXIL::TessellatorPartitioning::FractionalOdd:
  3354. return input;
  3355. default:
  3356. DXASSERT(0, "invalid partition mode");
  3357. return nullptr;
  3358. }
  3359. }
  3360. Value *TranslateProcessIsolineTessFactors(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  3361. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  3362. hlsl::OP *hlslOP = &helper.hlslOP;
  3363. // Get partition mode
  3364. DXASSERT(helper.functionProps, "");
  3365. DXASSERT(helper.functionProps->shaderKind == ShaderModel::Kind::Hull, "must be hull shader");
  3366. DXIL::TessellatorPartitioning partition = helper.functionProps->ShaderProps.HS.partition;
  3367. IRBuilder<> Builder(CI);
  3368. Value *rawDetailFactor = CI->getArgOperand(HLOperandIndex::kProcessTessFactorRawDetailFactor);
  3369. rawDetailFactor = Builder.CreateExtractElement(rawDetailFactor, (uint64_t)0);
  3370. Value *rawDensityFactor = CI->getArgOperand(HLOperandIndex::kProcessTessFactorRawDensityFactor);
  3371. rawDensityFactor = Builder.CreateExtractElement(rawDensityFactor, (uint64_t)0);
  3372. Value *init = UndefValue::get(VectorType::get(helper.f32Ty, 2));
  3373. init = Builder.CreateInsertElement(init, rawDetailFactor, (uint64_t)0);
  3374. init = Builder.CreateInsertElement(init, rawDetailFactor, (uint64_t)1);
  3375. Value *clamped = ClampTessFactor(init, partition, hlslOP, Builder);
  3376. Value *rounded = RoundUpTessFactor(clamped, partition, hlslOP, Builder);
  3377. Value *roundedDetailFactor = CI->getArgOperand(HLOperandIndex::kProcessTessFactorRoundedDetailFactor);
  3378. Value *temp = UndefValue::get(VectorType::get(helper.f32Ty, 1));
  3379. Value *roundedX = Builder.CreateExtractElement(rounded, (uint64_t)0);
  3380. temp = Builder.CreateInsertElement(temp, roundedX, (uint64_t)0);
  3381. Builder.CreateStore(temp, roundedDetailFactor);
  3382. Value *roundedDensityFactor = CI->getArgOperand(HLOperandIndex::kProcessTessFactorRoundedDensityFactor);
  3383. Value *roundedY = Builder.CreateExtractElement(rounded, 1);
  3384. temp = Builder.CreateInsertElement(temp, roundedY, (uint64_t)0);
  3385. Builder.CreateStore(temp, roundedDensityFactor);
  3386. return nullptr;
  3387. }
  3388. // 3 inputs, 1 result
  3389. Value *ApplyTriTessFactorOp(Value *input, DXIL::OpCode opcode, hlsl::OP *hlslOP,
  3390. IRBuilder<> &Builder) {
  3391. Value *input0 = Builder.CreateExtractElement(input, (uint64_t)0);
  3392. Value *input1 = Builder.CreateExtractElement(input, 1);
  3393. Value *input2 = Builder.CreateExtractElement(input, 2);
  3394. if (opcode == DXIL::OpCode::FMax || opcode == DXIL::OpCode::FMin) {
  3395. Value *temp =
  3396. TrivialDxilBinaryOperation(opcode, input0, input1, hlslOP, Builder);
  3397. Value *combined =
  3398. TrivialDxilBinaryOperation(opcode, temp, input2, hlslOP, Builder);
  3399. return combined;
  3400. } else {
  3401. // Avg.
  3402. Value *temp = Builder.CreateFAdd(input0, input1);
  3403. Value *combined = Builder.CreateFAdd(temp, input2);
  3404. Value *rcp = ConstantFP::get(input0->getType(), 1.0 / 3.0);
  3405. combined = Builder.CreateFMul(combined, rcp);
  3406. return combined;
  3407. }
  3408. }
  3409. // 4 inputs, 1 result
  3410. Value *ApplyQuadTessFactorOp(Value *input, DXIL::OpCode opcode,
  3411. hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  3412. Value *input0 = Builder.CreateExtractElement(input, (uint64_t)0);
  3413. Value *input1 = Builder.CreateExtractElement(input, 1);
  3414. Value *input2 = Builder.CreateExtractElement(input, 2);
  3415. Value *input3 = Builder.CreateExtractElement(input, 3);
  3416. if (opcode == DXIL::OpCode::FMax || opcode == DXIL::OpCode::FMin) {
  3417. Value *temp0 =
  3418. TrivialDxilBinaryOperation(opcode, input0, input1, hlslOP, Builder);
  3419. Value *temp1 =
  3420. TrivialDxilBinaryOperation(opcode, input2, input3, hlslOP, Builder);
  3421. Value *combined =
  3422. TrivialDxilBinaryOperation(opcode, temp0, temp1, hlslOP, Builder);
  3423. return combined;
  3424. } else {
  3425. // Avg.
  3426. Value *temp0 = Builder.CreateFAdd(input0, input1);
  3427. Value *temp1 = Builder.CreateFAdd(input2, input3);
  3428. Value *combined = Builder.CreateFAdd(temp0, temp1);
  3429. Value *rcp = ConstantFP::get(input0->getType(), 0.25);
  3430. combined = Builder.CreateFMul(combined, rcp);
  3431. return combined;
  3432. }
  3433. }
  3434. // 4 inputs, 2 result
  3435. Value *Apply2DQuadTessFactorOp(Value *input, DXIL::OpCode opcode,
  3436. hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  3437. Value *input0 = Builder.CreateExtractElement(input, (uint64_t)0);
  3438. Value *input1 = Builder.CreateExtractElement(input, 1);
  3439. Value *input2 = Builder.CreateExtractElement(input, 2);
  3440. Value *input3 = Builder.CreateExtractElement(input, 3);
  3441. if (opcode == DXIL::OpCode::FMax || opcode == DXIL::OpCode::FMin) {
  3442. Value *temp0 =
  3443. TrivialDxilBinaryOperation(opcode, input0, input1, hlslOP, Builder);
  3444. Value *temp1 =
  3445. TrivialDxilBinaryOperation(opcode, input2, input3, hlslOP, Builder);
  3446. Value *combined = UndefValue::get(VectorType::get(input0->getType(), 2));
  3447. combined = Builder.CreateInsertElement(combined, temp0, (uint64_t)0);
  3448. combined = Builder.CreateInsertElement(combined, temp1, 1);
  3449. return combined;
  3450. } else {
  3451. // Avg.
  3452. Value *temp0 = Builder.CreateFAdd(input0, input1);
  3453. Value *temp1 = Builder.CreateFAdd(input2, input3);
  3454. Value *combined = UndefValue::get(VectorType::get(input0->getType(), 2));
  3455. combined = Builder.CreateInsertElement(combined, temp0, (uint64_t)0);
  3456. combined = Builder.CreateInsertElement(combined, temp1, 1);
  3457. Constant *rcp = ConstantFP::get(input0->getType(), 0.5);
  3458. rcp = ConstantVector::getSplat(2, rcp);
  3459. combined = Builder.CreateFMul(combined, rcp);
  3460. return combined;
  3461. }
  3462. }
  3463. Value *ResolveSmallValue(Value **pClampedResult, Value *rounded, Value *averageUnscaled,
  3464. float cutoffVal, DXIL::TessellatorPartitioning partitionMode, hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  3465. Value *clampedResult = *pClampedResult;
  3466. Value *clampedVal = clampedResult;
  3467. Value *roundedVal = rounded;
  3468. // Do partitioning-specific clamping.
  3469. Value *clampedAvg = ClampTessFactor(averageUnscaled, partitionMode, hlslOP, Builder);
  3470. Constant *cutoffVals = ConstantFP::get(Type::getFloatTy(rounded->getContext()), cutoffVal);
  3471. if (clampedAvg->getType()->isVectorTy())
  3472. cutoffVals = ConstantVector::getSplat(clampedAvg->getType()->getVectorNumElements(), cutoffVals);
  3473. // Limit the value.
  3474. clampedAvg = TrivialDxilBinaryOperation(DXIL::OpCode::FMin, clampedAvg, cutoffVals, hlslOP, Builder);
  3475. // Round up for integer/pow2 partitioning.
  3476. Value *roundedAvg = RoundUpTessFactor(clampedAvg, partitionMode, hlslOP, Builder);
  3477. if (rounded->getType() != cutoffVals->getType())
  3478. cutoffVals = ConstantVector::getSplat(rounded->getType()->getVectorNumElements(), cutoffVals);
  3479. // If the scaled value is less than three, then take the unscaled average.
  3480. Value *lt = Builder.CreateFCmpOLT(rounded, cutoffVals);
  3481. if (clampedAvg->getType() != clampedVal->getType())
  3482. clampedAvg = SplatToVector(clampedAvg, clampedVal->getType(), Builder);
  3483. *pClampedResult = Builder.CreateSelect(lt, clampedAvg, clampedVal);
  3484. if (roundedAvg->getType() != roundedVal->getType())
  3485. roundedAvg = SplatToVector(roundedAvg, roundedVal->getType(), Builder);
  3486. Value *result = Builder.CreateSelect(lt, roundedAvg, roundedVal);
  3487. return result;
  3488. }
  3489. void ResolveQuadAxes( Value **pFinalResult, Value **pClampedResult,
  3490. float cutoffVal, DXIL::TessellatorPartitioning partitionMode, hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  3491. Value *finalResult = *pFinalResult;
  3492. Value *clampedResult = *pClampedResult;
  3493. Value *clampR = clampedResult;
  3494. Value *finalR = finalResult;
  3495. Type *f32Ty = Type::getFloatTy(finalR->getContext());
  3496. Constant *cutoffVals = ConstantFP::get(f32Ty, cutoffVal);
  3497. Value *minValsX = cutoffVals;
  3498. Value *minValsY = RoundUpTessFactor(cutoffVals, partitionMode, hlslOP, Builder);
  3499. Value *clampRX = Builder.CreateExtractElement(clampR, (uint64_t)0);
  3500. Value *clampRY = Builder.CreateExtractElement(clampR, 1);
  3501. Value *maxValsX = TrivialDxilBinaryOperation(DXIL::OpCode::FMax, clampRX, clampRY, hlslOP, Builder);
  3502. Value *finalRX = Builder.CreateExtractElement(finalR, (uint64_t)0);
  3503. Value *finalRY = Builder.CreateExtractElement(finalR, 1);
  3504. Value *maxValsY = TrivialDxilBinaryOperation(DXIL::OpCode::FMax, finalRX, finalRY, hlslOP, Builder);
  3505. // Don't go over our threshold ("final" one is rounded).
  3506. Value * optionX = TrivialDxilBinaryOperation(DXIL::OpCode::FMin, maxValsX, minValsX, hlslOP, Builder);
  3507. Value * optionY = TrivialDxilBinaryOperation(DXIL::OpCode::FMin, maxValsY, minValsY, hlslOP, Builder);
  3508. Value *clampL = SplatToVector(optionX, clampR->getType(), Builder);
  3509. Value *finalL = SplatToVector(optionY, finalR->getType(), Builder);
  3510. cutoffVals = ConstantVector::getSplat(2, cutoffVals);
  3511. Value *lt = Builder.CreateFCmpOLT(clampedResult, cutoffVals);
  3512. *pClampedResult = Builder.CreateSelect(lt, clampL, clampR);
  3513. *pFinalResult = Builder.CreateSelect(lt, finalL, finalR);
  3514. }
  3515. Value *TranslateProcessTessFactors(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  3516. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  3517. hlsl::OP *hlslOP = &helper.hlslOP;
  3518. // Get partition mode
  3519. DXASSERT(helper.functionProps, "");
  3520. DXASSERT(helper.functionProps->shaderKind == ShaderModel::Kind::Hull, "must be hull shader");
  3521. DXIL::TessellatorPartitioning partition = helper.functionProps->ShaderProps.HS.partition;
  3522. IRBuilder<> Builder(CI);
  3523. DXIL::OpCode tessFactorOp = DXIL::OpCode::NumOpCodes;
  3524. switch (IOP) {
  3525. case IntrinsicOp::IOP_Process2DQuadTessFactorsMax:
  3526. case IntrinsicOp::IOP_ProcessQuadTessFactorsMax:
  3527. case IntrinsicOp::IOP_ProcessTriTessFactorsMax:
  3528. tessFactorOp = DXIL::OpCode::FMax;
  3529. break;
  3530. case IntrinsicOp::IOP_Process2DQuadTessFactorsMin:
  3531. case IntrinsicOp::IOP_ProcessQuadTessFactorsMin:
  3532. case IntrinsicOp::IOP_ProcessTriTessFactorsMin:
  3533. tessFactorOp = DXIL::OpCode::FMin;
  3534. break;
  3535. default:
  3536. // Default is Avg.
  3537. break;
  3538. }
  3539. Value *rawEdgeFactor = CI->getArgOperand(HLOperandIndex::kProcessTessFactorRawEdgeFactor);
  3540. Value *insideScale = CI->getArgOperand(HLOperandIndex::kProcessTessFactorInsideScale);
  3541. // Clamp to [0.0f..1.0f], NaN->0.0f.
  3542. Value *scales = CleanupTessFactorScale(insideScale, hlslOP, Builder);
  3543. // Do partitioning-specific clamping.
  3544. Value *clamped = ClampTessFactor(rawEdgeFactor, partition, hlslOP, Builder);
  3545. // Round up for integer/pow2 partitioning.
  3546. Value *rounded = RoundUpTessFactor(clamped, partition, hlslOP, Builder);
  3547. // Store the output.
  3548. Value *roundedEdgeFactor = CI->getArgOperand(HLOperandIndex::kProcessTessFactorRoundedEdgeFactor);
  3549. Builder.CreateStore(rounded, roundedEdgeFactor);
  3550. // Clamp to [1.0f..Inf], NaN->1.0f.
  3551. bool isQuad = false;
  3552. Value *clean = CleanupTessFactor(rawEdgeFactor, hlslOP, Builder);
  3553. Value *factors = nullptr;
  3554. switch (IOP) {
  3555. case IntrinsicOp::IOP_Process2DQuadTessFactorsAvg:
  3556. case IntrinsicOp::IOP_Process2DQuadTessFactorsMax:
  3557. case IntrinsicOp::IOP_Process2DQuadTessFactorsMin:
  3558. factors = Apply2DQuadTessFactorOp(clean, tessFactorOp, hlslOP, Builder);
  3559. break;
  3560. case IntrinsicOp::IOP_ProcessQuadTessFactorsAvg:
  3561. case IntrinsicOp::IOP_ProcessQuadTessFactorsMax:
  3562. case IntrinsicOp::IOP_ProcessQuadTessFactorsMin:
  3563. factors = ApplyQuadTessFactorOp(clean, tessFactorOp, hlslOP, Builder);
  3564. isQuad = true;
  3565. break;
  3566. case IntrinsicOp::IOP_ProcessTriTessFactorsAvg:
  3567. case IntrinsicOp::IOP_ProcessTriTessFactorsMax:
  3568. case IntrinsicOp::IOP_ProcessTriTessFactorsMin:
  3569. factors = ApplyTriTessFactorOp(clean, tessFactorOp, hlslOP, Builder);
  3570. break;
  3571. default:
  3572. DXASSERT(0, "invalid opcode for ProcessTessFactor");
  3573. break;
  3574. }
  3575. Value *scaledI = nullptr;
  3576. if (scales->getType() == factors->getType())
  3577. scaledI = Builder.CreateFMul(factors, scales);
  3578. else {
  3579. Value *vecFactors = SplatToVector(factors, scales->getType(), Builder);
  3580. scaledI = Builder.CreateFMul(vecFactors, scales);
  3581. }
  3582. // Do partitioning-specific clamping.
  3583. Value *clampedI = ClampTessFactor(scaledI, partition, hlslOP, Builder);
  3584. // Round up for integer/pow2 partitioning.
  3585. Value *roundedI = RoundUpTessFactor(clampedI, partition, hlslOP, Builder);
  3586. Value *finalI = roundedI;
  3587. if (partition == DXIL::TessellatorPartitioning::FractionalOdd) {
  3588. // If not max, set to AVG.
  3589. if (tessFactorOp != DXIL::OpCode::FMax)
  3590. tessFactorOp = DXIL::OpCode::NumOpCodes;
  3591. bool b2D = false;
  3592. Value *avgFactorsI = nullptr;
  3593. switch (IOP) {
  3594. case IntrinsicOp::IOP_Process2DQuadTessFactorsAvg:
  3595. case IntrinsicOp::IOP_Process2DQuadTessFactorsMax:
  3596. case IntrinsicOp::IOP_Process2DQuadTessFactorsMin:
  3597. avgFactorsI = Apply2DQuadTessFactorOp(clean, tessFactorOp, hlslOP, Builder);
  3598. b2D = true;
  3599. break;
  3600. case IntrinsicOp::IOP_ProcessQuadTessFactorsAvg:
  3601. case IntrinsicOp::IOP_ProcessQuadTessFactorsMax:
  3602. case IntrinsicOp::IOP_ProcessQuadTessFactorsMin:
  3603. avgFactorsI = ApplyQuadTessFactorOp(clean, tessFactorOp, hlslOP, Builder);
  3604. break;
  3605. case IntrinsicOp::IOP_ProcessTriTessFactorsAvg:
  3606. case IntrinsicOp::IOP_ProcessTriTessFactorsMax:
  3607. case IntrinsicOp::IOP_ProcessTriTessFactorsMin:
  3608. avgFactorsI = ApplyTriTessFactorOp(clean, tessFactorOp, hlslOP, Builder);
  3609. break;
  3610. default:
  3611. DXASSERT(0, "invalid opcode for ProcessTessFactor");
  3612. break;
  3613. }
  3614. finalI =
  3615. ResolveSmallValue(/*inout*/&clampedI, roundedI, avgFactorsI, /*cufoff*/ 3.0,
  3616. partition, hlslOP, Builder);
  3617. if (b2D)
  3618. ResolveQuadAxes(/*inout*/&finalI, /*inout*/&clampedI, /*cutoff*/3.0, partition, hlslOP, Builder);
  3619. }
  3620. Value *unroundedInsideFactor = CI->getArgOperand(HLOperandIndex::kProcessTessFactorUnRoundedInsideFactor);
  3621. Type *outFactorTy = unroundedInsideFactor->getType()->getPointerElementType();
  3622. if (outFactorTy != clampedI->getType()) {
  3623. DXASSERT(isQuad, "quad only write one channel of out factor");
  3624. clampedI = Builder.CreateExtractElement(clampedI, (uint64_t)0);
  3625. // Splat clampedI to float2.
  3626. clampedI = SplatToVector(clampedI, outFactorTy, Builder);
  3627. }
  3628. Builder.CreateStore(clampedI, unroundedInsideFactor);
  3629. Value *roundedInsideFactor = CI->getArgOperand(HLOperandIndex::kProcessTessFactorRoundedInsideFactor);
  3630. if (outFactorTy != finalI->getType()) {
  3631. DXASSERT(isQuad, "quad only write one channel of out factor");
  3632. finalI = Builder.CreateExtractElement(finalI, (uint64_t)0);
  3633. // Splat finalI to float2.
  3634. finalI = SplatToVector(finalI, outFactorTy, Builder);
  3635. }
  3636. Builder.CreateStore(finalI, roundedInsideFactor);
  3637. return nullptr;
  3638. }
  3639. }
  3640. // Lower table.
  3641. namespace {
  3642. Value *EmptyLower(CallInst *CI, IntrinsicOp IOP, DXIL::OpCode opcode,
  3643. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  3644. DXASSERT(0, "unsupported intrinsic");
  3645. return nullptr;
  3646. }
  3647. Value *StreamOutputLower(CallInst *CI, IntrinsicOp IOP, DXIL::OpCode opcode,
  3648. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  3649. // Translated in DxilGenerationPass::GenerateStreamOutputOperation.
  3650. // Do nothing here.
  3651. // Mark not translated.
  3652. Translated = false;
  3653. return nullptr;
  3654. }
  3655. IntrinsicLower gLowerTable[static_cast<unsigned>(IntrinsicOp::Num_Intrinsics)] = {
  3656. {IntrinsicOp::IOP_AddUint64, TranslateAddUint64, DXIL::OpCode::UAddc},
  3657. {IntrinsicOp::IOP_AllMemoryBarrier, TrivialBarrier, DXIL::OpCode::Barrier},
  3658. {IntrinsicOp::IOP_AllMemoryBarrierWithGroupSync, TrivialBarrier, DXIL::OpCode::Barrier},
  3659. {IntrinsicOp::IOP_CheckAccessFullyMapped, TrivialUnaryOperation, DXIL::OpCode::CheckAccessFullyMapped},
  3660. {IntrinsicOp::IOP_D3DCOLORtoUBYTE4, TranslateD3DColorToUByte4, DXIL::OpCode::NumOpCodes},
  3661. {IntrinsicOp::IOP_DeviceMemoryBarrier, TrivialBarrier, DXIL::OpCode::Barrier},
  3662. {IntrinsicOp::IOP_DeviceMemoryBarrierWithGroupSync, TrivialBarrier, DXIL::OpCode::Barrier},
  3663. {IntrinsicOp::IOP_EvaluateAttributeAtSample, TranslateEvalSample, DXIL::OpCode::NumOpCodes},
  3664. {IntrinsicOp::IOP_EvaluateAttributeCentroid, TranslateEvalCentroid, DXIL::OpCode::EvalCentroid},
  3665. {IntrinsicOp::IOP_EvaluateAttributeSnapped, TranslateEvalSnapped, DXIL::OpCode::NumOpCodes},
  3666. {IntrinsicOp::IOP_GetAttributeAtVertex, TranslateGetAttributeAtVertex, DXIL::OpCode::AttributeAtVertex},
  3667. {IntrinsicOp::IOP_GetRenderTargetSampleCount, TrivialNoArgOperation, DXIL::OpCode::RenderTargetGetSampleCount},
  3668. {IntrinsicOp::IOP_GetRenderTargetSamplePosition, TranslateGetRTSamplePos, DXIL::OpCode::NumOpCodes},
  3669. {IntrinsicOp::IOP_GroupMemoryBarrier, TrivialBarrier, DXIL::OpCode::Barrier},
  3670. {IntrinsicOp::IOP_GroupMemoryBarrierWithGroupSync, TrivialBarrier, DXIL::OpCode::Barrier},
  3671. {IntrinsicOp::IOP_InterlockedAdd, TranslateIopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3672. {IntrinsicOp::IOP_InterlockedAnd, TranslateIopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3673. {IntrinsicOp::IOP_InterlockedCompareExchange, TranslateIopAtomicCmpXChg, DXIL::OpCode::NumOpCodes},
  3674. {IntrinsicOp::IOP_InterlockedCompareStore, TranslateIopAtomicCmpXChg, DXIL::OpCode::NumOpCodes},
  3675. {IntrinsicOp::IOP_InterlockedExchange, TranslateIopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3676. {IntrinsicOp::IOP_InterlockedMax, TranslateIopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3677. {IntrinsicOp::IOP_InterlockedMin, TranslateIopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3678. {IntrinsicOp::IOP_InterlockedOr, TranslateIopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3679. {IntrinsicOp::IOP_InterlockedXor, TranslateIopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3680. {IntrinsicOp::IOP_NonUniformResourceIndex, TranslateNonUniformResourceIndex, DXIL::OpCode::NumOpCodes},
  3681. {IntrinsicOp::IOP_Process2DQuadTessFactorsAvg, TranslateProcessTessFactors, DXIL::OpCode::NumOpCodes},
  3682. {IntrinsicOp::IOP_Process2DQuadTessFactorsMax, TranslateProcessTessFactors, DXIL::OpCode::NumOpCodes},
  3683. {IntrinsicOp::IOP_Process2DQuadTessFactorsMin, TranslateProcessTessFactors, DXIL::OpCode::NumOpCodes},
  3684. {IntrinsicOp::IOP_ProcessIsolineTessFactors, TranslateProcessIsolineTessFactors, DXIL::OpCode::NumOpCodes},
  3685. {IntrinsicOp::IOP_ProcessQuadTessFactorsAvg, TranslateProcessTessFactors, DXIL::OpCode::NumOpCodes},
  3686. {IntrinsicOp::IOP_ProcessQuadTessFactorsMax, TranslateProcessTessFactors, DXIL::OpCode::NumOpCodes},
  3687. {IntrinsicOp::IOP_ProcessQuadTessFactorsMin, TranslateProcessTessFactors, DXIL::OpCode::NumOpCodes},
  3688. {IntrinsicOp::IOP_ProcessTriTessFactorsAvg, TranslateProcessTessFactors, DXIL::OpCode::NumOpCodes},
  3689. {IntrinsicOp::IOP_ProcessTriTessFactorsMax, TranslateProcessTessFactors, DXIL::OpCode::NumOpCodes},
  3690. {IntrinsicOp::IOP_ProcessTriTessFactorsMin, TranslateProcessTessFactors, DXIL::OpCode::NumOpCodes},
  3691. {IntrinsicOp::IOP_QuadReadAcrossDiagonal, TranslateQuadReadAcross, DXIL::OpCode::QuadOp},
  3692. {IntrinsicOp::IOP_QuadReadAcrossX, TranslateQuadReadAcross, DXIL::OpCode::QuadOp},
  3693. {IntrinsicOp::IOP_QuadReadAcrossY, TranslateQuadReadAcross, DXIL::OpCode::QuadOp},
  3694. {IntrinsicOp::IOP_QuadReadLaneAt, TranslateQuadReadLaneAt, DXIL::OpCode::NumOpCodes},
  3695. {IntrinsicOp::IOP_WaveActiveAllEqual, TranslateWaveAllEqual, DXIL::OpCode::WaveActiveAllEqual},
  3696. {IntrinsicOp::IOP_WaveActiveAllTrue, TranslateWaveA2B, DXIL::OpCode::WaveAllTrue},
  3697. {IntrinsicOp::IOP_WaveActiveAnyTrue, TranslateWaveA2B, DXIL::OpCode::WaveAnyTrue},
  3698. {IntrinsicOp::IOP_WaveActiveBallot, TranslateWaveBallot, DXIL::OpCode::WaveActiveBallot},
  3699. {IntrinsicOp::IOP_WaveActiveBitAnd, TranslateWaveA2A, DXIL::OpCode::WaveActiveBit},
  3700. {IntrinsicOp::IOP_WaveActiveBitOr, TranslateWaveA2A, DXIL::OpCode::WaveActiveBit},
  3701. {IntrinsicOp::IOP_WaveActiveBitXor, TranslateWaveA2A, DXIL::OpCode::WaveActiveBit},
  3702. {IntrinsicOp::IOP_WaveActiveCountBits, TranslateWaveA2B, DXIL::OpCode::WaveAllBitCount},
  3703. {IntrinsicOp::IOP_WaveActiveMax, TranslateWaveA2A, DXIL::OpCode::WaveActiveOp},
  3704. {IntrinsicOp::IOP_WaveActiveMin, TranslateWaveA2A, DXIL::OpCode::WaveActiveOp},
  3705. {IntrinsicOp::IOP_WaveActiveProduct, TranslateWaveA2A, DXIL::OpCode::WaveActiveOp},
  3706. {IntrinsicOp::IOP_WaveActiveSum, TranslateWaveA2A, DXIL::OpCode::WaveActiveOp},
  3707. {IntrinsicOp::IOP_WaveGetLaneCount, TranslateWaveToVal, DXIL::OpCode::WaveGetLaneCount},
  3708. {IntrinsicOp::IOP_WaveGetLaneIndex, TranslateWaveToVal, DXIL::OpCode::WaveGetLaneIndex},
  3709. {IntrinsicOp::IOP_WaveIsFirstLane, TranslateWaveToVal, DXIL::OpCode::WaveIsFirstLane},
  3710. {IntrinsicOp::IOP_WavePrefixCountBits, TranslateWaveA2B, DXIL::OpCode::WavePrefixBitCount},
  3711. {IntrinsicOp::IOP_WavePrefixProduct, TranslateWaveA2A, DXIL::OpCode::WavePrefixOp},
  3712. {IntrinsicOp::IOP_WavePrefixSum, TranslateWaveA2A, DXIL::OpCode::WavePrefixOp},
  3713. {IntrinsicOp::IOP_WaveReadLaneAt, TranslateWaveReadLaneAt, DXIL::OpCode::WaveReadLaneAt},
  3714. {IntrinsicOp::IOP_WaveReadLaneFirst, TranslateWaveReadLaneFirst, DXIL::OpCode::WaveReadLaneFirst},
  3715. {IntrinsicOp::IOP_abort, EmptyLower, DXIL::OpCode::NumOpCodes},
  3716. {IntrinsicOp::IOP_abs, TransalteAbs, DXIL::OpCode::NumOpCodes},
  3717. {IntrinsicOp::IOP_acos, TrivialUnaryOperation, DXIL::OpCode::Acos},
  3718. {IntrinsicOp::IOP_all, TranslateAll, DXIL::OpCode::NumOpCodes},
  3719. {IntrinsicOp::IOP_any, TranslateAny, DXIL::OpCode::NumOpCodes},
  3720. {IntrinsicOp::IOP_asdouble, TranslateAsDouble, DXIL::OpCode::MakeDouble},
  3721. {IntrinsicOp::IOP_asfloat, TranslateBitcast, DXIL::OpCode::NumOpCodes},
  3722. {IntrinsicOp::IOP_asin, TrivialUnaryOperation, DXIL::OpCode::Asin},
  3723. {IntrinsicOp::IOP_asint, TranslateBitcast, DXIL::OpCode::NumOpCodes},
  3724. {IntrinsicOp::IOP_asuint, TranslateAsUint, DXIL::OpCode::SplitDouble},
  3725. {IntrinsicOp::IOP_atan, TrivialUnaryOperation, DXIL::OpCode::Atan},
  3726. {IntrinsicOp::IOP_atan2, TranslateAtan2, DXIL::OpCode::NumOpCodes},
  3727. {IntrinsicOp::IOP_ceil, TrivialUnaryOperation, DXIL::OpCode::Round_pi},
  3728. {IntrinsicOp::IOP_clamp, TranslateClamp, DXIL::OpCode::NumOpCodes},
  3729. {IntrinsicOp::IOP_clip, TranslateClip, DXIL::OpCode::NumOpCodes},
  3730. {IntrinsicOp::IOP_cos, TrivialUnaryOperation, DXIL::OpCode::Cos},
  3731. {IntrinsicOp::IOP_cosh, TrivialUnaryOperation, DXIL::OpCode::Hcos},
  3732. {IntrinsicOp::IOP_countbits, TrivialUnaryOperation, DXIL::OpCode::Countbits},
  3733. {IntrinsicOp::IOP_cross, TranslateCross, DXIL::OpCode::NumOpCodes},
  3734. {IntrinsicOp::IOP_ddx, TrivialUnaryOperation, DXIL::OpCode::DerivCoarseX},
  3735. {IntrinsicOp::IOP_ddx_coarse, TrivialUnaryOperation, DXIL::OpCode::DerivCoarseX},
  3736. {IntrinsicOp::IOP_ddx_fine, TrivialUnaryOperation, DXIL::OpCode::DerivFineX},
  3737. {IntrinsicOp::IOP_ddy, TrivialUnaryOperation, DXIL::OpCode::DerivCoarseY},
  3738. {IntrinsicOp::IOP_ddy_coarse, TrivialUnaryOperation, DXIL::OpCode::DerivCoarseY},
  3739. {IntrinsicOp::IOP_ddy_fine, TrivialUnaryOperation, DXIL::OpCode::DerivFineY},
  3740. {IntrinsicOp::IOP_degrees, TranslateDegrees, DXIL::OpCode::NumOpCodes},
  3741. {IntrinsicOp::IOP_determinant, EmptyLower, DXIL::OpCode::NumOpCodes},
  3742. {IntrinsicOp::IOP_distance, TranslateDistance, DXIL::OpCode::NumOpCodes},
  3743. {IntrinsicOp::IOP_dot, TranslateDot, DXIL::OpCode::NumOpCodes},
  3744. {IntrinsicOp::IOP_dst, TranslateDst, DXIL::OpCode::NumOpCodes},
  3745. {IntrinsicOp::IOP_exp, TranslateExp, DXIL::OpCode::NumOpCodes},
  3746. {IntrinsicOp::IOP_exp2, TrivialUnaryOperation, DXIL::OpCode::Exp},
  3747. {IntrinsicOp::IOP_f16tof32, TranslateF16ToF32, DXIL::OpCode::LegacyF16ToF32},
  3748. {IntrinsicOp::IOP_f32tof16, TranslateF32ToF16, DXIL::OpCode::LegacyF32ToF16},
  3749. {IntrinsicOp::IOP_faceforward, TranslateFaceforward, DXIL::OpCode::NumOpCodes},
  3750. {IntrinsicOp::IOP_firstbithigh, TranslateFirstbitHi, DXIL::OpCode::FirstbitSHi},
  3751. {IntrinsicOp::IOP_firstbitlow, TranslateFirstbitLo, DXIL::OpCode::FirstbitLo},
  3752. {IntrinsicOp::IOP_floor, TrivialUnaryOperation, DXIL::OpCode::Round_ni},
  3753. {IntrinsicOp::IOP_fma, TrivialTrinaryOperation, DXIL::OpCode::Fma},
  3754. {IntrinsicOp::IOP_fmod, TranslateFMod, DXIL::OpCode::NumOpCodes},
  3755. {IntrinsicOp::IOP_frac, TrivialUnaryOperation, DXIL::OpCode::Frc},
  3756. {IntrinsicOp::IOP_frexp, TranslateFrexp, DXIL::OpCode::NumOpCodes},
  3757. {IntrinsicOp::IOP_fwidth, TranslateFWidth, DXIL::OpCode::NumOpCodes},
  3758. {IntrinsicOp::IOP_isfinite, TrivialIsSpecialFloat, DXIL::OpCode::IsFinite},
  3759. {IntrinsicOp::IOP_isinf, TrivialIsSpecialFloat, DXIL::OpCode::IsInf},
  3760. {IntrinsicOp::IOP_isnan, TrivialIsSpecialFloat, DXIL::OpCode::IsNaN},
  3761. {IntrinsicOp::IOP_ldexp, TranslateLdExp, DXIL::OpCode::NumOpCodes},
  3762. {IntrinsicOp::IOP_length, TranslateLength, DXIL::OpCode::NumOpCodes},
  3763. {IntrinsicOp::IOP_lerp, TranslateLerp, DXIL::OpCode::NumOpCodes},
  3764. {IntrinsicOp::IOP_lit, TranslateLit, DXIL::OpCode::NumOpCodes},
  3765. {IntrinsicOp::IOP_log, TranslateLog, DXIL::OpCode::NumOpCodes},
  3766. {IntrinsicOp::IOP_log10, TranslateLog10, DXIL::OpCode::NumOpCodes},
  3767. {IntrinsicOp::IOP_log2, TrivialUnaryOperation, DXIL::OpCode::Log},
  3768. {IntrinsicOp::IOP_mad, TranslateFUITrinary, DXIL::OpCode::IMad},
  3769. {IntrinsicOp::IOP_max, TranslateFUIBinary, DXIL::OpCode::IMax},
  3770. {IntrinsicOp::IOP_min, TranslateFUIBinary, DXIL::OpCode::IMin},
  3771. {IntrinsicOp::IOP_modf, TranslateModF, DXIL::OpCode::NumOpCodes},
  3772. {IntrinsicOp::IOP_msad4, TranslateMSad4, DXIL::OpCode::NumOpCodes},
  3773. {IntrinsicOp::IOP_mul, EmptyLower, DXIL::OpCode::NumOpCodes},
  3774. {IntrinsicOp::IOP_normalize, TranslateNormalize, DXIL::OpCode::NumOpCodes},
  3775. {IntrinsicOp::IOP_pow, TranslatePow, DXIL::OpCode::NumOpCodes},
  3776. {IntrinsicOp::IOP_radians, TranslateRadians, DXIL::OpCode::NumOpCodes},
  3777. {IntrinsicOp::IOP_rcp, TranslateRCP, DXIL::OpCode::NumOpCodes},
  3778. {IntrinsicOp::IOP_reflect, TranslateReflect, DXIL::OpCode::NumOpCodes},
  3779. {IntrinsicOp::IOP_refract, TranslateRefract, DXIL::OpCode::NumOpCodes},
  3780. {IntrinsicOp::IOP_reversebits, TrivialUnaryOperation, DXIL::OpCode::Bfrev},
  3781. {IntrinsicOp::IOP_round, TrivialUnaryOperation, DXIL::OpCode::Round_ne},
  3782. {IntrinsicOp::IOP_rsqrt, TrivialUnaryOperation, DXIL::OpCode::Rsqrt},
  3783. {IntrinsicOp::IOP_saturate, TrivialUnaryOperation, DXIL::OpCode::Saturate},
  3784. {IntrinsicOp::IOP_sign, TranslateSign, DXIL::OpCode::NumOpCodes},
  3785. {IntrinsicOp::IOP_sin, TrivialUnaryOperation, DXIL::OpCode::Sin},
  3786. {IntrinsicOp::IOP_sincos, EmptyLower, DXIL::OpCode::NumOpCodes},
  3787. {IntrinsicOp::IOP_sinh, TrivialUnaryOperation, DXIL::OpCode::Hsin},
  3788. {IntrinsicOp::IOP_smoothstep, TranslateSmoothStep, DXIL::OpCode::NumOpCodes},
  3789. {IntrinsicOp::IOP_source_mark, EmptyLower, DXIL::OpCode::NumOpCodes},
  3790. {IntrinsicOp::IOP_sqrt, TrivialUnaryOperation, DXIL::OpCode::Sqrt},
  3791. {IntrinsicOp::IOP_step, TranslateStep, DXIL::OpCode::NumOpCodes},
  3792. {IntrinsicOp::IOP_tan, TrivialUnaryOperation, DXIL::OpCode::Tan},
  3793. {IntrinsicOp::IOP_tanh, TrivialUnaryOperation, DXIL::OpCode::Htan},
  3794. {IntrinsicOp::IOP_tex1D, EmptyLower, DXIL::OpCode::NumOpCodes},
  3795. {IntrinsicOp::IOP_tex1Dbias, EmptyLower, DXIL::OpCode::NumOpCodes},
  3796. {IntrinsicOp::IOP_tex1Dgrad, EmptyLower, DXIL::OpCode::NumOpCodes},
  3797. {IntrinsicOp::IOP_tex1Dlod, EmptyLower, DXIL::OpCode::NumOpCodes},
  3798. {IntrinsicOp::IOP_tex1Dproj, EmptyLower, DXIL::OpCode::NumOpCodes},
  3799. {IntrinsicOp::IOP_tex2D, EmptyLower, DXIL::OpCode::NumOpCodes},
  3800. {IntrinsicOp::IOP_tex2Dbias, EmptyLower, DXIL::OpCode::NumOpCodes},
  3801. {IntrinsicOp::IOP_tex2Dgrad, EmptyLower, DXIL::OpCode::NumOpCodes},
  3802. {IntrinsicOp::IOP_tex2Dlod, EmptyLower, DXIL::OpCode::NumOpCodes},
  3803. {IntrinsicOp::IOP_tex2Dproj, EmptyLower, DXIL::OpCode::NumOpCodes},
  3804. {IntrinsicOp::IOP_tex3D, EmptyLower, DXIL::OpCode::NumOpCodes},
  3805. {IntrinsicOp::IOP_tex3Dbias, EmptyLower, DXIL::OpCode::NumOpCodes},
  3806. {IntrinsicOp::IOP_tex3Dgrad, EmptyLower, DXIL::OpCode::NumOpCodes},
  3807. {IntrinsicOp::IOP_tex3Dlod, EmptyLower, DXIL::OpCode::NumOpCodes},
  3808. {IntrinsicOp::IOP_tex3Dproj, EmptyLower, DXIL::OpCode::NumOpCodes},
  3809. {IntrinsicOp::IOP_texCUBE, EmptyLower, DXIL::OpCode::NumOpCodes},
  3810. {IntrinsicOp::IOP_texCUBEbias, EmptyLower, DXIL::OpCode::NumOpCodes},
  3811. {IntrinsicOp::IOP_texCUBEgrad, EmptyLower, DXIL::OpCode::NumOpCodes},
  3812. {IntrinsicOp::IOP_texCUBElod, EmptyLower, DXIL::OpCode::NumOpCodes},
  3813. {IntrinsicOp::IOP_texCUBEproj, EmptyLower, DXIL::OpCode::NumOpCodes},
  3814. {IntrinsicOp::IOP_transpose, EmptyLower, DXIL::OpCode::NumOpCodes},
  3815. {IntrinsicOp::IOP_trunc, TrivialUnaryOperation, DXIL::OpCode::Round_z},
  3816. {IntrinsicOp::MOP_Append, StreamOutputLower, DXIL::OpCode::EmitStream},
  3817. {IntrinsicOp::MOP_RestartStrip, StreamOutputLower, DXIL::OpCode::CutStream},
  3818. {IntrinsicOp::MOP_CalculateLevelOfDetail, TranslateCalculateLOD, DXIL::OpCode::NumOpCodes},
  3819. {IntrinsicOp::MOP_CalculateLevelOfDetailUnclamped, TranslateCalculateLOD, DXIL::OpCode::NumOpCodes},
  3820. {IntrinsicOp::MOP_GetDimensions, TranslateGetDimensions, DXIL::OpCode::NumOpCodes},
  3821. {IntrinsicOp::MOP_Load, TranslateResourceLoad, DXIL::OpCode::NumOpCodes},
  3822. {IntrinsicOp::MOP_Sample, TranslateSample, DXIL::OpCode::Sample},
  3823. {IntrinsicOp::MOP_SampleBias, TranslateSample, DXIL::OpCode::SampleBias},
  3824. {IntrinsicOp::MOP_SampleCmp, TranslateSample, DXIL::OpCode::SampleCmp},
  3825. {IntrinsicOp::MOP_SampleCmpLevelZero, TranslateSample, DXIL::OpCode::SampleCmpLevelZero},
  3826. {IntrinsicOp::MOP_SampleGrad, TranslateSample, DXIL::OpCode::SampleGrad},
  3827. {IntrinsicOp::MOP_SampleLevel, TranslateSample, DXIL::OpCode::SampleLevel},
  3828. {IntrinsicOp::MOP_Gather, TranslateGather, DXIL::OpCode::TextureGather},
  3829. {IntrinsicOp::MOP_GatherAlpha, TranslateGather, DXIL::OpCode::TextureGather},
  3830. {IntrinsicOp::MOP_GatherBlue, TranslateGather, DXIL::OpCode::TextureGather},
  3831. {IntrinsicOp::MOP_GatherCmp, TranslateGather, DXIL::OpCode::TextureGatherCmp},
  3832. {IntrinsicOp::MOP_GatherCmpAlpha, TranslateGather, DXIL::OpCode::TextureGatherCmp},
  3833. {IntrinsicOp::MOP_GatherCmpBlue, TranslateGather, DXIL::OpCode::TextureGatherCmp},
  3834. {IntrinsicOp::MOP_GatherCmpGreen, TranslateGather, DXIL::OpCode::TextureGatherCmp},
  3835. {IntrinsicOp::MOP_GatherCmpRed, TranslateGather, DXIL::OpCode::TextureGatherCmp},
  3836. {IntrinsicOp::MOP_GatherGreen, TranslateGather, DXIL::OpCode::TextureGather},
  3837. {IntrinsicOp::MOP_GatherRed, TranslateGather, DXIL::OpCode::TextureGather},
  3838. {IntrinsicOp::MOP_GetSamplePosition, TranslateGetSamplePosition, DXIL::OpCode::NumOpCodes},
  3839. {IntrinsicOp::MOP_Load2, TranslateResourceLoad, DXIL::OpCode::NumOpCodes},
  3840. {IntrinsicOp::MOP_Load3, TranslateResourceLoad, DXIL::OpCode::NumOpCodes},
  3841. {IntrinsicOp::MOP_Load4, TranslateResourceLoad, DXIL::OpCode::NumOpCodes},
  3842. {IntrinsicOp::MOP_InterlockedAdd, TranslateMopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3843. {IntrinsicOp::MOP_InterlockedAnd, TranslateMopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3844. {IntrinsicOp::MOP_InterlockedCompareExchange, TranslateMopAtomicCmpXChg, DXIL::OpCode::NumOpCodes},
  3845. {IntrinsicOp::MOP_InterlockedCompareStore, TranslateMopAtomicCmpXChg, DXIL::OpCode::NumOpCodes},
  3846. {IntrinsicOp::MOP_InterlockedExchange, TranslateMopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3847. {IntrinsicOp::MOP_InterlockedMax, TranslateMopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3848. {IntrinsicOp::MOP_InterlockedMin, TranslateMopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3849. {IntrinsicOp::MOP_InterlockedOr, TranslateMopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3850. {IntrinsicOp::MOP_InterlockedXor, TranslateMopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3851. {IntrinsicOp::MOP_Store, TranslateResourceStore, DXIL::OpCode::NumOpCodes},
  3852. {IntrinsicOp::MOP_Store2, TranslateResourceStore, DXIL::OpCode::NumOpCodes},
  3853. {IntrinsicOp::MOP_Store3, TranslateResourceStore, DXIL::OpCode::NumOpCodes},
  3854. {IntrinsicOp::MOP_Store4, TranslateResourceStore, DXIL::OpCode::NumOpCodes},
  3855. {IntrinsicOp::MOP_DecrementCounter, GenerateUpdateCounter, DXIL::OpCode::NumOpCodes},
  3856. {IntrinsicOp::MOP_IncrementCounter, GenerateUpdateCounter, DXIL::OpCode::NumOpCodes},
  3857. {IntrinsicOp::MOP_Consume, EmptyLower, DXIL::OpCode::NumOpCodes},
  3858. // Manully added part.
  3859. { IntrinsicOp::IOP_InterlockedUMax, TranslateIopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes },
  3860. { IntrinsicOp::IOP_InterlockedUMin, TranslateIopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes },
  3861. { IntrinsicOp::IOP_WaveActiveUMax, TranslateWaveA2A, DXIL::OpCode::WaveActiveOp },
  3862. { IntrinsicOp::IOP_WaveActiveUMin, TranslateWaveA2A, DXIL::OpCode::WaveActiveOp },
  3863. { IntrinsicOp::IOP_WaveActiveUProduct, TranslateWaveA2A, DXIL::OpCode::WaveActiveOp },
  3864. { IntrinsicOp::IOP_WaveActiveUSum, TranslateWaveA2A, DXIL::OpCode::WaveActiveOp },
  3865. { IntrinsicOp::IOP_WavePrefixUProduct, TranslateWaveA2A, DXIL::OpCode::WavePrefixOp },
  3866. { IntrinsicOp::IOP_WavePrefixUSum, TranslateWaveA2A, DXIL::OpCode::WavePrefixOp },
  3867. { IntrinsicOp::IOP_uclamp, TranslateClamp, DXIL::OpCode::NumOpCodes },
  3868. { IntrinsicOp::IOP_ufirstbithigh, TranslateFirstbitHi, DXIL::OpCode::FirstbitHi },
  3869. { IntrinsicOp::IOP_umad, TranslateFUITrinary, DXIL::OpCode::UMad},
  3870. { IntrinsicOp::IOP_umax, TranslateFUIBinary, DXIL::OpCode::UMax},
  3871. { IntrinsicOp::IOP_umin, TranslateFUIBinary, DXIL::OpCode::UMin },
  3872. { IntrinsicOp::IOP_umul, TranslateFUIBinary, DXIL::OpCode::UMul },
  3873. { IntrinsicOp::MOP_InterlockedUMax, TranslateMopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes },
  3874. { IntrinsicOp::MOP_InterlockedUMin, TranslateMopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes },
  3875. };
  3876. }
  3877. static void TranslateBuiltinIntrinsic(CallInst *CI,
  3878. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  3879. unsigned opcode = hlsl::GetHLOpcode(CI);
  3880. const IntrinsicLower &lower = gLowerTable[opcode];
  3881. Value *Result =
  3882. lower.LowerFunc(CI, lower.IntriOpcode, lower.DxilOpcode, helper, pObjHelper, Translated);
  3883. if (Result)
  3884. CI->replaceAllUsesWith(Result);
  3885. }
  3886. // SharedMem.
  3887. namespace {
  3888. bool IsSharedMemPtr(Value *Ptr) {
  3889. return Ptr->getType()->getPointerAddressSpace() == DXIL::kTGSMAddrSpace;
  3890. }
  3891. bool IsLocalVariablePtr(Value *Ptr) {
  3892. while (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
  3893. Ptr = GEP->getPointerOperand();
  3894. }
  3895. bool isAlloca = isa<AllocaInst>(Ptr);
  3896. if (isAlloca) return true;
  3897. GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr);
  3898. if (!GV) return false;
  3899. return GV->getLinkage() == GlobalValue::LinkageTypes::InternalLinkage;
  3900. }
  3901. }
  3902. // Constant buffer.
  3903. namespace {
  3904. unsigned GetEltTypeByteSizeForConstBuf(Type *EltType, const DataLayout &DL) {
  3905. DXASSERT(EltType->isIntegerTy() || EltType->isFloatingPointTy(),
  3906. "not an element type");
  3907. // TODO: Use real size after change constant buffer into linear layout.
  3908. if (DL.getTypeSizeInBits(EltType) <= 32) {
  3909. // Constant buffer is 4 bytes align.
  3910. return 4;
  3911. } else
  3912. return 8;
  3913. }
  3914. Value *GenerateCBLoad(Value *handle, Value *offset, Type *EltTy, OP *hlslOP,
  3915. IRBuilder<> &Builder) {
  3916. Constant *OpArg = hlslOP->GetU32Const((unsigned)OP::OpCode::CBufferLoad);
  3917. // Align to 8 bytes for now.
  3918. Constant *align = hlslOP->GetU32Const(8);
  3919. Type *i1Ty = Type::getInt1Ty(EltTy->getContext());
  3920. if (EltTy != i1Ty) {
  3921. Function *CBLoad = hlslOP->GetOpFunc(OP::OpCode::CBufferLoad, EltTy);
  3922. return Builder.CreateCall(CBLoad, {OpArg, handle, offset, align});
  3923. } else {
  3924. Type *i32Ty = Type::getInt32Ty(EltTy->getContext());
  3925. Function *CBLoad = hlslOP->GetOpFunc(OP::OpCode::CBufferLoad, i32Ty);
  3926. Value *Result = Builder.CreateCall(CBLoad, {OpArg, handle, offset, align});
  3927. return Builder.CreateICmpEQ(Result, hlslOP->GetU32Const(0));
  3928. }
  3929. }
  3930. Value *TranslateConstBufMatLd(Type *matType, Value *handle, Value *offset,
  3931. bool colMajor, OP *OP, const DataLayout &DL,
  3932. IRBuilder<> &Builder) {
  3933. unsigned col, row;
  3934. Type *EltTy = HLMatrixLower::GetMatrixInfo(matType, col, row);
  3935. unsigned matSize = col * row;
  3936. std::vector<Value *> elts(matSize);
  3937. Value *EltByteSize = ConstantInt::get(
  3938. offset->getType(), GetEltTypeByteSizeForConstBuf(EltTy, DL));
  3939. // TODO: use real size after change constant buffer into linear layout.
  3940. Value *baseOffset = offset;
  3941. for (unsigned i = 0; i < matSize; i++) {
  3942. elts[i] = GenerateCBLoad(handle, baseOffset, EltTy, OP, Builder);
  3943. baseOffset = Builder.CreateAdd(baseOffset, EltByteSize);
  3944. }
  3945. return HLMatrixLower::BuildVector(EltTy, col * row, elts, Builder);
  3946. }
  3947. void TranslateCBGep(GetElementPtrInst *GEP, Value *handle, Value *baseOffset,
  3948. hlsl::OP *hlslOP, IRBuilder<> &Builder,
  3949. DxilFieldAnnotation *prevFieldAnnotation,
  3950. const DataLayout &DL, DxilTypeSystem &dxilTypeSys);
  3951. Value *GenerateVecEltFromGEP(Value *ldData, GetElementPtrInst *GEP,
  3952. IRBuilder<> &Builder) {
  3953. DXASSERT(GEP->getNumIndices() == 2, "must have 2 level");
  3954. Value *baseIdx = (GEP->idx_begin())->get();
  3955. Value *zeroIdx = Builder.getInt32(0);
  3956. DXASSERT_LOCALVAR(baseIdx && zeroIdx, baseIdx == zeroIdx,
  3957. "base index must be 0");
  3958. Value *idx = (GEP->idx_begin() + 1)->get();
  3959. if (ConstantInt *cidx = dyn_cast<ConstantInt>(idx)) {
  3960. return Builder.CreateExtractElement(ldData, idx);
  3961. } else {
  3962. // Dynamic indexing.
  3963. // Copy vec to array.
  3964. Type *Ty = ldData->getType();
  3965. Type *EltTy = Ty->getVectorElementType();
  3966. unsigned vecSize = Ty->getVectorNumElements();
  3967. ArrayType *AT = ArrayType::get(EltTy, vecSize);
  3968. IRBuilder<> AllocaBuilder(
  3969. GEP->getParent()->getParent()->getEntryBlock().getFirstInsertionPt());
  3970. Value *tempArray = AllocaBuilder.CreateAlloca(AT);
  3971. Value *zero = Builder.getInt32(0);
  3972. for (unsigned int i = 0; i < vecSize; i++) {
  3973. Value *Elt = Builder.CreateExtractElement(ldData, Builder.getInt32(i));
  3974. Value *Ptr =
  3975. Builder.CreateInBoundsGEP(tempArray, {zero, Builder.getInt32(i)});
  3976. Builder.CreateStore(Elt, Ptr);
  3977. }
  3978. // Load from temp array.
  3979. Value *EltGEP = Builder.CreateInBoundsGEP(tempArray, {zero, idx});
  3980. return Builder.CreateLoad(EltGEP);
  3981. }
  3982. }
  3983. void TranslateCBAddressUser(Instruction *user, Value *handle, Value *baseOffset,
  3984. hlsl::OP *hlslOP,
  3985. DxilFieldAnnotation *prevFieldAnnotation,
  3986. DxilTypeSystem &dxilTypeSys, const DataLayout &DL) {
  3987. IRBuilder<> Builder(user);
  3988. if (CallInst *CI = dyn_cast<CallInst>(user)) {
  3989. HLOpcodeGroup group = GetHLOpcodeGroupByName(CI->getCalledFunction());
  3990. unsigned opcode = GetHLOpcode(CI);
  3991. if (group == HLOpcodeGroup::HLMatLoadStore) {
  3992. HLMatLoadStoreOpcode matOp = static_cast<HLMatLoadStoreOpcode>(opcode);
  3993. bool colMajor = matOp == HLMatLoadStoreOpcode::ColMatLoad;
  3994. DXASSERT(matOp == HLMatLoadStoreOpcode::ColMatLoad ||
  3995. matOp == HLMatLoadStoreOpcode::RowMatLoad,
  3996. "No store on cbuffer");
  3997. Type *matType = CI->getArgOperand(HLOperandIndex::kMatLoadPtrOpIdx)
  3998. ->getType()
  3999. ->getPointerElementType();
  4000. Value *newLd = TranslateConstBufMatLd(matType, handle, baseOffset,
  4001. colMajor, hlslOP, DL, Builder);
  4002. CI->replaceAllUsesWith(newLd);
  4003. CI->eraseFromParent();
  4004. } else if (group == HLOpcodeGroup::HLSubscript) {
  4005. HLSubscriptOpcode subOp = static_cast<HLSubscriptOpcode>(opcode);
  4006. Value *basePtr = CI->getArgOperand(HLOperandIndex::kMatSubscriptMatOpIdx);
  4007. Type *matType = basePtr->getType()->getPointerElementType();
  4008. unsigned col, row;
  4009. Type *EltTy = HLMatrixLower::GetMatrixInfo(matType, col, row);
  4010. Value *EltByteSize = ConstantInt::get(
  4011. baseOffset->getType(), GetEltTypeByteSizeForConstBuf(EltTy, DL));
  4012. Value *idx = CI->getArgOperand(HLOperandIndex::kMatSubscriptSubOpIdx);
  4013. Type *resultType = CI->getType()->getPointerElementType();
  4014. unsigned resultSize = 1;
  4015. if (resultType->isVectorTy())
  4016. resultSize = resultType->getVectorNumElements();
  4017. DXASSERT(resultSize <= 16, "up to 4x4 elements in vector or matrix");
  4018. _Analysis_assume_(resultSize <= 16);
  4019. Value *idxList[16];
  4020. switch (subOp) {
  4021. case HLSubscriptOpcode::ColMatSubscript:
  4022. case HLSubscriptOpcode::RowMatSubscript: {
  4023. for (unsigned i = 0; i < resultSize; i++) {
  4024. Value *idx =
  4025. CI->getArgOperand(HLOperandIndex::kMatSubscriptSubOpIdx + i);
  4026. Value *offset = Builder.CreateMul(idx, EltByteSize);
  4027. idxList[i] = Builder.CreateAdd(baseOffset, offset);
  4028. }
  4029. } break;
  4030. case HLSubscriptOpcode::RowMatElement:
  4031. case HLSubscriptOpcode::ColMatElement: {
  4032. Constant *EltIdxs = cast<Constant>(idx);
  4033. for (unsigned i = 0; i < resultSize; i++) {
  4034. Value *offset =
  4035. Builder.CreateMul(EltIdxs->getAggregateElement(i), EltByteSize);
  4036. idxList[i] = Builder.CreateAdd(baseOffset, offset);
  4037. }
  4038. } break;
  4039. default:
  4040. DXASSERT(0, "invalid operation on const buffer");
  4041. break;
  4042. }
  4043. Value *ldData = UndefValue::get(resultType);
  4044. if (resultType->isVectorTy()) {
  4045. for (unsigned i = 0; i < resultSize; i++) {
  4046. Value *eltData =
  4047. GenerateCBLoad(handle, idxList[i], EltTy, hlslOP, Builder);
  4048. ldData = Builder.CreateInsertElement(ldData, eltData, i);
  4049. }
  4050. } else {
  4051. ldData = GenerateCBLoad(handle, idxList[0], EltTy, hlslOP, Builder);
  4052. }
  4053. for (auto U = CI->user_begin(); U != CI->user_end();) {
  4054. Value *subsUser = *(U++);
  4055. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(subsUser)) {
  4056. Value *subData = GenerateVecEltFromGEP(ldData, GEP, Builder);
  4057. for (auto gepU = GEP->user_begin(); gepU != GEP->user_end();) {
  4058. Value *gepUser = *(gepU++);
  4059. // Must be load here;
  4060. LoadInst *ldUser = cast<LoadInst>(gepUser);
  4061. ldUser->replaceAllUsesWith(subData);
  4062. ldUser->eraseFromParent();
  4063. }
  4064. GEP->eraseFromParent();
  4065. } else {
  4066. // Must be load here.
  4067. LoadInst *ldUser = cast<LoadInst>(subsUser);
  4068. ldUser->replaceAllUsesWith(ldData);
  4069. ldUser->eraseFromParent();
  4070. }
  4071. }
  4072. CI->eraseFromParent();
  4073. } else {
  4074. DXASSERT(0, "not implemented yet");
  4075. }
  4076. } else if (LoadInst *ldInst = dyn_cast<LoadInst>(user)) {
  4077. Type *Ty = ldInst->getType();
  4078. Type *EltTy = Ty->getScalarType();
  4079. DXASSERT(!Ty->isAggregateType(), "should be flat in previous pass");
  4080. unsigned EltByteSize = GetEltTypeByteSizeForConstBuf(EltTy, DL);
  4081. Value *newLd = GenerateCBLoad(handle, baseOffset, EltTy, hlslOP, Builder);
  4082. if (Ty->isVectorTy()) {
  4083. Value *result = UndefValue::get(Ty);
  4084. result = Builder.CreateInsertElement(result, newLd, (uint64_t)0);
  4085. // Update offset by 4 bytes.
  4086. Value *offset =
  4087. Builder.CreateAdd(baseOffset, hlslOP->GetU32Const(EltByteSize));
  4088. for (unsigned i = 1; i < Ty->getVectorNumElements(); i++) {
  4089. Value *elt = GenerateCBLoad(handle, offset, EltTy, hlslOP, Builder);
  4090. result = Builder.CreateInsertElement(result, elt, i);
  4091. // Update offset by 4 bytes.
  4092. offset = Builder.CreateAdd(offset, hlslOP->GetU32Const(EltByteSize));
  4093. }
  4094. newLd = result;
  4095. }
  4096. ldInst->replaceAllUsesWith(newLd);
  4097. ldInst->eraseFromParent();
  4098. } else {
  4099. // Must be GEP here
  4100. GetElementPtrInst *GEP = cast<GetElementPtrInst>(user);
  4101. TranslateCBGep(GEP, handle, baseOffset, hlslOP, Builder,
  4102. prevFieldAnnotation, DL, dxilTypeSys);
  4103. GEP->eraseFromParent();
  4104. }
  4105. }
  4106. void TranslateCBGep(GetElementPtrInst *GEP, Value *handle, Value *baseOffset,
  4107. hlsl::OP *hlslOP, IRBuilder<> &Builder,
  4108. DxilFieldAnnotation *prevFieldAnnotation,
  4109. const DataLayout &DL, DxilTypeSystem &dxilTypeSys) {
  4110. SmallVector<Value *, 8> Indices(GEP->idx_begin(), GEP->idx_end());
  4111. Value *offset = baseOffset;
  4112. // update offset
  4113. DxilFieldAnnotation *fieldAnnotation = prevFieldAnnotation;
  4114. gep_type_iterator GEPIt = gep_type_begin(GEP), E = gep_type_end(GEP);
  4115. for (; GEPIt != E; GEPIt++) {
  4116. Value *idx = GEPIt.getOperand();
  4117. unsigned immIdx = 0;
  4118. bool bImmIdx = false;
  4119. if (Constant *constIdx = dyn_cast<Constant>(idx)) {
  4120. immIdx = constIdx->getUniqueInteger().getLimitedValue();
  4121. bImmIdx = true;
  4122. }
  4123. if (GEPIt->isPointerTy()) {
  4124. Type *EltTy = GEPIt->getPointerElementType();
  4125. unsigned size = 0;
  4126. if (StructType *ST = dyn_cast<StructType>(EltTy)) {
  4127. DxilStructAnnotation *annotation = dxilTypeSys.GetStructAnnotation(ST);
  4128. size = annotation->GetCBufferSize();
  4129. } else {
  4130. DXASSERT(fieldAnnotation, "must be a field");
  4131. if (ArrayType *AT = dyn_cast<ArrayType>(EltTy)) {
  4132. unsigned EltSize = HLModule::GetLegacyCBufferFieldElementSize(
  4133. *fieldAnnotation, EltTy, dxilTypeSys);
  4134. // Decide the nested array size.
  4135. unsigned nestedArraySize = 1;
  4136. Type *EltTy = AT->getArrayElementType();
  4137. // support multi level of array
  4138. while (EltTy->isArrayTy()) {
  4139. ArrayType *EltAT = cast<ArrayType>(EltTy);
  4140. nestedArraySize *= EltAT->getNumElements();
  4141. EltTy = EltAT->getElementType();
  4142. }
  4143. // Align to 4 * 4 bytes.
  4144. unsigned alignedSize = (EltSize + 15) & 0xfffffff0;
  4145. size = nestedArraySize * alignedSize;
  4146. } else {
  4147. size = DL.getTypeAllocSize(EltTy);
  4148. }
  4149. }
  4150. // Align to 4 * 4 bytes.
  4151. size = (size + 15) & 0xfffffff0;
  4152. if (bImmIdx) {
  4153. unsigned tempOffset = size * immIdx;
  4154. offset = Builder.CreateAdd(offset, hlslOP->GetU32Const(tempOffset));
  4155. } else {
  4156. Value *tempOffset = Builder.CreateMul(idx, hlslOP->GetU32Const(size));
  4157. offset = Builder.CreateAdd(offset, tempOffset);
  4158. }
  4159. } else if (GEPIt->isStructTy()) {
  4160. StructType *ST = cast<StructType>(*GEPIt);
  4161. DxilStructAnnotation *annotation = dxilTypeSys.GetStructAnnotation(ST);
  4162. fieldAnnotation = &annotation->GetFieldAnnotation(immIdx);
  4163. unsigned structOffset = fieldAnnotation->GetCBufferOffset();
  4164. offset = Builder.CreateAdd(offset, hlslOP->GetU32Const(structOffset));
  4165. } else if (GEPIt->isArrayTy()) {
  4166. DXASSERT(fieldAnnotation != nullptr, "must a field");
  4167. unsigned EltSize = HLModule::GetLegacyCBufferFieldElementSize(
  4168. *fieldAnnotation, *GEPIt, dxilTypeSys);
  4169. // Decide the nested array size.
  4170. unsigned nestedArraySize = 1;
  4171. Type *EltTy = GEPIt->getArrayElementType();
  4172. // support multi level of array
  4173. while (EltTy->isArrayTy()) {
  4174. ArrayType *EltAT = cast<ArrayType>(EltTy);
  4175. nestedArraySize *= EltAT->getNumElements();
  4176. EltTy = EltAT->getElementType();
  4177. }
  4178. // Align to 4 * 4 bytes.
  4179. unsigned alignedSize = (EltSize + 15) & 0xfffffff0;
  4180. unsigned size = nestedArraySize * alignedSize;
  4181. if (bImmIdx) {
  4182. unsigned tempOffset = size * immIdx;
  4183. offset = Builder.CreateAdd(offset, hlslOP->GetU32Const(tempOffset));
  4184. } else {
  4185. Value *tempOffset = Builder.CreateMul(idx, hlslOP->GetU32Const(size));
  4186. offset = Builder.CreateAdd(offset, tempOffset);
  4187. }
  4188. } else if (GEPIt->isVectorTy()) {
  4189. unsigned size = DL.getTypeAllocSize(GEPIt->getVectorElementType());
  4190. if (bImmIdx) {
  4191. unsigned tempOffset = size * immIdx;
  4192. offset = Builder.CreateAdd(offset, hlslOP->GetU32Const(tempOffset));
  4193. } else {
  4194. Value *tempOffset = Builder.CreateMul(idx, hlslOP->GetU32Const(size));
  4195. offset = Builder.CreateAdd(offset, tempOffset);
  4196. }
  4197. } else {
  4198. gep_type_iterator temp = GEPIt;
  4199. temp++;
  4200. DXASSERT(temp == E, "scalar type must be the last");
  4201. }
  4202. }
  4203. for (auto U = GEP->user_begin(); U != GEP->user_end();) {
  4204. Instruction *user = cast<Instruction>(*(U++));
  4205. TranslateCBAddressUser(user, handle, offset, hlslOP, fieldAnnotation,
  4206. dxilTypeSys, DL);
  4207. }
  4208. }
  4209. void TranslateCBOperations(Value *handle, Value *ptr, Value *offset, OP *hlslOP,
  4210. DxilTypeSystem &dxilTypeSys, const DataLayout &DL) {
  4211. auto User = ptr->user_begin();
  4212. auto UserE = ptr->user_end();
  4213. for (; User != UserE;) {
  4214. // Must be Instruction.
  4215. Instruction *I = cast<Instruction>(*(User++));
  4216. TranslateCBAddressUser(I, handle, offset, hlslOP,
  4217. /*prevFieldAnnotation*/ nullptr, dxilTypeSys, DL);
  4218. }
  4219. }
  4220. Value *GenerateCBLoadLegacy(Value *handle, Value *legacyIdx,
  4221. unsigned channelOffset, Type *EltTy, OP *hlslOP,
  4222. IRBuilder<> &Builder) {
  4223. DXASSERT((channelOffset) < 4, "legacy cbuffer don't across 16 bytes register.");
  4224. Constant *OpArg = hlslOP->GetU32Const((unsigned)OP::OpCode::CBufferLoadLegacy);
  4225. Type *i1Ty = Type::getInt1Ty(EltTy->getContext());
  4226. Type *doubleTy = Type::getDoubleTy(EltTy->getContext());
  4227. Type *i64Ty = Type::getInt64Ty(EltTy->getContext());
  4228. bool isBool = EltTy == i1Ty;
  4229. bool is64 = (EltTy == doubleTy) | (EltTy == i64Ty);
  4230. bool isNormal = !isBool && !is64;
  4231. if (isNormal) {
  4232. Function *CBLoad = hlslOP->GetOpFunc(OP::OpCode::CBufferLoadLegacy, EltTy);
  4233. Value *loadLegacy = Builder.CreateCall(CBLoad, {OpArg, handle, legacyIdx});
  4234. return Builder.CreateExtractValue(loadLegacy, channelOffset);
  4235. } else if (is64) {
  4236. Function *CBLoad = hlslOP->GetOpFunc(OP::OpCode::CBufferLoadLegacy, EltTy);
  4237. Value *loadLegacy = Builder.CreateCall(CBLoad, {OpArg, handle, legacyIdx});
  4238. DXASSERT((channelOffset&1)==0,"channel offset must be even for double");
  4239. unsigned eltIdx = channelOffset>>1;
  4240. Value *Result = Builder.CreateExtractValue(loadLegacy, eltIdx);
  4241. return Result;
  4242. } else {
  4243. DXASSERT(isBool, "bool should be i1");
  4244. Type *i32Ty = Type::getInt32Ty(EltTy->getContext());
  4245. Function *CBLoad = hlslOP->GetOpFunc(OP::OpCode::CBufferLoadLegacy, i32Ty);
  4246. Value *loadLegacy = Builder.CreateCall(CBLoad, {OpArg, handle, legacyIdx});
  4247. Value *Result = Builder.CreateExtractValue(loadLegacy, channelOffset);
  4248. return Builder.CreateICmpEQ(Result, hlslOP->GetU32Const(0));
  4249. }
  4250. }
  4251. Value *GenerateCBLoadLegacy(Value *handle, Value *legacyIdx,
  4252. unsigned channelOffset, Type *EltTy,
  4253. unsigned vecSize, OP *hlslOP,
  4254. IRBuilder<> &Builder) {
  4255. DXASSERT((channelOffset + vecSize) <= 4, "legacy cbuffer don't across 16 bytes register.");
  4256. Constant *OpArg = hlslOP->GetU32Const((unsigned)OP::OpCode::CBufferLoadLegacy);
  4257. Type *i1Ty = Type::getInt1Ty(EltTy->getContext());
  4258. Type *doubleTy = Type::getDoubleTy(EltTy->getContext());
  4259. Type *i64Ty = Type::getInt64Ty(EltTy->getContext());
  4260. bool isBool = EltTy == i1Ty;
  4261. bool is64 = (EltTy == doubleTy) | (EltTy == i64Ty);
  4262. bool isNormal = !isBool && !is64;
  4263. if (isNormal) {
  4264. Function *CBLoad = hlslOP->GetOpFunc(OP::OpCode::CBufferLoadLegacy, EltTy);
  4265. Value *loadLegacy = Builder.CreateCall(CBLoad, {OpArg, handle, legacyIdx});
  4266. Value *Result = UndefValue::get(VectorType::get(EltTy, vecSize));
  4267. for (unsigned i = 0; i < vecSize; ++i) {
  4268. Value *NewElt = Builder.CreateExtractValue(loadLegacy, channelOffset+i);
  4269. Result = Builder.CreateInsertElement(Result, NewElt, i);
  4270. }
  4271. return Result;
  4272. } else if (is64) {
  4273. Function *CBLoad = hlslOP->GetOpFunc(OP::OpCode::CBufferLoadLegacy, EltTy);
  4274. Value *loadLegacy = Builder.CreateCall(CBLoad, {OpArg, handle, legacyIdx});
  4275. Value *Result = UndefValue::get(VectorType::get(EltTy, vecSize));
  4276. unsigned smallVecSize = 2;
  4277. if (vecSize < smallVecSize)
  4278. smallVecSize = vecSize;
  4279. for (unsigned i = 0; i < smallVecSize; ++i) {
  4280. Value *NewElt = Builder.CreateExtractValue(loadLegacy, channelOffset+i);
  4281. Result = Builder.CreateInsertElement(Result, NewElt, i);
  4282. }
  4283. if (vecSize > 2) {
  4284. // Got to next cb register.
  4285. legacyIdx = Builder.CreateAdd(legacyIdx, hlslOP->GetU32Const(1));
  4286. Value *loadLegacy = Builder.CreateCall(CBLoad, {OpArg, handle, legacyIdx});
  4287. for (unsigned i = 2; i < vecSize; ++i) {
  4288. Value *NewElt =
  4289. Builder.CreateExtractValue(loadLegacy, i-2);
  4290. Result = Builder.CreateInsertElement(Result, NewElt, i);
  4291. }
  4292. }
  4293. return Result;
  4294. } else {
  4295. DXASSERT(isBool, "bool should be i1");
  4296. Type *i32Ty = Type::getInt32Ty(EltTy->getContext());
  4297. Function *CBLoad = hlslOP->GetOpFunc(OP::OpCode::CBufferLoadLegacy, i32Ty);
  4298. Value *loadLegacy = Builder.CreateCall(CBLoad, {OpArg, handle, legacyIdx});
  4299. Value *Result = UndefValue::get(VectorType::get(i32Ty, vecSize));
  4300. for (unsigned i = 0; i < vecSize; ++i) {
  4301. Value *NewElt = Builder.CreateExtractValue(loadLegacy, channelOffset+i);
  4302. Result = Builder.CreateInsertElement(Result, NewElt, i);
  4303. }
  4304. return Builder.CreateICmpEQ(Result, ConstantAggregateZero::get(Result->getType()));
  4305. }
  4306. }
  4307. Value *TranslateConstBufMatLdLegacy(Type *matType, Value *handle,
  4308. Value *legacyIdx, bool colMajor, OP *OP,
  4309. const DataLayout &DL,
  4310. IRBuilder<> &Builder) {
  4311. unsigned col, row;
  4312. Type *EltTy = HLMatrixLower::GetMatrixInfo(matType, col, row);
  4313. unsigned matSize = col * row;
  4314. std::vector<Value *> elts(matSize);
  4315. unsigned EltByteSize = GetEltTypeByteSizeForConstBuf(EltTy, DL);
  4316. if (colMajor) {
  4317. unsigned colByteSize = 4 * EltByteSize;
  4318. unsigned colRegSize = (colByteSize + 15) >> 4;
  4319. for (unsigned c = 0; c < col; c++) {
  4320. Value *col = GenerateCBLoadLegacy(handle, legacyIdx, /*channelOffset*/ 0,
  4321. EltTy, row, OP, Builder);
  4322. for (unsigned r = 0; r < row; r++) {
  4323. unsigned matIdx = HLMatrixLower::GetColMajorIdx(r, c, row);
  4324. elts[matIdx] = Builder.CreateExtractElement(col, r);
  4325. }
  4326. // Update offset for a column.
  4327. legacyIdx = Builder.CreateAdd(legacyIdx, OP->GetU32Const(colRegSize));
  4328. }
  4329. } else {
  4330. unsigned rowByteSize = 4 * EltByteSize;
  4331. unsigned rowRegSize = (rowByteSize + 15) >> 4;
  4332. for (unsigned r = 0; r < row; r++) {
  4333. Value *row = GenerateCBLoadLegacy(handle, legacyIdx, /*channelOffset*/ 0,
  4334. EltTy, col, OP, Builder);
  4335. for (unsigned c = 0; c < col; c++) {
  4336. unsigned matIdx = HLMatrixLower::GetRowMajorIdx(r, c, col);
  4337. elts[matIdx] = Builder.CreateExtractElement(row, c);
  4338. }
  4339. // Update offset for a row.
  4340. legacyIdx = Builder.CreateAdd(legacyIdx, OP->GetU32Const(rowRegSize));
  4341. }
  4342. }
  4343. return HLMatrixLower::BuildVector(EltTy, col * row, elts, Builder);
  4344. }
  4345. void TranslateCBGepLegacy(GetElementPtrInst *GEP, Value *handle,
  4346. Value *legacyIdx, unsigned channelOffset,
  4347. hlsl::OP *hlslOP, IRBuilder<> &Builder,
  4348. DxilFieldAnnotation *prevFieldAnnotation,
  4349. const DataLayout &DL, DxilTypeSystem &dxilTypeSys,
  4350. HLObjectOperationLowerHelper *pObjHelper);
  4351. void TranslateResourceInCB(LoadInst *LI,
  4352. HLObjectOperationLowerHelper *pObjHelper,
  4353. GlobalVariable *CbGV) {
  4354. if (LI->user_empty()) {
  4355. LI->eraseFromParent();
  4356. return;
  4357. }
  4358. GetElementPtrInst *Ptr = cast<GetElementPtrInst>(LI->getPointerOperand());
  4359. CallInst *CI = cast<CallInst>(LI->user_back());
  4360. MDNode *MD = HLModule::GetDxilResourceAttrib(CI->getCalledFunction());
  4361. Value *ResPtr = pObjHelper->GetOrCreateResourceForCbPtr(Ptr, CbGV, MD);
  4362. // Lower Ptr to GV base Ptr.
  4363. Value *GvPtr = pObjHelper->LowerCbResourcePtr(Ptr, ResPtr);
  4364. IRBuilder<> Builder(LI);
  4365. Value *GvLd = Builder.CreateLoad(GvPtr);
  4366. LI->replaceAllUsesWith(GvLd);
  4367. LI->eraseFromParent();
  4368. }
  4369. void TranslateCBAddressUserLegacy(Instruction *user, Value *handle,
  4370. Value *legacyIdx, unsigned channelOffset,
  4371. hlsl::OP *hlslOP,
  4372. DxilFieldAnnotation *prevFieldAnnotation,
  4373. DxilTypeSystem &dxilTypeSys,
  4374. const DataLayout &DL,
  4375. HLObjectOperationLowerHelper *pObjHelper) {
  4376. IRBuilder<> Builder(user);
  4377. if (CallInst *CI = dyn_cast<CallInst>(user)) {
  4378. HLOpcodeGroup group = GetHLOpcodeGroupByName(CI->getCalledFunction());
  4379. unsigned opcode = GetHLOpcode(CI);
  4380. if (group == HLOpcodeGroup::HLMatLoadStore) {
  4381. HLMatLoadStoreOpcode matOp = static_cast<HLMatLoadStoreOpcode>(opcode);
  4382. bool colMajor = matOp == HLMatLoadStoreOpcode::ColMatLoad;
  4383. DXASSERT(matOp == HLMatLoadStoreOpcode::ColMatLoad ||
  4384. matOp == HLMatLoadStoreOpcode::RowMatLoad,
  4385. "No store on cbuffer");
  4386. Type *matType = CI->getArgOperand(HLOperandIndex::kMatLoadPtrOpIdx)
  4387. ->getType()
  4388. ->getPointerElementType();
  4389. Value *newLd = TranslateConstBufMatLdLegacy(
  4390. matType, handle, legacyIdx, colMajor, hlslOP, DL, Builder);
  4391. CI->replaceAllUsesWith(newLd);
  4392. CI->eraseFromParent();
  4393. } else if (group == HLOpcodeGroup::HLSubscript) {
  4394. HLSubscriptOpcode subOp = static_cast<HLSubscriptOpcode>(opcode);
  4395. Value *basePtr = CI->getArgOperand(HLOperandIndex::kMatSubscriptMatOpIdx);
  4396. Type *matType = basePtr->getType()->getPointerElementType();
  4397. unsigned col, row;
  4398. Type *EltTy = HLMatrixLower::GetMatrixInfo(matType, col, row);
  4399. Value *idx = CI->getArgOperand(HLOperandIndex::kMatSubscriptSubOpIdx);
  4400. Type *resultType = CI->getType()->getPointerElementType();
  4401. unsigned resultSize = 1;
  4402. if (resultType->isVectorTy())
  4403. resultSize = resultType->getVectorNumElements();
  4404. DXASSERT(resultSize <= 16, "up to 4x4 elements in vector or matrix");
  4405. _Analysis_assume_(resultSize <= 16);
  4406. Value *idxList[16];
  4407. bool colMajor = subOp == HLSubscriptOpcode::ColMatSubscript ||
  4408. subOp == HLSubscriptOpcode::ColMatElement;
  4409. bool dynamicIndexing = !isa<ConstantInt>(idx) &&
  4410. !isa<ConstantAggregateZero>(idx) &&
  4411. !isa<ConstantDataSequential>(idx);
  4412. Value *ldData = UndefValue::get(resultType);
  4413. if (!dynamicIndexing) {
  4414. Value *matLd = TranslateConstBufMatLdLegacy(
  4415. matType, handle, legacyIdx, colMajor, hlslOP, DL, Builder);
  4416. // The matLd is keep original layout, just use the idx calc in
  4417. // EmitHLSLMatrixElement and EmitHLSLMatrixSubscript.
  4418. switch (subOp) {
  4419. case HLSubscriptOpcode::RowMatSubscript:
  4420. case HLSubscriptOpcode::ColMatSubscript: {
  4421. for (unsigned i = 0; i < resultSize; i++) {
  4422. idxList[i] =
  4423. CI->getArgOperand(HLOperandIndex::kMatSubscriptSubOpIdx + i);
  4424. }
  4425. } break;
  4426. case HLSubscriptOpcode::RowMatElement:
  4427. case HLSubscriptOpcode::ColMatElement: {
  4428. Constant *EltIdxs = cast<Constant>(idx);
  4429. for (unsigned i = 0; i < resultSize; i++) {
  4430. idxList[i] = EltIdxs->getAggregateElement(i);
  4431. }
  4432. } break;
  4433. default:
  4434. DXASSERT(0, "invalid operation on const buffer");
  4435. break;
  4436. }
  4437. if (resultType->isVectorTy()) {
  4438. for (unsigned i = 0; i < resultSize; i++) {
  4439. Value *eltData = Builder.CreateExtractElement(matLd, idxList[i]);
  4440. ldData = Builder.CreateInsertElement(ldData, eltData, i);
  4441. }
  4442. } else {
  4443. Value *eltData = Builder.CreateExtractElement(matLd, idxList[0]);
  4444. ldData = eltData;
  4445. }
  4446. } else {
  4447. // Must be matSub here.
  4448. Value *idx = CI->getArgOperand(HLOperandIndex::kMatSubscriptSubOpIdx);
  4449. if (colMajor) {
  4450. // idx is c * row + r.
  4451. // For first col, c is 0, so idx is r.
  4452. Value *one = Builder.getInt32(1);
  4453. // row.x = c[0].[idx]
  4454. // row.y = c[1].[idx]
  4455. // row.z = c[2].[idx]
  4456. // row.w = c[3].[idx]
  4457. Value *Elts[4];
  4458. ArrayType *AT = ArrayType::get(EltTy, col);
  4459. IRBuilder<> AllocaBuilder(user->getParent()
  4460. ->getParent()
  4461. ->getEntryBlock()
  4462. .getFirstInsertionPt());
  4463. Value *tempArray = AllocaBuilder.CreateAlloca(AT);
  4464. Value *zero = AllocaBuilder.getInt32(0);
  4465. Value *cbufIdx = legacyIdx;
  4466. for (unsigned int c = 0; c < col; c++) {
  4467. Value *ColVal =
  4468. GenerateCBLoadLegacy(handle, cbufIdx, /*channelOffset*/ 0,
  4469. EltTy, row, hlslOP, Builder);
  4470. // Convert ColVal to array for indexing.
  4471. for (unsigned int r = 0; r < row; r++) {
  4472. Value *Elt =
  4473. Builder.CreateExtractElement(ColVal, Builder.getInt32(r));
  4474. Value *Ptr = Builder.CreateInBoundsGEP(
  4475. tempArray, {zero, Builder.getInt32(r)});
  4476. Builder.CreateStore(Elt, Ptr);
  4477. }
  4478. Value *Ptr = Builder.CreateInBoundsGEP(tempArray, {zero, idx});
  4479. Elts[c] = Builder.CreateLoad(Ptr);
  4480. // Update cbufIdx.
  4481. cbufIdx = Builder.CreateAdd(cbufIdx, one);
  4482. }
  4483. if (resultType->isVectorTy()) {
  4484. for (unsigned int c = 0; c < col; c++) {
  4485. ldData = Builder.CreateInsertElement(ldData, Elts[c], c);
  4486. }
  4487. } else {
  4488. ldData = Elts[0];
  4489. }
  4490. } else {
  4491. // idx is r * col + c;
  4492. // r = idx / col;
  4493. Value *cCol = ConstantInt::get(idx->getType(), col);
  4494. idx = Builder.CreateUDiv(idx, cCol);
  4495. idx = Builder.CreateAdd(idx, legacyIdx);
  4496. // Just return a row.
  4497. ldData = GenerateCBLoadLegacy(handle, idx, /*channelOffset*/ 0, EltTy,
  4498. row, hlslOP, Builder);
  4499. }
  4500. if (!resultType->isVectorTy()) {
  4501. ldData = Builder.CreateExtractElement(ldData, Builder.getInt32(0));
  4502. }
  4503. }
  4504. for (auto U = CI->user_begin(); U != CI->user_end();) {
  4505. Value *subsUser = *(U++);
  4506. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(subsUser)) {
  4507. Value *subData = GenerateVecEltFromGEP(ldData, GEP, Builder);
  4508. for (auto gepU = GEP->user_begin(); gepU != GEP->user_end();) {
  4509. Value *gepUser = *(gepU++);
  4510. // Must be load here;
  4511. LoadInst *ldUser = cast<LoadInst>(gepUser);
  4512. ldUser->replaceAllUsesWith(subData);
  4513. ldUser->eraseFromParent();
  4514. }
  4515. GEP->eraseFromParent();
  4516. } else {
  4517. // Must be load here.
  4518. LoadInst *ldUser = cast<LoadInst>(subsUser);
  4519. ldUser->replaceAllUsesWith(ldData);
  4520. ldUser->eraseFromParent();
  4521. }
  4522. }
  4523. CI->eraseFromParent();
  4524. } else {
  4525. DXASSERT(0, "not implemented yet");
  4526. }
  4527. } else if (LoadInst *ldInst = dyn_cast<LoadInst>(user)) {
  4528. Type *Ty = ldInst->getType();
  4529. Type *EltTy = Ty->getScalarType();
  4530. // Resource inside cbuffer is lowered after GenerateDxilOperations.
  4531. if (HLModule::IsHLSLObjectType(Ty)) {
  4532. CallInst *CI = cast<CallInst>(handle);
  4533. GlobalVariable *CbGV = cast<GlobalVariable>(
  4534. CI->getArgOperand(HLOperandIndex::kCreateHandleResourceOpIdx));
  4535. TranslateResourceInCB(ldInst, pObjHelper, CbGV);
  4536. return;
  4537. }
  4538. DXASSERT(!Ty->isAggregateType(), "should be flat in previous pass");
  4539. Value *newLd = nullptr;
  4540. if (Ty->isVectorTy())
  4541. newLd = GenerateCBLoadLegacy(handle, legacyIdx, channelOffset, EltTy,
  4542. Ty->getVectorNumElements(), hlslOP, Builder);
  4543. else
  4544. newLd = GenerateCBLoadLegacy(handle, legacyIdx, channelOffset, EltTy,
  4545. hlslOP, Builder);
  4546. ldInst->replaceAllUsesWith(newLd);
  4547. ldInst->eraseFromParent();
  4548. } else {
  4549. // Must be GEP here
  4550. GetElementPtrInst *GEP = cast<GetElementPtrInst>(user);
  4551. TranslateCBGepLegacy(GEP, handle, legacyIdx, channelOffset, hlslOP, Builder,
  4552. prevFieldAnnotation, DL, dxilTypeSys, pObjHelper);
  4553. GEP->eraseFromParent();
  4554. }
  4555. }
  4556. void TranslateCBGepLegacy(GetElementPtrInst *GEP, Value *handle,
  4557. Value *legacyIndex, unsigned channel,
  4558. hlsl::OP *hlslOP, IRBuilder<> &Builder,
  4559. DxilFieldAnnotation *prevFieldAnnotation,
  4560. const DataLayout &DL, DxilTypeSystem &dxilTypeSys,
  4561. HLObjectOperationLowerHelper *pObjHelper) {
  4562. SmallVector<Value *, 8> Indices(GEP->idx_begin(), GEP->idx_end());
  4563. // update offset
  4564. DxilFieldAnnotation *fieldAnnotation = prevFieldAnnotation;
  4565. gep_type_iterator GEPIt = gep_type_begin(GEP), E = gep_type_end(GEP);
  4566. for (; GEPIt != E; GEPIt++) {
  4567. Value *idx = GEPIt.getOperand();
  4568. unsigned immIdx = 0;
  4569. bool bImmIdx = false;
  4570. if (Constant *constIdx = dyn_cast<Constant>(idx)) {
  4571. immIdx = constIdx->getUniqueInteger().getLimitedValue();
  4572. bImmIdx = true;
  4573. }
  4574. if (GEPIt->isPointerTy()) {
  4575. Type *EltTy = GEPIt->getPointerElementType();
  4576. unsigned size = 0;
  4577. if (StructType *ST = dyn_cast<StructType>(EltTy)) {
  4578. DxilStructAnnotation *annotation = dxilTypeSys.GetStructAnnotation(ST);
  4579. size = annotation->GetCBufferSize();
  4580. } else {
  4581. DXASSERT(fieldAnnotation, "must be a field");
  4582. if (ArrayType *AT = dyn_cast<ArrayType>(EltTy)) {
  4583. unsigned EltSize = HLModule::GetLegacyCBufferFieldElementSize(
  4584. *fieldAnnotation, EltTy, dxilTypeSys);
  4585. // Decide the nested array size.
  4586. unsigned nestedArraySize = 1;
  4587. Type *EltTy = AT->getArrayElementType();
  4588. // support multi level of array
  4589. while (EltTy->isArrayTy()) {
  4590. ArrayType *EltAT = cast<ArrayType>(EltTy);
  4591. nestedArraySize *= EltAT->getNumElements();
  4592. EltTy = EltAT->getElementType();
  4593. }
  4594. // Align to 4 * 4 bytes.
  4595. unsigned alignedSize = (EltSize + 15) & 0xfffffff0;
  4596. size = nestedArraySize * alignedSize;
  4597. } else {
  4598. size = DL.getTypeAllocSize(EltTy);
  4599. }
  4600. }
  4601. // Skip 0 idx.
  4602. if (bImmIdx && immIdx == 0)
  4603. continue;
  4604. // Align to 4 * 4 bytes.
  4605. size = (size + 15) & 0xfffffff0;
  4606. // Take this as array idxing.
  4607. if (bImmIdx) {
  4608. unsigned tempOffset = size * immIdx;
  4609. unsigned idxInc = tempOffset >> 4;
  4610. legacyIndex = Builder.CreateAdd(legacyIndex, hlslOP->GetU32Const(idxInc));
  4611. } else {
  4612. Value *tempOffset = Builder.CreateMul(idx, hlslOP->GetU32Const(size));
  4613. Value *idxInc = Builder.CreateLShr(tempOffset, 4);
  4614. legacyIndex = Builder.CreateAdd(legacyIndex, idxInc);
  4615. }
  4616. // Array always start from x channel.
  4617. channel = 0;
  4618. } else if (GEPIt->isStructTy()) {
  4619. StructType *ST = cast<StructType>(*GEPIt);
  4620. DxilStructAnnotation *annotation = dxilTypeSys.GetStructAnnotation(ST);
  4621. fieldAnnotation = &annotation->GetFieldAnnotation(immIdx);
  4622. unsigned structOffset = fieldAnnotation->GetCBufferOffset() >>2;
  4623. channel += structOffset;
  4624. unsigned idxInc = channel >> 2;
  4625. channel = channel & 3;
  4626. if (idxInc)
  4627. legacyIndex = Builder.CreateAdd(legacyIndex, hlslOP->GetU32Const(idxInc));
  4628. } else if (GEPIt->isArrayTy()) {
  4629. DXASSERT(fieldAnnotation != nullptr, "must a field");
  4630. unsigned EltSize = HLModule::GetLegacyCBufferFieldElementSize(
  4631. *fieldAnnotation, *GEPIt, dxilTypeSys);
  4632. // Decide the nested array size.
  4633. unsigned nestedArraySize = 1;
  4634. Type *EltTy = GEPIt->getArrayElementType();
  4635. // support multi level of array
  4636. while (EltTy->isArrayTy()) {
  4637. ArrayType *EltAT = cast<ArrayType>(EltTy);
  4638. nestedArraySize *= EltAT->getNumElements();
  4639. EltTy = EltAT->getElementType();
  4640. }
  4641. // Align to 4 * 4 bytes.
  4642. unsigned alignedSize = (EltSize + 15) & 0xfffffff0;
  4643. unsigned size = nestedArraySize * alignedSize;
  4644. if (bImmIdx) {
  4645. unsigned tempOffset = size * immIdx;
  4646. unsigned idxInc = tempOffset >> 4;
  4647. legacyIndex = Builder.CreateAdd(legacyIndex, hlslOP->GetU32Const(idxInc));
  4648. } else {
  4649. Value *tempOffset = Builder.CreateMul(idx, hlslOP->GetU32Const(size));
  4650. Value *idxInc = Builder.CreateLShr(tempOffset, 4);
  4651. legacyIndex = Builder.CreateAdd(legacyIndex, idxInc);
  4652. }
  4653. // Array always start from x channel.
  4654. channel = 0;
  4655. } else if (GEPIt->isVectorTy()) {
  4656. unsigned size = DL.getTypeAllocSize(GEPIt->getVectorElementType());
  4657. // Indexing on vector.
  4658. if (bImmIdx) {
  4659. unsigned tempOffset = size * immIdx;
  4660. unsigned channelInc = tempOffset >> 2;
  4661. DXASSERT((channel + channelInc)<=4, "vector should not cross cb register");
  4662. channel += channelInc;
  4663. if (channel == 4) {
  4664. // Get to another row.
  4665. // Update index and channel.
  4666. channel = 0;
  4667. legacyIndex = Builder.CreateAdd(legacyIndex, Builder.getInt32(1));
  4668. }
  4669. } else {
  4670. Type *EltTy = GEPIt->getVectorElementType();
  4671. // Load the whole register.
  4672. Value *newLd = GenerateCBLoadLegacy(handle, legacyIndex,
  4673. /*channelOffset*/ 0, EltTy,
  4674. /*vecSize*/ 4, hlslOP, Builder);
  4675. // Copy to array.
  4676. IRBuilder<> AllocaBuilder(GEP->getParent()->getParent()->getEntryBlock().getFirstInsertionPt());
  4677. Value *tempArray = AllocaBuilder.CreateAlloca(ArrayType::get(EltTy, 4));
  4678. Value *zeroIdx = hlslOP->GetU32Const(0);
  4679. for (unsigned i = 0; i < 4; i++) {
  4680. Value *Elt = Builder.CreateExtractElement(newLd, i);
  4681. Value *EltGEP = Builder.CreateInBoundsGEP(tempArray, {zeroIdx, hlslOP->GetU32Const(i)});
  4682. Builder.CreateStore(Elt, EltGEP);
  4683. }
  4684. // Make sure this is the end of GEP.
  4685. gep_type_iterator temp = GEPIt;
  4686. temp++;
  4687. DXASSERT(temp == E, "scalar type must be the last");
  4688. // Replace the GEP with array GEP.
  4689. Value *ArrayGEP = Builder.CreateInBoundsGEP(tempArray, {zeroIdx, idx});
  4690. GEP->replaceAllUsesWith(ArrayGEP);
  4691. return;
  4692. }
  4693. } else {
  4694. gep_type_iterator temp = GEPIt;
  4695. temp++;
  4696. DXASSERT(temp == E, "scalar type must be the last");
  4697. }
  4698. }
  4699. for (auto U = GEP->user_begin(); U != GEP->user_end();) {
  4700. Instruction *user = cast<Instruction>(*(U++));
  4701. TranslateCBAddressUserLegacy(user, handle, legacyIndex, channel, hlslOP, fieldAnnotation,
  4702. dxilTypeSys, DL, pObjHelper);
  4703. }
  4704. }
  4705. void TranslateCBOperationsLegacy(Value *handle, Value *ptr, OP *hlslOP,
  4706. DxilTypeSystem &dxilTypeSys,
  4707. const DataLayout &DL,
  4708. HLObjectOperationLowerHelper *pObjHelper) {
  4709. auto User = ptr->user_begin();
  4710. auto UserE = ptr->user_end();
  4711. Value *zeroIdx = hlslOP->GetU32Const(0);
  4712. for (; User != UserE;) {
  4713. // Must be Instruction.
  4714. Instruction *I = cast<Instruction>(*(User++));
  4715. TranslateCBAddressUserLegacy(
  4716. I, handle, zeroIdx, /*channelOffset*/ 0, hlslOP,
  4717. /*prevFieldAnnotation*/ nullptr, dxilTypeSys, DL, pObjHelper);
  4718. }
  4719. }
  4720. }
  4721. // Structured buffer.
  4722. namespace {
  4723. // Calculate offset.
  4724. Value *GEPIdxToOffset(GetElementPtrInst *GEP, IRBuilder<> &Builder,
  4725. hlsl::OP *OP, const DataLayout &DL) {
  4726. SmallVector<Value *, 8> Indices(GEP->idx_begin(), GEP->idx_end());
  4727. Value *addr = nullptr;
  4728. // update offset
  4729. if (GEP->hasAllConstantIndices()) {
  4730. unsigned gepOffset =
  4731. DL.getIndexedOffset(GEP->getPointerOperandType(), Indices);
  4732. addr = OP->GetU32Const(gepOffset);
  4733. } else {
  4734. Value *offset = OP->GetU32Const(0);
  4735. gep_type_iterator GEPIt = gep_type_begin(GEP), E = gep_type_end(GEP);
  4736. for (; GEPIt != E; GEPIt++) {
  4737. Value *idx = GEPIt.getOperand();
  4738. unsigned immIdx = 0;
  4739. if (llvm::Constant *constIdx = dyn_cast<llvm::Constant>(idx)) {
  4740. immIdx = constIdx->getUniqueInteger().getLimitedValue();
  4741. if (immIdx == 0) {
  4742. continue;
  4743. }
  4744. }
  4745. if (GEPIt->isPointerTy()) {
  4746. unsigned size = DL.getTypeAllocSize(GEPIt->getPointerElementType());
  4747. if (immIdx) {
  4748. unsigned tempOffset = size * immIdx;
  4749. offset = Builder.CreateAdd(offset, OP->GetU32Const(tempOffset));
  4750. } else {
  4751. Value *tempOffset = Builder.CreateMul(idx, OP->GetU32Const(size));
  4752. offset = Builder.CreateAdd(offset, tempOffset);
  4753. }
  4754. } else if (GEPIt->isStructTy()) {
  4755. unsigned structOffset = 0;
  4756. for (unsigned i = 0; i < immIdx; i++) {
  4757. structOffset += DL.getTypeAllocSize(GEPIt->getStructElementType(i));
  4758. }
  4759. offset = Builder.CreateAdd(offset, OP->GetU32Const(structOffset));
  4760. } else if (GEPIt->isArrayTy()) {
  4761. unsigned size = DL.getTypeAllocSize(GEPIt->getArrayElementType());
  4762. if (immIdx) {
  4763. unsigned tempOffset = size * immIdx;
  4764. offset = Builder.CreateAdd(offset, OP->GetU32Const(tempOffset));
  4765. } else {
  4766. Value *tempOffset = Builder.CreateMul(idx, OP->GetU32Const(size));
  4767. offset = Builder.CreateAdd(offset, tempOffset);
  4768. }
  4769. } else if (GEPIt->isVectorTy()) {
  4770. unsigned size = DL.getTypeAllocSize(GEPIt->getVectorElementType());
  4771. if (immIdx) {
  4772. unsigned tempOffset = size * immIdx;
  4773. offset = Builder.CreateAdd(offset, OP->GetU32Const(tempOffset));
  4774. } else {
  4775. Value *tempOffset = Builder.CreateMul(idx, OP->GetU32Const(size));
  4776. offset = Builder.CreateAdd(offset, tempOffset);
  4777. }
  4778. } else {
  4779. gep_type_iterator temp = GEPIt;
  4780. temp++;
  4781. DXASSERT(temp == E, "scalar type must be the last");
  4782. }
  4783. };
  4784. addr = offset;
  4785. }
  4786. // TODO: x4 for byte address
  4787. return addr;
  4788. }
  4789. void GenerateStructBufLd(Value *handle, Value *bufIdx, Value *offset,
  4790. Value *status, Type *EltTy,
  4791. MutableArrayRef<Value *> resultElts, hlsl::OP *OP,
  4792. IRBuilder<> &Builder) {
  4793. OP::OpCode opcode = OP::OpCode::BufferLoad;
  4794. DXASSERT(resultElts.size() <= 4,
  4795. "buffer load cannot load more than 4 values");
  4796. Value *Args[] = {OP->GetU32Const((unsigned)opcode), handle, bufIdx, offset};
  4797. Type *i64Ty = Builder.getInt64Ty();
  4798. Type *doubleTy = Builder.getDoubleTy();
  4799. bool is64 = EltTy == i64Ty || EltTy == doubleTy;
  4800. if (!is64) {
  4801. Function *dxilF = OP->GetOpFunc(opcode, EltTy);
  4802. Value *Ld = Builder.CreateCall(dxilF, Args, OP::GetOpCodeName(opcode));
  4803. for (unsigned i = 0; i < resultElts.size(); i++) {
  4804. resultElts[i] = Builder.CreateExtractValue(Ld, i);
  4805. }
  4806. // status
  4807. UpdateStatus(Ld, status, Builder);
  4808. return;
  4809. } else {
  4810. // 64 bit.
  4811. Function *dxilF = OP->GetOpFunc(opcode, Builder.getInt32Ty());
  4812. Value *Ld = Builder.CreateCall(dxilF, Args, OP::GetOpCodeName(opcode));
  4813. Value *resultElts32[8];
  4814. unsigned size = resultElts.size();
  4815. unsigned eltBase = 0;
  4816. for (unsigned i = 0; i < size; i++) {
  4817. if (i == 2) {
  4818. // Update offset 4 by 4 bytes.
  4819. Args[DXIL::OperandIndex::kBufferLoadCoord1OpIdx] =
  4820. Builder.CreateAdd(offset, Builder.getInt32(4 * 4));
  4821. Ld = Builder.CreateCall(dxilF, Args, OP::GetOpCodeName(opcode));
  4822. eltBase = 4;
  4823. }
  4824. unsigned resBase = 2 * i;
  4825. resultElts32[resBase] = Builder.CreateExtractValue(Ld, resBase - eltBase);
  4826. resultElts32[resBase + 1] =
  4827. Builder.CreateExtractValue(Ld, resBase + 1 - eltBase);
  4828. }
  4829. Make64bitResultForLoad(EltTy, resultElts32, size, resultElts, OP, Builder);
  4830. // status
  4831. UpdateStatus(Ld, status, Builder);
  4832. return;
  4833. }
  4834. }
  4835. void GenerateStructBufSt(Value *handle, Value *bufIdx, Value *offset,
  4836. Type *EltTy, hlsl::OP *OP, IRBuilder<> &Builder,
  4837. ArrayRef<Value *> vals, uint8_t mask) {
  4838. OP::OpCode opcode = OP::OpCode::BufferStore;
  4839. DXASSERT(vals.size() == 4, "buffer store need 4 values");
  4840. Type *i64Ty = Builder.getInt64Ty();
  4841. Type *doubleTy = Builder.getDoubleTy();
  4842. bool is64 = EltTy == i64Ty || EltTy == doubleTy;
  4843. if (!is64) {
  4844. Value *Args[] = {OP->GetU32Const((unsigned)opcode),
  4845. handle,
  4846. bufIdx,
  4847. offset,
  4848. vals[0],
  4849. vals[1],
  4850. vals[2],
  4851. vals[3],
  4852. OP->GetU8Const(mask)};
  4853. Function *dxilF = OP->GetOpFunc(opcode, EltTy);
  4854. Builder.CreateCall(dxilF, Args);
  4855. } else {
  4856. Type *i32Ty = Builder.getInt32Ty();
  4857. Function *dxilF = OP->GetOpFunc(opcode, i32Ty);
  4858. Value *undefI32 = UndefValue::get(i32Ty);
  4859. Value *vals32[8] = {undefI32, undefI32, undefI32, undefI32,
  4860. undefI32, undefI32, undefI32, undefI32};
  4861. unsigned maskLo = 0;
  4862. unsigned maskHi = 0;
  4863. unsigned size = 0;
  4864. switch (mask) {
  4865. case 1:
  4866. maskLo = 3;
  4867. size = 1;
  4868. break;
  4869. case 3:
  4870. maskLo = 15;
  4871. size = 2;
  4872. break;
  4873. case 7:
  4874. maskLo = 15;
  4875. maskHi = 3;
  4876. size = 3;
  4877. break;
  4878. case 15:
  4879. maskLo = 15;
  4880. maskHi = 15;
  4881. size = 4;
  4882. break;
  4883. default:
  4884. DXASSERT(0, "invalid mask");
  4885. }
  4886. Split64bitValForStore(EltTy, vals, size, vals32, OP, Builder);
  4887. Value *Args[] = {OP->GetU32Const((unsigned)opcode),
  4888. handle,
  4889. bufIdx,
  4890. offset,
  4891. vals32[0],
  4892. vals32[1],
  4893. vals32[2],
  4894. vals32[3],
  4895. OP->GetU8Const(maskLo)};
  4896. Builder.CreateCall(dxilF, Args);
  4897. if (maskHi) {
  4898. // Update offset 4 by 4 bytes.
  4899. offset = Builder.CreateAdd(offset, Builder.getInt32(4 * 4));
  4900. Value *Args[] = {OP->GetU32Const((unsigned)opcode),
  4901. handle,
  4902. bufIdx,
  4903. offset,
  4904. vals32[4],
  4905. vals32[5],
  4906. vals32[6],
  4907. vals32[7],
  4908. OP->GetU8Const(maskHi)};
  4909. Builder.CreateCall(dxilF, Args);
  4910. }
  4911. }
  4912. }
  4913. Value *TranslateStructBufMatLd(Type *matType, IRBuilder<> &Builder,
  4914. Value *handle, hlsl::OP *OP, Value *status,
  4915. Value *bufIdx, Value *baseOffset,
  4916. bool colMajor) {
  4917. unsigned col, row;
  4918. Type *EltTy = HLMatrixLower::GetMatrixInfo(matType, col, row);
  4919. Value *offset = baseOffset;
  4920. if (baseOffset == nullptr)
  4921. offset = OP->GetU32Const(0);
  4922. unsigned matSize = col * row;
  4923. std::vector<Value *> elts(matSize);
  4924. unsigned rest = (matSize % 4);
  4925. if (rest) {
  4926. Value *ResultElts[4];
  4927. GenerateStructBufLd(handle, bufIdx, offset, status, EltTy, ResultElts, OP, Builder);
  4928. for (unsigned i = 0; i < rest; i++)
  4929. elts[i] = ResultElts[i];
  4930. offset = Builder.CreateAdd(offset, OP->GetU32Const(4 * rest));
  4931. }
  4932. for (unsigned i = rest; i < matSize; i += 4) {
  4933. Value *ResultElts[4];
  4934. GenerateStructBufLd(handle, bufIdx, offset, status, EltTy, ResultElts, OP, Builder);
  4935. elts[i] = ResultElts[0];
  4936. elts[i + 1] = ResultElts[1];
  4937. elts[i + 2] = ResultElts[2];
  4938. elts[i + 3] = ResultElts[3];
  4939. // Update offset by 4*4bytes.
  4940. offset = Builder.CreateAdd(offset, OP->GetU32Const(4 * 4));
  4941. }
  4942. return HLMatrixLower::BuildVector(EltTy, col * row, elts, Builder);
  4943. }
  4944. void TranslateStructBufMatSt(Type *matType, IRBuilder<> &Builder, Value *handle,
  4945. hlsl::OP *OP, Value *bufIdx, Value *baseOffset,
  4946. Value *val, bool colMajor) {
  4947. unsigned col, row;
  4948. Type *EltTy = HLMatrixLower::GetMatrixInfo(matType, col, row);
  4949. Value *offset = baseOffset;
  4950. if (baseOffset == nullptr)
  4951. offset = OP->GetU32Const(0);
  4952. unsigned matSize = col * row;
  4953. Value *undefElt = UndefValue::get(EltTy);
  4954. unsigned storeSize = matSize;
  4955. if (matSize % 4) {
  4956. storeSize = matSize + 4 - (matSize & 3);
  4957. }
  4958. std::vector<Value *> elts(storeSize, undefElt);
  4959. if (colMajor) {
  4960. for (unsigned i = 0; i < matSize; i++)
  4961. elts[i] = Builder.CreateExtractElement(val, i);
  4962. } else {
  4963. for (unsigned r = 0; r < row; r++)
  4964. for (unsigned c = 0; c < col; c++) {
  4965. unsigned rowMajorIdx = r * col + c;
  4966. unsigned colMajorIdx = c * row + r;
  4967. elts[rowMajorIdx] = Builder.CreateExtractElement(val, colMajorIdx);
  4968. }
  4969. }
  4970. for (unsigned i = 0; i < matSize; i += 4) {
  4971. uint8_t mask = 0;
  4972. for (unsigned j = 0; j < 4 && (i+j) < matSize; j++) {
  4973. if (elts[i+j] != undefElt)
  4974. mask |= (1<<j);
  4975. }
  4976. GenerateStructBufSt(handle, bufIdx, offset, EltTy, OP, Builder,
  4977. {elts[i], elts[i + 1], elts[i + 2], elts[i + 3]}, mask);
  4978. // Update offset by 4*4bytes.
  4979. offset = Builder.CreateAdd(offset, OP->GetU32Const(4 * 4));
  4980. }
  4981. }
  4982. void TranslateStructBufMatLdSt(CallInst *CI, Value *handle, hlsl::OP *OP,
  4983. Value *status, Value *bufIdx,
  4984. Value *baseOffset) {
  4985. IRBuilder<> Builder(CI);
  4986. HLOpcodeGroup group = hlsl::GetHLOpcodeGroupByName(CI->getCalledFunction());
  4987. unsigned opcode = GetHLOpcode(CI);
  4988. DXASSERT_LOCALVAR(group, group == HLOpcodeGroup::HLMatLoadStore,
  4989. "only translate matrix loadStore here.");
  4990. HLMatLoadStoreOpcode matOp = static_cast<HLMatLoadStoreOpcode>(opcode);
  4991. switch (matOp) {
  4992. case HLMatLoadStoreOpcode::ColMatLoad: {
  4993. Value *ptr = CI->getArgOperand(HLOperandIndex::kMatLoadPtrOpIdx);
  4994. Value *NewLd = TranslateStructBufMatLd(
  4995. ptr->getType()->getPointerElementType(), Builder, handle, OP, status,
  4996. bufIdx, baseOffset, /*colMajor*/ true);
  4997. CI->replaceAllUsesWith(NewLd);
  4998. } break;
  4999. case HLMatLoadStoreOpcode::RowMatLoad: {
  5000. Value *ptr = CI->getArgOperand(HLOperandIndex::kMatLoadPtrOpIdx);
  5001. Value *NewLd = TranslateStructBufMatLd(
  5002. ptr->getType()->getPointerElementType(), Builder, handle, OP, status,
  5003. bufIdx, baseOffset, /*colMajor*/ false);
  5004. CI->replaceAllUsesWith(NewLd);
  5005. } break;
  5006. case HLMatLoadStoreOpcode::ColMatStore: {
  5007. Value *ptr = CI->getArgOperand(HLOperandIndex::kMatStoreDstPtrOpIdx);
  5008. Value *val = CI->getArgOperand(HLOperandIndex::kMatStoreValOpIdx);
  5009. TranslateStructBufMatSt(ptr->getType()->getPointerElementType(), Builder,
  5010. handle, OP, bufIdx, baseOffset, val,
  5011. /*colMajor*/ true);
  5012. } break;
  5013. case HLMatLoadStoreOpcode::RowMatStore: {
  5014. Value *ptr = CI->getArgOperand(HLOperandIndex::kMatStoreDstPtrOpIdx);
  5015. Value *val = CI->getArgOperand(HLOperandIndex::kMatStoreValOpIdx);
  5016. TranslateStructBufMatSt(ptr->getType()->getPointerElementType(), Builder,
  5017. handle, OP, bufIdx, baseOffset, val,
  5018. /*colMajor*/ false);
  5019. } break;
  5020. }
  5021. CI->eraseFromParent();
  5022. }
  5023. void TranslateStructBufSubscriptUser(Instruction *user, Value *handle,
  5024. Value *bufIdx, Value *baseOffset,
  5025. Value *status, hlsl::OP *OP, const DataLayout &DL);
  5026. void TranslateStructBufMatSubscript(CallInst *CI, Value *handle,
  5027. hlsl::OP *hlslOP, Value *bufIdx,
  5028. Value *baseOffset, Value *status,
  5029. const DataLayout &DL) {
  5030. Value *zeroIdx = hlslOP->GetU32Const(0);
  5031. if (baseOffset == nullptr)
  5032. baseOffset = zeroIdx;
  5033. unsigned opcode = GetHLOpcode(CI);
  5034. IRBuilder<> subBuilder(CI);
  5035. HLSubscriptOpcode subOp = static_cast<HLSubscriptOpcode>(opcode);
  5036. Value *basePtr = CI->getArgOperand(HLOperandIndex::kMatSubscriptMatOpIdx);
  5037. Type *matType = basePtr->getType()->getPointerElementType();
  5038. unsigned col, row;
  5039. Type *EltTy = HLMatrixLower::GetMatrixInfo(matType, col, row);
  5040. Value *EltByteSize = ConstantInt::get(
  5041. baseOffset->getType(), GetEltTypeByteSizeForConstBuf(EltTy, DL));
  5042. Value *idx = CI->getArgOperand(HLOperandIndex::kMatSubscriptSubOpIdx);
  5043. Type *resultType = CI->getType()->getPointerElementType();
  5044. unsigned resultSize = 1;
  5045. if (resultType->isVectorTy())
  5046. resultSize = resultType->getVectorNumElements();
  5047. DXASSERT(resultSize <= 16, "up to 4x4 elements in vector or matrix");
  5048. _Analysis_assume_(resultSize <= 16);
  5049. Value *idxList[16];
  5050. switch (subOp) {
  5051. case HLSubscriptOpcode::ColMatSubscript:
  5052. case HLSubscriptOpcode::RowMatSubscript: {
  5053. for (unsigned i = 0; i < resultSize; i++) {
  5054. Value *offset =
  5055. CI->getArgOperand(HLOperandIndex::kMatSubscriptSubOpIdx + i);
  5056. offset = subBuilder.CreateMul(offset, EltByteSize);
  5057. idxList[i] = subBuilder.CreateAdd(baseOffset, offset);
  5058. }
  5059. } break;
  5060. case HLSubscriptOpcode::RowMatElement:
  5061. case HLSubscriptOpcode::ColMatElement: {
  5062. Constant *EltIdxs = cast<Constant>(idx);
  5063. for (unsigned i = 0; i < resultSize; i++) {
  5064. Value *offset =
  5065. subBuilder.CreateMul(EltIdxs->getAggregateElement(i), EltByteSize);
  5066. idxList[i] = subBuilder.CreateAdd(baseOffset, offset);
  5067. }
  5068. } break;
  5069. default:
  5070. DXASSERT(0, "invalid operation on const buffer");
  5071. break;
  5072. }
  5073. Value *undefElt = UndefValue::get(EltTy);
  5074. for (auto U = CI->user_begin(); U != CI->user_end();) {
  5075. Value *subsUser = *(U++);
  5076. if (resultSize == 1) {
  5077. TranslateStructBufSubscriptUser(cast<Instruction>(subsUser), handle,
  5078. bufIdx, idxList[0], status, hlslOP, DL);
  5079. continue;
  5080. }
  5081. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(subsUser)) {
  5082. Value *GEPOffset =
  5083. HLMatrixLower::LowerGEPOnMatIndexListToIndex(GEP, idxList);
  5084. for (auto gepU = GEP->user_begin(); gepU != GEP->user_end();) {
  5085. Instruction *gepUserInst = cast<Instruction>(*(gepU++));
  5086. TranslateStructBufSubscriptUser(gepUserInst, handle, bufIdx, GEPOffset,
  5087. status, hlslOP, DL);
  5088. }
  5089. GEP->eraseFromParent();
  5090. } else if (StoreInst *stUser = dyn_cast<StoreInst>(subsUser)) {
  5091. IRBuilder<> stBuilder(stUser);
  5092. Value *Val = stUser->getValueOperand();
  5093. if (Val->getType()->isVectorTy()) {
  5094. for (unsigned i = 0; i < resultSize; i++) {
  5095. Value *EltVal = stBuilder.CreateExtractElement(Val, i);
  5096. uint8_t mask = DXIL::kCompMask_X;
  5097. GenerateStructBufSt(handle, bufIdx, idxList[i], EltTy, hlslOP,
  5098. stBuilder, {EltVal, undefElt, undefElt, undefElt},
  5099. mask);
  5100. }
  5101. } else {
  5102. uint8_t mask = DXIL::kCompMask_X;
  5103. GenerateStructBufSt(handle, bufIdx, idxList[0], EltTy, hlslOP,
  5104. stBuilder, {Val, undefElt, undefElt, undefElt},
  5105. mask);
  5106. }
  5107. stUser->eraseFromParent();
  5108. } else {
  5109. // Must be load here.
  5110. LoadInst *ldUser = cast<LoadInst>(subsUser);
  5111. IRBuilder<> ldBuilder(ldUser);
  5112. Value *ldData = UndefValue::get(resultType);
  5113. if (resultType->isVectorTy()) {
  5114. for (unsigned i = 0; i < resultSize; i++) {
  5115. Value *ResultElt;
  5116. GenerateStructBufLd(handle, bufIdx, idxList[i],
  5117. /*status*/ nullptr, EltTy, ResultElt, hlslOP,
  5118. ldBuilder);
  5119. ldData = ldBuilder.CreateInsertElement(ldData, ResultElt, i);
  5120. }
  5121. } else {
  5122. GenerateStructBufLd(handle, bufIdx, idxList[0], /*status*/ nullptr,
  5123. EltTy, ldData, hlslOP, ldBuilder);
  5124. }
  5125. ldUser->replaceAllUsesWith(ldData);
  5126. ldUser->eraseFromParent();
  5127. }
  5128. }
  5129. CI->eraseFromParent();
  5130. }
  5131. void TranslateStructBufSubscriptUser(Instruction *user, Value *handle,
  5132. Value *bufIdx, Value *baseOffset,
  5133. Value *status, hlsl::OP *OP, const DataLayout &DL) {
  5134. IRBuilder<> Builder(user);
  5135. if (CallInst *userCall = dyn_cast<CallInst>(user)) {
  5136. HLOpcodeGroup group =
  5137. hlsl::GetHLOpcodeGroupByName(userCall->getCalledFunction());
  5138. unsigned opcode = GetHLOpcode(userCall);
  5139. // For case element type of structure buffer is not structure type.
  5140. if (baseOffset == nullptr)
  5141. baseOffset = OP->GetU32Const(0);
  5142. if (group == HLOpcodeGroup::HLIntrinsic) {
  5143. IntrinsicOp IOP = static_cast<IntrinsicOp>(opcode);
  5144. switch (IOP) {
  5145. case IntrinsicOp::MOP_Load: {
  5146. if (userCall->getType()->isPointerTy()) {
  5147. // Struct will return pointers which like []
  5148. } else {
  5149. // Use builtin types on structuredBuffer.
  5150. }
  5151. DXASSERT(0, "not implement yet");
  5152. } break;
  5153. case IntrinsicOp::IOP_InterlockedAdd: {
  5154. AtomicHelper helper(userCall, DXIL::OpCode::AtomicBinOp, handle, bufIdx,
  5155. baseOffset);
  5156. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::Add,
  5157. Builder, OP);
  5158. } break;
  5159. case IntrinsicOp::IOP_InterlockedAnd: {
  5160. AtomicHelper helper(userCall, DXIL::OpCode::AtomicBinOp, handle, bufIdx,
  5161. baseOffset);
  5162. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::And,
  5163. Builder, OP);
  5164. } break;
  5165. case IntrinsicOp::IOP_InterlockedExchange: {
  5166. AtomicHelper helper(userCall, DXIL::OpCode::AtomicBinOp, handle, bufIdx,
  5167. baseOffset);
  5168. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::Exchange,
  5169. Builder, OP);
  5170. } break;
  5171. case IntrinsicOp::IOP_InterlockedMax: {
  5172. AtomicHelper helper(userCall, DXIL::OpCode::AtomicBinOp, handle, bufIdx,
  5173. baseOffset);
  5174. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::IMax,
  5175. Builder, OP);
  5176. } break;
  5177. case IntrinsicOp::IOP_InterlockedMin: {
  5178. AtomicHelper helper(userCall, DXIL::OpCode::AtomicBinOp, handle, bufIdx,
  5179. baseOffset);
  5180. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::IMin,
  5181. Builder, OP);
  5182. } break;
  5183. case IntrinsicOp::IOP_InterlockedUMax: {
  5184. AtomicHelper helper(userCall, DXIL::OpCode::AtomicBinOp, handle, bufIdx,
  5185. baseOffset);
  5186. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::UMax,
  5187. Builder, OP);
  5188. } break;
  5189. case IntrinsicOp::IOP_InterlockedUMin: {
  5190. AtomicHelper helper(userCall, DXIL::OpCode::AtomicBinOp, handle, bufIdx,
  5191. baseOffset);
  5192. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::UMin,
  5193. Builder, OP);
  5194. } break;
  5195. case IntrinsicOp::IOP_InterlockedOr: {
  5196. AtomicHelper helper(userCall, DXIL::OpCode::AtomicBinOp, handle, bufIdx,
  5197. baseOffset);
  5198. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::Or,
  5199. Builder, OP);
  5200. } break;
  5201. case IntrinsicOp::IOP_InterlockedXor: {
  5202. AtomicHelper helper(userCall, DXIL::OpCode::AtomicBinOp, handle, bufIdx,
  5203. baseOffset);
  5204. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::Xor,
  5205. Builder, OP);
  5206. } break;
  5207. case IntrinsicOp::IOP_InterlockedCompareStore:
  5208. case IntrinsicOp::IOP_InterlockedCompareExchange: {
  5209. AtomicHelper helper(userCall, DXIL::OpCode::AtomicCompareExchange,
  5210. handle, bufIdx, baseOffset);
  5211. TranslateAtomicCmpXChg(helper, Builder, OP);
  5212. } break;
  5213. default:
  5214. DXASSERT(0, "invalid opcode");
  5215. break;
  5216. }
  5217. userCall->eraseFromParent();
  5218. } else if (group == HLOpcodeGroup::HLMatLoadStore)
  5219. // TODO: support 64 bit.
  5220. TranslateStructBufMatLdSt(userCall, handle, OP, status, bufIdx,
  5221. baseOffset);
  5222. else if (group == HLOpcodeGroup::HLSubscript) {
  5223. TranslateStructBufMatSubscript(userCall, handle, OP, bufIdx, baseOffset, status, DL);
  5224. }
  5225. } else if (isa<LoadInst>(user) || isa<StoreInst>(user)) {
  5226. LoadInst *ldInst = dyn_cast<LoadInst>(user);
  5227. StoreInst *stInst = dyn_cast<StoreInst>(user);
  5228. Type *Ty = isa<LoadInst>(user) ? ldInst->getType()
  5229. : stInst->getValueOperand()->getType();
  5230. Type *pOverloadTy = Ty->getScalarType();
  5231. Value *offset = baseOffset;
  5232. if (baseOffset == nullptr)
  5233. offset = OP->GetU32Const(0);
  5234. unsigned arraySize = 1;
  5235. Value *eltSize = nullptr;
  5236. if (pOverloadTy->isArrayTy()) {
  5237. arraySize = pOverloadTy->getArrayNumElements();
  5238. eltSize = OP->GetU32Const(
  5239. DL.getTypeAllocSize(pOverloadTy->getArrayElementType()));
  5240. pOverloadTy = pOverloadTy->getArrayElementType()->getScalarType();
  5241. }
  5242. if (ldInst) {
  5243. auto LdElement = [&](Value *offset, IRBuilder<> &Builder) -> Value * {
  5244. Value *ResultElts[4];
  5245. GenerateStructBufLd(handle, bufIdx, offset, status, pOverloadTy,
  5246. ResultElts, OP, Builder);
  5247. return ScalarizeElements(Ty, ResultElts, Builder);
  5248. };
  5249. Value *newLd = LdElement(offset, Builder);
  5250. if (arraySize > 1) {
  5251. newLd =
  5252. Builder.CreateInsertValue(UndefValue::get(Ty), newLd, (uint64_t)0);
  5253. for (unsigned i = 1; i < arraySize; i++) {
  5254. offset = Builder.CreateAdd(offset, eltSize);
  5255. Value *eltLd = LdElement(offset, Builder);
  5256. newLd = Builder.CreateInsertValue(newLd, eltLd, i);
  5257. }
  5258. }
  5259. ldInst->replaceAllUsesWith(newLd);
  5260. } else {
  5261. Value *val = stInst->getValueOperand();
  5262. auto StElement = [&](Value *offset, Value *val, IRBuilder<> &Builder) {
  5263. Value *undefVal = llvm::UndefValue::get(pOverloadTy);
  5264. Value *vals[] = {undefVal, undefVal, undefVal, undefVal};
  5265. uint8_t mask = 0;
  5266. if (Ty->isVectorTy()) {
  5267. unsigned vectorNumElements = Ty->getVectorNumElements();
  5268. DXASSERT(vectorNumElements <= 4, "up to 4 elements in vector");
  5269. _Analysis_assume_(vectorNumElements <= 4);
  5270. for (unsigned i = 0; i < vectorNumElements; i++) {
  5271. vals[i] = Builder.CreateExtractElement(val, i);
  5272. mask |= (1<<i);
  5273. }
  5274. } else {
  5275. vals[0] = val;
  5276. mask = DXIL::kCompMask_X;
  5277. }
  5278. GenerateStructBufSt(handle, bufIdx, offset, pOverloadTy, OP, Builder,
  5279. vals, mask);
  5280. };
  5281. if (arraySize > 1)
  5282. val = Builder.CreateExtractValue(val, 0);
  5283. StElement(offset, val, Builder);
  5284. if (arraySize > 1) {
  5285. val = stInst->getValueOperand();
  5286. for (unsigned i = 1; i < arraySize; i++) {
  5287. offset = Builder.CreateAdd(offset, eltSize);
  5288. Value *eltVal = Builder.CreateExtractValue(val, i);
  5289. StElement(offset, eltVal, Builder);
  5290. }
  5291. }
  5292. }
  5293. user->eraseFromParent();
  5294. } else {
  5295. // should only used by GEP
  5296. GetElementPtrInst *GEP = cast<GetElementPtrInst>(user);
  5297. Type *Ty = GEP->getType()->getPointerElementType();
  5298. DXASSERT_LOCALVAR(Ty, !Ty->isStructTy() || HLMatrixLower::IsMatrixType(Ty),
  5299. "should be flattened");
  5300. Value *offset = GEPIdxToOffset(GEP, Builder, OP, DL);
  5301. DXASSERT(offset->getType() == Type::getInt32Ty(Ty->getContext()),
  5302. "else bitness is wrong");
  5303. if (baseOffset)
  5304. offset = Builder.CreateAdd(offset, baseOffset);
  5305. for (auto U = GEP->user_begin(); U != GEP->user_end();) {
  5306. Value *GEPUser = *(U++);
  5307. TranslateStructBufSubscriptUser(cast<Instruction>(GEPUser), handle,
  5308. bufIdx, offset, status, OP, DL);
  5309. }
  5310. // delete the inst
  5311. GEP->eraseFromParent();
  5312. }
  5313. }
  5314. void TranslateStructBufSubscript(CallInst *CI, Value *handle, Value *status,
  5315. hlsl::OP *OP, const DataLayout &DL) {
  5316. Value *bufIdx = CI->getArgOperand(HLOperandIndex::kSubscriptIndexOpIdx);
  5317. for (auto U = CI->user_begin(); U != CI->user_end();) {
  5318. Value *user = *(U++);
  5319. TranslateStructBufSubscriptUser(cast<Instruction>(user), handle, bufIdx,
  5320. /*baseOffset*/ nullptr, status, OP, DL);
  5321. }
  5322. }
  5323. }
  5324. // HLSubscript.
  5325. namespace {
  5326. Value *TranslateTypedBufLoad(CallInst *CI, DXIL::ResourceKind RK,
  5327. DXIL::ResourceClass RC, Value *handle,
  5328. LoadInst *ldInst, IRBuilder<> &Builder,
  5329. hlsl::OP *hlslOP, const DataLayout &DL) {
  5330. ResLoadHelper ldHelper(CI, RK, RC, handle, /*bForSubscript*/ true);
  5331. // Default sampleIdx for 2DMS textures.
  5332. if (RK == DxilResource::Kind::Texture2DMS ||
  5333. RK == DxilResource::Kind::Texture2DMSArray)
  5334. ldHelper.mipLevel = hlslOP->GetU32Const(0);
  5335. // use ldInst as retVal
  5336. ldHelper.retVal = ldInst;
  5337. TranslateLoad(ldHelper, RK, Builder, hlslOP, DL);
  5338. // delete the ld
  5339. ldInst->eraseFromParent();
  5340. return ldHelper.retVal;
  5341. }
  5342. Value *UpdateVectorElt(Value *VecVal, Value *EltVal, Value *EltIdx,
  5343. unsigned vectorSize, Instruction *InsertPt) {
  5344. IRBuilder<> Builder(InsertPt);
  5345. if (ConstantInt *CEltIdx = dyn_cast<ConstantInt>(EltIdx)) {
  5346. VecVal =
  5347. Builder.CreateInsertElement(VecVal, EltVal, CEltIdx->getLimitedValue());
  5348. } else {
  5349. BasicBlock *BB = InsertPt->getParent();
  5350. BasicBlock *EndBB = BB->splitBasicBlock(InsertPt);
  5351. TerminatorInst *TI = BB->getTerminator();
  5352. IRBuilder<> SwitchBuilder(TI);
  5353. LLVMContext &Ctx = InsertPt->getContext();
  5354. SwitchInst *Switch = SwitchBuilder.CreateSwitch(EltIdx, EndBB, vectorSize);
  5355. TI->eraseFromParent();
  5356. Function *F = EndBB->getParent();
  5357. IRBuilder<> endSwitchBuilder(EndBB->begin());
  5358. Type *Ty = VecVal->getType();
  5359. PHINode *VecPhi = endSwitchBuilder.CreatePHI(Ty, vectorSize + 1);
  5360. for (unsigned i = 0; i < vectorSize; i++) {
  5361. BasicBlock *CaseBB = BasicBlock::Create(Ctx, "case", F, EndBB);
  5362. Switch->addCase(SwitchBuilder.getInt32(i), CaseBB);
  5363. IRBuilder<> CaseBuilder(CaseBB);
  5364. Value *CaseVal = CaseBuilder.CreateInsertElement(VecVal, EltVal, i);
  5365. VecPhi->addIncoming(CaseVal, CaseBB);
  5366. CaseBuilder.CreateBr(EndBB);
  5367. }
  5368. VecPhi->addIncoming(VecVal, BB);
  5369. VecVal = VecPhi;
  5370. }
  5371. return VecVal;
  5372. }
  5373. void TranslateDefaultSubscript(CallInst *CI, HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  5374. auto U = CI->user_begin();
  5375. Value *ptr = CI->getArgOperand(HLOperandIndex::kSubscriptObjectOpIdx);
  5376. hlsl::OP *hlslOP = &helper.hlslOP;
  5377. // Resource ptr.
  5378. Value *handle = ptr;
  5379. DXIL::ResourceClass RC = pObjHelper->GetRC(handle);
  5380. DXIL::ResourceKind RK = pObjHelper->GetRK(handle);
  5381. Type *Ty = CI->getType()->getPointerElementType();
  5382. for (auto It = CI->user_begin(); It != CI->user_end(); ) {
  5383. User *user = *(It++);
  5384. Instruction *I = cast<Instruction>(user);
  5385. IRBuilder<> Builder(I);
  5386. if (LoadInst *ldInst = dyn_cast<LoadInst>(user)) {
  5387. TranslateTypedBufLoad(CI, RK, RC, handle, ldInst, Builder, hlslOP, helper.legacyDataLayout);
  5388. } else if (StoreInst *stInst = dyn_cast<StoreInst>(user)) {
  5389. Value *val = stInst->getValueOperand();
  5390. TranslateStore(RK, handle, val,
  5391. CI->getArgOperand(HLOperandIndex::kStoreOffsetOpIdx),
  5392. Builder, hlslOP);
  5393. // delete the st
  5394. stInst->eraseFromParent();
  5395. } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(user)) {
  5396. // Must be vector type here.
  5397. unsigned vectorSize = Ty->getVectorNumElements();
  5398. DXASSERT(GEP->getNumIndices() == 2, "");
  5399. Use *GEPIdx = GEP->idx_begin();
  5400. GEPIdx++;
  5401. Value *EltIdx = *GEPIdx;
  5402. for (auto GEPIt = GEP->user_begin(); GEPIt != GEP->user_end();) {
  5403. User *GEPUser = *(GEPIt++);
  5404. if (StoreInst *SI = dyn_cast<StoreInst>(GEPUser)) {
  5405. IRBuilder<> StBuilder(SI);
  5406. // Generate Ld.
  5407. LoadInst *tmpLd = StBuilder.CreateLoad(CI);
  5408. Value *ldVal = TranslateTypedBufLoad(CI, RK, RC, handle, tmpLd, StBuilder,
  5409. hlslOP, helper.legacyDataLayout);
  5410. // Update vector.
  5411. ldVal = UpdateVectorElt(ldVal, SI->getValueOperand(), EltIdx,
  5412. vectorSize, SI);
  5413. // Generate St.
  5414. // Reset insert point, UpdateVectorElt may move SI to different block.
  5415. StBuilder.SetInsertPoint(SI);
  5416. TranslateStore(RK, handle, ldVal,
  5417. CI->getArgOperand(HLOperandIndex::kStoreOffsetOpIdx),
  5418. StBuilder, hlslOP);
  5419. SI->eraseFromParent();
  5420. continue;
  5421. }
  5422. if (!isa<CallInst>(GEPUser)) {
  5423. // Invalid operations.
  5424. Translated = false;
  5425. CI->getContext().emitError(GEP, "Invalid operation on typed buffer");
  5426. return;
  5427. }
  5428. CallInst *userCall = cast<CallInst>(GEPUser);
  5429. HLOpcodeGroup group =
  5430. hlsl::GetHLOpcodeGroupByName(userCall->getCalledFunction());
  5431. if (group != HLOpcodeGroup::HLIntrinsic) {
  5432. // Invalid operations.
  5433. Translated = false;
  5434. CI->getContext().emitError(userCall,
  5435. "Invalid operation on typed buffer");
  5436. return;
  5437. }
  5438. unsigned opcode = hlsl::GetHLOpcode(userCall);
  5439. IntrinsicOp IOP = static_cast<IntrinsicOp>(opcode);
  5440. switch (IOP) {
  5441. case IntrinsicOp::IOP_InterlockedAdd:
  5442. case IntrinsicOp::IOP_InterlockedAnd:
  5443. case IntrinsicOp::IOP_InterlockedExchange:
  5444. case IntrinsicOp::IOP_InterlockedMax:
  5445. case IntrinsicOp::IOP_InterlockedMin:
  5446. case IntrinsicOp::IOP_InterlockedUMax:
  5447. case IntrinsicOp::IOP_InterlockedUMin:
  5448. case IntrinsicOp::IOP_InterlockedOr:
  5449. case IntrinsicOp::IOP_InterlockedXor:
  5450. case IntrinsicOp::IOP_InterlockedCompareStore:
  5451. case IntrinsicOp::IOP_InterlockedCompareExchange: {
  5452. // Invalid operations.
  5453. Translated = false;
  5454. CI->getContext().emitError(
  5455. userCall, "Atomic operation on typed buffer is not supported");
  5456. return;
  5457. } break;
  5458. default:
  5459. // Invalid operations.
  5460. Translated = false;
  5461. CI->getContext().emitError(userCall,
  5462. "Invalid operation on typed buffer");
  5463. return;
  5464. break;
  5465. }
  5466. }
  5467. GEP->eraseFromParent();
  5468. } else {
  5469. CallInst *userCall = cast<CallInst>(user);
  5470. HLOpcodeGroup group =
  5471. hlsl::GetHLOpcodeGroupByName(userCall->getCalledFunction());
  5472. unsigned opcode = hlsl::GetHLOpcode(userCall);
  5473. if (group == HLOpcodeGroup::HLIntrinsic) {
  5474. IntrinsicOp IOP = static_cast<IntrinsicOp>(opcode);
  5475. if (RC == DXIL::ResourceClass::SRV) {
  5476. // Invalid operations.
  5477. Translated = false;
  5478. switch (IOP) {
  5479. case IntrinsicOp::IOP_InterlockedAdd:
  5480. case IntrinsicOp::IOP_InterlockedAnd:
  5481. case IntrinsicOp::IOP_InterlockedExchange:
  5482. case IntrinsicOp::IOP_InterlockedMax:
  5483. case IntrinsicOp::IOP_InterlockedMin:
  5484. case IntrinsicOp::IOP_InterlockedUMax:
  5485. case IntrinsicOp::IOP_InterlockedUMin:
  5486. case IntrinsicOp::IOP_InterlockedOr:
  5487. case IntrinsicOp::IOP_InterlockedXor:
  5488. case IntrinsicOp::IOP_InterlockedCompareStore:
  5489. case IntrinsicOp::IOP_InterlockedCompareExchange: {
  5490. CI->getContext().emitError(
  5491. userCall, "Atomic operation targets must be groupshared on UAV");
  5492. return;
  5493. } break;
  5494. default:
  5495. CI->getContext().emitError(userCall,
  5496. "Invalid operation on typed buffer");
  5497. return;
  5498. break;
  5499. }
  5500. }
  5501. switch (IOP) {
  5502. case IntrinsicOp::IOP_InterlockedAdd: {
  5503. ResLoadHelper helper(CI, RK, RC, handle);
  5504. AtomicHelper atomHelper(userCall, DXIL::OpCode::AtomicBinOp, handle,
  5505. helper.addr, /*offset*/ nullptr);
  5506. TranslateAtomicBinaryOperation(atomHelper, DXIL::AtomicBinOpCode::Add,
  5507. Builder, hlslOP);
  5508. } break;
  5509. case IntrinsicOp::IOP_InterlockedAnd: {
  5510. ResLoadHelper helper(CI, RK, RC, handle);
  5511. AtomicHelper atomHelper(userCall, DXIL::OpCode::AtomicBinOp, handle,
  5512. helper.addr, /*offset*/ nullptr);
  5513. TranslateAtomicBinaryOperation(atomHelper, DXIL::AtomicBinOpCode::And,
  5514. Builder, hlslOP);
  5515. } break;
  5516. case IntrinsicOp::IOP_InterlockedExchange: {
  5517. ResLoadHelper helper(CI, RK, RC, handle);
  5518. AtomicHelper atomHelper(userCall, DXIL::OpCode::AtomicBinOp, handle,
  5519. helper.addr, /*offset*/ nullptr);
  5520. TranslateAtomicBinaryOperation(
  5521. atomHelper, DXIL::AtomicBinOpCode::Exchange, Builder, hlslOP);
  5522. } break;
  5523. case IntrinsicOp::IOP_InterlockedMax: {
  5524. ResLoadHelper helper(CI, RK, RC, handle);
  5525. AtomicHelper atomHelper(userCall, DXIL::OpCode::AtomicBinOp, handle,
  5526. helper.addr, /*offset*/ nullptr);
  5527. TranslateAtomicBinaryOperation(
  5528. atomHelper, DXIL::AtomicBinOpCode::IMax, Builder, hlslOP);
  5529. } break;
  5530. case IntrinsicOp::IOP_InterlockedMin: {
  5531. ResLoadHelper helper(CI, RK, RC, handle);
  5532. AtomicHelper atomHelper(userCall, DXIL::OpCode::AtomicBinOp, handle,
  5533. helper.addr, /*offset*/ nullptr);
  5534. TranslateAtomicBinaryOperation(
  5535. atomHelper, DXIL::AtomicBinOpCode::IMin, Builder, hlslOP);
  5536. } break;
  5537. case IntrinsicOp::IOP_InterlockedUMax: {
  5538. ResLoadHelper helper(CI, RK, RC, handle);
  5539. AtomicHelper atomHelper(userCall, DXIL::OpCode::AtomicBinOp, handle,
  5540. helper.addr, /*offset*/ nullptr);
  5541. TranslateAtomicBinaryOperation(
  5542. atomHelper, DXIL::AtomicBinOpCode::UMax, Builder, hlslOP);
  5543. } break;
  5544. case IntrinsicOp::IOP_InterlockedUMin: {
  5545. ResLoadHelper helper(CI, RK, RC, handle);
  5546. AtomicHelper atomHelper(userCall, DXIL::OpCode::AtomicBinOp, handle,
  5547. helper.addr, /*offset*/ nullptr);
  5548. TranslateAtomicBinaryOperation(
  5549. atomHelper, DXIL::AtomicBinOpCode::UMin, Builder, hlslOP);
  5550. } break;
  5551. case IntrinsicOp::IOP_InterlockedOr: {
  5552. ResLoadHelper helper(CI, RK, RC, handle);
  5553. AtomicHelper atomHelper(userCall, DXIL::OpCode::AtomicBinOp, handle,
  5554. helper.addr, /*offset*/ nullptr);
  5555. TranslateAtomicBinaryOperation(atomHelper, DXIL::AtomicBinOpCode::Or,
  5556. Builder, hlslOP);
  5557. } break;
  5558. case IntrinsicOp::IOP_InterlockedXor: {
  5559. ResLoadHelper helper(CI, RK, RC, handle);
  5560. AtomicHelper atomHelper(userCall, DXIL::OpCode::AtomicBinOp, handle,
  5561. helper.addr, /*offset*/ nullptr);
  5562. TranslateAtomicBinaryOperation(atomHelper, DXIL::AtomicBinOpCode::Xor,
  5563. Builder, hlslOP);
  5564. } break;
  5565. case IntrinsicOp::IOP_InterlockedCompareStore:
  5566. case IntrinsicOp::IOP_InterlockedCompareExchange: {
  5567. ResLoadHelper helper(CI, RK, RC, handle);
  5568. AtomicHelper atomHelper(userCall, DXIL::OpCode::AtomicCompareExchange,
  5569. handle, helper.addr, /*offset*/ nullptr);
  5570. TranslateAtomicCmpXChg(atomHelper, Builder, hlslOP);
  5571. } break;
  5572. default:
  5573. DXASSERT(0, "invalid opcode");
  5574. break;
  5575. }
  5576. } else {
  5577. DXASSERT(0, "invalid group");
  5578. }
  5579. userCall->eraseFromParent();
  5580. }
  5581. }
  5582. }
  5583. void TranslateHLSubscript(CallInst *CI, HLSubscriptOpcode opcode,
  5584. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  5585. if (CI->user_empty()) {
  5586. Translated = true;
  5587. return;
  5588. }
  5589. hlsl::OP *hlslOP = &helper.hlslOP;
  5590. Value *ptr = CI->getArgOperand(HLOperandIndex::kSubscriptObjectOpIdx);
  5591. if (opcode == HLSubscriptOpcode::CBufferSubscript) {
  5592. HLModule::MergeGepUse(CI);
  5593. // Resource ptr.
  5594. Value *handle = CI->getArgOperand(HLOperandIndex::kSubscriptObjectOpIdx);
  5595. if (helper.bLegacyCBufferLoad)
  5596. TranslateCBOperationsLegacy(handle, CI, hlslOP, helper.dxilTypeSys,
  5597. helper.legacyDataLayout, pObjHelper);
  5598. else {
  5599. TranslateCBOperations(handle, CI, /*offset*/ hlslOP->GetU32Const(0),
  5600. hlslOP, helper.dxilTypeSys,
  5601. CI->getModule()->getDataLayout());
  5602. }
  5603. Translated = true;
  5604. return;
  5605. } else if (opcode == HLSubscriptOpcode::DoubleSubscript) {
  5606. // Resource ptr.
  5607. Value *handle = ptr;
  5608. DXIL::ResourceKind RK = pObjHelper->GetRK(handle);
  5609. Value *coord = CI->getArgOperand(HLOperandIndex::kSubscriptIndexOpIdx);
  5610. Value *mipLevel =
  5611. CI->getArgOperand(HLOperandIndex::kDoubleSubscriptMipLevelOpIdx);
  5612. auto U = CI->user_begin();
  5613. DXASSERT(CI->hasOneUse(), "subscript should only has one use");
  5614. // TODO: support store.
  5615. Instruction *ldInst = cast<Instruction>(*U);
  5616. ResLoadHelper ldHelper(ldInst, handle, coord, mipLevel);
  5617. IRBuilder<> Builder(CI);
  5618. TranslateLoad(ldHelper, RK, Builder, hlslOP, helper.legacyDataLayout);
  5619. ldInst->eraseFromParent();
  5620. Translated = true;
  5621. return;
  5622. } else {
  5623. Type *HandleTy = hlslOP->GetHandleType();
  5624. if (ptr->getType() == HandleTy) {
  5625. // Resource ptr.
  5626. Value *handle = ptr;
  5627. DXIL::ResourceKind RK = pObjHelper->GetRK(handle);
  5628. if (RK == DxilResource::Kind::Invalid) {
  5629. Translated = false;
  5630. return;
  5631. }
  5632. Translated = true;
  5633. Type *ObjTy = pObjHelper->GetResourceType(handle);
  5634. Type *RetTy = ObjTy->getStructElementType(0);
  5635. if (RK == DxilResource::Kind::StructuredBuffer) {
  5636. TranslateStructBufSubscript(CI, handle, /*status*/ nullptr, hlslOP,
  5637. helper.legacyDataLayout);
  5638. } else if (RetTy->isAggregateType() &&
  5639. RK == DxilResource::Kind::TypedBuffer) {
  5640. TranslateStructBufSubscript(CI, handle, /*status*/ nullptr, hlslOP,
  5641. helper.legacyDataLayout);
  5642. // Clear offset for typed buf.
  5643. for (auto User : handle->users()) {
  5644. CallInst *CI = cast<CallInst>(User);
  5645. // Skip not lowered HL functions.
  5646. if (hlsl::GetHLOpcodeGroupByName(CI->getCalledFunction()) != HLOpcodeGroup::NotHL)
  5647. continue;
  5648. switch (hlslOP->GetDxilOpFuncCallInst(CI)) {
  5649. case DXIL::OpCode::BufferLoad: {
  5650. CI->setArgOperand(DXIL::OperandIndex::kBufferLoadCoord1OpIdx,
  5651. UndefValue::get(helper.i32Ty));
  5652. } break;
  5653. case DXIL::OpCode::BufferStore: {
  5654. CI->setArgOperand(DXIL::OperandIndex::kBufferStoreCoord1OpIdx,
  5655. UndefValue::get(helper.i32Ty));
  5656. } break;
  5657. case DXIL::OpCode::AtomicBinOp: {
  5658. CI->setArgOperand(DXIL::OperandIndex::kAtomicBinOpCoord1OpIdx,
  5659. UndefValue::get(helper.i32Ty));
  5660. } break;
  5661. case DXIL::OpCode::AtomicCompareExchange: {
  5662. CI->setArgOperand(DXIL::OperandIndex::kAtomicCmpExchangeCoord1OpIdx,
  5663. UndefValue::get(helper.i32Ty));
  5664. } break;
  5665. default:
  5666. DXASSERT(0, "Invalid operation on resource handle");
  5667. break;
  5668. }
  5669. }
  5670. } else {
  5671. TranslateDefaultSubscript(CI, helper, pObjHelper, Translated);
  5672. }
  5673. return;
  5674. }
  5675. }
  5676. Value *basePtr = CI->getArgOperand(HLOperandIndex::kMatSubscriptMatOpIdx);
  5677. if (IsLocalVariablePtr(basePtr) || IsSharedMemPtr(basePtr)) {
  5678. // Translate matrix into vector of array for share memory or local
  5679. // variable should be done in HLMatrixLowerPass
  5680. DXASSERT_NOMSG(0);
  5681. Translated = true;
  5682. return;
  5683. }
  5684. // Other case should be take care in TranslateStructBufSubscript or
  5685. // TranslateCBOperations.
  5686. Translated = false;
  5687. return;
  5688. }
  5689. }
  5690. void TranslateSubscriptOperation(Function *F, HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper) {
  5691. for (auto U = F->user_begin(); U != F->user_end();) {
  5692. Value *user = *(U++);
  5693. if (!isa<Instruction>(user))
  5694. continue;
  5695. // must be call inst
  5696. CallInst *CI = cast<CallInst>(user);
  5697. unsigned opcode = GetHLOpcode(CI);
  5698. bool Translated = true;
  5699. TranslateHLSubscript(
  5700. CI, static_cast<HLSubscriptOpcode>(opcode), helper, pObjHelper, Translated);
  5701. if (Translated) {
  5702. // delete the call
  5703. DXASSERT(CI->use_empty(),
  5704. "else TranslateHLSubscript didn't replace/erase uses");
  5705. CI->eraseFromParent();
  5706. }
  5707. }
  5708. }
  5709. void TranslateHLBuiltinOperation(Function *F, HLOperationLowerHelper &helper,
  5710. hlsl::HLOpcodeGroup group, HLObjectOperationLowerHelper *pObjHelper) {
  5711. if (group == HLOpcodeGroup::HLIntrinsic) {
  5712. // map to dxil operations
  5713. for (auto U = F->user_begin(); U != F->user_end();) {
  5714. Value *User = *(U++);
  5715. if (!isa<Instruction>(User))
  5716. continue;
  5717. // must be call inst
  5718. CallInst *CI = cast<CallInst>(User);
  5719. // Keep the instruction to lower by other function.
  5720. bool Translated = true;
  5721. TranslateBuiltinIntrinsic(CI, helper, pObjHelper, Translated);
  5722. if (Translated) {
  5723. // delete the call
  5724. DXASSERT(CI->use_empty(),
  5725. "else TranslateBuiltinIntrinsic didn't replace/erase uses");
  5726. CI->eraseFromParent();
  5727. }
  5728. }
  5729. } else {
  5730. if (group == HLOpcodeGroup::HLMatLoadStore) {
  5731. // Both ld/st use arg1 for the pointer.
  5732. Type *PtrTy =
  5733. F->getFunctionType()->getParamType(HLOperandIndex::kMatLoadPtrOpIdx);
  5734. if (PtrTy->getPointerAddressSpace() == DXIL::kTGSMAddrSpace ||
  5735. // TODO: use DeviceAddressSpace for SRV/UAV and CBufferAddressSpace
  5736. // for CBuffer.
  5737. PtrTy->getPointerAddressSpace() == DXIL::kDefaultAddrSpace) {
  5738. // Translate matrix into vector of array for share memory or local
  5739. // variable should be done in HLMatrixLowerPass.
  5740. if (!F->user_empty())
  5741. F->getContext().emitError("Fail to lower matrix load/store.");
  5742. }
  5743. } else if (group == HLOpcodeGroup::HLSubscript) {
  5744. TranslateSubscriptOperation(F, helper, pObjHelper);
  5745. }
  5746. // map to math function or llvm ir
  5747. }
  5748. }
  5749. typedef std::unordered_map<llvm::Instruction *, llvm::Value *> HandleMap;
  5750. static void TranslateHLExtension(Function *F,
  5751. HLSLExtensionsCodegenHelper *helper,
  5752. OP& hlslOp) {
  5753. // Find all calls to the function F.
  5754. // Store the calls in a vector for now to be replaced the loop below.
  5755. // We use a two step "find then replace" to avoid removing uses while
  5756. // iterating.
  5757. SmallVector<CallInst *, 8> CallsToReplace;
  5758. for (User *U : F->users()) {
  5759. if (CallInst *CI = dyn_cast<CallInst>(U)) {
  5760. CallsToReplace.push_back(CI);
  5761. }
  5762. }
  5763. // Get the lowering strategy to use for this intrinsic.
  5764. llvm::StringRef LowerStrategy = GetHLLowerStrategy(F);
  5765. ExtensionLowering lower(LowerStrategy, helper, hlslOp);
  5766. // Replace all calls that were successfully translated.
  5767. for (CallInst *CI : CallsToReplace) {
  5768. Value *Result = lower.Translate(CI);
  5769. if (Result && Result != CI) {
  5770. CI->replaceAllUsesWith(Result);
  5771. CI->eraseFromParent();
  5772. }
  5773. }
  5774. }
  5775. namespace hlsl {
  5776. void TranslateBuiltinOperations(
  5777. HLModule &HLM, HLSLExtensionsCodegenHelper *extCodegenHelper,
  5778. std::unordered_set<LoadInst *> &UpdateCounterSet,
  5779. std::unordered_set<Value *> &NonUniformSet) {
  5780. HLOperationLowerHelper helper(HLM);
  5781. HLObjectOperationLowerHelper objHelper = {HLM, UpdateCounterSet,
  5782. NonUniformSet};
  5783. Module *M = HLM.GetModule();
  5784. // generate dxil operation
  5785. for (iplist<Function>::iterator F : M->getFunctionList()) {
  5786. if (!F->isDeclaration()) {
  5787. continue;
  5788. }
  5789. if (F->user_empty())
  5790. continue;
  5791. hlsl::HLOpcodeGroup group = hlsl::GetHLOpcodeGroup(F);
  5792. if (group == HLOpcodeGroup::NotHL) {
  5793. // Nothing to do.
  5794. continue;
  5795. }
  5796. if (group == HLOpcodeGroup::HLExtIntrinsic) {
  5797. TranslateHLExtension(F, extCodegenHelper, helper.hlslOP);
  5798. continue;
  5799. }
  5800. if (group == HLOpcodeGroup::HLCreateHandle) {
  5801. // Will lower in later pass.
  5802. continue;
  5803. }
  5804. TranslateHLBuiltinOperation(F, helper, group, &objHelper);
  5805. }
  5806. }
  5807. }