CGHLSLMS.cpp 243 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587
  1. //===----- CGHLSLMS.cpp - Interface to HLSL Runtime ----------------===//
  2. ///////////////////////////////////////////////////////////////////////////////
  3. // //
  4. // CGHLSLMS.cpp //
  5. // Copyright (C) Microsoft Corporation. All rights reserved. //
  6. // This file is distributed under the University of Illinois Open Source //
  7. // License. See LICENSE.TXT for details. //
  8. // //
  9. // This provides a class for HLSL code generation. //
  10. // //
  11. ///////////////////////////////////////////////////////////////////////////////
  12. #include "CGHLSLRuntime.h"
  13. #include "CodeGenFunction.h"
  14. #include "CodeGenModule.h"
  15. #include "CGRecordLayout.h"
  16. #include "dxc/HlslIntrinsicOp.h"
  17. #include "dxc/HLSL/HLMatrixLowerHelper.h"
  18. #include "dxc/HLSL/HLModule.h"
  19. #include "dxc/HLSL/DxilUtil.h"
  20. #include "dxc/HLSL/HLOperations.h"
  21. #include "dxc/HLSL/DxilOperations.h"
  22. #include "dxc/HLSL/DxilTypeSystem.h"
  23. #include "clang/AST/DeclTemplate.h"
  24. #include "clang/AST/HlslTypes.h"
  25. #include "clang/Frontend/CodeGenOptions.h"
  26. #include "clang/Lex/HLSLMacroExpander.h"
  27. #include "llvm/ADT/STLExtras.h"
  28. #include "llvm/ADT/StringSwitch.h"
  29. #include "llvm/IR/Constants.h"
  30. #include "llvm/IR/IRBuilder.h"
  31. #include "llvm/IR/GetElementPtrTypeIterator.h"
  32. #include "llvm/Transforms/Utils/Cloning.h"
  33. #include "llvm/IR/InstIterator.h"
  34. #include <memory>
  35. #include <unordered_map>
  36. #include <unordered_set>
  37. #include "dxc/HLSL/DxilRootSignature.h"
  38. #include "dxc/HLSL/DxilCBuffer.h"
  39. #include "clang/Parse/ParseHLSL.h" // root sig would be in Parser if part of lang
  40. #include "dxc/Support/WinIncludes.h" // stream support
  41. #include "dxc/dxcapi.h" // stream support
  42. #include "dxc/HLSL/HLSLExtensionsCodegenHelper.h"
  43. #include "dxc/HLSL/DxilGenerationPass.h" // support pause/resume passes
  44. using namespace clang;
  45. using namespace CodeGen;
  46. using namespace hlsl;
  47. using namespace llvm;
  48. using std::unique_ptr;
  49. static const bool KeepUndefinedTrue = true; // Keep interpolation mode undefined if not set explicitly.
  50. namespace {
  51. /// Use this class to represent HLSL cbuffer in high-level DXIL.
  52. class HLCBuffer : public DxilCBuffer {
  53. public:
  54. HLCBuffer() = default;
  55. virtual ~HLCBuffer() = default;
  56. void AddConst(std::unique_ptr<DxilResourceBase> &pItem);
  57. std::vector<std::unique_ptr<DxilResourceBase>> &GetConstants();
  58. private:
  59. std::vector<std::unique_ptr<DxilResourceBase>> constants; // constants inside const buffer
  60. };
  61. //------------------------------------------------------------------------------
  62. //
  63. // HLCBuffer methods.
  64. //
  65. void HLCBuffer::AddConst(std::unique_ptr<DxilResourceBase> &pItem) {
  66. pItem->SetID(constants.size());
  67. constants.push_back(std::move(pItem));
  68. }
  69. std::vector<std::unique_ptr<DxilResourceBase>> &HLCBuffer::GetConstants() {
  70. return constants;
  71. }
  72. class CGMSHLSLRuntime : public CGHLSLRuntime {
  73. private:
  74. /// Convenience reference to LLVM Context
  75. llvm::LLVMContext &Context;
  76. /// Convenience reference to the current module
  77. llvm::Module &TheModule;
  78. HLModule *m_pHLModule;
  79. llvm::Type *CBufferType;
  80. uint32_t globalCBIndex;
  81. // TODO: make sure how minprec works
  82. llvm::DataLayout dataLayout;
  83. // decl map to constant id for program
  84. llvm::DenseMap<HLSLBufferDecl *, uint32_t> constantBufMap;
  85. // Map for resource type to resource metadata value.
  86. std::unordered_map<llvm::Type *, MDNode*> resMetadataMap;
  87. bool m_bDebugInfo;
  88. bool m_bIsLib;
  89. HLCBuffer &GetGlobalCBuffer() {
  90. return *static_cast<HLCBuffer*>(&(m_pHLModule->GetCBuffer(globalCBIndex)));
  91. }
  92. void AddConstant(VarDecl *constDecl, HLCBuffer &CB);
  93. uint32_t AddSampler(VarDecl *samplerDecl);
  94. uint32_t AddUAVSRV(VarDecl *decl, hlsl::DxilResourceBase::Class resClass);
  95. bool SetUAVSRV(SourceLocation loc, hlsl::DxilResourceBase::Class resClass,
  96. DxilResource *hlslRes, const RecordDecl *RD);
  97. uint32_t AddCBuffer(HLSLBufferDecl *D);
  98. hlsl::DxilResourceBase::Class TypeToClass(clang::QualType Ty);
  99. // Save the entryFunc so don't need to find it with original name.
  100. struct EntryFunctionInfo {
  101. clang::SourceLocation SL = clang::SourceLocation();
  102. llvm::Function *Func = nullptr;
  103. };
  104. EntryFunctionInfo Entry;
  105. // Map to save patch constant functions
  106. struct PatchConstantInfo {
  107. clang::SourceLocation SL = clang::SourceLocation();
  108. llvm::Function *Func = nullptr;
  109. std::uint32_t NumOverloads = 0;
  110. };
  111. StringMap<PatchConstantInfo> patchConstantFunctionMap;
  112. std::unordered_map<Function *, std::unique_ptr<DxilFunctionProps>>
  113. patchConstantFunctionPropsMap;
  114. bool IsPatchConstantFunction(const Function *F);
  115. std::unordered_map<Function *, const clang::HLSLPatchConstantFuncAttr *>
  116. HSEntryPatchConstantFuncAttr;
  117. // Map to save entry functions.
  118. StringMap<EntryFunctionInfo> entryFunctionMap;
  119. // Map to save static global init exp.
  120. std::unordered_map<Expr *, GlobalVariable *> staticConstGlobalInitMap;
  121. std::unordered_map<GlobalVariable *, std::vector<Constant *>>
  122. staticConstGlobalInitListMap;
  123. std::unordered_map<GlobalVariable *, Function *> staticConstGlobalCtorMap;
  124. // List for functions with clip plane.
  125. std::vector<Function *> clipPlaneFuncList;
  126. std::unordered_map<Value *, DebugLoc> debugInfoMap;
  127. DxilRootSignatureVersion rootSigVer;
  128. Value *EmitHLSLMatrixLoad(CGBuilderTy &Builder, Value *Ptr, QualType Ty);
  129. void EmitHLSLMatrixStore(CGBuilderTy &Builder, Value *Val, Value *DestPtr,
  130. QualType Ty);
  131. // Flatten the val into scalar val and push into elts and eltTys.
  132. void FlattenValToInitList(CodeGenFunction &CGF, SmallVector<Value *, 4> &elts,
  133. SmallVector<QualType, 4> &eltTys, QualType Ty,
  134. Value *val);
  135. // Push every value on InitListExpr into EltValList and EltTyList.
  136. void ScanInitList(CodeGenFunction &CGF, InitListExpr *E,
  137. SmallVector<Value *, 4> &EltValList,
  138. SmallVector<QualType, 4> &EltTyList);
  139. void FlattenAggregatePtrToGepList(CodeGenFunction &CGF, Value *Ptr,
  140. SmallVector<Value *, 4> &idxList,
  141. clang::QualType Type, llvm::Type *Ty,
  142. SmallVector<Value *, 4> &GepList,
  143. SmallVector<QualType, 4> &EltTyList);
  144. void LoadFlattenedGepList(CodeGenFunction &CGF, ArrayRef<Value *> GepList,
  145. ArrayRef<QualType> EltTyList,
  146. SmallVector<Value *, 4> &EltList);
  147. void StoreFlattenedGepList(CodeGenFunction &CGF, ArrayRef<Value *> GepList,
  148. ArrayRef<QualType> GepTyList,
  149. ArrayRef<Value *> EltValList,
  150. ArrayRef<QualType> SrcTyList);
  151. void EmitHLSLAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  152. llvm::Value *DestPtr,
  153. SmallVector<Value *, 4> &idxList,
  154. clang::QualType SrcType,
  155. clang::QualType DestType,
  156. llvm::Type *Ty);
  157. void EmitHLSLFlatConversionToAggregate(CodeGenFunction &CGF, Value *SrcVal,
  158. llvm::Value *DestPtr,
  159. SmallVector<Value *, 4> &idxList,
  160. QualType Type, QualType SrcType,
  161. llvm::Type *Ty);
  162. void EmitHLSLRootSignature(CodeGenFunction &CGF, HLSLRootSignatureAttr *RSA,
  163. llvm::Function *Fn);
  164. void CheckParameterAnnotation(SourceLocation SLoc,
  165. const DxilParameterAnnotation &paramInfo,
  166. bool isPatchConstantFunction);
  167. void CheckParameterAnnotation(SourceLocation SLoc,
  168. DxilParamInputQual paramQual,
  169. llvm::StringRef semFullName,
  170. bool isPatchConstantFunction);
  171. void SetEntryFunction();
  172. SourceLocation SetSemantic(const NamedDecl *decl,
  173. DxilParameterAnnotation &paramInfo);
  174. hlsl::InterpolationMode GetInterpMode(const Decl *decl, CompType compType,
  175. bool bKeepUndefined);
  176. hlsl::CompType GetCompType(const BuiltinType *BT);
  177. // save intrinsic opcode
  178. std::vector<std::pair<Function *, unsigned>> m_IntrinsicMap;
  179. void AddHLSLIntrinsicOpcodeToFunction(Function *, unsigned opcode);
  180. // Type annotation related.
  181. unsigned ConstructStructAnnotation(DxilStructAnnotation *annotation,
  182. const RecordDecl *RD,
  183. DxilTypeSystem &dxilTypeSys);
  184. unsigned AddTypeAnnotation(QualType Ty, DxilTypeSystem &dxilTypeSys,
  185. unsigned &arrayEltSize);
  186. MDNode *GetOrAddResTypeMD(QualType resTy);
  187. void ConstructFieldAttributedAnnotation(DxilFieldAnnotation &fieldAnnotation,
  188. QualType fieldTy,
  189. bool bDefaultRowMajor);
  190. std::unordered_map<Constant*, DxilFieldAnnotation> m_ConstVarAnnotationMap;
  191. public:
  192. CGMSHLSLRuntime(CodeGenModule &CGM);
  193. bool IsHlslObjectType(llvm::Type * Ty) override;
  194. /// Add resouce to the program
  195. void addResource(Decl *D) override;
  196. void SetPatchConstantFunction(const EntryFunctionInfo &EntryFunc);
  197. void SetPatchConstantFunctionWithAttr(
  198. const EntryFunctionInfo &EntryFunc,
  199. const clang::HLSLPatchConstantFuncAttr *PatchConstantFuncAttr);
  200. void FinishCodeGen() override;
  201. bool IsTrivalInitListExpr(CodeGenFunction &CGF, InitListExpr *E) override;
  202. Value *EmitHLSLInitListExpr(CodeGenFunction &CGF, InitListExpr *E, Value *DestPtr) override;
  203. Constant *EmitHLSLConstInitListExpr(CodeGenModule &CGM, InitListExpr *E) override;
  204. RValue EmitHLSLBuiltinCallExpr(CodeGenFunction &CGF, const FunctionDecl *FD,
  205. const CallExpr *E,
  206. ReturnValueSlot ReturnValue) override;
  207. void EmitHLSLOutParamConversionInit(
  208. CodeGenFunction &CGF, const FunctionDecl *FD, const CallExpr *E,
  209. llvm::SmallVector<LValue, 8> &castArgList,
  210. llvm::SmallVector<const Stmt *, 8> &argList,
  211. const std::function<void(const VarDecl *, llvm::Value *)> &TmpArgMap)
  212. override;
  213. void EmitHLSLOutParamConversionCopyBack(
  214. CodeGenFunction &CGF, llvm::SmallVector<LValue, 8> &castArgList) override;
  215. Value *EmitHLSLMatrixOperationCall(CodeGenFunction &CGF, const clang::Expr *E,
  216. llvm::Type *RetType,
  217. ArrayRef<Value *> paramList) override;
  218. void EmitHLSLDiscard(CodeGenFunction &CGF) override;
  219. Value *EmitHLSLMatrixSubscript(CodeGenFunction &CGF, llvm::Type *RetType,
  220. Value *Ptr, Value *Idx, QualType Ty) override;
  221. Value *EmitHLSLMatrixElement(CodeGenFunction &CGF, llvm::Type *RetType,
  222. ArrayRef<Value *> paramList,
  223. QualType Ty) override;
  224. Value *EmitHLSLMatrixLoad(CodeGenFunction &CGF, Value *Ptr,
  225. QualType Ty) override;
  226. void EmitHLSLMatrixStore(CodeGenFunction &CGF, Value *Val, Value *DestPtr,
  227. QualType Ty) override;
  228. void EmitHLSLAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  229. llvm::Value *DestPtr,
  230. clang::QualType Ty) override;
  231. void EmitHLSLAggregateStore(CodeGenFunction &CGF, llvm::Value *Val,
  232. llvm::Value *DestPtr,
  233. clang::QualType Ty) override;
  234. void EmitHLSLFlatConversionToAggregate(CodeGenFunction &CGF, Value *Val,
  235. Value *DestPtr,
  236. QualType Ty,
  237. QualType SrcTy) override;
  238. Value *EmitHLSLLiteralCast(CodeGenFunction &CGF, Value *Src, QualType SrcType,
  239. QualType DstType) override;
  240. void EmitHLSLFlatConversionAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  241. clang::QualType SrcTy,
  242. llvm::Value *DestPtr,
  243. clang::QualType DestTy) override;
  244. void AddHLSLFunctionInfo(llvm::Function *, const FunctionDecl *FD) override;
  245. void EmitHLSLFunctionProlog(llvm::Function *, const FunctionDecl *FD) override;
  246. void AddControlFlowHint(CodeGenFunction &CGF, const Stmt &S,
  247. llvm::TerminatorInst *TI,
  248. ArrayRef<const Attr *> Attrs) override;
  249. void FinishAutoVar(CodeGenFunction &CGF, const VarDecl &D, llvm::Value *V) override;
  250. /// Get or add constant to the program
  251. HLCBuffer &GetOrCreateCBuffer(HLSLBufferDecl *D);
  252. };
  253. }
  254. void clang::CompileRootSignature(
  255. StringRef rootSigStr, DiagnosticsEngine &Diags, SourceLocation SLoc,
  256. hlsl::DxilRootSignatureVersion rootSigVer,
  257. hlsl::RootSignatureHandle *pRootSigHandle) {
  258. std::string OSStr;
  259. llvm::raw_string_ostream OS(OSStr);
  260. hlsl::DxilVersionedRootSignatureDesc *D = nullptr;
  261. if (ParseHLSLRootSignature(rootSigStr.data(), rootSigStr.size(), rootSigVer,
  262. &D, SLoc, Diags)) {
  263. CComPtr<IDxcBlob> pSignature;
  264. CComPtr<IDxcBlobEncoding> pErrors;
  265. hlsl::SerializeRootSignature(D, &pSignature, &pErrors, false);
  266. if (pSignature == nullptr) {
  267. assert(pErrors != nullptr && "else serialize failed with no msg");
  268. ReportHLSLRootSigError(Diags, SLoc, (char *)pErrors->GetBufferPointer(),
  269. pErrors->GetBufferSize());
  270. hlsl::DeleteRootSignature(D);
  271. } else {
  272. pRootSigHandle->Assign(D, pSignature);
  273. }
  274. }
  275. }
  276. //------------------------------------------------------------------------------
  277. //
  278. // CGMSHLSLRuntime methods.
  279. //
  280. CGMSHLSLRuntime::CGMSHLSLRuntime(CodeGenModule &CGM)
  281. : CGHLSLRuntime(CGM), Context(CGM.getLLVMContext()), Entry(),
  282. TheModule(CGM.getModule()),
  283. dataLayout(CGM.getLangOpts().UseMinPrecision
  284. ? hlsl::DXIL::kLegacyLayoutString
  285. : hlsl::DXIL::kNewLayoutString),
  286. CBufferType(
  287. llvm::StructType::create(TheModule.getContext(), "ConstantBuffer")) {
  288. const hlsl::ShaderModel *SM =
  289. hlsl::ShaderModel::GetByName(CGM.getCodeGenOpts().HLSLProfile.c_str());
  290. // Only accept valid, 6.0 shader model.
  291. if (!SM->IsValid() || SM->GetMajor() != 6) {
  292. DiagnosticsEngine &Diags = CGM.getDiags();
  293. unsigned DiagID =
  294. Diags.getCustomDiagID(DiagnosticsEngine::Error, "invalid profile %0");
  295. Diags.Report(DiagID) << CGM.getCodeGenOpts().HLSLProfile;
  296. return;
  297. }
  298. m_bIsLib = SM->IsLib();
  299. // TODO: add AllResourceBound.
  300. if (CGM.getCodeGenOpts().HLSLAvoidControlFlow && !CGM.getCodeGenOpts().HLSLAllResourcesBound) {
  301. if (SM->IsSM51Plus()) {
  302. DiagnosticsEngine &Diags = CGM.getDiags();
  303. unsigned DiagID =
  304. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  305. "Gfa option cannot be used in SM_5_1+ unless "
  306. "all_resources_bound flag is specified");
  307. Diags.Report(DiagID);
  308. }
  309. }
  310. // Create HLModule.
  311. const bool skipInit = true;
  312. m_pHLModule = &TheModule.GetOrCreateHLModule(skipInit);
  313. // Set Option.
  314. HLOptions opts;
  315. opts.bIEEEStrict = CGM.getCodeGenOpts().UnsafeFPMath;
  316. opts.bDefaultRowMajor = CGM.getCodeGenOpts().HLSLDefaultRowMajor;
  317. opts.bDisableOptimizations = CGM.getCodeGenOpts().DisableLLVMOpts;
  318. opts.bLegacyCBufferLoad = !CGM.getCodeGenOpts().HLSLNotUseLegacyCBufLoad;
  319. opts.bAllResourcesBound = CGM.getCodeGenOpts().HLSLAllResourcesBound;
  320. opts.PackingStrategy = CGM.getCodeGenOpts().HLSLSignaturePackingStrategy;
  321. opts.bUseMinPrecision = CGM.getLangOpts().UseMinPrecision;
  322. m_pHLModule->SetHLOptions(opts);
  323. m_pHLModule->SetValidatorVersion(CGM.getCodeGenOpts().HLSLValidatorMajorVer, CGM.getCodeGenOpts().HLSLValidatorMinorVer);
  324. m_bDebugInfo = CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::FullDebugInfo;
  325. // set profile
  326. m_pHLModule->SetShaderModel(SM);
  327. // set entry name
  328. m_pHLModule->SetEntryFunctionName(CGM.getCodeGenOpts().HLSLEntryFunction);
  329. // set root signature version.
  330. if (CGM.getLangOpts().RootSigMinor == 0) {
  331. rootSigVer = hlsl::DxilRootSignatureVersion::Version_1_0;
  332. }
  333. else {
  334. DXASSERT(CGM.getLangOpts().RootSigMinor == 1,
  335. "else CGMSHLSLRuntime Constructor needs to be updated");
  336. rootSigVer = hlsl::DxilRootSignatureVersion::Version_1_1;
  337. }
  338. DXASSERT(CGM.getLangOpts().RootSigMajor == 1,
  339. "else CGMSHLSLRuntime Constructor needs to be updated");
  340. // add globalCB
  341. unique_ptr<HLCBuffer> CB = llvm::make_unique<HLCBuffer>();
  342. std::string globalCBName = "$Globals";
  343. CB->SetGlobalSymbol(nullptr);
  344. CB->SetGlobalName(globalCBName);
  345. globalCBIndex = m_pHLModule->GetCBuffers().size();
  346. CB->SetID(globalCBIndex);
  347. CB->SetRangeSize(1);
  348. CB->SetLowerBound(UINT_MAX);
  349. DXVERIFY_NOMSG(globalCBIndex == m_pHLModule->AddCBuffer(std::move(CB)));
  350. // set Float Denorm Mode
  351. m_pHLModule->SetFloat32DenormMode(CGM.getCodeGenOpts().HLSLFloat32DenormMode);
  352. }
  353. bool CGMSHLSLRuntime::IsHlslObjectType(llvm::Type *Ty) {
  354. return HLModule::IsHLSLObjectType(Ty);
  355. }
  356. void CGMSHLSLRuntime::AddHLSLIntrinsicOpcodeToFunction(Function *F,
  357. unsigned opcode) {
  358. m_IntrinsicMap.emplace_back(F,opcode);
  359. }
  360. void CGMSHLSLRuntime::CheckParameterAnnotation(
  361. SourceLocation SLoc, const DxilParameterAnnotation &paramInfo,
  362. bool isPatchConstantFunction) {
  363. if (!paramInfo.HasSemanticString()) {
  364. return;
  365. }
  366. llvm::StringRef semFullName = paramInfo.GetSemanticStringRef();
  367. DxilParamInputQual paramQual = paramInfo.GetParamInputQual();
  368. if (paramQual == DxilParamInputQual::Inout) {
  369. CheckParameterAnnotation(SLoc, DxilParamInputQual::In, semFullName, isPatchConstantFunction);
  370. CheckParameterAnnotation(SLoc, DxilParamInputQual::Out, semFullName, isPatchConstantFunction);
  371. return;
  372. }
  373. CheckParameterAnnotation(SLoc, paramQual, semFullName, isPatchConstantFunction);
  374. }
  375. void CGMSHLSLRuntime::CheckParameterAnnotation(
  376. SourceLocation SLoc, DxilParamInputQual paramQual, llvm::StringRef semFullName,
  377. bool isPatchConstantFunction) {
  378. const ShaderModel *SM = m_pHLModule->GetShaderModel();
  379. DXIL::SigPointKind sigPoint = SigPointFromInputQual(
  380. paramQual, SM->GetKind(), isPatchConstantFunction);
  381. llvm::StringRef semName;
  382. unsigned semIndex;
  383. Semantic::DecomposeNameAndIndex(semFullName, &semName, &semIndex);
  384. const Semantic *pSemantic =
  385. Semantic::GetByName(semName, sigPoint, SM->GetMajor(), SM->GetMinor());
  386. if (pSemantic->IsInvalid()) {
  387. DiagnosticsEngine &Diags = CGM.getDiags();
  388. const ShaderModel *shader = m_pHLModule->GetShaderModel();
  389. unsigned DiagID =
  390. Diags.getCustomDiagID(DiagnosticsEngine::Error, "invalid semantic '%0' for %1 %2.%3");
  391. Diags.Report(SLoc, DiagID) << semName << shader->GetKindName() << shader->GetMajor() << shader->GetMinor();
  392. }
  393. }
  394. SourceLocation
  395. CGMSHLSLRuntime::SetSemantic(const NamedDecl *decl,
  396. DxilParameterAnnotation &paramInfo) {
  397. for (const hlsl::UnusualAnnotation *it : decl->getUnusualAnnotations()) {
  398. if (it->getKind() == hlsl::UnusualAnnotation::UA_SemanticDecl) {
  399. const hlsl::SemanticDecl *sd = cast<hlsl::SemanticDecl>(it);
  400. paramInfo.SetSemanticString(sd->SemanticName);
  401. return it->Loc;
  402. }
  403. }
  404. return SourceLocation();
  405. }
  406. static DXIL::TessellatorDomain StringToDomain(StringRef domain) {
  407. if (domain == "isoline")
  408. return DXIL::TessellatorDomain::IsoLine;
  409. if (domain == "tri")
  410. return DXIL::TessellatorDomain::Tri;
  411. if (domain == "quad")
  412. return DXIL::TessellatorDomain::Quad;
  413. return DXIL::TessellatorDomain::Undefined;
  414. }
  415. static DXIL::TessellatorPartitioning StringToPartitioning(StringRef partition) {
  416. if (partition == "integer")
  417. return DXIL::TessellatorPartitioning::Integer;
  418. if (partition == "pow2")
  419. return DXIL::TessellatorPartitioning::Pow2;
  420. if (partition == "fractional_even")
  421. return DXIL::TessellatorPartitioning::FractionalEven;
  422. if (partition == "fractional_odd")
  423. return DXIL::TessellatorPartitioning::FractionalOdd;
  424. return DXIL::TessellatorPartitioning::Undefined;
  425. }
  426. static DXIL::TessellatorOutputPrimitive
  427. StringToTessOutputPrimitive(StringRef primitive) {
  428. if (primitive == "point")
  429. return DXIL::TessellatorOutputPrimitive::Point;
  430. if (primitive == "line")
  431. return DXIL::TessellatorOutputPrimitive::Line;
  432. if (primitive == "triangle_cw")
  433. return DXIL::TessellatorOutputPrimitive::TriangleCW;
  434. if (primitive == "triangle_ccw")
  435. return DXIL::TessellatorOutputPrimitive::TriangleCCW;
  436. return DXIL::TessellatorOutputPrimitive::Undefined;
  437. }
  438. static unsigned RoundToAlign(unsigned num, unsigned mod) {
  439. // round num to next highest mod
  440. if (mod != 0)
  441. return mod * ((num + mod - 1) / mod);
  442. return num;
  443. }
  444. // Align cbuffer offset in legacy mode (16 bytes per row).
  445. static unsigned AlignBufferOffsetInLegacy(unsigned offset, unsigned size,
  446. unsigned scalarSizeInBytes,
  447. bool bNeedNewRow) {
  448. if (unsigned remainder = (offset & 0xf)) {
  449. // Start from new row
  450. if (remainder + size > 16 || bNeedNewRow) {
  451. return offset + 16 - remainder;
  452. }
  453. // If not, naturally align data
  454. return RoundToAlign(offset, scalarSizeInBytes);
  455. }
  456. return offset;
  457. }
  458. static unsigned AlignBaseOffset(unsigned baseOffset, unsigned size,
  459. QualType Ty, bool bDefaultRowMajor) {
  460. bool needNewAlign = Ty->isArrayType();
  461. if (IsHLSLMatType(Ty)) {
  462. bool bColMajor = !bDefaultRowMajor;
  463. if (const AttributedType *AT = dyn_cast<AttributedType>(Ty)) {
  464. switch (AT->getAttrKind()) {
  465. case AttributedType::Kind::attr_hlsl_column_major:
  466. bColMajor = true;
  467. break;
  468. case AttributedType::Kind::attr_hlsl_row_major:
  469. bColMajor = false;
  470. break;
  471. default:
  472. // Do nothing
  473. break;
  474. }
  475. }
  476. unsigned row, col;
  477. hlsl::GetHLSLMatRowColCount(Ty, row, col);
  478. needNewAlign |= bColMajor && col > 1;
  479. needNewAlign |= !bColMajor && row > 1;
  480. }
  481. unsigned scalarSizeInBytes = 4;
  482. const clang::BuiltinType *BT = Ty->getAs<clang::BuiltinType>();
  483. if (hlsl::IsHLSLVecMatType(Ty)) {
  484. BT = CGHLSLRuntime::GetHLSLVecMatElementType(Ty)->getAs<clang::BuiltinType>();
  485. }
  486. if (BT) {
  487. if (BT->getKind() == clang::BuiltinType::Kind::Double ||
  488. BT->getKind() == clang::BuiltinType::Kind::LongLong)
  489. scalarSizeInBytes = 8;
  490. else if (BT->getKind() == clang::BuiltinType::Kind::Half ||
  491. BT->getKind() == clang::BuiltinType::Kind::Short ||
  492. BT->getKind() == clang::BuiltinType::Kind::UShort)
  493. scalarSizeInBytes = 2;
  494. }
  495. return AlignBufferOffsetInLegacy(baseOffset, size, scalarSizeInBytes, needNewAlign);
  496. }
  497. static unsigned AlignBaseOffset(QualType Ty, unsigned baseOffset,
  498. bool bDefaultRowMajor,
  499. CodeGen::CodeGenModule &CGM,
  500. llvm::DataLayout &layout) {
  501. QualType paramTy = Ty.getCanonicalType();
  502. if (const ReferenceType *RefType = dyn_cast<ReferenceType>(paramTy))
  503. paramTy = RefType->getPointeeType();
  504. // Get size.
  505. llvm::Type *Type = CGM.getTypes().ConvertType(paramTy);
  506. unsigned size = layout.getTypeAllocSize(Type);
  507. return AlignBaseOffset(baseOffset, size, paramTy, bDefaultRowMajor);
  508. }
  509. static unsigned GetMatrixSizeInCB(QualType Ty, bool defaultRowMajor,
  510. bool b64Bit) {
  511. bool bColMajor = !defaultRowMajor;
  512. if (const AttributedType *AT = dyn_cast<AttributedType>(Ty)) {
  513. switch (AT->getAttrKind()) {
  514. case AttributedType::Kind::attr_hlsl_column_major:
  515. bColMajor = true;
  516. break;
  517. case AttributedType::Kind::attr_hlsl_row_major:
  518. bColMajor = false;
  519. break;
  520. default:
  521. // Do nothing
  522. break;
  523. }
  524. }
  525. unsigned row, col;
  526. hlsl::GetHLSLMatRowColCount(Ty, row, col);
  527. unsigned EltSize = b64Bit ? 8 : 4;
  528. // Align to 4 * 4bytes.
  529. unsigned alignment = 4 * 4;
  530. if (bColMajor) {
  531. unsigned rowSize = EltSize * row;
  532. // 3x64bit or 4x64bit align to 32 bytes.
  533. if (rowSize > alignment)
  534. alignment <<= 1;
  535. return alignment * (col - 1) + row * EltSize;
  536. } else {
  537. unsigned rowSize = EltSize * col;
  538. // 3x64bit or 4x64bit align to 32 bytes.
  539. if (rowSize > alignment)
  540. alignment <<= 1;
  541. return alignment * (row - 1) + col * EltSize;
  542. }
  543. }
  544. static CompType::Kind BuiltinTyToCompTy(const BuiltinType *BTy, bool bSNorm,
  545. bool bUNorm) {
  546. CompType::Kind kind = CompType::Kind::Invalid;
  547. switch (BTy->getKind()) {
  548. case BuiltinType::UInt:
  549. kind = CompType::Kind::U32;
  550. break;
  551. case BuiltinType::UShort:
  552. kind = CompType::Kind::U16;
  553. break;
  554. case BuiltinType::ULongLong:
  555. kind = CompType::Kind::U64;
  556. break;
  557. case BuiltinType::Int:
  558. kind = CompType::Kind::I32;
  559. break;
  560. case BuiltinType::Min12Int:
  561. case BuiltinType::Short:
  562. kind = CompType::Kind::I16;
  563. break;
  564. case BuiltinType::LongLong:
  565. kind = CompType::Kind::I64;
  566. break;
  567. case BuiltinType::Min10Float:
  568. case BuiltinType::Half:
  569. if (bSNorm)
  570. kind = CompType::Kind::SNormF16;
  571. else if (bUNorm)
  572. kind = CompType::Kind::UNormF16;
  573. else
  574. kind = CompType::Kind::F16;
  575. break;
  576. case BuiltinType::Float:
  577. if (bSNorm)
  578. kind = CompType::Kind::SNormF32;
  579. else if (bUNorm)
  580. kind = CompType::Kind::UNormF32;
  581. else
  582. kind = CompType::Kind::F32;
  583. break;
  584. case BuiltinType::Double:
  585. if (bSNorm)
  586. kind = CompType::Kind::SNormF64;
  587. else if (bUNorm)
  588. kind = CompType::Kind::UNormF64;
  589. else
  590. kind = CompType::Kind::F64;
  591. break;
  592. case BuiltinType::Bool:
  593. kind = CompType::Kind::I1;
  594. break;
  595. }
  596. return kind;
  597. }
  598. static DxilSampler::SamplerKind KeywordToSamplerKind(llvm::StringRef keyword) {
  599. // TODO: refactor for faster search (switch by 1/2/3 first letters, then
  600. // compare)
  601. return llvm::StringSwitch<DxilSampler::SamplerKind>(keyword)
  602. .Case("SamplerState", DxilSampler::SamplerKind::Default)
  603. .Case("SamplerComparisonState", DxilSampler::SamplerKind::Comparison)
  604. .Default(DxilSampler::SamplerKind::Invalid);
  605. }
  606. MDNode *CGMSHLSLRuntime::GetOrAddResTypeMD(QualType resTy) {
  607. const RecordType *RT = resTy->getAs<RecordType>();
  608. if (!RT)
  609. return nullptr;
  610. RecordDecl *RD = RT->getDecl();
  611. SourceLocation loc = RD->getLocation();
  612. hlsl::DxilResourceBase::Class resClass = TypeToClass(resTy);
  613. llvm::Type *Ty = CGM.getTypes().ConvertType(resTy);
  614. auto it = resMetadataMap.find(Ty);
  615. if (it != resMetadataMap.end())
  616. return it->second;
  617. // Save resource type metadata.
  618. switch (resClass) {
  619. case DXIL::ResourceClass::UAV: {
  620. DxilResource UAV;
  621. // TODO: save globalcoherent to variable in EmitHLSLBuiltinCallExpr.
  622. SetUAVSRV(loc, resClass, &UAV, RD);
  623. // Set global symbol to save type.
  624. UAV.SetGlobalSymbol(UndefValue::get(Ty));
  625. MDNode *MD = m_pHLModule->DxilUAVToMDNode(UAV);
  626. resMetadataMap[Ty] = MD;
  627. return MD;
  628. } break;
  629. case DXIL::ResourceClass::SRV: {
  630. DxilResource SRV;
  631. SetUAVSRV(loc, resClass, &SRV, RD);
  632. // Set global symbol to save type.
  633. SRV.SetGlobalSymbol(UndefValue::get(Ty));
  634. MDNode *MD = m_pHLModule->DxilSRVToMDNode(SRV);
  635. resMetadataMap[Ty] = MD;
  636. return MD;
  637. } break;
  638. case DXIL::ResourceClass::Sampler: {
  639. DxilSampler S;
  640. DxilSampler::SamplerKind kind = KeywordToSamplerKind(RD->getName());
  641. S.SetSamplerKind(kind);
  642. // Set global symbol to save type.
  643. S.SetGlobalSymbol(UndefValue::get(Ty));
  644. MDNode *MD = m_pHLModule->DxilSamplerToMDNode(S);
  645. resMetadataMap[Ty] = MD;
  646. return MD;
  647. }
  648. default:
  649. // Skip OutputStream for GS.
  650. return nullptr;
  651. }
  652. }
  653. void CGMSHLSLRuntime::ConstructFieldAttributedAnnotation(
  654. DxilFieldAnnotation &fieldAnnotation, QualType fieldTy,
  655. bool bDefaultRowMajor) {
  656. QualType Ty = fieldTy;
  657. if (Ty->isReferenceType())
  658. Ty = Ty.getNonReferenceType();
  659. // Get element type.
  660. if (Ty->isArrayType()) {
  661. while (isa<clang::ArrayType>(Ty)) {
  662. const clang::ArrayType *ATy = dyn_cast<clang::ArrayType>(Ty);
  663. Ty = ATy->getElementType();
  664. }
  665. }
  666. QualType EltTy = Ty;
  667. if (hlsl::IsHLSLMatType(Ty)) {
  668. DxilMatrixAnnotation Matrix;
  669. Matrix.Orientation = bDefaultRowMajor ? MatrixOrientation::RowMajor
  670. : MatrixOrientation::ColumnMajor;
  671. if (const AttributedType *AT = dyn_cast<AttributedType>(Ty)) {
  672. switch (AT->getAttrKind()) {
  673. case AttributedType::Kind::attr_hlsl_column_major:
  674. Matrix.Orientation = MatrixOrientation::ColumnMajor;
  675. break;
  676. case AttributedType::Kind::attr_hlsl_row_major:
  677. Matrix.Orientation = MatrixOrientation::RowMajor;
  678. break;
  679. default:
  680. // Do nothing
  681. break;
  682. }
  683. }
  684. hlsl::GetHLSLMatRowColCount(Ty, Matrix.Rows, Matrix.Cols);
  685. fieldAnnotation.SetMatrixAnnotation(Matrix);
  686. EltTy = hlsl::GetHLSLMatElementType(Ty);
  687. }
  688. if (hlsl::IsHLSLVecType(Ty))
  689. EltTy = hlsl::GetHLSLVecElementType(Ty);
  690. if (IsHLSLResourceType(Ty)) {
  691. MDNode *MD = GetOrAddResTypeMD(Ty);
  692. fieldAnnotation.SetResourceAttribute(MD);
  693. }
  694. bool bSNorm = false;
  695. bool bUNorm = false;
  696. if (const AttributedType *AT = dyn_cast<AttributedType>(Ty)) {
  697. switch (AT->getAttrKind()) {
  698. case AttributedType::Kind::attr_hlsl_snorm:
  699. bSNorm = true;
  700. break;
  701. case AttributedType::Kind::attr_hlsl_unorm:
  702. bUNorm = true;
  703. break;
  704. default:
  705. // Do nothing
  706. break;
  707. }
  708. }
  709. if (EltTy->isBuiltinType()) {
  710. const BuiltinType *BTy = EltTy->getAs<BuiltinType>();
  711. CompType::Kind kind = BuiltinTyToCompTy(BTy, bSNorm, bUNorm);
  712. fieldAnnotation.SetCompType(kind);
  713. } else if (EltTy->isEnumeralType()) {
  714. const EnumType *ETy = EltTy->getAs<EnumType>();
  715. QualType type = ETy->getDecl()->getIntegerType();
  716. if (const BuiltinType *BTy =
  717. dyn_cast<BuiltinType>(type->getCanonicalTypeInternal()))
  718. fieldAnnotation.SetCompType(BuiltinTyToCompTy(BTy, bSNorm, bUNorm));
  719. } else
  720. DXASSERT(!bSNorm && !bUNorm,
  721. "snorm/unorm on invalid type, validate at handleHLSLTypeAttr");
  722. }
  723. static void ConstructFieldInterpolation(DxilFieldAnnotation &fieldAnnotation,
  724. FieldDecl *fieldDecl) {
  725. // Keep undefined for interpMode here.
  726. InterpolationMode InterpMode = {fieldDecl->hasAttr<HLSLNoInterpolationAttr>(),
  727. fieldDecl->hasAttr<HLSLLinearAttr>(),
  728. fieldDecl->hasAttr<HLSLNoPerspectiveAttr>(),
  729. fieldDecl->hasAttr<HLSLCentroidAttr>(),
  730. fieldDecl->hasAttr<HLSLSampleAttr>()};
  731. if (InterpMode.GetKind() != InterpolationMode::Kind::Undefined)
  732. fieldAnnotation.SetInterpolationMode(InterpMode);
  733. }
  734. unsigned CGMSHLSLRuntime::ConstructStructAnnotation(DxilStructAnnotation *annotation,
  735. const RecordDecl *RD,
  736. DxilTypeSystem &dxilTypeSys) {
  737. unsigned fieldIdx = 0;
  738. unsigned offset = 0;
  739. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  740. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  741. if (CXXRD->getNumBases()) {
  742. // Add base as field.
  743. for (const auto &I : CXXRD->bases()) {
  744. const CXXRecordDecl *BaseDecl =
  745. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  746. std::string fieldSemName = "";
  747. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  748. // Align offset.
  749. offset = AlignBaseOffset(parentTy, offset, bDefaultRowMajor, CGM,
  750. dataLayout);
  751. unsigned CBufferOffset = offset;
  752. unsigned arrayEltSize = 0;
  753. // Process field to make sure the size of field is ready.
  754. unsigned size =
  755. AddTypeAnnotation(parentTy, dxilTypeSys, arrayEltSize);
  756. // Update offset.
  757. offset += size;
  758. if (size > 0) {
  759. DxilFieldAnnotation &fieldAnnotation =
  760. annotation->GetFieldAnnotation(fieldIdx++);
  761. fieldAnnotation.SetCBufferOffset(CBufferOffset);
  762. fieldAnnotation.SetFieldName(BaseDecl->getNameAsString());
  763. }
  764. }
  765. }
  766. }
  767. for (auto fieldDecl : RD->fields()) {
  768. std::string fieldSemName = "";
  769. QualType fieldTy = fieldDecl->getType();
  770. // Align offset.
  771. offset = AlignBaseOffset(fieldTy, offset, bDefaultRowMajor, CGM, dataLayout);
  772. unsigned CBufferOffset = offset;
  773. bool userOffset = false;
  774. // Try to get info from fieldDecl.
  775. for (const hlsl::UnusualAnnotation *it :
  776. fieldDecl->getUnusualAnnotations()) {
  777. switch (it->getKind()) {
  778. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  779. const hlsl::SemanticDecl *sd = cast<hlsl::SemanticDecl>(it);
  780. fieldSemName = sd->SemanticName;
  781. } break;
  782. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  783. const hlsl::ConstantPacking *cp = cast<hlsl::ConstantPacking>(it);
  784. CBufferOffset = cp->Subcomponent << 2;
  785. CBufferOffset += cp->ComponentOffset;
  786. // Change to byte.
  787. CBufferOffset <<= 2;
  788. userOffset = true;
  789. } break;
  790. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  791. // register assignment only works on global constant.
  792. DiagnosticsEngine &Diags = CGM.getDiags();
  793. unsigned DiagID = Diags.getCustomDiagID(
  794. DiagnosticsEngine::Error,
  795. "location semantics cannot be specified on members.");
  796. Diags.Report(it->Loc, DiagID);
  797. return 0;
  798. } break;
  799. default:
  800. llvm_unreachable("only semantic for input/output");
  801. break;
  802. }
  803. }
  804. unsigned arrayEltSize = 0;
  805. // Process field to make sure the size of field is ready.
  806. unsigned size = AddTypeAnnotation(fieldDecl->getType(), dxilTypeSys, arrayEltSize);
  807. // Update offset.
  808. offset += size;
  809. DxilFieldAnnotation &fieldAnnotation = annotation->GetFieldAnnotation(fieldIdx++);
  810. ConstructFieldAttributedAnnotation(fieldAnnotation, fieldTy, bDefaultRowMajor);
  811. ConstructFieldInterpolation(fieldAnnotation, fieldDecl);
  812. if (fieldDecl->hasAttr<HLSLPreciseAttr>())
  813. fieldAnnotation.SetPrecise();
  814. fieldAnnotation.SetCBufferOffset(CBufferOffset);
  815. fieldAnnotation.SetFieldName(fieldDecl->getName());
  816. if (!fieldSemName.empty())
  817. fieldAnnotation.SetSemanticString(fieldSemName);
  818. }
  819. annotation->SetCBufferSize(offset);
  820. if (offset == 0) {
  821. annotation->MarkEmptyStruct();
  822. }
  823. return offset;
  824. }
  825. static bool IsElementInputOutputType(QualType Ty) {
  826. return Ty->isBuiltinType() || hlsl::IsHLSLVecMatType(Ty) || Ty->isEnumeralType();
  827. }
  828. // Return the size for constant buffer of each decl.
  829. unsigned CGMSHLSLRuntime::AddTypeAnnotation(QualType Ty,
  830. DxilTypeSystem &dxilTypeSys,
  831. unsigned &arrayEltSize) {
  832. QualType paramTy = Ty.getCanonicalType();
  833. if (const ReferenceType *RefType = dyn_cast<ReferenceType>(paramTy))
  834. paramTy = RefType->getPointeeType();
  835. // Get size.
  836. llvm::Type *Type = CGM.getTypes().ConvertType(paramTy);
  837. unsigned size = dataLayout.getTypeAllocSize(Type);
  838. if (IsHLSLMatType(Ty)) {
  839. unsigned col, row;
  840. llvm::Type *EltTy = HLMatrixLower::GetMatrixInfo(Type, col, row);
  841. bool b64Bit = dataLayout.getTypeAllocSize(EltTy) == 8;
  842. size = GetMatrixSizeInCB(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor,
  843. b64Bit);
  844. }
  845. // Skip element types.
  846. if (IsElementInputOutputType(paramTy))
  847. return size;
  848. else if (IsHLSLStreamOutputType(Ty)) {
  849. return AddTypeAnnotation(GetHLSLOutputPatchElementType(Ty), dxilTypeSys,
  850. arrayEltSize);
  851. } else if (IsHLSLInputPatchType(Ty))
  852. return AddTypeAnnotation(GetHLSLInputPatchElementType(Ty), dxilTypeSys,
  853. arrayEltSize);
  854. else if (IsHLSLOutputPatchType(Ty))
  855. return AddTypeAnnotation(GetHLSLOutputPatchElementType(Ty), dxilTypeSys,
  856. arrayEltSize);
  857. else if (const RecordType *RT = paramTy->getAsStructureType()) {
  858. RecordDecl *RD = RT->getDecl();
  859. llvm::StructType *ST = CGM.getTypes().ConvertRecordDeclType(RD);
  860. // Skip if already created.
  861. if (DxilStructAnnotation *annotation = dxilTypeSys.GetStructAnnotation(ST)) {
  862. unsigned structSize = annotation->GetCBufferSize();
  863. return structSize;
  864. }
  865. DxilStructAnnotation *annotation = dxilTypeSys.AddStructAnnotation(ST);
  866. return ConstructStructAnnotation(annotation, RD, dxilTypeSys);
  867. } else if (const RecordType *RT = dyn_cast<RecordType>(paramTy)) {
  868. // For this pointer.
  869. RecordDecl *RD = RT->getDecl();
  870. llvm::StructType *ST = CGM.getTypes().ConvertRecordDeclType(RD);
  871. // Skip if already created.
  872. if (DxilStructAnnotation *annotation = dxilTypeSys.GetStructAnnotation(ST)) {
  873. unsigned structSize = annotation->GetCBufferSize();
  874. return structSize;
  875. }
  876. DxilStructAnnotation *annotation = dxilTypeSys.AddStructAnnotation(ST);
  877. return ConstructStructAnnotation(annotation, RD, dxilTypeSys);
  878. } else if (IsHLSLResourceType(Ty)) {
  879. // Save result type info.
  880. AddTypeAnnotation(GetHLSLResourceResultType(Ty), dxilTypeSys, arrayEltSize);
  881. // Resource don't count for cbuffer size.
  882. return 0;
  883. } else {
  884. unsigned arraySize = 0;
  885. QualType arrayElementTy = Ty;
  886. if (Ty->isConstantArrayType()) {
  887. const ConstantArrayType *arrayTy =
  888. CGM.getContext().getAsConstantArrayType(Ty);
  889. DXASSERT(arrayTy != nullptr, "Must array type here");
  890. arraySize = arrayTy->getSize().getLimitedValue();
  891. arrayElementTy = arrayTy->getElementType();
  892. }
  893. else if (Ty->isIncompleteArrayType()) {
  894. const IncompleteArrayType *arrayTy = CGM.getContext().getAsIncompleteArrayType(Ty);
  895. arrayElementTy = arrayTy->getElementType();
  896. } else
  897. DXASSERT(0, "Must array type here");
  898. unsigned elementSize = AddTypeAnnotation(arrayElementTy, dxilTypeSys, arrayEltSize);
  899. // Only set arrayEltSize once.
  900. if (arrayEltSize == 0)
  901. arrayEltSize = elementSize;
  902. // Align to 4 * 4bytes.
  903. unsigned alignedSize = (elementSize + 15) & 0xfffffff0;
  904. return alignedSize * (arraySize - 1) + elementSize;
  905. }
  906. }
  907. static DxilResource::Kind KeywordToKind(StringRef keyword) {
  908. // TODO: refactor for faster search (switch by 1/2/3 first letters, then
  909. // compare)
  910. if (keyword == "Texture1D" || keyword == "RWTexture1D" || keyword == "RasterizerOrderedTexture1D")
  911. return DxilResource::Kind::Texture1D;
  912. if (keyword == "Texture2D" || keyword == "RWTexture2D" || keyword == "RasterizerOrderedTexture2D")
  913. return DxilResource::Kind::Texture2D;
  914. if (keyword == "Texture2DMS" || keyword == "RWTexture2DMS")
  915. return DxilResource::Kind::Texture2DMS;
  916. if (keyword == "Texture3D" || keyword == "RWTexture3D" || keyword == "RasterizerOrderedTexture3D")
  917. return DxilResource::Kind::Texture3D;
  918. if (keyword == "TextureCube" || keyword == "RWTextureCube")
  919. return DxilResource::Kind::TextureCube;
  920. if (keyword == "Texture1DArray" || keyword == "RWTexture1DArray" || keyword == "RasterizerOrderedTexture1DArray")
  921. return DxilResource::Kind::Texture1DArray;
  922. if (keyword == "Texture2DArray" || keyword == "RWTexture2DArray" || keyword == "RasterizerOrderedTexture2DArray")
  923. return DxilResource::Kind::Texture2DArray;
  924. if (keyword == "Texture2DMSArray" || keyword == "RWTexture2DMSArray")
  925. return DxilResource::Kind::Texture2DMSArray;
  926. if (keyword == "TextureCubeArray" || keyword == "RWTextureCubeArray")
  927. return DxilResource::Kind::TextureCubeArray;
  928. if (keyword == "ByteAddressBuffer" || keyword == "RWByteAddressBuffer" || keyword == "RasterizerOrderedByteAddressBuffer")
  929. return DxilResource::Kind::RawBuffer;
  930. if (keyword == "StructuredBuffer" || keyword == "RWStructuredBuffer" || keyword == "RasterizerOrderedStructuredBuffer")
  931. return DxilResource::Kind::StructuredBuffer;
  932. if (keyword == "AppendStructuredBuffer" || keyword == "ConsumeStructuredBuffer")
  933. return DxilResource::Kind::StructuredBuffer;
  934. // TODO: this is not efficient.
  935. bool isBuffer = keyword == "Buffer";
  936. isBuffer |= keyword == "RWBuffer";
  937. isBuffer |= keyword == "RasterizerOrderedBuffer";
  938. if (isBuffer)
  939. return DxilResource::Kind::TypedBuffer;
  940. if (keyword == "RaytracingAccelerationStructure")
  941. return DxilResource::Kind::RTAccelerationStructure;
  942. return DxilResource::Kind::Invalid;
  943. }
  944. void CGMSHLSLRuntime::AddHLSLFunctionInfo(Function *F, const FunctionDecl *FD) {
  945. // Add hlsl intrinsic attr
  946. unsigned intrinsicOpcode;
  947. StringRef intrinsicGroup;
  948. if (hlsl::GetIntrinsicOp(FD, intrinsicOpcode, intrinsicGroup)) {
  949. AddHLSLIntrinsicOpcodeToFunction(F, intrinsicOpcode);
  950. F->addFnAttr(hlsl::HLPrefix, intrinsicGroup);
  951. // Save resource type annotation.
  952. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  953. const CXXRecordDecl *RD = MD->getParent();
  954. // For nested case like sample_slice_type.
  955. if (const CXXRecordDecl *PRD =
  956. dyn_cast<CXXRecordDecl>(RD->getDeclContext())) {
  957. RD = PRD;
  958. }
  959. QualType recordTy = MD->getASTContext().getRecordType(RD);
  960. hlsl::DxilResourceBase::Class resClass = TypeToClass(recordTy);
  961. llvm::Type *Ty = CGM.getTypes().ConvertType(recordTy);
  962. llvm::FunctionType *FT = F->getFunctionType();
  963. // Save resource type metadata.
  964. switch (resClass) {
  965. case DXIL::ResourceClass::UAV: {
  966. MDNode *MD = GetOrAddResTypeMD(recordTy);
  967. DXASSERT(MD, "else invalid resource type");
  968. resMetadataMap[Ty] = MD;
  969. } break;
  970. case DXIL::ResourceClass::SRV: {
  971. MDNode *Meta = GetOrAddResTypeMD(recordTy);
  972. DXASSERT(Meta, "else invalid resource type");
  973. resMetadataMap[Ty] = Meta;
  974. if (FT->getNumParams() > 1) {
  975. QualType paramTy = MD->getParamDecl(0)->getType();
  976. // Add sampler type.
  977. if (TypeToClass(paramTy) == DXIL::ResourceClass::Sampler) {
  978. llvm::Type *Ty = FT->getParamType(1)->getPointerElementType();
  979. MDNode *MD = GetOrAddResTypeMD(paramTy);
  980. DXASSERT(MD, "else invalid resource type");
  981. resMetadataMap[Ty] = MD;
  982. }
  983. }
  984. } break;
  985. default:
  986. // Skip OutputStream for GS.
  987. break;
  988. }
  989. }
  990. if (intrinsicOpcode == (unsigned)IntrinsicOp::IOP_TraceRay) {
  991. QualType recordTy = FD->getParamDecl(0)->getType();
  992. llvm::Type *Ty = CGM.getTypes().ConvertType(recordTy);
  993. MDNode *MD = GetOrAddResTypeMD(recordTy);
  994. DXASSERT(MD, "else invalid resource type");
  995. resMetadataMap[Ty] = MD;
  996. }
  997. StringRef lower;
  998. if (hlsl::GetIntrinsicLowering(FD, lower))
  999. hlsl::SetHLLowerStrategy(F, lower);
  1000. // Don't need to add FunctionQual for intrinsic function.
  1001. return;
  1002. }
  1003. if (m_pHLModule->GetFloat32DenormMode() == DXIL::Float32DenormMode::FTZ) {
  1004. F->addFnAttr(DXIL::kFP32DenormKindString, DXIL::kFP32DenormValueFtzString);
  1005. }
  1006. else if (m_pHLModule->GetFloat32DenormMode() == DXIL::Float32DenormMode::Preserve) {
  1007. F->addFnAttr(DXIL::kFP32DenormKindString, DXIL::kFP32DenormValuePreserveString);
  1008. }
  1009. else if (m_pHLModule->GetFloat32DenormMode() == DXIL::Float32DenormMode::Any) {
  1010. F->addFnAttr(DXIL::kFP32DenormKindString, DXIL::kFP32DenormValueAnyString);
  1011. }
  1012. // Set entry function
  1013. const std::string &entryName = m_pHLModule->GetEntryFunctionName();
  1014. bool isEntry = FD->getNameAsString() == entryName;
  1015. if (isEntry) {
  1016. Entry.Func = F;
  1017. Entry.SL = FD->getLocation();
  1018. }
  1019. DiagnosticsEngine &Diags = CGM.getDiags();
  1020. std::unique_ptr<DxilFunctionProps> funcProps =
  1021. llvm::make_unique<DxilFunctionProps>();
  1022. funcProps->shaderKind = DXIL::ShaderKind::Invalid;
  1023. bool isCS = false;
  1024. bool isGS = false;
  1025. bool isHS = false;
  1026. bool isDS = false;
  1027. bool isVS = false;
  1028. bool isPS = false;
  1029. bool isRay = false;
  1030. if (const HLSLShaderAttr *Attr = FD->getAttr<HLSLShaderAttr>()) {
  1031. // Stage is already validate in HandleDeclAttributeForHLSL.
  1032. // Here just check first letter (or two).
  1033. switch (Attr->getStage()[0]) {
  1034. case 'c':
  1035. switch (Attr->getStage()[1]) {
  1036. case 'o':
  1037. isCS = true;
  1038. funcProps->shaderKind = DXIL::ShaderKind::Compute;
  1039. break;
  1040. case 'l':
  1041. isRay = true;
  1042. funcProps->shaderKind = DXIL::ShaderKind::ClosestHit;
  1043. break;
  1044. case 'a':
  1045. isRay = true;
  1046. funcProps->shaderKind = DXIL::ShaderKind::Callable;
  1047. break;
  1048. default:
  1049. break;
  1050. }
  1051. break;
  1052. case 'v':
  1053. isVS = true;
  1054. funcProps->shaderKind = DXIL::ShaderKind::Vertex;
  1055. break;
  1056. case 'h':
  1057. isHS = true;
  1058. funcProps->shaderKind = DXIL::ShaderKind::Hull;
  1059. break;
  1060. case 'd':
  1061. isDS = true;
  1062. funcProps->shaderKind = DXIL::ShaderKind::Domain;
  1063. break;
  1064. case 'g':
  1065. isGS = true;
  1066. funcProps->shaderKind = DXIL::ShaderKind::Geometry;
  1067. break;
  1068. case 'p':
  1069. isPS = true;
  1070. funcProps->shaderKind = DXIL::ShaderKind::Pixel;
  1071. break;
  1072. case 'r':
  1073. isRay = true;
  1074. funcProps->shaderKind = DXIL::ShaderKind::RayGeneration;
  1075. break;
  1076. case 'i':
  1077. isRay = true;
  1078. funcProps->shaderKind = DXIL::ShaderKind::Intersection;
  1079. break;
  1080. case 'a':
  1081. isRay = true;
  1082. funcProps->shaderKind = DXIL::ShaderKind::AnyHit;
  1083. break;
  1084. case 'm':
  1085. isRay = true;
  1086. funcProps->shaderKind = DXIL::ShaderKind::Miss;
  1087. break;
  1088. default:
  1089. break;
  1090. }
  1091. if (funcProps->shaderKind == DXIL::ShaderKind::Invalid) {
  1092. unsigned DiagID = Diags.getCustomDiagID(
  1093. DiagnosticsEngine::Error, "Invalid profile for shader attribute");
  1094. Diags.Report(Attr->getLocation(), DiagID);
  1095. }
  1096. if (isEntry && isRay) {
  1097. unsigned DiagID = Diags.getCustomDiagID(
  1098. DiagnosticsEngine::Error, "Ray function cannot be used as a global entry point");
  1099. Diags.Report(Attr->getLocation(), DiagID);
  1100. }
  1101. }
  1102. // Save patch constant function to patchConstantFunctionMap.
  1103. bool isPatchConstantFunction = false;
  1104. if (!isEntry && CGM.getContext().IsPatchConstantFunctionDecl(FD)) {
  1105. isPatchConstantFunction = true;
  1106. auto &PCI = patchConstantFunctionMap[FD->getName()];
  1107. PCI.SL = FD->getLocation();
  1108. PCI.Func = F;
  1109. ++PCI.NumOverloads;
  1110. for (ParmVarDecl *parmDecl : FD->parameters()) {
  1111. QualType Ty = parmDecl->getType();
  1112. if (IsHLSLOutputPatchType(Ty)) {
  1113. funcProps->ShaderProps.HS.outputControlPoints =
  1114. GetHLSLOutputPatchCount(parmDecl->getType());
  1115. } else if (IsHLSLInputPatchType(Ty)) {
  1116. funcProps->ShaderProps.HS.inputControlPoints =
  1117. GetHLSLInputPatchCount(parmDecl->getType());
  1118. }
  1119. }
  1120. funcProps->shaderKind = DXIL::ShaderKind::Hull;
  1121. }
  1122. const ShaderModel *SM = m_pHLModule->GetShaderModel();
  1123. if (isEntry) {
  1124. funcProps->shaderKind = SM->GetKind();
  1125. }
  1126. // Geometry shader.
  1127. if (const HLSLMaxVertexCountAttr *Attr =
  1128. FD->getAttr<HLSLMaxVertexCountAttr>()) {
  1129. isGS = true;
  1130. funcProps->shaderKind = DXIL::ShaderKind::Geometry;
  1131. funcProps->ShaderProps.GS.maxVertexCount = Attr->getCount();
  1132. funcProps->ShaderProps.GS.inputPrimitive = DXIL::InputPrimitive::Undefined;
  1133. if (isEntry && !SM->IsGS()) {
  1134. unsigned DiagID =
  1135. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1136. "attribute maxvertexcount only valid for GS.");
  1137. Diags.Report(Attr->getLocation(), DiagID);
  1138. return;
  1139. }
  1140. }
  1141. if (const HLSLInstanceAttr *Attr = FD->getAttr<HLSLInstanceAttr>()) {
  1142. unsigned instanceCount = Attr->getCount();
  1143. funcProps->ShaderProps.GS.instanceCount = instanceCount;
  1144. if (isEntry && !SM->IsGS()) {
  1145. unsigned DiagID =
  1146. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1147. "attribute maxvertexcount only valid for GS.");
  1148. Diags.Report(Attr->getLocation(), DiagID);
  1149. return;
  1150. }
  1151. } else {
  1152. // Set default instance count.
  1153. if (isGS)
  1154. funcProps->ShaderProps.GS.instanceCount = 1;
  1155. }
  1156. // Computer shader.
  1157. if (const HLSLNumThreadsAttr *Attr = FD->getAttr<HLSLNumThreadsAttr>()) {
  1158. isCS = true;
  1159. funcProps->shaderKind = DXIL::ShaderKind::Compute;
  1160. funcProps->ShaderProps.CS.numThreads[0] = Attr->getX();
  1161. funcProps->ShaderProps.CS.numThreads[1] = Attr->getY();
  1162. funcProps->ShaderProps.CS.numThreads[2] = Attr->getZ();
  1163. if (isEntry && !SM->IsCS()) {
  1164. unsigned DiagID = Diags.getCustomDiagID(
  1165. DiagnosticsEngine::Error, "attribute numthreads only valid for CS.");
  1166. Diags.Report(Attr->getLocation(), DiagID);
  1167. return;
  1168. }
  1169. }
  1170. // Hull shader.
  1171. if (const HLSLPatchConstantFuncAttr *Attr =
  1172. FD->getAttr<HLSLPatchConstantFuncAttr>()) {
  1173. if (isEntry && !SM->IsHS()) {
  1174. unsigned DiagID = Diags.getCustomDiagID(
  1175. DiagnosticsEngine::Error,
  1176. "attribute patchconstantfunc only valid for HS.");
  1177. Diags.Report(Attr->getLocation(), DiagID);
  1178. return;
  1179. }
  1180. isHS = true;
  1181. funcProps->shaderKind = DXIL::ShaderKind::Hull;
  1182. HSEntryPatchConstantFuncAttr[F] = Attr;
  1183. } else {
  1184. // TODO: This is a duplicate check. We also have this check in
  1185. // hlsl::DiagnoseTranslationUnit(clang::Sema*).
  1186. if (isEntry && SM->IsHS()) {
  1187. unsigned DiagID = Diags.getCustomDiagID(
  1188. DiagnosticsEngine::Error,
  1189. "HS entry point must have the patchconstantfunc attribute");
  1190. Diags.Report(FD->getLocation(), DiagID);
  1191. return;
  1192. }
  1193. }
  1194. if (const HLSLOutputControlPointsAttr *Attr =
  1195. FD->getAttr<HLSLOutputControlPointsAttr>()) {
  1196. if (isHS) {
  1197. funcProps->ShaderProps.HS.outputControlPoints = Attr->getCount();
  1198. } else if (isEntry && !SM->IsHS()) {
  1199. unsigned DiagID = Diags.getCustomDiagID(
  1200. DiagnosticsEngine::Error,
  1201. "attribute outputcontrolpoints only valid for HS.");
  1202. Diags.Report(Attr->getLocation(), DiagID);
  1203. return;
  1204. }
  1205. }
  1206. if (const HLSLPartitioningAttr *Attr = FD->getAttr<HLSLPartitioningAttr>()) {
  1207. if (isHS) {
  1208. DXIL::TessellatorPartitioning partition =
  1209. StringToPartitioning(Attr->getScheme());
  1210. funcProps->ShaderProps.HS.partition = partition;
  1211. } else if (isEntry && !SM->IsHS()) {
  1212. unsigned DiagID =
  1213. Diags.getCustomDiagID(DiagnosticsEngine::Warning,
  1214. "attribute partitioning only valid for HS.");
  1215. Diags.Report(Attr->getLocation(), DiagID);
  1216. }
  1217. }
  1218. if (const HLSLOutputTopologyAttr *Attr =
  1219. FD->getAttr<HLSLOutputTopologyAttr>()) {
  1220. if (isHS) {
  1221. DXIL::TessellatorOutputPrimitive primitive =
  1222. StringToTessOutputPrimitive(Attr->getTopology());
  1223. funcProps->ShaderProps.HS.outputPrimitive = primitive;
  1224. } else if (isEntry && !SM->IsHS()) {
  1225. unsigned DiagID =
  1226. Diags.getCustomDiagID(DiagnosticsEngine::Warning,
  1227. "attribute outputtopology only valid for HS.");
  1228. Diags.Report(Attr->getLocation(), DiagID);
  1229. }
  1230. }
  1231. if (isHS) {
  1232. funcProps->ShaderProps.HS.maxTessFactor = DXIL::kHSMaxTessFactorUpperBound;
  1233. }
  1234. if (const HLSLMaxTessFactorAttr *Attr =
  1235. FD->getAttr<HLSLMaxTessFactorAttr>()) {
  1236. if (isHS) {
  1237. // TODO: change getFactor to return float.
  1238. llvm::APInt intV(32, Attr->getFactor());
  1239. funcProps->ShaderProps.HS.maxTessFactor = intV.bitsToFloat();
  1240. } else if (isEntry && !SM->IsHS()) {
  1241. unsigned DiagID =
  1242. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1243. "attribute maxtessfactor only valid for HS.");
  1244. Diags.Report(Attr->getLocation(), DiagID);
  1245. return;
  1246. }
  1247. }
  1248. // Hull or domain shader.
  1249. if (const HLSLDomainAttr *Attr = FD->getAttr<HLSLDomainAttr>()) {
  1250. if (isEntry && !SM->IsHS() && !SM->IsDS()) {
  1251. unsigned DiagID =
  1252. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1253. "attribute domain only valid for HS or DS.");
  1254. Diags.Report(Attr->getLocation(), DiagID);
  1255. return;
  1256. }
  1257. isDS = !isHS;
  1258. if (isDS)
  1259. funcProps->shaderKind = DXIL::ShaderKind::Domain;
  1260. DXIL::TessellatorDomain domain = StringToDomain(Attr->getDomainType());
  1261. if (isHS)
  1262. funcProps->ShaderProps.HS.domain = domain;
  1263. else
  1264. funcProps->ShaderProps.DS.domain = domain;
  1265. }
  1266. // Vertex shader.
  1267. if (const HLSLClipPlanesAttr *Attr = FD->getAttr<HLSLClipPlanesAttr>()) {
  1268. if (isEntry && !SM->IsVS()) {
  1269. unsigned DiagID = Diags.getCustomDiagID(
  1270. DiagnosticsEngine::Error, "attribute clipplane only valid for VS.");
  1271. Diags.Report(Attr->getLocation(), DiagID);
  1272. return;
  1273. }
  1274. isVS = true;
  1275. // The real job is done at EmitHLSLFunctionProlog where debug info is
  1276. // available. Only set shader kind here.
  1277. funcProps->shaderKind = DXIL::ShaderKind::Vertex;
  1278. }
  1279. // Pixel shader.
  1280. if (const HLSLEarlyDepthStencilAttr *Attr =
  1281. FD->getAttr<HLSLEarlyDepthStencilAttr>()) {
  1282. if (isEntry && !SM->IsPS()) {
  1283. unsigned DiagID = Diags.getCustomDiagID(
  1284. DiagnosticsEngine::Error,
  1285. "attribute earlydepthstencil only valid for PS.");
  1286. Diags.Report(Attr->getLocation(), DiagID);
  1287. return;
  1288. }
  1289. isPS = true;
  1290. funcProps->ShaderProps.PS.EarlyDepthStencil = true;
  1291. funcProps->shaderKind = DXIL::ShaderKind::Pixel;
  1292. }
  1293. const unsigned profileAttributes = isCS + isHS + isDS + isGS + isVS + isPS + isRay;
  1294. // TODO: check this in front-end and report error.
  1295. DXASSERT(profileAttributes < 2, "profile attributes are mutual exclusive");
  1296. if (isEntry) {
  1297. switch (funcProps->shaderKind) {
  1298. case ShaderModel::Kind::Compute:
  1299. case ShaderModel::Kind::Hull:
  1300. case ShaderModel::Kind::Domain:
  1301. case ShaderModel::Kind::Geometry:
  1302. case ShaderModel::Kind::Vertex:
  1303. case ShaderModel::Kind::Pixel:
  1304. DXASSERT(funcProps->shaderKind == SM->GetKind(),
  1305. "attribute profile not match entry function profile");
  1306. break;
  1307. }
  1308. }
  1309. DxilFunctionAnnotation *FuncAnnotation =
  1310. m_pHLModule->AddFunctionAnnotation(F);
  1311. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  1312. // Param Info
  1313. unsigned streamIndex = 0;
  1314. unsigned inputPatchCount = 0;
  1315. unsigned outputPatchCount = 0;
  1316. unsigned ArgNo = 0;
  1317. unsigned ParmIdx = 0;
  1318. if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FD)) {
  1319. QualType ThisTy = MethodDecl->getThisType(FD->getASTContext());
  1320. DxilParameterAnnotation &paramAnnotation =
  1321. FuncAnnotation->GetParameterAnnotation(ArgNo++);
  1322. // Construct annoation for this pointer.
  1323. ConstructFieldAttributedAnnotation(paramAnnotation, ThisTy,
  1324. bDefaultRowMajor);
  1325. }
  1326. // Ret Info
  1327. QualType retTy = FD->getReturnType();
  1328. DxilParameterAnnotation *pRetTyAnnotation = nullptr;
  1329. if (F->getReturnType()->isVoidTy() && !retTy->isVoidType()) {
  1330. // SRet.
  1331. pRetTyAnnotation = &FuncAnnotation->GetParameterAnnotation(ArgNo++);
  1332. } else {
  1333. pRetTyAnnotation = &FuncAnnotation->GetRetTypeAnnotation();
  1334. }
  1335. DxilParameterAnnotation &retTyAnnotation = *pRetTyAnnotation;
  1336. // keep Undefined here, we cannot decide for struct
  1337. retTyAnnotation.SetInterpolationMode(
  1338. GetInterpMode(FD, CompType::Kind::Invalid, /*bKeepUndefined*/ true)
  1339. .GetKind());
  1340. SourceLocation retTySemanticLoc = SetSemantic(FD, retTyAnnotation);
  1341. retTyAnnotation.SetParamInputQual(DxilParamInputQual::Out);
  1342. if (isEntry) {
  1343. CheckParameterAnnotation(retTySemanticLoc, retTyAnnotation,
  1344. /*isPatchConstantFunction*/ false);
  1345. }
  1346. if (isRay && !retTy->isVoidType()) {
  1347. Diags.Report(FD->getLocation(), Diags.getCustomDiagID(
  1348. DiagnosticsEngine::Error, "return type for ray tracing shaders must be void"));
  1349. }
  1350. ConstructFieldAttributedAnnotation(retTyAnnotation, retTy, bDefaultRowMajor);
  1351. if (FD->hasAttr<HLSLPreciseAttr>())
  1352. retTyAnnotation.SetPrecise();
  1353. if (isRay) {
  1354. funcProps->ShaderProps.Ray.payloadSizeInBytes = 0;
  1355. funcProps->ShaderProps.Ray.attributeSizeInBytes = 0;
  1356. }
  1357. for (; ArgNo < F->arg_size(); ++ArgNo, ++ParmIdx) {
  1358. DxilParameterAnnotation &paramAnnotation =
  1359. FuncAnnotation->GetParameterAnnotation(ArgNo);
  1360. const ParmVarDecl *parmDecl = FD->getParamDecl(ParmIdx);
  1361. ConstructFieldAttributedAnnotation(paramAnnotation, parmDecl->getType(),
  1362. bDefaultRowMajor);
  1363. if (parmDecl->hasAttr<HLSLPreciseAttr>())
  1364. paramAnnotation.SetPrecise();
  1365. // keep Undefined here, we cannot decide for struct
  1366. InterpolationMode paramIM =
  1367. GetInterpMode(parmDecl, CompType::Kind::Invalid, KeepUndefinedTrue);
  1368. paramAnnotation.SetInterpolationMode(paramIM);
  1369. SourceLocation paramSemanticLoc = SetSemantic(parmDecl, paramAnnotation);
  1370. DxilParamInputQual dxilInputQ = DxilParamInputQual::In;
  1371. if (parmDecl->hasAttr<HLSLInOutAttr>())
  1372. dxilInputQ = DxilParamInputQual::Inout;
  1373. else if (parmDecl->hasAttr<HLSLOutAttr>())
  1374. dxilInputQ = DxilParamInputQual::Out;
  1375. if (parmDecl->hasAttr<HLSLOutAttr>() && parmDecl->hasAttr<HLSLInAttr>())
  1376. dxilInputQ = DxilParamInputQual::Inout;
  1377. DXIL::InputPrimitive inputPrimitive = DXIL::InputPrimitive::Undefined;
  1378. if (IsHLSLOutputPatchType(parmDecl->getType())) {
  1379. outputPatchCount++;
  1380. if (dxilInputQ != DxilParamInputQual::In) {
  1381. unsigned DiagID = Diags.getCustomDiagID(
  1382. DiagnosticsEngine::Error,
  1383. "OutputPatch should not be out/inout parameter");
  1384. Diags.Report(parmDecl->getLocation(), DiagID);
  1385. continue;
  1386. }
  1387. dxilInputQ = DxilParamInputQual::OutputPatch;
  1388. if (isDS)
  1389. funcProps->ShaderProps.DS.inputControlPoints =
  1390. GetHLSLOutputPatchCount(parmDecl->getType());
  1391. } else if (IsHLSLInputPatchType(parmDecl->getType())) {
  1392. inputPatchCount++;
  1393. if (dxilInputQ != DxilParamInputQual::In) {
  1394. unsigned DiagID = Diags.getCustomDiagID(
  1395. DiagnosticsEngine::Error,
  1396. "InputPatch should not be out/inout parameter");
  1397. Diags.Report(parmDecl->getLocation(), DiagID);
  1398. continue;
  1399. }
  1400. dxilInputQ = DxilParamInputQual::InputPatch;
  1401. if (isHS) {
  1402. funcProps->ShaderProps.HS.inputControlPoints =
  1403. GetHLSLInputPatchCount(parmDecl->getType());
  1404. } else if (isGS) {
  1405. inputPrimitive = (DXIL::InputPrimitive)(
  1406. (unsigned)DXIL::InputPrimitive::ControlPointPatch1 +
  1407. GetHLSLInputPatchCount(parmDecl->getType()) - 1);
  1408. }
  1409. } else if (IsHLSLStreamOutputType(parmDecl->getType())) {
  1410. // TODO: validation this at ASTContext::getFunctionType in
  1411. // AST/ASTContext.cpp
  1412. DXASSERT(dxilInputQ == DxilParamInputQual::Inout,
  1413. "stream output parameter must be inout");
  1414. switch (streamIndex) {
  1415. case 0:
  1416. dxilInputQ = DxilParamInputQual::OutStream0;
  1417. break;
  1418. case 1:
  1419. dxilInputQ = DxilParamInputQual::OutStream1;
  1420. break;
  1421. case 2:
  1422. dxilInputQ = DxilParamInputQual::OutStream2;
  1423. break;
  1424. case 3:
  1425. default:
  1426. // TODO: validation this at ASTContext::getFunctionType in
  1427. // AST/ASTContext.cpp
  1428. DXASSERT(streamIndex == 3, "stream number out of bound");
  1429. dxilInputQ = DxilParamInputQual::OutStream3;
  1430. break;
  1431. }
  1432. DXIL::PrimitiveTopology &streamTopology =
  1433. funcProps->ShaderProps.GS.streamPrimitiveTopologies[streamIndex];
  1434. if (IsHLSLPointStreamType(parmDecl->getType()))
  1435. streamTopology = DXIL::PrimitiveTopology::PointList;
  1436. else if (IsHLSLLineStreamType(parmDecl->getType()))
  1437. streamTopology = DXIL::PrimitiveTopology::LineStrip;
  1438. else {
  1439. DXASSERT(IsHLSLTriangleStreamType(parmDecl->getType()),
  1440. "invalid StreamType");
  1441. streamTopology = DXIL::PrimitiveTopology::TriangleStrip;
  1442. }
  1443. if (streamIndex > 0) {
  1444. bool bAllPoint =
  1445. streamTopology == DXIL::PrimitiveTopology::PointList &&
  1446. funcProps->ShaderProps.GS.streamPrimitiveTopologies[0] ==
  1447. DXIL::PrimitiveTopology::PointList;
  1448. if (!bAllPoint) {
  1449. unsigned DiagID = Diags.getCustomDiagID(
  1450. DiagnosticsEngine::Error, "when multiple GS output streams are "
  1451. "used they must be pointlists.");
  1452. Diags.Report(FD->getLocation(), DiagID);
  1453. }
  1454. }
  1455. streamIndex++;
  1456. }
  1457. unsigned GsInputArrayDim = 0;
  1458. if (parmDecl->hasAttr<HLSLTriangleAttr>()) {
  1459. inputPrimitive = DXIL::InputPrimitive::Triangle;
  1460. GsInputArrayDim = 3;
  1461. } else if (parmDecl->hasAttr<HLSLTriangleAdjAttr>()) {
  1462. inputPrimitive = DXIL::InputPrimitive::TriangleWithAdjacency;
  1463. GsInputArrayDim = 6;
  1464. } else if (parmDecl->hasAttr<HLSLPointAttr>()) {
  1465. inputPrimitive = DXIL::InputPrimitive::Point;
  1466. GsInputArrayDim = 1;
  1467. } else if (parmDecl->hasAttr<HLSLLineAdjAttr>()) {
  1468. inputPrimitive = DXIL::InputPrimitive::LineWithAdjacency;
  1469. GsInputArrayDim = 4;
  1470. } else if (parmDecl->hasAttr<HLSLLineAttr>()) {
  1471. inputPrimitive = DXIL::InputPrimitive::Line;
  1472. GsInputArrayDim = 2;
  1473. }
  1474. if (inputPrimitive != DXIL::InputPrimitive::Undefined) {
  1475. // Set to InputPrimitive for GS.
  1476. dxilInputQ = DxilParamInputQual::InputPrimitive;
  1477. if (funcProps->ShaderProps.GS.inputPrimitive ==
  1478. DXIL::InputPrimitive::Undefined) {
  1479. funcProps->ShaderProps.GS.inputPrimitive = inputPrimitive;
  1480. } else if (funcProps->ShaderProps.GS.inputPrimitive != inputPrimitive) {
  1481. unsigned DiagID = Diags.getCustomDiagID(
  1482. DiagnosticsEngine::Error, "input parameter conflicts with geometry "
  1483. "specifier of previous input parameters");
  1484. Diags.Report(parmDecl->getLocation(), DiagID);
  1485. }
  1486. }
  1487. if (GsInputArrayDim != 0) {
  1488. QualType Ty = parmDecl->getType();
  1489. if (!Ty->isConstantArrayType()) {
  1490. unsigned DiagID = Diags.getCustomDiagID(
  1491. DiagnosticsEngine::Error,
  1492. "input types for geometry shader must be constant size arrays");
  1493. Diags.Report(parmDecl->getLocation(), DiagID);
  1494. } else {
  1495. const ConstantArrayType *CAT = cast<ConstantArrayType>(Ty);
  1496. if (CAT->getSize().getLimitedValue() != GsInputArrayDim) {
  1497. StringRef primtiveNames[] = {
  1498. "invalid", // 0
  1499. "point", // 1
  1500. "line", // 2
  1501. "triangle", // 3
  1502. "lineadj", // 4
  1503. "invalid", // 5
  1504. "triangleadj", // 6
  1505. };
  1506. DXASSERT(GsInputArrayDim < llvm::array_lengthof(primtiveNames),
  1507. "Invalid array dim");
  1508. unsigned DiagID = Diags.getCustomDiagID(
  1509. DiagnosticsEngine::Error, "array dimension for %0 must be %1");
  1510. Diags.Report(parmDecl->getLocation(), DiagID)
  1511. << primtiveNames[GsInputArrayDim] << GsInputArrayDim;
  1512. }
  1513. }
  1514. }
  1515. // Validate Ray Tracing function parameter (some validation may be pushed into front end)
  1516. if (isRay) {
  1517. switch (funcProps->shaderKind) {
  1518. case DXIL::ShaderKind::RayGeneration:
  1519. case DXIL::ShaderKind::Intersection:
  1520. // RayGeneration and Intersection shaders are not allowed to have any input parameters
  1521. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1522. DiagnosticsEngine::Error, "parameters are not allowed for %0 shader"))
  1523. << (funcProps->shaderKind == DXIL::ShaderKind::RayGeneration ?
  1524. "raygeneration" : "intersection");
  1525. break;
  1526. case DXIL::ShaderKind::AnyHit:
  1527. case DXIL::ShaderKind::ClosestHit:
  1528. if (0 == ArgNo && dxilInputQ != DxilParamInputQual::Inout) {
  1529. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1530. DiagnosticsEngine::Error,
  1531. "ray payload parameter must be inout"));
  1532. } else if (1 == ArgNo && dxilInputQ != DxilParamInputQual::In) {
  1533. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1534. DiagnosticsEngine::Error,
  1535. "intersection attributes parameter must be in"));
  1536. } else if (ArgNo > 1) {
  1537. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1538. DiagnosticsEngine::Error,
  1539. "too many parameters, expected payload and attributes parameters only."));
  1540. }
  1541. if (ArgNo < 2) {
  1542. if (!IsHLSLNumericUserDefinedType(parmDecl->getType())) {
  1543. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1544. DiagnosticsEngine::Error,
  1545. "payload and attribute structures must be user defined types with only numeric contents."));
  1546. } else {
  1547. DataLayout DL(&this->TheModule);
  1548. unsigned size = DL.getTypeAllocSize(F->getFunctionType()->getFunctionParamType(ArgNo)->getPointerElementType());
  1549. if (0 == ArgNo)
  1550. funcProps->ShaderProps.Ray.payloadSizeInBytes = size;
  1551. else
  1552. funcProps->ShaderProps.Ray.attributeSizeInBytes = size;
  1553. }
  1554. }
  1555. break;
  1556. case DXIL::ShaderKind::Miss:
  1557. if (ArgNo > 0) {
  1558. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1559. DiagnosticsEngine::Error,
  1560. "only one parameter (ray payload) allowed for miss shader"));
  1561. } else if (dxilInputQ != DxilParamInputQual::Inout) {
  1562. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1563. DiagnosticsEngine::Error,
  1564. "ray payload parameter must be declared inout"));
  1565. }
  1566. if (ArgNo < 1) {
  1567. if (!IsHLSLNumericUserDefinedType(parmDecl->getType())) {
  1568. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1569. DiagnosticsEngine::Error,
  1570. "ray payload parameter must be a user defined type with only numeric contents."));
  1571. } else {
  1572. DataLayout DL(&this->TheModule);
  1573. unsigned size = DL.getTypeAllocSize(F->getFunctionType()->getFunctionParamType(ArgNo)->getPointerElementType());
  1574. funcProps->ShaderProps.Ray.payloadSizeInBytes = size;
  1575. }
  1576. }
  1577. break;
  1578. case DXIL::ShaderKind::Callable:
  1579. if (ArgNo > 0) {
  1580. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1581. DiagnosticsEngine::Error,
  1582. "only one parameter allowed for callable shader"));
  1583. } else if (dxilInputQ != DxilParamInputQual::Inout) {
  1584. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1585. DiagnosticsEngine::Error,
  1586. "callable parameter must be declared inout"));
  1587. }
  1588. if (ArgNo < 1) {
  1589. if (!IsHLSLNumericUserDefinedType(parmDecl->getType())) {
  1590. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1591. DiagnosticsEngine::Error,
  1592. "callable parameter must be a user defined type with only numeric contents."));
  1593. } else {
  1594. DataLayout DL(&this->TheModule);
  1595. unsigned size = DL.getTypeAllocSize(F->getFunctionType()->getFunctionParamType(ArgNo)->getPointerElementType());
  1596. funcProps->ShaderProps.Ray.paramSizeInBytes = size;
  1597. }
  1598. }
  1599. break;
  1600. }
  1601. }
  1602. paramAnnotation.SetParamInputQual(dxilInputQ);
  1603. if (isEntry) {
  1604. CheckParameterAnnotation(paramSemanticLoc, paramAnnotation,
  1605. /*isPatchConstantFunction*/ false);
  1606. }
  1607. }
  1608. if (inputPatchCount > 1) {
  1609. unsigned DiagID = Diags.getCustomDiagID(
  1610. DiagnosticsEngine::Error, "may only have one InputPatch parameter");
  1611. Diags.Report(FD->getLocation(), DiagID);
  1612. }
  1613. if (outputPatchCount > 1) {
  1614. unsigned DiagID = Diags.getCustomDiagID(
  1615. DiagnosticsEngine::Error, "may only have one OutputPatch parameter");
  1616. Diags.Report(FD->getLocation(), DiagID);
  1617. }
  1618. // If Shader is a ray shader that requires parameters, make sure size is non-zero
  1619. if (isRay) {
  1620. bool bNeedsAttributes = false;
  1621. bool bNeedsPayload = false;
  1622. switch (funcProps->shaderKind) {
  1623. case DXIL::ShaderKind::AnyHit:
  1624. case DXIL::ShaderKind::ClosestHit:
  1625. bNeedsAttributes = true;
  1626. case DXIL::ShaderKind::Miss:
  1627. bNeedsPayload = true;
  1628. case DXIL::ShaderKind::Callable:
  1629. if (0 == funcProps->ShaderProps.Ray.payloadSizeInBytes) {
  1630. unsigned DiagID = bNeedsPayload ?
  1631. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1632. "shader must include inout payload structure parameter.") :
  1633. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1634. "shader must include inout parameter structure.");
  1635. Diags.Report(FD->getLocation(), DiagID);
  1636. }
  1637. }
  1638. if (bNeedsAttributes &&
  1639. 0 == funcProps->ShaderProps.Ray.attributeSizeInBytes) {
  1640. Diags.Report(FD->getLocation(), Diags.getCustomDiagID(
  1641. DiagnosticsEngine::Error,
  1642. "shader must include attributes structure parameter."));
  1643. }
  1644. }
  1645. // Type annotation for parameters and return type.
  1646. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  1647. unsigned arrayEltSize = 0;
  1648. AddTypeAnnotation(FD->getReturnType(), dxilTypeSys, arrayEltSize);
  1649. // Type annotation for this pointer.
  1650. if (const CXXMethodDecl *MFD = dyn_cast<CXXMethodDecl>(FD)) {
  1651. const CXXRecordDecl *RD = MFD->getParent();
  1652. QualType Ty = CGM.getContext().getTypeDeclType(RD);
  1653. AddTypeAnnotation(Ty, dxilTypeSys, arrayEltSize);
  1654. }
  1655. for (const ValueDecl *param : FD->params()) {
  1656. QualType Ty = param->getType();
  1657. AddTypeAnnotation(Ty, dxilTypeSys, arrayEltSize);
  1658. }
  1659. // Only add functionProps when exist.
  1660. if (profileAttributes || isEntry)
  1661. m_pHLModule->AddDxilFunctionProps(F, funcProps);
  1662. if (isPatchConstantFunction)
  1663. patchConstantFunctionPropsMap[F] = std::move(funcProps);
  1664. // Save F to entry map.
  1665. if (profileAttributes) {
  1666. if (entryFunctionMap.count(FD->getName())) {
  1667. DiagnosticsEngine &Diags = CGM.getDiags();
  1668. unsigned DiagID = Diags.getCustomDiagID(
  1669. DiagnosticsEngine::Error,
  1670. "redefinition of %0");
  1671. Diags.Report(FD->getLocStart(), DiagID) << FD->getName();
  1672. }
  1673. auto &Entry = entryFunctionMap[FD->getNameAsString()];
  1674. Entry.SL = FD->getLocation();
  1675. Entry.Func= F;
  1676. }
  1677. // Add target-dependent experimental function attributes
  1678. for (const auto &Attr : FD->specific_attrs<HLSLExperimentalAttr>()) {
  1679. F->addFnAttr(Twine("exp-", Attr->getName()).str(), Attr->getValue());
  1680. }
  1681. }
  1682. void CGMSHLSLRuntime::EmitHLSLFunctionProlog(Function *F, const FunctionDecl *FD) {
  1683. // Support clip plane need debug info which not available when create function attribute.
  1684. if (const HLSLClipPlanesAttr *Attr = FD->getAttr<HLSLClipPlanesAttr>()) {
  1685. DxilFunctionProps &funcProps = m_pHLModule->GetDxilFunctionProps(F);
  1686. // Initialize to null.
  1687. memset(funcProps.ShaderProps.VS.clipPlanes, 0, sizeof(funcProps.ShaderProps.VS.clipPlanes));
  1688. // Create global for each clip plane, and use the clip plane val as init val.
  1689. auto AddClipPlane = [&](Expr *clipPlane, unsigned idx) {
  1690. if (DeclRefExpr *decl = dyn_cast<DeclRefExpr>(clipPlane)) {
  1691. const VarDecl *VD = cast<VarDecl>(decl->getDecl());
  1692. Constant *clipPlaneVal = CGM.GetAddrOfGlobalVar(VD);
  1693. funcProps.ShaderProps.VS.clipPlanes[idx] = clipPlaneVal;
  1694. if (m_bDebugInfo) {
  1695. CodeGenFunction CGF(CGM);
  1696. ApplyDebugLocation applyDebugLoc(CGF, clipPlane);
  1697. debugInfoMap[clipPlaneVal] = CGF.Builder.getCurrentDebugLocation();
  1698. }
  1699. } else {
  1700. // Must be a MemberExpr.
  1701. const MemberExpr *ME = cast<MemberExpr>(clipPlane);
  1702. CodeGenFunction CGF(CGM);
  1703. CodeGen::LValue LV = CGF.EmitMemberExpr(ME);
  1704. Value *addr = LV.getAddress();
  1705. funcProps.ShaderProps.VS.clipPlanes[idx] = cast<Constant>(addr);
  1706. if (m_bDebugInfo) {
  1707. CodeGenFunction CGF(CGM);
  1708. ApplyDebugLocation applyDebugLoc(CGF, clipPlane);
  1709. debugInfoMap[addr] = CGF.Builder.getCurrentDebugLocation();
  1710. }
  1711. }
  1712. };
  1713. if (Expr *clipPlane = Attr->getClipPlane1())
  1714. AddClipPlane(clipPlane, 0);
  1715. if (Expr *clipPlane = Attr->getClipPlane2())
  1716. AddClipPlane(clipPlane, 1);
  1717. if (Expr *clipPlane = Attr->getClipPlane3())
  1718. AddClipPlane(clipPlane, 2);
  1719. if (Expr *clipPlane = Attr->getClipPlane4())
  1720. AddClipPlane(clipPlane, 3);
  1721. if (Expr *clipPlane = Attr->getClipPlane5())
  1722. AddClipPlane(clipPlane, 4);
  1723. if (Expr *clipPlane = Attr->getClipPlane6())
  1724. AddClipPlane(clipPlane, 5);
  1725. clipPlaneFuncList.emplace_back(F);
  1726. }
  1727. }
  1728. void CGMSHLSLRuntime::AddControlFlowHint(CodeGenFunction &CGF, const Stmt &S,
  1729. llvm::TerminatorInst *TI,
  1730. ArrayRef<const Attr *> Attrs) {
  1731. // Build hints.
  1732. bool bNoBranchFlatten = true;
  1733. bool bBranch = false;
  1734. bool bFlatten = false;
  1735. std::vector<DXIL::ControlFlowHint> hints;
  1736. for (const auto *Attr : Attrs) {
  1737. if (isa<HLSLBranchAttr>(Attr)) {
  1738. hints.emplace_back(DXIL::ControlFlowHint::Branch);
  1739. bNoBranchFlatten = false;
  1740. bBranch = true;
  1741. }
  1742. else if (isa<HLSLFlattenAttr>(Attr)) {
  1743. hints.emplace_back(DXIL::ControlFlowHint::Flatten);
  1744. bNoBranchFlatten = false;
  1745. bFlatten = true;
  1746. } else if (isa<HLSLForceCaseAttr>(Attr)) {
  1747. if (isa<SwitchStmt>(&S)) {
  1748. hints.emplace_back(DXIL::ControlFlowHint::ForceCase);
  1749. }
  1750. }
  1751. // Ignore fastopt, allow_uav_condition and call for now.
  1752. }
  1753. if (bNoBranchFlatten) {
  1754. // CHECK control flow option.
  1755. if (CGF.CGM.getCodeGenOpts().HLSLPreferControlFlow)
  1756. hints.emplace_back(DXIL::ControlFlowHint::Branch);
  1757. else if (CGF.CGM.getCodeGenOpts().HLSLAvoidControlFlow)
  1758. hints.emplace_back(DXIL::ControlFlowHint::Flatten);
  1759. }
  1760. if (bFlatten && bBranch) {
  1761. DiagnosticsEngine &Diags = CGM.getDiags();
  1762. unsigned DiagID = Diags.getCustomDiagID(
  1763. DiagnosticsEngine::Error,
  1764. "can't use branch and flatten attributes together");
  1765. Diags.Report(S.getLocStart(), DiagID);
  1766. }
  1767. if (hints.size()) {
  1768. // Add meta data to the instruction.
  1769. MDNode *hintsNode = DxilMDHelper::EmitControlFlowHints(Context, hints);
  1770. TI->setMetadata(DxilMDHelper::kDxilControlFlowHintMDName, hintsNode);
  1771. }
  1772. }
  1773. void CGMSHLSLRuntime::FinishAutoVar(CodeGenFunction &CGF, const VarDecl &D, llvm::Value *V) {
  1774. if (D.hasAttr<HLSLPreciseAttr>()) {
  1775. AllocaInst *AI = cast<AllocaInst>(V);
  1776. HLModule::MarkPreciseAttributeWithMetadata(AI);
  1777. }
  1778. // Add type annotation for local variable.
  1779. DxilTypeSystem &typeSys = m_pHLModule->GetTypeSystem();
  1780. unsigned arrayEltSize = 0;
  1781. AddTypeAnnotation(D.getType(), typeSys, arrayEltSize);
  1782. }
  1783. hlsl::InterpolationMode CGMSHLSLRuntime::GetInterpMode(const Decl *decl,
  1784. CompType compType,
  1785. bool bKeepUndefined) {
  1786. InterpolationMode Interp(
  1787. decl->hasAttr<HLSLNoInterpolationAttr>(), decl->hasAttr<HLSLLinearAttr>(),
  1788. decl->hasAttr<HLSLNoPerspectiveAttr>(), decl->hasAttr<HLSLCentroidAttr>(),
  1789. decl->hasAttr<HLSLSampleAttr>());
  1790. DXASSERT(Interp.IsValid(), "otherwise front-end missing validation");
  1791. if (Interp.IsUndefined() && !bKeepUndefined) {
  1792. // Type-based default: linear for floats, constant for others.
  1793. if (compType.IsFloatTy())
  1794. Interp = InterpolationMode::Kind::Linear;
  1795. else
  1796. Interp = InterpolationMode::Kind::Constant;
  1797. }
  1798. return Interp;
  1799. }
  1800. hlsl::CompType CGMSHLSLRuntime::GetCompType(const BuiltinType *BT) {
  1801. hlsl::CompType ElementType = hlsl::CompType::getInvalid();
  1802. switch (BT->getKind()) {
  1803. case BuiltinType::Bool:
  1804. ElementType = hlsl::CompType::getI1();
  1805. break;
  1806. case BuiltinType::Double:
  1807. ElementType = hlsl::CompType::getF64();
  1808. break;
  1809. case BuiltinType::Float:
  1810. ElementType = hlsl::CompType::getF32();
  1811. break;
  1812. case BuiltinType::Min10Float:
  1813. case BuiltinType::Half:
  1814. ElementType = hlsl::CompType::getF16();
  1815. break;
  1816. case BuiltinType::Int:
  1817. ElementType = hlsl::CompType::getI32();
  1818. break;
  1819. case BuiltinType::LongLong:
  1820. ElementType = hlsl::CompType::getI64();
  1821. break;
  1822. case BuiltinType::Min12Int:
  1823. case BuiltinType::Short:
  1824. ElementType = hlsl::CompType::getI16();
  1825. break;
  1826. case BuiltinType::UInt:
  1827. ElementType = hlsl::CompType::getU32();
  1828. break;
  1829. case BuiltinType::ULongLong:
  1830. ElementType = hlsl::CompType::getU64();
  1831. break;
  1832. case BuiltinType::UShort:
  1833. ElementType = hlsl::CompType::getU16();
  1834. break;
  1835. default:
  1836. llvm_unreachable("unsupported type");
  1837. break;
  1838. }
  1839. return ElementType;
  1840. }
  1841. /// Add resouce to the program
  1842. void CGMSHLSLRuntime::addResource(Decl *D) {
  1843. if (HLSLBufferDecl *BD = dyn_cast<HLSLBufferDecl>(D))
  1844. GetOrCreateCBuffer(BD);
  1845. else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1846. hlsl::DxilResourceBase::Class resClass = TypeToClass(VD->getType());
  1847. // skip decl has init which is resource.
  1848. if (VD->hasInit() && resClass != DXIL::ResourceClass::Invalid)
  1849. return;
  1850. // skip static global.
  1851. if (!VD->isExternallyVisible()) {
  1852. if (VD->hasInit() && VD->getType().isConstQualified()) {
  1853. Expr* InitExp = VD->getInit();
  1854. GlobalVariable *GV = cast<GlobalVariable>(CGM.GetAddrOfGlobalVar(VD));
  1855. // Only save const static global of struct type.
  1856. if (GV->getType()->getElementType()->isStructTy()) {
  1857. staticConstGlobalInitMap[InitExp] = GV;
  1858. }
  1859. }
  1860. return;
  1861. }
  1862. if (D->hasAttr<HLSLGroupSharedAttr>()) {
  1863. GlobalVariable *GV = cast<GlobalVariable>(CGM.GetAddrOfGlobalVar(VD));
  1864. m_pHLModule->AddGroupSharedVariable(GV);
  1865. return;
  1866. }
  1867. switch (resClass) {
  1868. case hlsl::DxilResourceBase::Class::Sampler:
  1869. AddSampler(VD);
  1870. break;
  1871. case hlsl::DxilResourceBase::Class::UAV:
  1872. case hlsl::DxilResourceBase::Class::SRV:
  1873. AddUAVSRV(VD, resClass);
  1874. break;
  1875. case hlsl::DxilResourceBase::Class::Invalid: {
  1876. // normal global constant, add to global CB
  1877. HLCBuffer &globalCB = GetGlobalCBuffer();
  1878. AddConstant(VD, globalCB);
  1879. break;
  1880. }
  1881. case DXIL::ResourceClass::CBuffer:
  1882. DXASSERT(0, "cbuffer should not be here");
  1883. break;
  1884. }
  1885. }
  1886. }
  1887. // TODO: collect such helper utility functions in one place.
  1888. static DxilResourceBase::Class KeywordToClass(const std::string &keyword) {
  1889. // TODO: refactor for faster search (switch by 1/2/3 first letters, then
  1890. // compare)
  1891. if (keyword == "SamplerState")
  1892. return DxilResourceBase::Class::Sampler;
  1893. if (keyword == "SamplerComparisonState")
  1894. return DxilResourceBase::Class::Sampler;
  1895. if (keyword == "ConstantBuffer")
  1896. return DxilResourceBase::Class::CBuffer;
  1897. if (keyword == "TextureBuffer")
  1898. return DxilResourceBase::Class::SRV;
  1899. bool isSRV = keyword == "Buffer";
  1900. isSRV |= keyword == "ByteAddressBuffer";
  1901. isSRV |= keyword == "RaytracingAccelerationStructure";
  1902. isSRV |= keyword == "StructuredBuffer";
  1903. isSRV |= keyword == "Texture1D";
  1904. isSRV |= keyword == "Texture1DArray";
  1905. isSRV |= keyword == "Texture2D";
  1906. isSRV |= keyword == "Texture2DArray";
  1907. isSRV |= keyword == "Texture3D";
  1908. isSRV |= keyword == "TextureCube";
  1909. isSRV |= keyword == "TextureCubeArray";
  1910. isSRV |= keyword == "Texture2DMS";
  1911. isSRV |= keyword == "Texture2DMSArray";
  1912. if (isSRV)
  1913. return DxilResourceBase::Class::SRV;
  1914. bool isUAV = keyword == "RWBuffer";
  1915. isUAV |= keyword == "RWByteAddressBuffer";
  1916. isUAV |= keyword == "RWStructuredBuffer";
  1917. isUAV |= keyword == "RWTexture1D";
  1918. isUAV |= keyword == "RWTexture1DArray";
  1919. isUAV |= keyword == "RWTexture2D";
  1920. isUAV |= keyword == "RWTexture2DArray";
  1921. isUAV |= keyword == "RWTexture3D";
  1922. isUAV |= keyword == "RWTextureCube";
  1923. isUAV |= keyword == "RWTextureCubeArray";
  1924. isUAV |= keyword == "RWTexture2DMS";
  1925. isUAV |= keyword == "RWTexture2DMSArray";
  1926. isUAV |= keyword == "AppendStructuredBuffer";
  1927. isUAV |= keyword == "ConsumeStructuredBuffer";
  1928. isUAV |= keyword == "RasterizerOrderedBuffer";
  1929. isUAV |= keyword == "RasterizerOrderedByteAddressBuffer";
  1930. isUAV |= keyword == "RasterizerOrderedStructuredBuffer";
  1931. isUAV |= keyword == "RasterizerOrderedTexture1D";
  1932. isUAV |= keyword == "RasterizerOrderedTexture1DArray";
  1933. isUAV |= keyword == "RasterizerOrderedTexture2D";
  1934. isUAV |= keyword == "RasterizerOrderedTexture2DArray";
  1935. isUAV |= keyword == "RasterizerOrderedTexture3D";
  1936. if (isUAV)
  1937. return DxilResourceBase::Class::UAV;
  1938. return DxilResourceBase::Class::Invalid;
  1939. }
  1940. // This should probably be refactored to ASTContextHLSL, and follow types
  1941. // rather than do string comparisons.
  1942. DXIL::ResourceClass
  1943. hlsl::GetResourceClassForType(const clang::ASTContext &context,
  1944. clang::QualType Ty) {
  1945. Ty = Ty.getCanonicalType();
  1946. if (const clang::ArrayType *arrayType = context.getAsArrayType(Ty)) {
  1947. return GetResourceClassForType(context, arrayType->getElementType());
  1948. } else if (const RecordType *RT = Ty->getAsStructureType()) {
  1949. return KeywordToClass(RT->getDecl()->getName());
  1950. } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
  1951. if (const ClassTemplateSpecializationDecl *templateDecl =
  1952. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl())) {
  1953. return KeywordToClass(templateDecl->getName());
  1954. }
  1955. }
  1956. return hlsl::DxilResourceBase::Class::Invalid;
  1957. }
  1958. hlsl::DxilResourceBase::Class CGMSHLSLRuntime::TypeToClass(clang::QualType Ty) {
  1959. return hlsl::GetResourceClassForType(CGM.getContext(), Ty);
  1960. }
  1961. uint32_t CGMSHLSLRuntime::AddSampler(VarDecl *samplerDecl) {
  1962. llvm::Constant *val = CGM.GetAddrOfGlobalVar(samplerDecl);
  1963. unique_ptr<DxilSampler> hlslRes(new DxilSampler);
  1964. hlslRes->SetLowerBound(UINT_MAX);
  1965. hlslRes->SetGlobalSymbol(cast<llvm::GlobalVariable>(val));
  1966. hlslRes->SetGlobalName(samplerDecl->getName());
  1967. QualType VarTy = samplerDecl->getType();
  1968. if (const clang::ArrayType *arrayType =
  1969. CGM.getContext().getAsArrayType(VarTy)) {
  1970. if (arrayType->isConstantArrayType()) {
  1971. uint32_t arraySize =
  1972. cast<ConstantArrayType>(arrayType)->getSize().getLimitedValue();
  1973. hlslRes->SetRangeSize(arraySize);
  1974. } else {
  1975. hlslRes->SetRangeSize(UINT_MAX);
  1976. }
  1977. // use elementTy
  1978. VarTy = arrayType->getElementType();
  1979. // Support more dim.
  1980. while (const clang::ArrayType *arrayType =
  1981. CGM.getContext().getAsArrayType(VarTy)) {
  1982. unsigned rangeSize = hlslRes->GetRangeSize();
  1983. if (arrayType->isConstantArrayType()) {
  1984. uint32_t arraySize =
  1985. cast<ConstantArrayType>(arrayType)->getSize().getLimitedValue();
  1986. if (rangeSize != UINT_MAX)
  1987. hlslRes->SetRangeSize(rangeSize * arraySize);
  1988. } else
  1989. hlslRes->SetRangeSize(UINT_MAX);
  1990. // use elementTy
  1991. VarTy = arrayType->getElementType();
  1992. }
  1993. } else
  1994. hlslRes->SetRangeSize(1);
  1995. const RecordType *RT = VarTy->getAs<RecordType>();
  1996. DxilSampler::SamplerKind kind = KeywordToSamplerKind(RT->getDecl()->getName());
  1997. hlslRes->SetSamplerKind(kind);
  1998. for (hlsl::UnusualAnnotation *it : samplerDecl->getUnusualAnnotations()) {
  1999. switch (it->getKind()) {
  2000. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  2001. hlsl::RegisterAssignment *ra = cast<hlsl::RegisterAssignment>(it);
  2002. hlslRes->SetLowerBound(ra->RegisterNumber);
  2003. hlslRes->SetSpaceID(ra->RegisterSpace);
  2004. break;
  2005. }
  2006. case hlsl::UnusualAnnotation::UA_SemanticDecl:
  2007. // Ignore Semantics
  2008. break;
  2009. case hlsl::UnusualAnnotation::UA_ConstantPacking:
  2010. // Should be handled by front-end
  2011. llvm_unreachable("packoffset on sampler");
  2012. break;
  2013. default:
  2014. llvm_unreachable("unknown UnusualAnnotation on sampler");
  2015. break;
  2016. }
  2017. }
  2018. hlslRes->SetID(m_pHLModule->GetSamplers().size());
  2019. return m_pHLModule->AddSampler(std::move(hlslRes));
  2020. }
  2021. static void CollectScalarTypes(std::vector<llvm::Type *> &scalarTys, llvm::Type *Ty) {
  2022. if (llvm::StructType *ST = dyn_cast<llvm::StructType>(Ty)) {
  2023. for (llvm::Type *EltTy : ST->elements()) {
  2024. CollectScalarTypes(scalarTys, EltTy);
  2025. }
  2026. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty)) {
  2027. llvm::Type *EltTy = AT->getElementType();
  2028. for (unsigned i=0;i<AT->getNumElements();i++) {
  2029. CollectScalarTypes(scalarTys, EltTy);
  2030. }
  2031. } else if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(Ty)) {
  2032. llvm::Type *EltTy = VT->getElementType();
  2033. for (unsigned i=0;i<VT->getNumElements();i++) {
  2034. CollectScalarTypes(scalarTys, EltTy);
  2035. }
  2036. } else {
  2037. scalarTys.emplace_back(Ty);
  2038. }
  2039. }
  2040. static void CollectScalarTypes(std::vector<QualType> &ScalarTys, QualType Ty) {
  2041. if (Ty->isRecordType()) {
  2042. if (hlsl::IsHLSLMatType(Ty)) {
  2043. QualType EltTy = hlsl::GetHLSLMatElementType(Ty);
  2044. unsigned row = 0;
  2045. unsigned col = 0;
  2046. hlsl::GetRowsAndCols(Ty, row, col);
  2047. unsigned size = col*row;
  2048. for (unsigned i = 0; i < size; i++) {
  2049. CollectScalarTypes(ScalarTys, EltTy);
  2050. }
  2051. } else if (hlsl::IsHLSLVecType(Ty)) {
  2052. QualType EltTy = hlsl::GetHLSLVecElementType(Ty);
  2053. unsigned row = 0;
  2054. unsigned col = 0;
  2055. hlsl::GetRowsAndColsForAny(Ty, row, col);
  2056. unsigned size = col;
  2057. for (unsigned i = 0; i < size; i++) {
  2058. CollectScalarTypes(ScalarTys, EltTy);
  2059. }
  2060. } else {
  2061. const RecordType *RT = Ty->getAsStructureType();
  2062. // For CXXRecord.
  2063. if (!RT)
  2064. RT = Ty->getAs<RecordType>();
  2065. RecordDecl *RD = RT->getDecl();
  2066. for (FieldDecl *field : RD->fields())
  2067. CollectScalarTypes(ScalarTys, field->getType());
  2068. }
  2069. } else if (Ty->isArrayType()) {
  2070. const clang::ArrayType *AT = Ty->getAsArrayTypeUnsafe();
  2071. QualType EltTy = AT->getElementType();
  2072. // Set it to 5 for unsized array.
  2073. unsigned size = 5;
  2074. if (AT->isConstantArrayType()) {
  2075. size = cast<ConstantArrayType>(AT)->getSize().getLimitedValue();
  2076. }
  2077. for (unsigned i=0;i<size;i++) {
  2078. CollectScalarTypes(ScalarTys, EltTy);
  2079. }
  2080. } else {
  2081. ScalarTys.emplace_back(Ty);
  2082. }
  2083. }
  2084. bool CGMSHLSLRuntime::SetUAVSRV(SourceLocation loc,
  2085. hlsl::DxilResourceBase::Class resClass,
  2086. DxilResource *hlslRes, const RecordDecl *RD) {
  2087. hlsl::DxilResource::Kind kind = KeywordToKind(RD->getName());
  2088. hlslRes->SetKind(kind);
  2089. // Get the result type from handle field.
  2090. FieldDecl *FD = *(RD->field_begin());
  2091. DXASSERT(FD->getName() == "h", "must be handle field");
  2092. QualType resultTy = FD->getType();
  2093. // Type annotation for result type of resource.
  2094. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  2095. unsigned arrayEltSize = 0;
  2096. AddTypeAnnotation(QualType(RD->getTypeForDecl(),0), dxilTypeSys, arrayEltSize);
  2097. if (kind == hlsl::DxilResource::Kind::Texture2DMS ||
  2098. kind == hlsl::DxilResource::Kind::Texture2DMSArray) {
  2099. const ClassTemplateSpecializationDecl *templateDecl =
  2100. dyn_cast<ClassTemplateSpecializationDecl>(RD);
  2101. const clang::TemplateArgument &sampleCountArg =
  2102. templateDecl->getTemplateArgs()[1];
  2103. uint32_t sampleCount = sampleCountArg.getAsIntegral().getLimitedValue();
  2104. hlslRes->SetSampleCount(sampleCount);
  2105. }
  2106. if (kind != hlsl::DxilResource::Kind::StructuredBuffer) {
  2107. QualType Ty = resultTy;
  2108. QualType EltTy = Ty;
  2109. if (hlsl::IsHLSLVecType(Ty)) {
  2110. EltTy = hlsl::GetHLSLVecElementType(Ty);
  2111. } else if (hlsl::IsHLSLMatType(Ty)) {
  2112. EltTy = hlsl::GetHLSLMatElementType(Ty);
  2113. } else if (resultTy->isAggregateType()) {
  2114. // Struct or array in a none-struct resource.
  2115. std::vector<QualType> ScalarTys;
  2116. CollectScalarTypes(ScalarTys, resultTy);
  2117. unsigned size = ScalarTys.size();
  2118. if (size == 0) {
  2119. DiagnosticsEngine &Diags = CGM.getDiags();
  2120. unsigned DiagID = Diags.getCustomDiagID(
  2121. DiagnosticsEngine::Error,
  2122. "object's templated type must have at least one element");
  2123. Diags.Report(loc, DiagID);
  2124. return false;
  2125. }
  2126. if (size > 4) {
  2127. DiagnosticsEngine &Diags = CGM.getDiags();
  2128. unsigned DiagID = Diags.getCustomDiagID(
  2129. DiagnosticsEngine::Error, "elements of typed buffers and textures "
  2130. "must fit in four 32-bit quantities");
  2131. Diags.Report(loc, DiagID);
  2132. return false;
  2133. }
  2134. EltTy = ScalarTys[0];
  2135. for (QualType ScalarTy : ScalarTys) {
  2136. if (ScalarTy != EltTy) {
  2137. DiagnosticsEngine &Diags = CGM.getDiags();
  2138. unsigned DiagID = Diags.getCustomDiagID(
  2139. DiagnosticsEngine::Error,
  2140. "all template type components must have the same type");
  2141. Diags.Report(loc, DiagID);
  2142. return false;
  2143. }
  2144. }
  2145. }
  2146. EltTy = EltTy.getCanonicalType();
  2147. bool bSNorm = false;
  2148. bool bUNorm = false;
  2149. if (const AttributedType *AT = dyn_cast<AttributedType>(Ty)) {
  2150. switch (AT->getAttrKind()) {
  2151. case AttributedType::Kind::attr_hlsl_snorm:
  2152. bSNorm = true;
  2153. break;
  2154. case AttributedType::Kind::attr_hlsl_unorm:
  2155. bUNorm = true;
  2156. break;
  2157. default:
  2158. // Do nothing
  2159. break;
  2160. }
  2161. }
  2162. if (EltTy->isBuiltinType()) {
  2163. const BuiltinType *BTy = EltTy->getAs<BuiltinType>();
  2164. CompType::Kind kind = BuiltinTyToCompTy(BTy, bSNorm, bUNorm);
  2165. // 64bits types are implemented with u32.
  2166. if (kind == CompType::Kind::U64 || kind == CompType::Kind::I64 ||
  2167. kind == CompType::Kind::SNormF64 ||
  2168. kind == CompType::Kind::UNormF64 || kind == CompType::Kind::F64) {
  2169. kind = CompType::Kind::U32;
  2170. }
  2171. hlslRes->SetCompType(kind);
  2172. } else {
  2173. DXASSERT(!bSNorm && !bUNorm, "snorm/unorm on invalid type");
  2174. }
  2175. }
  2176. hlslRes->SetROV(RD->getName().startswith("RasterizerOrdered"));
  2177. if (kind == hlsl::DxilResource::Kind::TypedBuffer ||
  2178. kind == hlsl::DxilResource::Kind::StructuredBuffer) {
  2179. const ClassTemplateSpecializationDecl *templateDecl =
  2180. dyn_cast<ClassTemplateSpecializationDecl>(RD);
  2181. const clang::TemplateArgument &retTyArg =
  2182. templateDecl->getTemplateArgs()[0];
  2183. llvm::Type *retTy = CGM.getTypes().ConvertType(retTyArg.getAsType());
  2184. uint32_t strideInBytes = dataLayout.getTypeAllocSize(retTy);
  2185. hlslRes->SetElementStride(strideInBytes);
  2186. }
  2187. if (resClass == hlsl::DxilResourceBase::Class::SRV) {
  2188. if (hlslRes->IsGloballyCoherent()) {
  2189. DiagnosticsEngine &Diags = CGM.getDiags();
  2190. unsigned DiagID = Diags.getCustomDiagID(
  2191. DiagnosticsEngine::Error, "globallycoherent can only be used with "
  2192. "Unordered Access View buffers.");
  2193. Diags.Report(loc, DiagID);
  2194. return false;
  2195. }
  2196. hlslRes->SetRW(false);
  2197. hlslRes->SetID(m_pHLModule->GetSRVs().size());
  2198. } else {
  2199. hlslRes->SetRW(true);
  2200. hlslRes->SetID(m_pHLModule->GetUAVs().size());
  2201. }
  2202. return true;
  2203. }
  2204. uint32_t CGMSHLSLRuntime::AddUAVSRV(VarDecl *decl,
  2205. hlsl::DxilResourceBase::Class resClass) {
  2206. llvm::GlobalVariable *val =
  2207. cast<llvm::GlobalVariable>(CGM.GetAddrOfGlobalVar(decl));
  2208. QualType VarTy = decl->getType().getCanonicalType();
  2209. unique_ptr<HLResource> hlslRes(new HLResource);
  2210. hlslRes->SetLowerBound(UINT_MAX);
  2211. hlslRes->SetGlobalSymbol(val);
  2212. hlslRes->SetGlobalName(decl->getName());
  2213. if (const clang::ArrayType *arrayType =
  2214. CGM.getContext().getAsArrayType(VarTy)) {
  2215. if (arrayType->isConstantArrayType()) {
  2216. uint32_t arraySize =
  2217. cast<ConstantArrayType>(arrayType)->getSize().getLimitedValue();
  2218. hlslRes->SetRangeSize(arraySize);
  2219. } else
  2220. hlslRes->SetRangeSize(UINT_MAX);
  2221. // use elementTy
  2222. VarTy = arrayType->getElementType();
  2223. // Support more dim.
  2224. while (const clang::ArrayType *arrayType =
  2225. CGM.getContext().getAsArrayType(VarTy)) {
  2226. unsigned rangeSize = hlslRes->GetRangeSize();
  2227. if (arrayType->isConstantArrayType()) {
  2228. uint32_t arraySize =
  2229. cast<ConstantArrayType>(arrayType)->getSize().getLimitedValue();
  2230. if (rangeSize != UINT_MAX)
  2231. hlslRes->SetRangeSize(rangeSize * arraySize);
  2232. } else
  2233. hlslRes->SetRangeSize(UINT_MAX);
  2234. // use elementTy
  2235. VarTy = arrayType->getElementType();
  2236. }
  2237. } else
  2238. hlslRes->SetRangeSize(1);
  2239. for (hlsl::UnusualAnnotation *it : decl->getUnusualAnnotations()) {
  2240. switch (it->getKind()) {
  2241. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  2242. hlsl::RegisterAssignment *ra = cast<hlsl::RegisterAssignment>(it);
  2243. hlslRes->SetLowerBound(ra->RegisterNumber);
  2244. hlslRes->SetSpaceID(ra->RegisterSpace);
  2245. break;
  2246. }
  2247. case hlsl::UnusualAnnotation::UA_SemanticDecl:
  2248. // Ignore Semantics
  2249. break;
  2250. case hlsl::UnusualAnnotation::UA_ConstantPacking:
  2251. // Should be handled by front-end
  2252. llvm_unreachable("packoffset on uav/srv");
  2253. break;
  2254. default:
  2255. llvm_unreachable("unknown UnusualAnnotation on uav/srv");
  2256. break;
  2257. }
  2258. }
  2259. const RecordType *RT = VarTy->getAs<RecordType>();
  2260. RecordDecl *RD = RT->getDecl();
  2261. if (decl->hasAttr<HLSLGloballyCoherentAttr>()) {
  2262. hlslRes->SetGloballyCoherent(true);
  2263. }
  2264. if (!SetUAVSRV(decl->getLocation(), resClass, hlslRes.get(), RD))
  2265. return 0;
  2266. if (resClass == hlsl::DxilResourceBase::Class::SRV) {
  2267. return m_pHLModule->AddSRV(std::move(hlslRes));
  2268. } else {
  2269. return m_pHLModule->AddUAV(std::move(hlslRes));
  2270. }
  2271. }
  2272. static bool IsResourceInType(const clang::ASTContext &context,
  2273. clang::QualType Ty) {
  2274. Ty = Ty.getCanonicalType();
  2275. if (const clang::ArrayType *arrayType = context.getAsArrayType(Ty)) {
  2276. return IsResourceInType(context, arrayType->getElementType());
  2277. } else if (const RecordType *RT = Ty->getAsStructureType()) {
  2278. if (KeywordToClass(RT->getDecl()->getName()) != DxilResourceBase::Class::Invalid)
  2279. return true;
  2280. const CXXRecordDecl* typeRecordDecl = RT->getAsCXXRecordDecl();
  2281. if (typeRecordDecl && !typeRecordDecl->isImplicit()) {
  2282. for (auto field : typeRecordDecl->fields()) {
  2283. if (IsResourceInType(context, field->getType()))
  2284. return true;
  2285. }
  2286. }
  2287. } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
  2288. if (const ClassTemplateSpecializationDecl *templateDecl =
  2289. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl())) {
  2290. if (KeywordToClass(templateDecl->getName()) != DxilResourceBase::Class::Invalid)
  2291. return true;
  2292. }
  2293. }
  2294. return false; // no resources found
  2295. }
  2296. void CGMSHLSLRuntime::AddConstant(VarDecl *constDecl, HLCBuffer &CB) {
  2297. if (constDecl->getStorageClass() == SC_Static) {
  2298. // For static inside cbuffer, take as global static.
  2299. // Don't add to cbuffer.
  2300. CGM.EmitGlobal(constDecl);
  2301. return;
  2302. }
  2303. // Search defined structure for resource objects and fail
  2304. if (CB.GetRangeSize() > 1 &&
  2305. IsResourceInType(CGM.getContext(), constDecl->getType())) {
  2306. DiagnosticsEngine &Diags = CGM.getDiags();
  2307. unsigned DiagID = Diags.getCustomDiagID(
  2308. DiagnosticsEngine::Error,
  2309. "object types not supported in cbuffer/tbuffer view arrays.");
  2310. Diags.Report(constDecl->getLocation(), DiagID);
  2311. return;
  2312. }
  2313. llvm::Constant *constVal = CGM.GetAddrOfGlobalVar(constDecl);
  2314. bool isGlobalCB = CB.GetID() == globalCBIndex;
  2315. uint32_t offset = 0;
  2316. bool userOffset = false;
  2317. for (hlsl::UnusualAnnotation *it : constDecl->getUnusualAnnotations()) {
  2318. switch (it->getKind()) {
  2319. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  2320. if (!isGlobalCB) {
  2321. // TODO: check cannot mix packoffset elements with nonpackoffset
  2322. // elements in a cbuffer.
  2323. hlsl::ConstantPacking *cp = cast<hlsl::ConstantPacking>(it);
  2324. offset = cp->Subcomponent << 2;
  2325. offset += cp->ComponentOffset;
  2326. // Change to byte.
  2327. offset <<= 2;
  2328. userOffset = true;
  2329. } else {
  2330. DiagnosticsEngine &Diags = CGM.getDiags();
  2331. unsigned DiagID = Diags.getCustomDiagID(
  2332. DiagnosticsEngine::Error,
  2333. "packoffset is only allowed in a constant buffer.");
  2334. Diags.Report(it->Loc, DiagID);
  2335. }
  2336. break;
  2337. }
  2338. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  2339. if (isGlobalCB) {
  2340. RegisterAssignment *ra = cast<RegisterAssignment>(it);
  2341. offset = ra->RegisterNumber << 2;
  2342. // Change to byte.
  2343. offset <<= 2;
  2344. userOffset = true;
  2345. }
  2346. break;
  2347. }
  2348. case hlsl::UnusualAnnotation::UA_SemanticDecl:
  2349. // skip semantic on constant
  2350. break;
  2351. }
  2352. }
  2353. std::unique_ptr<DxilResourceBase> pHlslConst = llvm::make_unique<DxilResourceBase>(DXIL::ResourceClass::Invalid);
  2354. pHlslConst->SetLowerBound(UINT_MAX);
  2355. pHlslConst->SetGlobalSymbol(cast<llvm::GlobalVariable>(constVal));
  2356. pHlslConst->SetGlobalName(constDecl->getName());
  2357. if (userOffset) {
  2358. pHlslConst->SetLowerBound(offset);
  2359. }
  2360. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  2361. // Just add type annotation here.
  2362. // Offset will be allocated later.
  2363. QualType Ty = constDecl->getType();
  2364. if (CB.GetRangeSize() != 1) {
  2365. while (Ty->isArrayType()) {
  2366. Ty = Ty->getAsArrayTypeUnsafe()->getElementType();
  2367. }
  2368. }
  2369. unsigned arrayEltSize = 0;
  2370. unsigned size = AddTypeAnnotation(Ty, dxilTypeSys, arrayEltSize);
  2371. pHlslConst->SetRangeSize(size);
  2372. CB.AddConst(pHlslConst);
  2373. // Save fieldAnnotation for the const var.
  2374. DxilFieldAnnotation fieldAnnotation;
  2375. if (userOffset)
  2376. fieldAnnotation.SetCBufferOffset(offset);
  2377. // Get the nested element type.
  2378. if (Ty->isArrayType()) {
  2379. while (const ConstantArrayType *arrayTy =
  2380. CGM.getContext().getAsConstantArrayType(Ty)) {
  2381. Ty = arrayTy->getElementType();
  2382. }
  2383. }
  2384. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  2385. ConstructFieldAttributedAnnotation(fieldAnnotation, Ty, bDefaultRowMajor);
  2386. m_ConstVarAnnotationMap[constVal] = fieldAnnotation;
  2387. }
  2388. uint32_t CGMSHLSLRuntime::AddCBuffer(HLSLBufferDecl *D) {
  2389. unique_ptr<HLCBuffer> CB = llvm::make_unique<HLCBuffer>();
  2390. // setup the CB
  2391. CB->SetGlobalSymbol(nullptr);
  2392. CB->SetGlobalName(D->getNameAsString());
  2393. CB->SetLowerBound(UINT_MAX);
  2394. if (!D->isCBuffer()) {
  2395. CB->SetKind(DXIL::ResourceKind::TBuffer);
  2396. }
  2397. // the global variable will only used once by the createHandle?
  2398. // SetHandle(llvm::Value *pHandle);
  2399. for (hlsl::UnusualAnnotation *it : D->getUnusualAnnotations()) {
  2400. switch (it->getKind()) {
  2401. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  2402. hlsl::RegisterAssignment *ra = cast<hlsl::RegisterAssignment>(it);
  2403. uint32_t regNum = ra->RegisterNumber;
  2404. uint32_t regSpace = ra->RegisterSpace;
  2405. CB->SetSpaceID(regSpace);
  2406. CB->SetLowerBound(regNum);
  2407. break;
  2408. }
  2409. case hlsl::UnusualAnnotation::UA_SemanticDecl:
  2410. // skip semantic on constant buffer
  2411. break;
  2412. case hlsl::UnusualAnnotation::UA_ConstantPacking:
  2413. llvm_unreachable("no packoffset on constant buffer");
  2414. break;
  2415. }
  2416. }
  2417. // Add constant
  2418. if (D->isConstantBufferView()) {
  2419. VarDecl *constDecl = cast<VarDecl>(*D->decls_begin());
  2420. CB->SetRangeSize(1);
  2421. QualType Ty = constDecl->getType();
  2422. if (Ty->isArrayType()) {
  2423. if (!Ty->isIncompleteArrayType()) {
  2424. unsigned arraySize = 1;
  2425. while (Ty->isArrayType()) {
  2426. Ty = Ty->getCanonicalTypeUnqualified();
  2427. const ConstantArrayType *AT = cast<ConstantArrayType>(Ty);
  2428. arraySize *= AT->getSize().getLimitedValue();
  2429. Ty = AT->getElementType();
  2430. }
  2431. CB->SetRangeSize(arraySize);
  2432. } else {
  2433. CB->SetRangeSize(UINT_MAX);
  2434. }
  2435. }
  2436. AddConstant(constDecl, *CB.get());
  2437. } else {
  2438. auto declsEnds = D->decls_end();
  2439. CB->SetRangeSize(1);
  2440. for (auto it = D->decls_begin(); it != declsEnds; it++) {
  2441. if (VarDecl *constDecl = dyn_cast<VarDecl>(*it)) {
  2442. AddConstant(constDecl, *CB.get());
  2443. } else if (isa<EmptyDecl>(*it)) {
  2444. // Nothing to do for this declaration.
  2445. } else if (isa<CXXRecordDecl>(*it)) {
  2446. // Nothing to do for this declaration.
  2447. } else if (isa<FunctionDecl>(*it)) {
  2448. // A function within an cbuffer is effectively a top-level function,
  2449. // as it only refers to globally scoped declarations.
  2450. this->CGM.EmitTopLevelDecl(*it);
  2451. } else {
  2452. HLSLBufferDecl *inner = cast<HLSLBufferDecl>(*it);
  2453. GetOrCreateCBuffer(inner);
  2454. }
  2455. }
  2456. }
  2457. CB->SetID(m_pHLModule->GetCBuffers().size());
  2458. return m_pHLModule->AddCBuffer(std::move(CB));
  2459. }
  2460. HLCBuffer &CGMSHLSLRuntime::GetOrCreateCBuffer(HLSLBufferDecl *D) {
  2461. if (constantBufMap.count(D) != 0) {
  2462. uint32_t cbIndex = constantBufMap[D];
  2463. return *static_cast<HLCBuffer*>(&(m_pHLModule->GetCBuffer(cbIndex)));
  2464. }
  2465. uint32_t cbID = AddCBuffer(D);
  2466. constantBufMap[D] = cbID;
  2467. return *static_cast<HLCBuffer*>(&(m_pHLModule->GetCBuffer(cbID)));
  2468. }
  2469. bool CGMSHLSLRuntime::IsPatchConstantFunction(const Function *F) {
  2470. DXASSERT_NOMSG(F != nullptr);
  2471. for (auto && p : patchConstantFunctionMap) {
  2472. if (p.second.Func == F) return true;
  2473. }
  2474. return false;
  2475. }
  2476. void CGMSHLSLRuntime::SetEntryFunction() {
  2477. if (Entry.Func == nullptr) {
  2478. DiagnosticsEngine &Diags = CGM.getDiags();
  2479. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2480. "cannot find entry function %0");
  2481. Diags.Report(DiagID) << CGM.getCodeGenOpts().HLSLEntryFunction;
  2482. return;
  2483. }
  2484. m_pHLModule->SetEntryFunction(Entry.Func);
  2485. }
  2486. // Here the size is CB size. So don't need check type.
  2487. static unsigned AlignCBufferOffset(unsigned offset, unsigned size, llvm::Type *Ty) {
  2488. DXASSERT(!(offset & 1), "otherwise we have an invalid offset.");
  2489. bool bNeedNewRow = Ty->isArrayTy();
  2490. unsigned scalarSizeInBytes = Ty->getScalarSizeInBits() / 8;
  2491. return AlignBufferOffsetInLegacy(offset, size, scalarSizeInBytes, bNeedNewRow);
  2492. }
  2493. static unsigned AllocateDxilConstantBuffer(HLCBuffer &CB) {
  2494. unsigned offset = 0;
  2495. // Scan user allocated constants first.
  2496. // Update offset.
  2497. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  2498. if (C->GetLowerBound() == UINT_MAX)
  2499. continue;
  2500. unsigned size = C->GetRangeSize();
  2501. unsigned nextOffset = size + C->GetLowerBound();
  2502. if (offset < nextOffset)
  2503. offset = nextOffset;
  2504. }
  2505. // Alloc after user allocated constants.
  2506. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  2507. if (C->GetLowerBound() != UINT_MAX)
  2508. continue;
  2509. unsigned size = C->GetRangeSize();
  2510. llvm::Type *Ty = C->GetGlobalSymbol()->getType()->getPointerElementType();
  2511. // Align offset.
  2512. offset = AlignCBufferOffset(offset, size, Ty);
  2513. if (C->GetLowerBound() == UINT_MAX) {
  2514. C->SetLowerBound(offset);
  2515. }
  2516. offset += size;
  2517. }
  2518. return offset;
  2519. }
  2520. static void AllocateDxilConstantBuffers(HLModule *pHLModule) {
  2521. for (unsigned i = 0; i < pHLModule->GetCBuffers().size(); i++) {
  2522. HLCBuffer &CB = *static_cast<HLCBuffer*>(&(pHLModule->GetCBuffer(i)));
  2523. unsigned size = AllocateDxilConstantBuffer(CB);
  2524. CB.SetSize(size);
  2525. }
  2526. }
  2527. static void ReplaceUseInFunction(Value *V, Value *NewV, Function *F,
  2528. IRBuilder<> &Builder) {
  2529. for (auto U = V->user_begin(); U != V->user_end(); ) {
  2530. User *user = *(U++);
  2531. if (Instruction *I = dyn_cast<Instruction>(user)) {
  2532. if (I->getParent()->getParent() == F) {
  2533. // replace use with GEP if in F
  2534. for (unsigned i = 0; i < I->getNumOperands(); i++) {
  2535. if (I->getOperand(i) == V)
  2536. I->setOperand(i, NewV);
  2537. }
  2538. }
  2539. } else {
  2540. // For constant operator, create local clone which use GEP.
  2541. // Only support GEP and bitcast.
  2542. if (GEPOperator *GEPOp = dyn_cast<GEPOperator>(user)) {
  2543. std::vector<Value *> idxList(GEPOp->idx_begin(), GEPOp->idx_end());
  2544. Value *NewGEP = Builder.CreateInBoundsGEP(NewV, idxList);
  2545. ReplaceUseInFunction(GEPOp, NewGEP, F, Builder);
  2546. } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(user)) {
  2547. // Change the init val into NewV with Store.
  2548. GV->setInitializer(nullptr);
  2549. Builder.CreateStore(NewV, GV);
  2550. } else {
  2551. // Must be bitcast here.
  2552. BitCastOperator *BC = cast<BitCastOperator>(user);
  2553. Value *NewBC = Builder.CreateBitCast(NewV, BC->getType());
  2554. ReplaceUseInFunction(BC, NewBC, F, Builder);
  2555. }
  2556. }
  2557. }
  2558. }
  2559. void MarkUsedFunctionForConst(Value *V, std::unordered_set<Function*> &usedFunc) {
  2560. for (auto U = V->user_begin(); U != V->user_end();) {
  2561. User *user = *(U++);
  2562. if (Instruction *I = dyn_cast<Instruction>(user)) {
  2563. Function *F = I->getParent()->getParent();
  2564. usedFunc.insert(F);
  2565. } else {
  2566. // For constant operator, create local clone which use GEP.
  2567. // Only support GEP and bitcast.
  2568. if (GEPOperator *GEPOp = dyn_cast<GEPOperator>(user)) {
  2569. MarkUsedFunctionForConst(GEPOp, usedFunc);
  2570. } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(user)) {
  2571. MarkUsedFunctionForConst(GV, usedFunc);
  2572. } else {
  2573. // Must be bitcast here.
  2574. BitCastOperator *BC = cast<BitCastOperator>(user);
  2575. MarkUsedFunctionForConst(BC, usedFunc);
  2576. }
  2577. }
  2578. }
  2579. }
  2580. static Function * GetOrCreateHLCreateHandle(HLModule &HLM, llvm::Type *HandleTy,
  2581. ArrayRef<Value*> paramList, MDNode *MD) {
  2582. SmallVector<llvm::Type *, 4> paramTyList;
  2583. for (Value *param : paramList) {
  2584. paramTyList.emplace_back(param->getType());
  2585. }
  2586. llvm::FunctionType *funcTy =
  2587. llvm::FunctionType::get(HandleTy, paramTyList, false);
  2588. llvm::Module &M = *HLM.GetModule();
  2589. Function *CreateHandle = GetOrCreateHLFunctionWithBody(M, funcTy, HLOpcodeGroup::HLCreateHandle,
  2590. /*opcode*/ 0, "");
  2591. if (CreateHandle->empty()) {
  2592. // Add body.
  2593. BasicBlock *BB =
  2594. BasicBlock::Create(CreateHandle->getContext(), "Entry", CreateHandle);
  2595. IRBuilder<> Builder(BB);
  2596. // Just return undef to make a body.
  2597. Builder.CreateRet(UndefValue::get(HandleTy));
  2598. // Mark resource attribute.
  2599. HLM.MarkDxilResourceAttrib(CreateHandle, MD);
  2600. }
  2601. return CreateHandle;
  2602. }
  2603. static bool CreateCBufferVariable(HLCBuffer &CB,
  2604. HLModule &HLM, llvm::Type *HandleTy) {
  2605. bool bUsed = false;
  2606. // Build Struct for CBuffer.
  2607. SmallVector<llvm::Type*, 4> Elements;
  2608. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  2609. Value *GV = C->GetGlobalSymbol();
  2610. if (GV->hasNUsesOrMore(1))
  2611. bUsed = true;
  2612. // Global variable must be pointer type.
  2613. llvm::Type *Ty = GV->getType()->getPointerElementType();
  2614. Elements.emplace_back(Ty);
  2615. }
  2616. // Don't create CBuffer variable for unused cbuffer.
  2617. if (!bUsed)
  2618. return false;
  2619. llvm::Module &M = *HLM.GetModule();
  2620. bool isCBArray = CB.GetRangeSize() != 1;
  2621. llvm::GlobalVariable *cbGV = nullptr;
  2622. llvm::Type *cbTy = nullptr;
  2623. unsigned cbIndexDepth = 0;
  2624. if (!isCBArray) {
  2625. llvm::StructType *CBStructTy =
  2626. llvm::StructType::create(Elements, CB.GetGlobalName());
  2627. cbGV = new llvm::GlobalVariable(M, CBStructTy, /*IsConstant*/ true,
  2628. llvm::GlobalValue::ExternalLinkage,
  2629. /*InitVal*/ nullptr, CB.GetGlobalName());
  2630. cbTy = cbGV->getType();
  2631. } else {
  2632. // For array of ConstantBuffer, create array of struct instead of struct of
  2633. // array.
  2634. DXASSERT(CB.GetConstants().size() == 1,
  2635. "ConstantBuffer should have 1 constant");
  2636. Value *GV = CB.GetConstants()[0]->GetGlobalSymbol();
  2637. llvm::Type *CBEltTy =
  2638. GV->getType()->getPointerElementType()->getArrayElementType();
  2639. cbIndexDepth = 1;
  2640. while (CBEltTy->isArrayTy()) {
  2641. CBEltTy = CBEltTy->getArrayElementType();
  2642. cbIndexDepth++;
  2643. }
  2644. // Add one level struct type to match normal case.
  2645. llvm::StructType *CBStructTy =
  2646. llvm::StructType::create({CBEltTy}, CB.GetGlobalName());
  2647. llvm::ArrayType *CBArrayTy =
  2648. llvm::ArrayType::get(CBStructTy, CB.GetRangeSize());
  2649. cbGV = new llvm::GlobalVariable(M, CBArrayTy, /*IsConstant*/ true,
  2650. llvm::GlobalValue::ExternalLinkage,
  2651. /*InitVal*/ nullptr, CB.GetGlobalName());
  2652. cbTy = llvm::PointerType::get(CBStructTy,
  2653. cbGV->getType()->getPointerAddressSpace());
  2654. }
  2655. CB.SetGlobalSymbol(cbGV);
  2656. llvm::Type *opcodeTy = llvm::Type::getInt32Ty(M.getContext());
  2657. llvm::Type *idxTy = opcodeTy;
  2658. Constant *zeroIdx = ConstantInt::get(opcodeTy, 0);
  2659. MDNode *MD = HLM.DxilCBufferToMDNode(CB);
  2660. Value *HandleArgs[] = { zeroIdx, cbGV, zeroIdx };
  2661. Function *CreateHandleFunc = GetOrCreateHLCreateHandle(HLM, HandleTy, HandleArgs, MD);
  2662. llvm::FunctionType *SubscriptFuncTy =
  2663. llvm::FunctionType::get(cbTy, { opcodeTy, HandleTy, idxTy}, false);
  2664. Function *subscriptFunc =
  2665. GetOrCreateHLFunction(M, SubscriptFuncTy, HLOpcodeGroup::HLSubscript,
  2666. (unsigned)HLSubscriptOpcode::CBufferSubscript);
  2667. Constant *opArg = ConstantInt::get(opcodeTy, (unsigned)HLSubscriptOpcode::CBufferSubscript);
  2668. Value *args[] = { opArg, nullptr, zeroIdx };
  2669. llvm::LLVMContext &Context = M.getContext();
  2670. llvm::Type *i32Ty = llvm::Type::getInt32Ty(Context);
  2671. Value *zero = ConstantInt::get(i32Ty, (uint64_t)0);
  2672. std::vector<Value *> indexArray(CB.GetConstants().size());
  2673. std::vector<std::unordered_set<Function*>> constUsedFuncList(CB.GetConstants().size());
  2674. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  2675. Value *idx = ConstantInt::get(i32Ty, C->GetID());
  2676. indexArray[C->GetID()] = idx;
  2677. Value *GV = C->GetGlobalSymbol();
  2678. MarkUsedFunctionForConst(GV, constUsedFuncList[C->GetID()]);
  2679. }
  2680. for (Function &F : M.functions()) {
  2681. if (F.isDeclaration())
  2682. continue;
  2683. if (GetHLOpcodeGroupByName(&F) != HLOpcodeGroup::NotHL)
  2684. continue;
  2685. IRBuilder<> Builder(F.getEntryBlock().getFirstInsertionPt());
  2686. // create HL subscript to make all the use of cbuffer start from it.
  2687. HandleArgs[HLOperandIndex::kCreateHandleResourceOpIdx] = cbGV;
  2688. CallInst *Handle = Builder.CreateCall(CreateHandleFunc, HandleArgs);
  2689. args[HLOperandIndex::kSubscriptObjectOpIdx] = Handle;
  2690. Instruction *cbSubscript =
  2691. cast<Instruction>(Builder.CreateCall(subscriptFunc, {args}));
  2692. // Replace constant var with GEP pGV
  2693. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  2694. Value *GV = C->GetGlobalSymbol();
  2695. if (constUsedFuncList[C->GetID()].count(&F) == 0)
  2696. continue;
  2697. Value *idx = indexArray[C->GetID()];
  2698. if (!isCBArray) {
  2699. Instruction *GEP = cast<Instruction>(
  2700. Builder.CreateInBoundsGEP(cbSubscript, {zero, idx}));
  2701. // TODO: make sure the debug info is synced to GEP.
  2702. // GEP->setDebugLoc(GV);
  2703. ReplaceUseInFunction(GV, GEP, &F, Builder);
  2704. // Delete if no use in F.
  2705. if (GEP->user_empty())
  2706. GEP->eraseFromParent();
  2707. } else {
  2708. for (auto U = GV->user_begin(); U != GV->user_end();) {
  2709. User *user = *(U++);
  2710. if (user->user_empty())
  2711. continue;
  2712. Instruction *I = dyn_cast<Instruction>(user);
  2713. if (I && I->getParent()->getParent() != &F)
  2714. continue;
  2715. IRBuilder<> *instBuilder = &Builder;
  2716. unique_ptr<IRBuilder<>> B;
  2717. if (I) {
  2718. B = llvm::make_unique<IRBuilder<>>(I);
  2719. instBuilder = B.get();
  2720. }
  2721. GEPOperator *GEPOp = cast<GEPOperator>(user);
  2722. std::vector<Value *> idxList;
  2723. DXASSERT(GEPOp->getNumIndices() >= 1 + cbIndexDepth,
  2724. "must indexing ConstantBuffer array");
  2725. idxList.reserve(GEPOp->getNumIndices() - (cbIndexDepth - 1));
  2726. gep_type_iterator GI = gep_type_begin(*GEPOp),
  2727. E = gep_type_end(*GEPOp);
  2728. idxList.push_back(GI.getOperand());
  2729. // change array index with 0 for struct index.
  2730. idxList.push_back(zero);
  2731. GI++;
  2732. Value *arrayIdx = GI.getOperand();
  2733. GI++;
  2734. for (unsigned curIndex = 1; GI != E && curIndex < cbIndexDepth;
  2735. ++GI, ++curIndex) {
  2736. arrayIdx = instBuilder->CreateMul(
  2737. arrayIdx, Builder.getInt32(GI->getArrayNumElements()));
  2738. arrayIdx = instBuilder->CreateAdd(arrayIdx, GI.getOperand());
  2739. }
  2740. for (; GI != E; ++GI) {
  2741. idxList.push_back(GI.getOperand());
  2742. }
  2743. HandleArgs[HLOperandIndex::kCreateHandleIndexOpIdx] = arrayIdx;
  2744. CallInst *Handle =
  2745. instBuilder->CreateCall(CreateHandleFunc, HandleArgs);
  2746. args[HLOperandIndex::kSubscriptObjectOpIdx] = Handle;
  2747. args[HLOperandIndex::kSubscriptIndexOpIdx] = arrayIdx;
  2748. Instruction *cbSubscript =
  2749. cast<Instruction>(instBuilder->CreateCall(subscriptFunc, {args}));
  2750. Instruction *NewGEP = cast<Instruction>(
  2751. instBuilder->CreateInBoundsGEP(cbSubscript, idxList));
  2752. ReplaceUseInFunction(GEPOp, NewGEP, &F, *instBuilder);
  2753. }
  2754. }
  2755. }
  2756. // Delete if no use in F.
  2757. if (cbSubscript->user_empty()) {
  2758. cbSubscript->eraseFromParent();
  2759. Handle->eraseFromParent();
  2760. }
  2761. }
  2762. return true;
  2763. }
  2764. static void ConstructCBufferAnnotation(
  2765. HLCBuffer &CB, DxilTypeSystem &dxilTypeSys,
  2766. std::unordered_map<Constant *, DxilFieldAnnotation> &AnnotationMap) {
  2767. Value *GV = CB.GetGlobalSymbol();
  2768. llvm::StructType *CBStructTy =
  2769. dyn_cast<llvm::StructType>(GV->getType()->getPointerElementType());
  2770. if (!CBStructTy) {
  2771. // For Array of ConstantBuffer.
  2772. llvm::ArrayType *CBArrayTy =
  2773. cast<llvm::ArrayType>(GV->getType()->getPointerElementType());
  2774. CBStructTy = cast<llvm::StructType>(CBArrayTy->getArrayElementType());
  2775. }
  2776. DxilStructAnnotation *CBAnnotation =
  2777. dxilTypeSys.AddStructAnnotation(CBStructTy);
  2778. CBAnnotation->SetCBufferSize(CB.GetSize());
  2779. // Set fieldAnnotation for each constant var.
  2780. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  2781. Constant *GV = C->GetGlobalSymbol();
  2782. DxilFieldAnnotation &fieldAnnotation =
  2783. CBAnnotation->GetFieldAnnotation(C->GetID());
  2784. fieldAnnotation = AnnotationMap[GV];
  2785. // This is after CBuffer allocation.
  2786. fieldAnnotation.SetCBufferOffset(C->GetLowerBound());
  2787. fieldAnnotation.SetFieldName(C->GetGlobalName());
  2788. }
  2789. }
  2790. static void ConstructCBuffer(
  2791. HLModule *pHLModule,
  2792. llvm::Type *CBufferType,
  2793. std::unordered_map<Constant *, DxilFieldAnnotation> &AnnotationMap) {
  2794. DxilTypeSystem &dxilTypeSys = pHLModule->GetTypeSystem();
  2795. llvm::Type *HandleTy = pHLModule->GetOP()->GetHandleType();
  2796. for (unsigned i = 0; i < pHLModule->GetCBuffers().size(); i++) {
  2797. HLCBuffer &CB = *static_cast<HLCBuffer*>(&(pHLModule->GetCBuffer(i)));
  2798. if (CB.GetConstants().size() == 0) {
  2799. // Create Fake variable for cbuffer which is empty.
  2800. llvm::GlobalVariable *pGV = new llvm::GlobalVariable(
  2801. *pHLModule->GetModule(), CBufferType, true,
  2802. llvm::GlobalValue::ExternalLinkage, nullptr, CB.GetGlobalName());
  2803. CB.SetGlobalSymbol(pGV);
  2804. } else {
  2805. bool bCreated =
  2806. CreateCBufferVariable(CB, *pHLModule, HandleTy);
  2807. if (bCreated)
  2808. ConstructCBufferAnnotation(CB, dxilTypeSys, AnnotationMap);
  2809. else {
  2810. // Create Fake variable for cbuffer which is unused.
  2811. llvm::GlobalVariable *pGV = new llvm::GlobalVariable(
  2812. *pHLModule->GetModule(), CBufferType, true,
  2813. llvm::GlobalValue::ExternalLinkage, nullptr, CB.GetGlobalName());
  2814. CB.SetGlobalSymbol(pGV);
  2815. }
  2816. }
  2817. // Clear the constants which useless now.
  2818. CB.GetConstants().clear();
  2819. }
  2820. }
  2821. static void ReplaceBoolVectorSubscript(CallInst *CI) {
  2822. Value *Ptr = CI->getArgOperand(0);
  2823. Value *Idx = CI->getArgOperand(1);
  2824. Value *IdxList[] = {ConstantInt::get(Idx->getType(), 0), Idx};
  2825. for (auto It = CI->user_begin(), E = CI->user_end(); It != E;) {
  2826. Instruction *user = cast<Instruction>(*(It++));
  2827. IRBuilder<> Builder(user);
  2828. Value *GEP = Builder.CreateInBoundsGEP(Ptr, IdxList);
  2829. if (LoadInst *LI = dyn_cast<LoadInst>(user)) {
  2830. Value *NewLd = Builder.CreateLoad(GEP);
  2831. Value *cast = Builder.CreateZExt(NewLd, LI->getType());
  2832. LI->replaceAllUsesWith(cast);
  2833. LI->eraseFromParent();
  2834. } else {
  2835. // Must be a store inst here.
  2836. StoreInst *SI = cast<StoreInst>(user);
  2837. Value *V = SI->getValueOperand();
  2838. Value *cast =
  2839. Builder.CreateICmpNE(V, llvm::ConstantInt::get(V->getType(), 0));
  2840. Builder.CreateStore(cast, GEP);
  2841. SI->eraseFromParent();
  2842. }
  2843. }
  2844. CI->eraseFromParent();
  2845. }
  2846. static void ReplaceBoolVectorSubscript(Function *F) {
  2847. for (auto It = F->user_begin(), E = F->user_end(); It != E; ) {
  2848. User *user = *(It++);
  2849. CallInst *CI = cast<CallInst>(user);
  2850. ReplaceBoolVectorSubscript(CI);
  2851. }
  2852. }
  2853. // Add function body for intrinsic if possible.
  2854. static Function *CreateOpFunction(llvm::Module &M, Function *F,
  2855. llvm::FunctionType *funcTy,
  2856. HLOpcodeGroup group, unsigned opcode) {
  2857. Function *opFunc = nullptr;
  2858. llvm::Type *opcodeTy = llvm::Type::getInt32Ty(M.getContext());
  2859. if (group == HLOpcodeGroup::HLIntrinsic) {
  2860. IntrinsicOp intriOp = static_cast<IntrinsicOp>(opcode);
  2861. switch (intriOp) {
  2862. case IntrinsicOp::MOP_Append:
  2863. case IntrinsicOp::MOP_Consume: {
  2864. bool bAppend = intriOp == IntrinsicOp::MOP_Append;
  2865. llvm::Type *handleTy = funcTy->getParamType(HLOperandIndex::kHandleOpIdx);
  2866. // Don't generate body for OutputStream::Append.
  2867. if (bAppend && HLModule::IsStreamOutputPtrType(handleTy)) {
  2868. opFunc = GetOrCreateHLFunction(M, funcTy, group, opcode);
  2869. break;
  2870. }
  2871. opFunc = GetOrCreateHLFunctionWithBody(M, funcTy, group, opcode,
  2872. bAppend ? "append" : "consume");
  2873. llvm::Type *counterTy = llvm::Type::getInt32Ty(M.getContext());
  2874. llvm::FunctionType *IncCounterFuncTy =
  2875. llvm::FunctionType::get(counterTy, {opcodeTy, handleTy}, false);
  2876. unsigned counterOpcode = bAppend ? (unsigned)IntrinsicOp::MOP_IncrementCounter:
  2877. (unsigned)IntrinsicOp::MOP_DecrementCounter;
  2878. Function *incCounterFunc =
  2879. GetOrCreateHLFunction(M, IncCounterFuncTy, group,
  2880. counterOpcode);
  2881. llvm::Type *idxTy = counterTy;
  2882. llvm::Type *valTy = bAppend ?
  2883. funcTy->getParamType(HLOperandIndex::kAppendValOpIndex):funcTy->getReturnType();
  2884. llvm::Type *subscriptTy = valTy;
  2885. if (!valTy->isPointerTy()) {
  2886. // Return type for subscript should be pointer type.
  2887. subscriptTy = llvm::PointerType::get(valTy, 0);
  2888. }
  2889. llvm::FunctionType *SubscriptFuncTy =
  2890. llvm::FunctionType::get(subscriptTy, {opcodeTy, handleTy, idxTy}, false);
  2891. Function *subscriptFunc =
  2892. GetOrCreateHLFunction(M, SubscriptFuncTy, HLOpcodeGroup::HLSubscript,
  2893. (unsigned)HLSubscriptOpcode::DefaultSubscript);
  2894. BasicBlock *BB = BasicBlock::Create(opFunc->getContext(), "Entry", opFunc);
  2895. IRBuilder<> Builder(BB);
  2896. auto argIter = opFunc->args().begin();
  2897. // Skip the opcode arg.
  2898. argIter++;
  2899. Argument *thisArg = argIter++;
  2900. // int counter = IncrementCounter/DecrementCounter(Buf);
  2901. Value *incCounterOpArg =
  2902. ConstantInt::get(idxTy, counterOpcode);
  2903. Value *counter =
  2904. Builder.CreateCall(incCounterFunc, {incCounterOpArg, thisArg});
  2905. // Buf[counter];
  2906. Value *subscriptOpArg = ConstantInt::get(
  2907. idxTy, (unsigned)HLSubscriptOpcode::DefaultSubscript);
  2908. Value *subscript =
  2909. Builder.CreateCall(subscriptFunc, {subscriptOpArg, thisArg, counter});
  2910. if (bAppend) {
  2911. Argument *valArg = argIter;
  2912. // Buf[counter] = val;
  2913. if (valTy->isPointerTy()) {
  2914. unsigned size = M.getDataLayout().getTypeAllocSize(subscript->getType()->getPointerElementType());
  2915. Builder.CreateMemCpy(subscript, valArg, size, 1);
  2916. } else
  2917. Builder.CreateStore(valArg, subscript);
  2918. Builder.CreateRetVoid();
  2919. } else {
  2920. // return Buf[counter];
  2921. if (valTy->isPointerTy())
  2922. Builder.CreateRet(subscript);
  2923. else {
  2924. Value *retVal = Builder.CreateLoad(subscript);
  2925. Builder.CreateRet(retVal);
  2926. }
  2927. }
  2928. } break;
  2929. case IntrinsicOp::IOP_sincos: {
  2930. opFunc = GetOrCreateHLFunctionWithBody(M, funcTy, group, opcode, "sincos");
  2931. llvm::Type *valTy = funcTy->getParamType(HLOperandIndex::kTrinaryOpSrc0Idx);
  2932. llvm::FunctionType *sinFuncTy =
  2933. llvm::FunctionType::get(valTy, {opcodeTy, valTy}, false);
  2934. unsigned sinOp = static_cast<unsigned>(IntrinsicOp::IOP_sin);
  2935. unsigned cosOp = static_cast<unsigned>(IntrinsicOp::IOP_cos);
  2936. Function *sinFunc = GetOrCreateHLFunction(M, sinFuncTy, group, sinOp);
  2937. Function *cosFunc = GetOrCreateHLFunction(M, sinFuncTy, group, cosOp);
  2938. BasicBlock *BB = BasicBlock::Create(opFunc->getContext(), "Entry", opFunc);
  2939. IRBuilder<> Builder(BB);
  2940. auto argIter = opFunc->args().begin();
  2941. // Skip the opcode arg.
  2942. argIter++;
  2943. Argument *valArg = argIter++;
  2944. Argument *sinPtrArg = argIter++;
  2945. Argument *cosPtrArg = argIter++;
  2946. Value *sinOpArg =
  2947. ConstantInt::get(opcodeTy, sinOp);
  2948. Value *sinVal = Builder.CreateCall(sinFunc, {sinOpArg, valArg});
  2949. Builder.CreateStore(sinVal, sinPtrArg);
  2950. Value *cosOpArg =
  2951. ConstantInt::get(opcodeTy, cosOp);
  2952. Value *cosVal = Builder.CreateCall(cosFunc, {cosOpArg, valArg});
  2953. Builder.CreateStore(cosVal, cosPtrArg);
  2954. // Ret.
  2955. Builder.CreateRetVoid();
  2956. } break;
  2957. default:
  2958. opFunc = GetOrCreateHLFunction(M, funcTy, group, opcode);
  2959. break;
  2960. }
  2961. }
  2962. else if (group == HLOpcodeGroup::HLExtIntrinsic) {
  2963. llvm::StringRef fnName = F->getName();
  2964. llvm::StringRef groupName = GetHLOpcodeGroupNameByAttr(F);
  2965. opFunc = GetOrCreateHLFunction(M, funcTy, group, &groupName, &fnName, opcode);
  2966. }
  2967. else {
  2968. opFunc = GetOrCreateHLFunction(M, funcTy, group, opcode);
  2969. }
  2970. // Add attribute
  2971. if (F->hasFnAttribute(Attribute::ReadNone))
  2972. opFunc->addFnAttr(Attribute::ReadNone);
  2973. if (F->hasFnAttribute(Attribute::ReadOnly))
  2974. opFunc->addFnAttr(Attribute::ReadOnly);
  2975. return opFunc;
  2976. }
  2977. static Value *CreateHandleFromResPtr(
  2978. Value *ResPtr, HLModule &HLM, llvm::Type *HandleTy,
  2979. std::unordered_map<llvm::Type *, MDNode *> &resMetaMap,
  2980. IRBuilder<> &Builder) {
  2981. llvm::Type *objTy = ResPtr->getType()->getPointerElementType();
  2982. DXASSERT(resMetaMap.count(objTy), "cannot find resource type");
  2983. MDNode *MD = resMetaMap[objTy];
  2984. // Load to make sure resource only have Ld/St use so mem2reg could remove
  2985. // temp resource.
  2986. Value *ldObj = Builder.CreateLoad(ResPtr);
  2987. Value *opcode = Builder.getInt32(0);
  2988. Value *args[] = {opcode, ldObj};
  2989. Function *CreateHandle = GetOrCreateHLCreateHandle(HLM, HandleTy, args, MD);
  2990. CallInst *Handle = Builder.CreateCall(CreateHandle, args);
  2991. return Handle;
  2992. }
  2993. static void AddOpcodeParamForIntrinsic(HLModule &HLM, Function *F,
  2994. unsigned opcode, llvm::Type *HandleTy,
  2995. std::unordered_map<llvm::Type *, MDNode*> &resMetaMap) {
  2996. llvm::Module &M = *HLM.GetModule();
  2997. llvm::FunctionType *oldFuncTy = F->getFunctionType();
  2998. SmallVector<llvm::Type *, 4> paramTyList;
  2999. // Add the opcode param
  3000. llvm::Type *opcodeTy = llvm::Type::getInt32Ty(M.getContext());
  3001. paramTyList.emplace_back(opcodeTy);
  3002. paramTyList.append(oldFuncTy->param_begin(), oldFuncTy->param_end());
  3003. for (unsigned i = 1; i < paramTyList.size(); i++) {
  3004. llvm::Type *Ty = paramTyList[i];
  3005. if (Ty->isPointerTy()) {
  3006. Ty = Ty->getPointerElementType();
  3007. if (HLModule::IsHLSLObjectType(Ty) &&
  3008. // StreamOutput don't need handle.
  3009. !HLModule::IsStreamOutputType(Ty)) {
  3010. // Use handle type for object type.
  3011. // This will make sure temp object variable only used by createHandle.
  3012. paramTyList[i] = HandleTy;
  3013. }
  3014. }
  3015. }
  3016. HLOpcodeGroup group = hlsl::GetHLOpcodeGroup(F);
  3017. if (group == HLOpcodeGroup::HLSubscript &&
  3018. opcode == static_cast<unsigned>(HLSubscriptOpcode::VectorSubscript)) {
  3019. llvm::FunctionType *FT = F->getFunctionType();
  3020. llvm::Type *VecArgTy = FT->getParamType(0);
  3021. llvm::VectorType *VType =
  3022. cast<llvm::VectorType>(VecArgTy->getPointerElementType());
  3023. llvm::Type *Ty = VType->getElementType();
  3024. DXASSERT(Ty->isIntegerTy(), "Only bool could use VectorSubscript");
  3025. llvm::IntegerType *ITy = cast<IntegerType>(Ty);
  3026. DXASSERT_LOCALVAR(ITy, ITy->getBitWidth() == 1, "Only bool could use VectorSubscript");
  3027. // The return type is i8*.
  3028. // Replace all uses with i1*.
  3029. ReplaceBoolVectorSubscript(F);
  3030. return;
  3031. }
  3032. bool isDoubleSubscriptFunc = group == HLOpcodeGroup::HLSubscript &&
  3033. opcode == static_cast<unsigned>(HLSubscriptOpcode::DoubleSubscript);
  3034. llvm::Type *RetTy = oldFuncTy->getReturnType();
  3035. if (isDoubleSubscriptFunc) {
  3036. CallInst *doubleSub = cast<CallInst>(*F->user_begin());
  3037. // Change currentIdx type into coord type.
  3038. auto U = doubleSub->user_begin();
  3039. Value *user = *U;
  3040. CallInst *secSub = cast<CallInst>(user);
  3041. unsigned coordIdx = HLOperandIndex::kSubscriptIndexOpIdx;
  3042. // opcode operand not add yet, so the index need -1.
  3043. if (GetHLOpcodeGroupByName(secSub->getCalledFunction()) == HLOpcodeGroup::NotHL)
  3044. coordIdx -= 1;
  3045. Value *coord = secSub->getArgOperand(coordIdx);
  3046. llvm::Type *coordTy = coord->getType();
  3047. paramTyList[HLOperandIndex::kSubscriptIndexOpIdx] = coordTy;
  3048. // Add the sampleIdx or mipLevel parameter to the end.
  3049. paramTyList.emplace_back(opcodeTy);
  3050. // Change return type to be resource ret type.
  3051. // opcode operand not add yet, so the index need -1.
  3052. Value *objPtr = doubleSub->getArgOperand(HLOperandIndex::kSubscriptObjectOpIdx-1);
  3053. // Must be a GEP
  3054. GEPOperator *objGEP = cast<GEPOperator>(objPtr);
  3055. gep_type_iterator GEPIt = gep_type_begin(objGEP), E = gep_type_end(objGEP);
  3056. llvm::Type *resTy = nullptr;
  3057. while (GEPIt != E) {
  3058. if (HLModule::IsHLSLObjectType(*GEPIt)) {
  3059. resTy = *GEPIt;
  3060. break;
  3061. }
  3062. GEPIt++;
  3063. }
  3064. DXASSERT(resTy, "must find the resource type");
  3065. // Change object type to handle type.
  3066. paramTyList[HLOperandIndex::kSubscriptObjectOpIdx] = HandleTy;
  3067. // Change RetTy into pointer of resource reture type.
  3068. RetTy = cast<StructType>(resTy)->getElementType(0)->getPointerTo();
  3069. llvm::Type *sliceTy = objGEP->getType()->getPointerElementType();
  3070. DXIL::ResourceClass RC = HLM.GetResourceClass(sliceTy);
  3071. DXIL::ResourceKind RK = HLM.GetResourceKind(sliceTy);
  3072. HLM.AddResourceTypeAnnotation(resTy, RC, RK);
  3073. }
  3074. llvm::FunctionType *funcTy =
  3075. llvm::FunctionType::get(RetTy, paramTyList, false);
  3076. Function *opFunc = CreateOpFunction(M, F, funcTy, group, opcode);
  3077. StringRef lower = hlsl::GetHLLowerStrategy(F);
  3078. if (!lower.empty())
  3079. hlsl::SetHLLowerStrategy(opFunc, lower);
  3080. for (auto user = F->user_begin(); user != F->user_end();) {
  3081. // User must be a call.
  3082. CallInst *oldCI = cast<CallInst>(*(user++));
  3083. SmallVector<Value *, 4> opcodeParamList;
  3084. Value *opcodeConst = Constant::getIntegerValue(opcodeTy, APInt(32, opcode));
  3085. opcodeParamList.emplace_back(opcodeConst);
  3086. opcodeParamList.append(oldCI->arg_operands().begin(),
  3087. oldCI->arg_operands().end());
  3088. IRBuilder<> Builder(oldCI);
  3089. if (isDoubleSubscriptFunc) {
  3090. // Change obj to the resource pointer.
  3091. Value *objVal = opcodeParamList[HLOperandIndex::kSubscriptObjectOpIdx];
  3092. GEPOperator *objGEP = cast<GEPOperator>(objVal);
  3093. SmallVector<Value *, 8> IndexList;
  3094. IndexList.append(objGEP->idx_begin(), objGEP->idx_end());
  3095. Value *lastIndex = IndexList.back();
  3096. ConstantInt *constIndex = cast<ConstantInt>(lastIndex);
  3097. DXASSERT_LOCALVAR(constIndex, constIndex->getLimitedValue() == 1, "last index must 1");
  3098. // Remove the last index.
  3099. IndexList.pop_back();
  3100. objVal = objGEP->getPointerOperand();
  3101. if (IndexList.size() > 1)
  3102. objVal = Builder.CreateInBoundsGEP(objVal, IndexList);
  3103. Value *Handle =
  3104. CreateHandleFromResPtr(objVal, HLM, HandleTy, resMetaMap, Builder);
  3105. // Change obj to the resource pointer.
  3106. opcodeParamList[HLOperandIndex::kSubscriptObjectOpIdx] = Handle;
  3107. // Set idx and mipIdx.
  3108. Value *mipIdx = opcodeParamList[HLOperandIndex::kSubscriptIndexOpIdx];
  3109. auto U = oldCI->user_begin();
  3110. Value *user = *U;
  3111. CallInst *secSub = cast<CallInst>(user);
  3112. unsigned idxOpIndex = HLOperandIndex::kSubscriptIndexOpIdx;
  3113. if (GetHLOpcodeGroupByName(secSub->getCalledFunction()) == HLOpcodeGroup::NotHL)
  3114. idxOpIndex--;
  3115. Value *idx = secSub->getArgOperand(idxOpIndex);
  3116. DXASSERT(secSub->hasOneUse(), "subscript should only has one use");
  3117. // Add the sampleIdx or mipLevel parameter to the end.
  3118. opcodeParamList[HLOperandIndex::kSubscriptIndexOpIdx] = idx;
  3119. opcodeParamList.emplace_back(mipIdx);
  3120. // Insert new call before secSub to make sure idx is ready to use.
  3121. Builder.SetInsertPoint(secSub);
  3122. }
  3123. for (unsigned i = 1; i < opcodeParamList.size(); i++) {
  3124. Value *arg = opcodeParamList[i];
  3125. llvm::Type *Ty = arg->getType();
  3126. if (Ty->isPointerTy()) {
  3127. Ty = Ty->getPointerElementType();
  3128. if (HLModule::IsHLSLObjectType(Ty) &&
  3129. // StreamOutput don't need handle.
  3130. !HLModule::IsStreamOutputType(Ty)) {
  3131. // Use object type directly, not by pointer.
  3132. // This will make sure temp object variable only used by ld/st.
  3133. if (GEPOperator *argGEP = dyn_cast<GEPOperator>(arg)) {
  3134. std::vector<Value*> idxList(argGEP->idx_begin(), argGEP->idx_end());
  3135. // Create instruction to avoid GEPOperator.
  3136. GetElementPtrInst *GEP = GetElementPtrInst::CreateInBounds(argGEP->getPointerOperand(),
  3137. idxList);
  3138. Builder.Insert(GEP);
  3139. arg = GEP;
  3140. }
  3141. Value *Handle = CreateHandleFromResPtr(arg, HLM, HandleTy,
  3142. resMetaMap, Builder);
  3143. opcodeParamList[i] = Handle;
  3144. }
  3145. }
  3146. }
  3147. Value *CI = Builder.CreateCall(opFunc, opcodeParamList);
  3148. if (!isDoubleSubscriptFunc) {
  3149. // replace new call and delete the old call
  3150. oldCI->replaceAllUsesWith(CI);
  3151. oldCI->eraseFromParent();
  3152. } else {
  3153. // For double script.
  3154. // Replace single users use with new CI.
  3155. auto U = oldCI->user_begin();
  3156. Value *user = *U;
  3157. CallInst *secSub = cast<CallInst>(user);
  3158. secSub->replaceAllUsesWith(CI);
  3159. secSub->eraseFromParent();
  3160. oldCI->eraseFromParent();
  3161. }
  3162. }
  3163. // delete the function
  3164. F->eraseFromParent();
  3165. }
  3166. static void AddOpcodeParamForIntrinsics(HLModule &HLM
  3167. , std::vector<std::pair<Function *, unsigned>> &intrinsicMap,
  3168. std::unordered_map<llvm::Type *, MDNode*> &resMetaMap) {
  3169. llvm::Type *HandleTy = HLM.GetOP()->GetHandleType();
  3170. for (auto mapIter : intrinsicMap) {
  3171. Function *F = mapIter.first;
  3172. if (F->user_empty()) {
  3173. // delete the function
  3174. F->eraseFromParent();
  3175. continue;
  3176. }
  3177. unsigned opcode = mapIter.second;
  3178. AddOpcodeParamForIntrinsic(HLM, F, opcode, HandleTy, resMetaMap);
  3179. }
  3180. }
  3181. static Value *CastLdValue(Value *Ptr, llvm::Type *FromTy, llvm::Type *ToTy, IRBuilder<> &Builder) {
  3182. if (ToTy->isVectorTy()) {
  3183. unsigned vecSize = ToTy->getVectorNumElements();
  3184. if (vecSize == 1 && ToTy->getVectorElementType() == FromTy) {
  3185. Value *V = Builder.CreateLoad(Ptr);
  3186. // ScalarToVec1Splat
  3187. // Change scalar into vec1.
  3188. Value *Vec1 = UndefValue::get(ToTy);
  3189. return Builder.CreateInsertElement(Vec1, V, (uint64_t)0);
  3190. } else if (FromTy->isVectorTy() && vecSize == 1) {
  3191. Value *V = Builder.CreateLoad(Ptr);
  3192. // VectorTrunc
  3193. // Change vector into vec1.
  3194. int mask[] = {0};
  3195. return Builder.CreateShuffleVector(V, V, mask);
  3196. } else if (FromTy->isArrayTy()) {
  3197. llvm::Type *FromEltTy = FromTy->getArrayElementType();
  3198. llvm::Type *ToEltTy = ToTy->getVectorElementType();
  3199. if (FromTy->getArrayNumElements() == vecSize && FromEltTy == ToEltTy) {
  3200. // ArrayToVector.
  3201. Value *NewLd = UndefValue::get(ToTy);
  3202. Value *zeroIdx = Builder.getInt32(0);
  3203. for (unsigned i = 0; i < vecSize; i++) {
  3204. Value *GEP = Builder.CreateInBoundsGEP(
  3205. Ptr, {zeroIdx, Builder.getInt32(i)});
  3206. Value *Elt = Builder.CreateLoad(GEP);
  3207. NewLd = Builder.CreateInsertElement(NewLd, Elt, i);
  3208. }
  3209. return NewLd;
  3210. }
  3211. }
  3212. } else if (FromTy == Builder.getInt1Ty()) {
  3213. Value *V = Builder.CreateLoad(Ptr);
  3214. // BoolCast
  3215. DXASSERT_NOMSG(ToTy->isIntegerTy());
  3216. return Builder.CreateZExt(V, ToTy);
  3217. }
  3218. return nullptr;
  3219. }
  3220. static Value *CastStValue(Value *Ptr, Value *V, llvm::Type *FromTy, llvm::Type *ToTy, IRBuilder<> &Builder) {
  3221. if (ToTy->isVectorTy()) {
  3222. unsigned vecSize = ToTy->getVectorNumElements();
  3223. if (vecSize == 1 && ToTy->getVectorElementType() == FromTy) {
  3224. // ScalarToVec1Splat
  3225. // Change vec1 back to scalar.
  3226. Value *Elt = Builder.CreateExtractElement(V, (uint64_t)0);
  3227. return Elt;
  3228. } else if (FromTy->isVectorTy() && vecSize == 1) {
  3229. // VectorTrunc
  3230. // Change vec1 into vector.
  3231. // Should not happen.
  3232. // Reported error at Sema::ImpCastExprToType.
  3233. DXASSERT_NOMSG(0);
  3234. } else if (FromTy->isArrayTy()) {
  3235. llvm::Type *FromEltTy = FromTy->getArrayElementType();
  3236. llvm::Type *ToEltTy = ToTy->getVectorElementType();
  3237. if (FromTy->getArrayNumElements() == vecSize && FromEltTy == ToEltTy) {
  3238. // ArrayToVector.
  3239. Value *zeroIdx = Builder.getInt32(0);
  3240. for (unsigned i = 0; i < vecSize; i++) {
  3241. Value *Elt = Builder.CreateExtractElement(V, i);
  3242. Value *GEP = Builder.CreateInBoundsGEP(
  3243. Ptr, {zeroIdx, Builder.getInt32(i)});
  3244. Builder.CreateStore(Elt, GEP);
  3245. }
  3246. // The store already done.
  3247. // Return null to ignore use of the return value.
  3248. return nullptr;
  3249. }
  3250. }
  3251. } else if (FromTy == Builder.getInt1Ty()) {
  3252. // BoolCast
  3253. // Change i1 to ToTy.
  3254. DXASSERT_NOMSG(ToTy->isIntegerTy());
  3255. Value *CastV = Builder.CreateICmpNE(V, ConstantInt::get(V->getType(), 0));
  3256. return CastV;
  3257. }
  3258. return nullptr;
  3259. }
  3260. static bool SimplifyBitCastLoad(LoadInst *LI, llvm::Type *FromTy, llvm::Type *ToTy, Value *Ptr) {
  3261. IRBuilder<> Builder(LI);
  3262. // Cast FromLd to ToTy.
  3263. Value *CastV = CastLdValue(Ptr, FromTy, ToTy, Builder);
  3264. if (CastV) {
  3265. LI->replaceAllUsesWith(CastV);
  3266. return true;
  3267. } else {
  3268. return false;
  3269. }
  3270. }
  3271. static bool SimplifyBitCastStore(StoreInst *SI, llvm::Type *FromTy, llvm::Type *ToTy, Value *Ptr) {
  3272. IRBuilder<> Builder(SI);
  3273. Value *V = SI->getValueOperand();
  3274. // Cast Val to FromTy.
  3275. Value *CastV = CastStValue(Ptr, V, FromTy, ToTy, Builder);
  3276. if (CastV) {
  3277. Builder.CreateStore(CastV, Ptr);
  3278. return true;
  3279. } else {
  3280. return false;
  3281. }
  3282. }
  3283. static bool SimplifyBitCastGEP(GEPOperator *GEP, llvm::Type *FromTy, llvm::Type *ToTy, Value *Ptr) {
  3284. if (ToTy->isVectorTy()) {
  3285. unsigned vecSize = ToTy->getVectorNumElements();
  3286. if (vecSize == 1 && ToTy->getVectorElementType() == FromTy) {
  3287. // ScalarToVec1Splat
  3288. GEP->replaceAllUsesWith(Ptr);
  3289. return true;
  3290. } else if (FromTy->isVectorTy() && vecSize == 1) {
  3291. // VectorTrunc
  3292. DXASSERT_NOMSG(
  3293. !isa<llvm::VectorType>(GEP->getType()->getPointerElementType()));
  3294. IRBuilder<> Builder(FromTy->getContext());
  3295. if (Instruction *I = dyn_cast<Instruction>(GEP))
  3296. Builder.SetInsertPoint(I);
  3297. std::vector<Value *> idxList(GEP->idx_begin(), GEP->idx_end());
  3298. Value *NewGEP = Builder.CreateInBoundsGEP(Ptr, idxList);
  3299. GEP->replaceAllUsesWith(NewGEP);
  3300. return true;
  3301. } else if (FromTy->isArrayTy()) {
  3302. llvm::Type *FromEltTy = FromTy->getArrayElementType();
  3303. llvm::Type *ToEltTy = ToTy->getVectorElementType();
  3304. if (FromTy->getArrayNumElements() == vecSize && FromEltTy == ToEltTy) {
  3305. // ArrayToVector.
  3306. }
  3307. }
  3308. } else if (FromTy == llvm::Type::getInt1Ty(FromTy->getContext())) {
  3309. // BoolCast
  3310. }
  3311. return false;
  3312. }
  3313. static void SimplifyBitCast(BitCastOperator *BC, std::vector<Instruction *> &deadInsts) {
  3314. Value *Ptr = BC->getOperand(0);
  3315. llvm::Type *FromTy = Ptr->getType();
  3316. llvm::Type *ToTy = BC->getType();
  3317. if (!FromTy->isPointerTy() || !ToTy->isPointerTy())
  3318. return;
  3319. FromTy = FromTy->getPointerElementType();
  3320. ToTy = ToTy->getPointerElementType();
  3321. // Take care case like %2 = bitcast %struct.T* %1 to <1 x float>*.
  3322. if (FromTy->isStructTy()) {
  3323. IRBuilder<> Builder(FromTy->getContext());
  3324. if (Instruction *I = dyn_cast<Instruction>(BC))
  3325. Builder.SetInsertPoint(I);
  3326. Value *zeroIdx = Builder.getInt32(0);
  3327. unsigned nestLevel = 1;
  3328. while (llvm::StructType *ST = dyn_cast<llvm::StructType>(FromTy)) {
  3329. FromTy = ST->getElementType(0);
  3330. nestLevel++;
  3331. }
  3332. std::vector<Value *> idxList(nestLevel, zeroIdx);
  3333. Ptr = Builder.CreateGEP(Ptr, idxList);
  3334. }
  3335. for (User *U : BC->users()) {
  3336. if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
  3337. if (SimplifyBitCastLoad(LI, FromTy, ToTy, Ptr)) {
  3338. LI->dropAllReferences();
  3339. deadInsts.emplace_back(LI);
  3340. }
  3341. } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  3342. if (SimplifyBitCastStore(SI, FromTy, ToTy, Ptr)) {
  3343. SI->dropAllReferences();
  3344. deadInsts.emplace_back(SI);
  3345. }
  3346. } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
  3347. if (SimplifyBitCastGEP(GEP, FromTy, ToTy, Ptr))
  3348. if (Instruction *I = dyn_cast<Instruction>(GEP)) {
  3349. I->dropAllReferences();
  3350. deadInsts.emplace_back(I);
  3351. }
  3352. } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
  3353. // Skip function call.
  3354. } else if (BitCastInst *Cast = dyn_cast<BitCastInst>(U)) {
  3355. // Skip bitcast.
  3356. } else {
  3357. DXASSERT(0, "not support yet");
  3358. }
  3359. }
  3360. }
  3361. typedef float(__cdecl *FloatUnaryEvalFuncType)(float);
  3362. typedef double(__cdecl *DoubleUnaryEvalFuncType)(double);
  3363. typedef float(__cdecl *FloatBinaryEvalFuncType)(float, float);
  3364. typedef double(__cdecl *DoubleBinaryEvalFuncType)(double, double);
  3365. static Value * EvalUnaryIntrinsic(ConstantFP *fpV,
  3366. FloatUnaryEvalFuncType floatEvalFunc,
  3367. DoubleUnaryEvalFuncType doubleEvalFunc) {
  3368. llvm::Type *Ty = fpV->getType();
  3369. Value *Result = nullptr;
  3370. if (Ty->isDoubleTy()) {
  3371. double dV = fpV->getValueAPF().convertToDouble();
  3372. Value *dResult = ConstantFP::get(Ty, doubleEvalFunc(dV));
  3373. Result = dResult;
  3374. } else {
  3375. DXASSERT_NOMSG(Ty->isFloatTy());
  3376. float fV = fpV->getValueAPF().convertToFloat();
  3377. Value *dResult = ConstantFP::get(Ty, floatEvalFunc(fV));
  3378. Result = dResult;
  3379. }
  3380. return Result;
  3381. }
  3382. static Value * EvalBinaryIntrinsic(ConstantFP *fpV0, ConstantFP *fpV1,
  3383. FloatBinaryEvalFuncType floatEvalFunc,
  3384. DoubleBinaryEvalFuncType doubleEvalFunc) {
  3385. llvm::Type *Ty = fpV0->getType();
  3386. Value *Result = nullptr;
  3387. if (Ty->isDoubleTy()) {
  3388. double dV0 = fpV0->getValueAPF().convertToDouble();
  3389. double dV1 = fpV1->getValueAPF().convertToDouble();
  3390. Value *dResult = ConstantFP::get(Ty, doubleEvalFunc(dV0, dV1));
  3391. Result = dResult;
  3392. } else {
  3393. DXASSERT_NOMSG(Ty->isFloatTy());
  3394. float fV0 = fpV0->getValueAPF().convertToFloat();
  3395. float fV1 = fpV1->getValueAPF().convertToFloat();
  3396. Value *dResult = ConstantFP::get(Ty, floatEvalFunc(fV0, fV1));
  3397. Result = dResult;
  3398. }
  3399. return Result;
  3400. }
  3401. static Value * EvalUnaryIntrinsic(CallInst *CI,
  3402. FloatUnaryEvalFuncType floatEvalFunc,
  3403. DoubleUnaryEvalFuncType doubleEvalFunc) {
  3404. Value *V = CI->getArgOperand(0);
  3405. llvm::Type *Ty = CI->getType();
  3406. Value *Result = nullptr;
  3407. if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(Ty)) {
  3408. Result = UndefValue::get(Ty);
  3409. Constant *CV = cast<Constant>(V);
  3410. IRBuilder<> Builder(CI);
  3411. for (unsigned i=0;i<VT->getNumElements();i++) {
  3412. ConstantFP *fpV = cast<ConstantFP>(CV->getAggregateElement(i));
  3413. Value *EltResult = EvalUnaryIntrinsic(fpV, floatEvalFunc, doubleEvalFunc);
  3414. Result = Builder.CreateInsertElement(Result, EltResult, i);
  3415. }
  3416. } else {
  3417. ConstantFP *fpV = cast<ConstantFP>(V);
  3418. Result = EvalUnaryIntrinsic(fpV, floatEvalFunc, doubleEvalFunc);
  3419. }
  3420. CI->replaceAllUsesWith(Result);
  3421. CI->eraseFromParent();
  3422. return Result;
  3423. }
  3424. static Value * EvalBinaryIntrinsic(CallInst *CI,
  3425. FloatBinaryEvalFuncType floatEvalFunc,
  3426. DoubleBinaryEvalFuncType doubleEvalFunc) {
  3427. Value *V0 = CI->getArgOperand(0);
  3428. Value *V1 = CI->getArgOperand(1);
  3429. llvm::Type *Ty = CI->getType();
  3430. Value *Result = nullptr;
  3431. if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(Ty)) {
  3432. Result = UndefValue::get(Ty);
  3433. Constant *CV0 = cast<Constant>(V0);
  3434. Constant *CV1 = cast<Constant>(V1);
  3435. IRBuilder<> Builder(CI);
  3436. for (unsigned i=0;i<VT->getNumElements();i++) {
  3437. ConstantFP *fpV0 = cast<ConstantFP>(CV0->getAggregateElement(i));
  3438. ConstantFP *fpV1 = cast<ConstantFP>(CV1->getAggregateElement(i));
  3439. Value *EltResult = EvalBinaryIntrinsic(fpV0, fpV1, floatEvalFunc, doubleEvalFunc);
  3440. Result = Builder.CreateInsertElement(Result, EltResult, i);
  3441. }
  3442. } else {
  3443. ConstantFP *fpV0 = cast<ConstantFP>(V0);
  3444. ConstantFP *fpV1 = cast<ConstantFP>(V1);
  3445. Result = EvalBinaryIntrinsic(fpV0, fpV1, floatEvalFunc, doubleEvalFunc);
  3446. }
  3447. CI->replaceAllUsesWith(Result);
  3448. CI->eraseFromParent();
  3449. return Result;
  3450. CI->eraseFromParent();
  3451. return Result;
  3452. }
  3453. static Value * TryEvalIntrinsic(CallInst *CI, IntrinsicOp intriOp) {
  3454. switch (intriOp) {
  3455. case IntrinsicOp::IOP_tan: {
  3456. return EvalUnaryIntrinsic(CI, tanf, tan);
  3457. } break;
  3458. case IntrinsicOp::IOP_tanh: {
  3459. return EvalUnaryIntrinsic(CI, tanhf, tanh);
  3460. } break;
  3461. case IntrinsicOp::IOP_sin: {
  3462. return EvalUnaryIntrinsic(CI, sinf, sin);
  3463. } break;
  3464. case IntrinsicOp::IOP_sinh: {
  3465. return EvalUnaryIntrinsic(CI, sinhf, sinh);
  3466. } break;
  3467. case IntrinsicOp::IOP_cos: {
  3468. return EvalUnaryIntrinsic(CI, cosf, cos);
  3469. } break;
  3470. case IntrinsicOp::IOP_cosh: {
  3471. return EvalUnaryIntrinsic(CI, coshf, cosh);
  3472. } break;
  3473. case IntrinsicOp::IOP_asin: {
  3474. return EvalUnaryIntrinsic(CI, asinf, asin);
  3475. } break;
  3476. case IntrinsicOp::IOP_acos: {
  3477. return EvalUnaryIntrinsic(CI, acosf, acos);
  3478. } break;
  3479. case IntrinsicOp::IOP_atan: {
  3480. return EvalUnaryIntrinsic(CI, atanf, atan);
  3481. } break;
  3482. case IntrinsicOp::IOP_atan2: {
  3483. Value *V0 = CI->getArgOperand(0);
  3484. ConstantFP *fpV0 = cast<ConstantFP>(V0);
  3485. Value *V1 = CI->getArgOperand(1);
  3486. ConstantFP *fpV1 = cast<ConstantFP>(V1);
  3487. llvm::Type *Ty = CI->getType();
  3488. Value *Result = nullptr;
  3489. if (Ty->isDoubleTy()) {
  3490. double dV0 = fpV0->getValueAPF().convertToDouble();
  3491. double dV1 = fpV1->getValueAPF().convertToDouble();
  3492. Value *atanV = ConstantFP::get(CI->getType(), atan(dV0 / dV1));
  3493. CI->replaceAllUsesWith(atanV);
  3494. Result = atanV;
  3495. } else {
  3496. DXASSERT_NOMSG(Ty->isFloatTy());
  3497. float fV0 = fpV0->getValueAPF().convertToFloat();
  3498. float fV1 = fpV1->getValueAPF().convertToFloat();
  3499. Value *atanV = ConstantFP::get(CI->getType(), atanf(fV0 / fV1));
  3500. CI->replaceAllUsesWith(atanV);
  3501. Result = atanV;
  3502. }
  3503. CI->eraseFromParent();
  3504. return Result;
  3505. } break;
  3506. case IntrinsicOp::IOP_sqrt: {
  3507. return EvalUnaryIntrinsic(CI, sqrtf, sqrt);
  3508. } break;
  3509. case IntrinsicOp::IOP_rsqrt: {
  3510. auto rsqrtF = [](float v) -> float { return 1.0 / sqrtf(v); };
  3511. auto rsqrtD = [](double v) -> double { return 1.0 / sqrt(v); };
  3512. return EvalUnaryIntrinsic(CI, rsqrtF, rsqrtD);
  3513. } break;
  3514. case IntrinsicOp::IOP_exp: {
  3515. return EvalUnaryIntrinsic(CI, expf, exp);
  3516. } break;
  3517. case IntrinsicOp::IOP_exp2: {
  3518. return EvalUnaryIntrinsic(CI, exp2f, exp2);
  3519. } break;
  3520. case IntrinsicOp::IOP_log: {
  3521. return EvalUnaryIntrinsic(CI, logf, log);
  3522. } break;
  3523. case IntrinsicOp::IOP_log10: {
  3524. return EvalUnaryIntrinsic(CI, log10f, log10);
  3525. } break;
  3526. case IntrinsicOp::IOP_log2: {
  3527. return EvalUnaryIntrinsic(CI, log2f, log2);
  3528. } break;
  3529. case IntrinsicOp::IOP_pow: {
  3530. return EvalBinaryIntrinsic(CI, powf, pow);
  3531. } break;
  3532. case IntrinsicOp::IOP_max: {
  3533. auto maxF = [](float a, float b) -> float { return a > b ? a:b; };
  3534. auto maxD = [](double a, double b) -> double { return a > b ? a:b; };
  3535. return EvalBinaryIntrinsic(CI, maxF, maxD);
  3536. } break;
  3537. case IntrinsicOp::IOP_min: {
  3538. auto minF = [](float a, float b) -> float { return a < b ? a:b; };
  3539. auto minD = [](double a, double b) -> double { return a < b ? a:b; };
  3540. return EvalBinaryIntrinsic(CI, minF, minD);
  3541. } break;
  3542. case IntrinsicOp::IOP_rcp: {
  3543. auto rcpF = [](float v) -> float { return 1.0 / v; };
  3544. auto rcpD = [](double v) -> double { return 1.0 / v; };
  3545. return EvalUnaryIntrinsic(CI, rcpF, rcpD);
  3546. } break;
  3547. case IntrinsicOp::IOP_ceil: {
  3548. return EvalUnaryIntrinsic(CI, ceilf, ceil);
  3549. } break;
  3550. case IntrinsicOp::IOP_floor: {
  3551. return EvalUnaryIntrinsic(CI, floorf, floor);
  3552. } break;
  3553. case IntrinsicOp::IOP_round: {
  3554. return EvalUnaryIntrinsic(CI, roundf, round);
  3555. } break;
  3556. case IntrinsicOp::IOP_trunc: {
  3557. return EvalUnaryIntrinsic(CI, truncf, trunc);
  3558. } break;
  3559. case IntrinsicOp::IOP_frac: {
  3560. auto fracF = [](float v) -> float {
  3561. int exp = 0;
  3562. return frexpf(v, &exp);
  3563. };
  3564. auto fracD = [](double v) -> double {
  3565. int exp = 0;
  3566. return frexp(v, &exp);
  3567. };
  3568. return EvalUnaryIntrinsic(CI, fracF, fracD);
  3569. } break;
  3570. case IntrinsicOp::IOP_isnan: {
  3571. Value *V = CI->getArgOperand(0);
  3572. ConstantFP *fV = cast<ConstantFP>(V);
  3573. bool isNan = fV->getValueAPF().isNaN();
  3574. Constant *cNan = ConstantInt::get(CI->getType(), isNan ? 1 : 0);
  3575. CI->replaceAllUsesWith(cNan);
  3576. CI->eraseFromParent();
  3577. return cNan;
  3578. } break;
  3579. default:
  3580. return nullptr;
  3581. }
  3582. }
  3583. static void SimpleTransformForHLDXIR(Instruction *I,
  3584. std::vector<Instruction *> &deadInsts) {
  3585. unsigned opcode = I->getOpcode();
  3586. switch (opcode) {
  3587. case Instruction::BitCast: {
  3588. BitCastOperator *BCI = cast<BitCastOperator>(I);
  3589. SimplifyBitCast(BCI, deadInsts);
  3590. } break;
  3591. case Instruction::Load: {
  3592. LoadInst *ldInst = cast<LoadInst>(I);
  3593. DXASSERT(!HLMatrixLower::IsMatrixType(ldInst->getType()),
  3594. "matrix load should use HL LdStMatrix");
  3595. Value *Ptr = ldInst->getPointerOperand();
  3596. if (ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(Ptr)) {
  3597. if (BitCastOperator *BCO = dyn_cast<BitCastOperator>(CE)) {
  3598. SimplifyBitCast(BCO, deadInsts);
  3599. }
  3600. }
  3601. } break;
  3602. case Instruction::Store: {
  3603. StoreInst *stInst = cast<StoreInst>(I);
  3604. Value *V = stInst->getValueOperand();
  3605. DXASSERT_LOCALVAR(V, !HLMatrixLower::IsMatrixType(V->getType()),
  3606. "matrix store should use HL LdStMatrix");
  3607. Value *Ptr = stInst->getPointerOperand();
  3608. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
  3609. if (BitCastOperator *BCO = dyn_cast<BitCastOperator>(CE)) {
  3610. SimplifyBitCast(BCO, deadInsts);
  3611. }
  3612. }
  3613. } break;
  3614. case Instruction::LShr:
  3615. case Instruction::AShr:
  3616. case Instruction::Shl: {
  3617. llvm::BinaryOperator *BO = cast<llvm::BinaryOperator>(I);
  3618. Value *op2 = BO->getOperand(1);
  3619. IntegerType *Ty = cast<IntegerType>(BO->getType()->getScalarType());
  3620. unsigned bitWidth = Ty->getBitWidth();
  3621. // Clamp op2 to 0 ~ bitWidth-1
  3622. if (ConstantInt *cOp2 = dyn_cast<ConstantInt>(op2)) {
  3623. unsigned iOp2 = cOp2->getLimitedValue();
  3624. unsigned clampedOp2 = iOp2 & (bitWidth - 1);
  3625. if (iOp2 != clampedOp2) {
  3626. BO->setOperand(1, ConstantInt::get(op2->getType(), clampedOp2));
  3627. }
  3628. } else {
  3629. Value *mask = ConstantInt::get(op2->getType(), bitWidth - 1);
  3630. IRBuilder<> Builder(I);
  3631. op2 = Builder.CreateAnd(op2, mask);
  3632. BO->setOperand(1, op2);
  3633. }
  3634. } break;
  3635. }
  3636. }
  3637. // Do simple transform to make later lower pass easier.
  3638. static void SimpleTransformForHLDXIR(llvm::Module *pM) {
  3639. std::vector<Instruction *> deadInsts;
  3640. for (Function &F : pM->functions()) {
  3641. for (BasicBlock &BB : F.getBasicBlockList()) {
  3642. for (BasicBlock::iterator Iter = BB.begin(); Iter != BB.end(); ) {
  3643. Instruction *I = (Iter++);
  3644. SimpleTransformForHLDXIR(I, deadInsts);
  3645. }
  3646. }
  3647. }
  3648. for (Instruction * I : deadInsts)
  3649. I->dropAllReferences();
  3650. for (Instruction * I : deadInsts)
  3651. I->eraseFromParent();
  3652. deadInsts.clear();
  3653. for (GlobalVariable &GV : pM->globals()) {
  3654. if (dxilutil::IsStaticGlobal(&GV)) {
  3655. for (User *U : GV.users()) {
  3656. if (BitCastOperator *BCO = dyn_cast<BitCastOperator>(U)) {
  3657. SimplifyBitCast(BCO, deadInsts);
  3658. }
  3659. }
  3660. }
  3661. }
  3662. for (Instruction * I : deadInsts)
  3663. I->dropAllReferences();
  3664. for (Instruction * I : deadInsts)
  3665. I->eraseFromParent();
  3666. }
  3667. // Clone shader entry function to be called by other functions.
  3668. // The original function will be used as shader entry.
  3669. static void CloneShaderEntry(Function *ShaderF, StringRef EntryName,
  3670. HLModule &HLM) {
  3671. // Use mangled name for cloned one.
  3672. Function *F = Function::Create(ShaderF->getFunctionType(),
  3673. GlobalValue::LinkageTypes::ExternalLinkage,
  3674. "", HLM.GetModule());
  3675. F->takeName(ShaderF);
  3676. // Set to name before mangled.
  3677. ShaderF->setName(EntryName);
  3678. SmallVector<ReturnInst *, 2> Returns;
  3679. ValueToValueMapTy vmap;
  3680. // Map params.
  3681. auto entryParamIt = F->arg_begin();
  3682. for (Argument &param : ShaderF->args()) {
  3683. vmap[&param] = (entryParamIt++);
  3684. }
  3685. llvm::CloneFunctionInto(F, ShaderF, vmap, /*ModuleLevelChagnes*/ false,
  3686. Returns);
  3687. // Copy function annotation.
  3688. DxilFunctionAnnotation *shaderAnnot = HLM.GetFunctionAnnotation(ShaderF);
  3689. DxilFunctionAnnotation *annot = HLM.AddFunctionAnnotation(F);
  3690. DxilParameterAnnotation &retAnnot = shaderAnnot->GetRetTypeAnnotation();
  3691. DxilParameterAnnotation &cloneRetAnnot = annot->GetRetTypeAnnotation();
  3692. cloneRetAnnot = retAnnot;
  3693. // Clear semantic for cloned one.
  3694. cloneRetAnnot.SetSemanticString("");
  3695. cloneRetAnnot.SetSemanticIndexVec({});
  3696. for (unsigned i = 0; i < shaderAnnot->GetNumParameters(); i++) {
  3697. DxilParameterAnnotation &cloneParamAnnot = annot->GetParameterAnnotation(i);
  3698. DxilParameterAnnotation &paramAnnot =
  3699. shaderAnnot->GetParameterAnnotation(i);
  3700. cloneParamAnnot = paramAnnot;
  3701. // Clear semantic for cloned one.
  3702. cloneParamAnnot.SetSemanticString("");
  3703. cloneParamAnnot.SetSemanticIndexVec({});
  3704. }
  3705. }
  3706. // For case like:
  3707. //cbuffer A {
  3708. // float a;
  3709. // int b;
  3710. //}
  3711. //
  3712. //const static struct {
  3713. // float a;
  3714. // int b;
  3715. //} ST = { a, b };
  3716. // Replace user of ST with a and b.
  3717. static bool ReplaceConstStaticGlobalUser(GEPOperator *GEP,
  3718. std::vector<Constant *> &InitList,
  3719. IRBuilder<> &Builder) {
  3720. if (GEP->getNumIndices() < 2) {
  3721. // Don't use sub element.
  3722. return false;
  3723. }
  3724. SmallVector<Value *, 4> idxList;
  3725. auto iter = GEP->idx_begin();
  3726. idxList.emplace_back(*(iter++));
  3727. ConstantInt *subIdx = dyn_cast<ConstantInt>(*(iter++));
  3728. DXASSERT(subIdx, "else dynamic indexing on struct field");
  3729. unsigned subIdxImm = subIdx->getLimitedValue();
  3730. DXASSERT(subIdxImm < InitList.size(), "else struct index out of bound");
  3731. Constant *subPtr = InitList[subIdxImm];
  3732. // Move every idx to idxList except idx for InitList.
  3733. while (iter != GEP->idx_end()) {
  3734. idxList.emplace_back(*(iter++));
  3735. }
  3736. Value *NewGEP = Builder.CreateGEP(subPtr, idxList);
  3737. GEP->replaceAllUsesWith(NewGEP);
  3738. return true;
  3739. }
  3740. static void ReplaceConstStaticGlobals(
  3741. std::unordered_map<GlobalVariable *, std::vector<Constant *>>
  3742. &staticConstGlobalInitListMap,
  3743. std::unordered_map<GlobalVariable *, Function *>
  3744. &staticConstGlobalCtorMap) {
  3745. for (auto &iter : staticConstGlobalInitListMap) {
  3746. GlobalVariable *GV = iter.first;
  3747. std::vector<Constant *> &InitList = iter.second;
  3748. LLVMContext &Ctx = GV->getContext();
  3749. // Do the replace.
  3750. bool bPass = true;
  3751. for (User *U : GV->users()) {
  3752. IRBuilder<> Builder(Ctx);
  3753. if (GetElementPtrInst *GEPInst = dyn_cast<GetElementPtrInst>(U)) {
  3754. Builder.SetInsertPoint(GEPInst);
  3755. bPass &= ReplaceConstStaticGlobalUser(cast<GEPOperator>(GEPInst), InitList, Builder);
  3756. } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
  3757. bPass &= ReplaceConstStaticGlobalUser(GEP, InitList, Builder);
  3758. } else {
  3759. DXASSERT(false, "invalid user of const static global");
  3760. }
  3761. }
  3762. // Clear the Ctor which is useless now.
  3763. if (bPass) {
  3764. Function *Ctor = staticConstGlobalCtorMap[GV];
  3765. Ctor->getBasicBlockList().clear();
  3766. BasicBlock *Entry = BasicBlock::Create(Ctx, "", Ctor);
  3767. IRBuilder<> Builder(Entry);
  3768. Builder.CreateRetVoid();
  3769. }
  3770. }
  3771. }
  3772. bool BuildImmInit(Function *Ctor) {
  3773. GlobalVariable *GV = nullptr;
  3774. SmallVector<Constant *, 4> ImmList;
  3775. bool allConst = true;
  3776. for (inst_iterator I = inst_begin(Ctor), E = inst_end(Ctor); I != E; ++I) {
  3777. if (StoreInst *SI = dyn_cast<StoreInst>(&(*I))) {
  3778. Value *V = SI->getValueOperand();
  3779. if (!isa<Constant>(V) || V->getType()->isPointerTy()) {
  3780. allConst = false;
  3781. break;
  3782. }
  3783. ImmList.emplace_back(cast<Constant>(V));
  3784. Value *Ptr = SI->getPointerOperand();
  3785. if (GEPOperator *GepOp = dyn_cast<GEPOperator>(Ptr)) {
  3786. Ptr = GepOp->getPointerOperand();
  3787. if (GlobalVariable *pGV = dyn_cast<GlobalVariable>(Ptr)) {
  3788. if (GV == nullptr)
  3789. GV = pGV;
  3790. else
  3791. DXASSERT(GV == pGV, "else pointer mismatch");
  3792. }
  3793. }
  3794. } else {
  3795. if (!isa<ReturnInst>(*I)) {
  3796. allConst = false;
  3797. break;
  3798. }
  3799. }
  3800. }
  3801. if (!allConst)
  3802. return false;
  3803. if (!GV)
  3804. return false;
  3805. llvm::Type *Ty = GV->getType()->getElementType();
  3806. llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty);
  3807. // TODO: support other types.
  3808. if (!AT)
  3809. return false;
  3810. if (ImmList.size() != AT->getNumElements())
  3811. return false;
  3812. Constant *Init = llvm::ConstantArray::get(AT, ImmList);
  3813. GV->setInitializer(Init);
  3814. return true;
  3815. }
  3816. void ProcessCtorFunctions(llvm::Module &M, StringRef globalName,
  3817. Instruction *InsertPt) {
  3818. // add global call to entry func
  3819. GlobalVariable *GV = M.getGlobalVariable(globalName);
  3820. if (GV) {
  3821. if (ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer())) {
  3822. IRBuilder<> Builder(InsertPt);
  3823. for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e;
  3824. ++i) {
  3825. if (isa<ConstantAggregateZero>(*i))
  3826. continue;
  3827. ConstantStruct *CS = cast<ConstantStruct>(*i);
  3828. if (isa<ConstantPointerNull>(CS->getOperand(1)))
  3829. continue;
  3830. // Must have a function or null ptr.
  3831. if (!isa<Function>(CS->getOperand(1)))
  3832. continue;
  3833. Function *Ctor = cast<Function>(CS->getOperand(1));
  3834. DXASSERT(Ctor->getReturnType()->isVoidTy() && Ctor->arg_size() == 0,
  3835. "function type must be void (void)");
  3836. for (inst_iterator I = inst_begin(Ctor), E = inst_end(Ctor); I != E;
  3837. ++I) {
  3838. if (CallInst *CI = dyn_cast<CallInst>(&(*I))) {
  3839. Function *F = CI->getCalledFunction();
  3840. // Try to build imm initilizer.
  3841. // If not work, add global call to entry func.
  3842. if (BuildImmInit(F) == false) {
  3843. Builder.CreateCall(F);
  3844. }
  3845. } else {
  3846. DXASSERT(isa<ReturnInst>(&(*I)),
  3847. "else invalid Global constructor function");
  3848. }
  3849. }
  3850. }
  3851. // remove the GV
  3852. GV->eraseFromParent();
  3853. }
  3854. }
  3855. }
  3856. void CGMSHLSLRuntime::SetPatchConstantFunction(const EntryFunctionInfo &EntryFunc) {
  3857. auto AttrsIter = HSEntryPatchConstantFuncAttr.find(EntryFunc.Func);
  3858. DXASSERT(AttrsIter != HSEntryPatchConstantFuncAttr.end(),
  3859. "we have checked this in AddHLSLFunctionInfo()");
  3860. SetPatchConstantFunctionWithAttr(Entry, AttrsIter->second);
  3861. }
  3862. void CGMSHLSLRuntime::SetPatchConstantFunctionWithAttr(
  3863. const EntryFunctionInfo &EntryFunc,
  3864. const clang::HLSLPatchConstantFuncAttr *PatchConstantFuncAttr) {
  3865. StringRef funcName = PatchConstantFuncAttr->getFunctionName();
  3866. auto Entry = patchConstantFunctionMap.find(funcName);
  3867. if (Entry == patchConstantFunctionMap.end()) {
  3868. DiagnosticsEngine &Diags = CGM.getDiags();
  3869. unsigned DiagID =
  3870. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  3871. "Cannot find patchconstantfunc %0.");
  3872. Diags.Report(PatchConstantFuncAttr->getLocation(), DiagID)
  3873. << funcName;
  3874. return;
  3875. }
  3876. if (Entry->second.NumOverloads != 1) {
  3877. DiagnosticsEngine &Diags = CGM.getDiags();
  3878. unsigned DiagID =
  3879. Diags.getCustomDiagID(DiagnosticsEngine::Warning,
  3880. "Multiple overloads of patchconstantfunc %0.");
  3881. unsigned NoteID =
  3882. Diags.getCustomDiagID(DiagnosticsEngine::Note,
  3883. "This overload was selected.");
  3884. Diags.Report(PatchConstantFuncAttr->getLocation(), DiagID)
  3885. << funcName;
  3886. Diags.Report(Entry->second.SL, NoteID);
  3887. }
  3888. Function *patchConstFunc = Entry->second.Func;
  3889. DXASSERT(m_pHLModule->HasDxilFunctionProps(EntryFunc.Func),
  3890. " else AddHLSLFunctionInfo did not save the dxil function props for the "
  3891. "HS entry.");
  3892. DxilFunctionProps *HSProps = &m_pHLModule->GetDxilFunctionProps(EntryFunc.Func);
  3893. m_pHLModule->SetPatchConstantFunctionForHS(EntryFunc.Func, patchConstFunc);
  3894. DXASSERT_NOMSG(patchConstantFunctionPropsMap.count(patchConstFunc));
  3895. // Check no inout parameter for patch constant function.
  3896. DxilFunctionAnnotation *patchConstFuncAnnotation =
  3897. m_pHLModule->GetFunctionAnnotation(patchConstFunc);
  3898. for (unsigned i = 0; i < patchConstFuncAnnotation->GetNumParameters(); i++) {
  3899. if (patchConstFuncAnnotation->GetParameterAnnotation(i)
  3900. .GetParamInputQual() == DxilParamInputQual::Inout) {
  3901. DiagnosticsEngine &Diags = CGM.getDiags();
  3902. unsigned DiagID = Diags.getCustomDiagID(
  3903. DiagnosticsEngine::Error,
  3904. "Patch Constant function %0 should not have inout param.");
  3905. Diags.Report(Entry->second.SL, DiagID) << funcName;
  3906. }
  3907. }
  3908. // Input/Output control point validation.
  3909. if (patchConstantFunctionPropsMap.count(patchConstFunc)) {
  3910. const DxilFunctionProps &patchProps =
  3911. *patchConstantFunctionPropsMap[patchConstFunc];
  3912. if (patchProps.ShaderProps.HS.inputControlPoints != 0 &&
  3913. patchProps.ShaderProps.HS.inputControlPoints !=
  3914. HSProps->ShaderProps.HS.inputControlPoints) {
  3915. DiagnosticsEngine &Diags = CGM.getDiags();
  3916. unsigned DiagID =
  3917. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  3918. "Patch constant function's input patch input "
  3919. "should have %0 elements, but has %1.");
  3920. Diags.Report(Entry->second.SL, DiagID)
  3921. << HSProps->ShaderProps.HS.inputControlPoints
  3922. << patchProps.ShaderProps.HS.inputControlPoints;
  3923. }
  3924. if (patchProps.ShaderProps.HS.outputControlPoints != 0 &&
  3925. patchProps.ShaderProps.HS.outputControlPoints !=
  3926. HSProps->ShaderProps.HS.outputControlPoints) {
  3927. DiagnosticsEngine &Diags = CGM.getDiags();
  3928. unsigned DiagID = Diags.getCustomDiagID(
  3929. DiagnosticsEngine::Error,
  3930. "Patch constant function's output patch input "
  3931. "should have %0 elements, but has %1.");
  3932. Diags.Report(Entry->second.SL, DiagID)
  3933. << HSProps->ShaderProps.HS.outputControlPoints
  3934. << patchProps.ShaderProps.HS.outputControlPoints;
  3935. }
  3936. }
  3937. }
  3938. void CGMSHLSLRuntime::FinishCodeGen() {
  3939. // Library don't have entry.
  3940. if (!m_bIsLib) {
  3941. SetEntryFunction();
  3942. // If at this point we haven't determined the entry function it's an error.
  3943. if (m_pHLModule->GetEntryFunction() == nullptr) {
  3944. assert(CGM.getDiags().hasErrorOccurred() &&
  3945. "else SetEntryFunction should have reported this condition");
  3946. return;
  3947. }
  3948. if (m_pHLModule->GetShaderModel()->IsHS()) {
  3949. SetPatchConstantFunction(Entry);
  3950. }
  3951. } else {
  3952. for (auto &it : entryFunctionMap) {
  3953. // skip clone if RT entry
  3954. if (m_pHLModule->GetDxilFunctionProps(it.second.Func).IsRay())
  3955. continue;
  3956. CloneShaderEntry(it.second.Func, it.getKey(), *m_pHLModule);
  3957. auto AttrIter = HSEntryPatchConstantFuncAttr.find(it.second.Func);
  3958. if (AttrIter != HSEntryPatchConstantFuncAttr.end()) {
  3959. SetPatchConstantFunctionWithAttr(it.second, AttrIter->second);
  3960. }
  3961. }
  3962. }
  3963. ReplaceConstStaticGlobals(staticConstGlobalInitListMap,
  3964. staticConstGlobalCtorMap);
  3965. // Create copy for clip plane.
  3966. for (Function *F : clipPlaneFuncList) {
  3967. DxilFunctionProps &props = m_pHLModule->GetDxilFunctionProps(F);
  3968. IRBuilder<> Builder(F->getEntryBlock().getFirstInsertionPt());
  3969. for (unsigned i = 0; i < DXIL::kNumClipPlanes; i++) {
  3970. Value *clipPlane = props.ShaderProps.VS.clipPlanes[i];
  3971. if (!clipPlane)
  3972. continue;
  3973. if (m_bDebugInfo) {
  3974. Builder.SetCurrentDebugLocation(debugInfoMap[clipPlane]);
  3975. }
  3976. llvm::Type *Ty = clipPlane->getType()->getPointerElementType();
  3977. // Constant *zeroInit = ConstantFP::get(Ty, 0);
  3978. GlobalVariable *GV = new llvm::GlobalVariable(
  3979. TheModule, Ty, /*IsConstant*/ false, // constant false to store.
  3980. llvm::GlobalValue::ExternalLinkage,
  3981. /*InitVal*/ nullptr, Twine("SV_ClipPlane") + Twine(i));
  3982. Value *initVal = Builder.CreateLoad(clipPlane);
  3983. Builder.CreateStore(initVal, GV);
  3984. props.ShaderProps.VS.clipPlanes[i] = GV;
  3985. }
  3986. }
  3987. // Allocate constant buffers.
  3988. AllocateDxilConstantBuffers(m_pHLModule);
  3989. // TODO: create temp variable for constant which has store use.
  3990. // Create Global variable and type annotation for each CBuffer.
  3991. ConstructCBuffer(m_pHLModule, CBufferType, m_ConstVarAnnotationMap);
  3992. if (!m_bIsLib) {
  3993. // need this for "llvm.global_dtors"?
  3994. ProcessCtorFunctions(TheModule ,"llvm.global_ctors",
  3995. Entry.Func->getEntryBlock().getFirstInsertionPt());
  3996. }
  3997. // translate opcode into parameter for intrinsic functions
  3998. AddOpcodeParamForIntrinsics(*m_pHLModule, m_IntrinsicMap, resMetadataMap);
  3999. // Pin entry point and constant buffers, mark everything else internal.
  4000. for (Function &f : m_pHLModule->GetModule()->functions()) {
  4001. if (!m_bIsLib) {
  4002. if (&f == m_pHLModule->GetEntryFunction() ||
  4003. IsPatchConstantFunction(&f) || f.isDeclaration()) {
  4004. f.setLinkage(GlobalValue::LinkageTypes::ExternalLinkage);
  4005. } else {
  4006. f.setLinkage(GlobalValue::LinkageTypes::InternalLinkage);
  4007. }
  4008. }
  4009. // Skip no inline functions.
  4010. if (f.hasFnAttribute(llvm::Attribute::NoInline))
  4011. continue;
  4012. // Always inline for used functions.
  4013. if (!f.user_empty())
  4014. f.addFnAttr(llvm::Attribute::AlwaysInline);
  4015. }
  4016. // Do simple transform to make later lower pass easier.
  4017. SimpleTransformForHLDXIR(m_pHLModule->GetModule());
  4018. // Handle lang extensions if provided.
  4019. if (CGM.getCodeGenOpts().HLSLExtensionsCodegen) {
  4020. // Add semantic defines for extensions if any are available.
  4021. HLSLExtensionsCodegenHelper::SemanticDefineErrorList errors =
  4022. CGM.getCodeGenOpts().HLSLExtensionsCodegen->WriteSemanticDefines(m_pHLModule->GetModule());
  4023. DiagnosticsEngine &Diags = CGM.getDiags();
  4024. for (const HLSLExtensionsCodegenHelper::SemanticDefineError& error : errors) {
  4025. DiagnosticsEngine::Level level = DiagnosticsEngine::Error;
  4026. if (error.IsWarning())
  4027. level = DiagnosticsEngine::Warning;
  4028. unsigned DiagID = Diags.getCustomDiagID(level, "%0");
  4029. Diags.Report(SourceLocation::getFromRawEncoding(error.Location()), DiagID) << error.Message();
  4030. }
  4031. // Add root signature from a #define. Overrides root signature in function attribute.
  4032. {
  4033. using Status = HLSLExtensionsCodegenHelper::CustomRootSignature::Status;
  4034. HLSLExtensionsCodegenHelper::CustomRootSignature customRootSig;
  4035. Status status = CGM.getCodeGenOpts().HLSLExtensionsCodegen->GetCustomRootSignature(&customRootSig);
  4036. if (status == Status::FOUND) {
  4037. CompileRootSignature(customRootSig.RootSignature, Diags,
  4038. SourceLocation::getFromRawEncoding(customRootSig.EncodedSourceLocation),
  4039. rootSigVer, &m_pHLModule->GetRootSignature());
  4040. }
  4041. }
  4042. }
  4043. // At this point, we have a high-level DXIL module - record this.
  4044. SetPauseResumePasses(*m_pHLModule->GetModule(), "hlsl-hlemit", "hlsl-hlensure");
  4045. }
  4046. RValue CGMSHLSLRuntime::EmitHLSLBuiltinCallExpr(CodeGenFunction &CGF,
  4047. const FunctionDecl *FD,
  4048. const CallExpr *E,
  4049. ReturnValueSlot ReturnValue) {
  4050. StringRef name = FD->getName();
  4051. const Decl *TargetDecl = E->getCalleeDecl();
  4052. llvm::Value *Callee = CGF.EmitScalarExpr(E->getCallee());
  4053. RValue RV = CGF.EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue,
  4054. TargetDecl);
  4055. if (RV.isScalar() && RV.getScalarVal() != nullptr) {
  4056. if (CallInst *CI = dyn_cast<CallInst>(RV.getScalarVal())) {
  4057. Function *F = CI->getCalledFunction();
  4058. HLOpcodeGroup group = hlsl::GetHLOpcodeGroup(F);
  4059. if (group == HLOpcodeGroup::HLIntrinsic) {
  4060. bool allOperandImm = true;
  4061. for (auto &operand : CI->arg_operands()) {
  4062. bool isImm = isa<ConstantInt>(operand) || isa<ConstantFP>(operand) ||
  4063. isa<ConstantAggregateZero>(operand) || isa<ConstantDataVector>(operand);
  4064. if (!isImm) {
  4065. allOperandImm = false;
  4066. break;
  4067. } else if (operand->getType()->isHalfTy()) {
  4068. // Not support half Eval yet.
  4069. allOperandImm = false;
  4070. break;
  4071. }
  4072. }
  4073. if (allOperandImm) {
  4074. unsigned intrinsicOpcode;
  4075. StringRef intrinsicGroup;
  4076. hlsl::GetIntrinsicOp(FD, intrinsicOpcode, intrinsicGroup);
  4077. IntrinsicOp opcode = static_cast<IntrinsicOp>(intrinsicOpcode);
  4078. if (Value *Result = TryEvalIntrinsic(CI, opcode)) {
  4079. RV = RValue::get(Result);
  4080. }
  4081. }
  4082. }
  4083. }
  4084. }
  4085. return RV;
  4086. }
  4087. static HLOpcodeGroup GetHLOpcodeGroup(const clang::Stmt::StmtClass stmtClass) {
  4088. switch (stmtClass) {
  4089. case Stmt::CStyleCastExprClass:
  4090. case Stmt::ImplicitCastExprClass:
  4091. case Stmt::CXXFunctionalCastExprClass:
  4092. return HLOpcodeGroup::HLCast;
  4093. case Stmt::InitListExprClass:
  4094. return HLOpcodeGroup::HLInit;
  4095. case Stmt::BinaryOperatorClass:
  4096. case Stmt::CompoundAssignOperatorClass:
  4097. return HLOpcodeGroup::HLBinOp;
  4098. case Stmt::UnaryOperatorClass:
  4099. return HLOpcodeGroup::HLUnOp;
  4100. case Stmt::ExtMatrixElementExprClass:
  4101. return HLOpcodeGroup::HLSubscript;
  4102. case Stmt::CallExprClass:
  4103. return HLOpcodeGroup::HLIntrinsic;
  4104. case Stmt::ConditionalOperatorClass:
  4105. return HLOpcodeGroup::HLSelect;
  4106. default:
  4107. llvm_unreachable("not support operation");
  4108. }
  4109. }
  4110. // NOTE: This table must match BinaryOperator::Opcode
  4111. static const HLBinaryOpcode BinaryOperatorKindMap[] = {
  4112. HLBinaryOpcode::Invalid, // PtrMemD
  4113. HLBinaryOpcode::Invalid, // PtrMemI
  4114. HLBinaryOpcode::Mul, HLBinaryOpcode::Div, HLBinaryOpcode::Rem,
  4115. HLBinaryOpcode::Add, HLBinaryOpcode::Sub, HLBinaryOpcode::Shl,
  4116. HLBinaryOpcode::Shr, HLBinaryOpcode::LT, HLBinaryOpcode::GT,
  4117. HLBinaryOpcode::LE, HLBinaryOpcode::GE, HLBinaryOpcode::EQ,
  4118. HLBinaryOpcode::NE, HLBinaryOpcode::And, HLBinaryOpcode::Xor,
  4119. HLBinaryOpcode::Or, HLBinaryOpcode::LAnd, HLBinaryOpcode::LOr,
  4120. HLBinaryOpcode::Invalid, // Assign,
  4121. // The assign part is done by matrix store
  4122. HLBinaryOpcode::Mul, // MulAssign
  4123. HLBinaryOpcode::Div, // DivAssign
  4124. HLBinaryOpcode::Rem, // RemAssign
  4125. HLBinaryOpcode::Add, // AddAssign
  4126. HLBinaryOpcode::Sub, // SubAssign
  4127. HLBinaryOpcode::Shl, // ShlAssign
  4128. HLBinaryOpcode::Shr, // ShrAssign
  4129. HLBinaryOpcode::And, // AndAssign
  4130. HLBinaryOpcode::Xor, // XorAssign
  4131. HLBinaryOpcode::Or, // OrAssign
  4132. HLBinaryOpcode::Invalid, // Comma
  4133. };
  4134. // NOTE: This table must match UnaryOperator::Opcode
  4135. static const HLUnaryOpcode UnaryOperatorKindMap[] = {
  4136. HLUnaryOpcode::PostInc, HLUnaryOpcode::PostDec,
  4137. HLUnaryOpcode::PreInc, HLUnaryOpcode::PreDec,
  4138. HLUnaryOpcode::Invalid, // AddrOf,
  4139. HLUnaryOpcode::Invalid, // Deref,
  4140. HLUnaryOpcode::Plus, HLUnaryOpcode::Minus,
  4141. HLUnaryOpcode::Not, HLUnaryOpcode::LNot,
  4142. HLUnaryOpcode::Invalid, // Real,
  4143. HLUnaryOpcode::Invalid, // Imag,
  4144. HLUnaryOpcode::Invalid, // Extension
  4145. };
  4146. static bool IsRowMajorMatrix(QualType Ty, bool bDefaultRowMajor) {
  4147. if (const AttributedType *AT = Ty->getAs<AttributedType>()) {
  4148. if (AT->getAttrKind() == AttributedType::attr_hlsl_row_major)
  4149. return true;
  4150. else if (AT->getAttrKind() == AttributedType::attr_hlsl_column_major)
  4151. return false;
  4152. else
  4153. return bDefaultRowMajor;
  4154. } else {
  4155. return bDefaultRowMajor;
  4156. }
  4157. }
  4158. static bool IsUnsigned(QualType Ty) {
  4159. Ty = Ty.getCanonicalType().getNonReferenceType();
  4160. if (hlsl::IsHLSLVecMatType(Ty))
  4161. Ty = CGHLSLRuntime::GetHLSLVecMatElementType(Ty);
  4162. if (Ty->isExtVectorType())
  4163. Ty = Ty->getAs<clang::ExtVectorType>()->getElementType();
  4164. return Ty->isUnsignedIntegerType();
  4165. }
  4166. static unsigned GetHLOpcode(const Expr *E) {
  4167. switch (E->getStmtClass()) {
  4168. case Stmt::CompoundAssignOperatorClass:
  4169. case Stmt::BinaryOperatorClass: {
  4170. const clang::BinaryOperator *binOp = cast<clang::BinaryOperator>(E);
  4171. HLBinaryOpcode binOpcode = BinaryOperatorKindMap[binOp->getOpcode()];
  4172. if (HasUnsignedOpcode(binOpcode)) {
  4173. if (IsUnsigned(binOp->getLHS()->getType())) {
  4174. binOpcode = GetUnsignedOpcode(binOpcode);
  4175. }
  4176. }
  4177. return static_cast<unsigned>(binOpcode);
  4178. }
  4179. case Stmt::UnaryOperatorClass: {
  4180. const UnaryOperator *unOp = cast<clang::UnaryOperator>(E);
  4181. HLUnaryOpcode unOpcode = UnaryOperatorKindMap[unOp->getOpcode()];
  4182. return static_cast<unsigned>(unOpcode);
  4183. }
  4184. case Stmt::ImplicitCastExprClass:
  4185. case Stmt::CStyleCastExprClass: {
  4186. const CastExpr *CE = cast<CastExpr>(E);
  4187. bool toUnsigned = IsUnsigned(E->getType());
  4188. bool fromUnsigned = IsUnsigned(CE->getSubExpr()->getType());
  4189. if (toUnsigned && fromUnsigned)
  4190. return static_cast<unsigned>(HLCastOpcode::UnsignedUnsignedCast);
  4191. else if (toUnsigned)
  4192. return static_cast<unsigned>(HLCastOpcode::ToUnsignedCast);
  4193. else if (fromUnsigned)
  4194. return static_cast<unsigned>(HLCastOpcode::FromUnsignedCast);
  4195. else
  4196. return static_cast<unsigned>(HLCastOpcode::DefaultCast);
  4197. }
  4198. default:
  4199. return 0;
  4200. }
  4201. }
  4202. static Value *
  4203. EmitHLSLMatrixOperationCallImp(CGBuilderTy &Builder, HLOpcodeGroup group,
  4204. unsigned opcode, llvm::Type *RetType,
  4205. ArrayRef<Value *> paramList, llvm::Module &M) {
  4206. SmallVector<llvm::Type *, 4> paramTyList;
  4207. // Add the opcode param
  4208. llvm::Type *opcodeTy = llvm::Type::getInt32Ty(M.getContext());
  4209. paramTyList.emplace_back(opcodeTy);
  4210. for (Value *param : paramList) {
  4211. paramTyList.emplace_back(param->getType());
  4212. }
  4213. llvm::FunctionType *funcTy =
  4214. llvm::FunctionType::get(RetType, paramTyList, false);
  4215. Function *opFunc = GetOrCreateHLFunction(M, funcTy, group, opcode);
  4216. SmallVector<Value *, 4> opcodeParamList;
  4217. Value *opcodeConst = Constant::getIntegerValue(opcodeTy, APInt(32, opcode));
  4218. opcodeParamList.emplace_back(opcodeConst);
  4219. opcodeParamList.append(paramList.begin(), paramList.end());
  4220. return Builder.CreateCall(opFunc, opcodeParamList);
  4221. }
  4222. static Value *EmitHLSLArrayInit(CGBuilderTy &Builder, HLOpcodeGroup group,
  4223. unsigned opcode, llvm::Type *RetType,
  4224. ArrayRef<Value *> paramList, llvm::Module &M) {
  4225. // It's a matrix init.
  4226. if (!RetType->isVoidTy())
  4227. return EmitHLSLMatrixOperationCallImp(Builder, group, opcode, RetType,
  4228. paramList, M);
  4229. Value *arrayPtr = paramList[0];
  4230. llvm::ArrayType *AT =
  4231. cast<llvm::ArrayType>(arrayPtr->getType()->getPointerElementType());
  4232. // Avoid the arrayPtr.
  4233. unsigned paramSize = paramList.size() - 1;
  4234. // Support simple case here.
  4235. if (paramSize == AT->getArrayNumElements()) {
  4236. bool typeMatch = true;
  4237. llvm::Type *EltTy = AT->getArrayElementType();
  4238. if (EltTy->isAggregateType()) {
  4239. // Aggregate Type use pointer in initList.
  4240. EltTy = llvm::PointerType::get(EltTy, 0);
  4241. }
  4242. for (unsigned i = 1; i < paramList.size(); i++) {
  4243. if (paramList[i]->getType() != EltTy) {
  4244. typeMatch = false;
  4245. break;
  4246. }
  4247. }
  4248. // Both size and type match.
  4249. if (typeMatch) {
  4250. bool isPtr = EltTy->isPointerTy();
  4251. llvm::Type *i32Ty = llvm::Type::getInt32Ty(EltTy->getContext());
  4252. Constant *zero = ConstantInt::get(i32Ty, 0);
  4253. for (unsigned i = 1; i < paramList.size(); i++) {
  4254. Constant *idx = ConstantInt::get(i32Ty, i - 1);
  4255. Value *GEP = Builder.CreateInBoundsGEP(arrayPtr, {zero, idx});
  4256. Value *Elt = paramList[i];
  4257. if (isPtr) {
  4258. Elt = Builder.CreateLoad(Elt);
  4259. }
  4260. Builder.CreateStore(Elt, GEP);
  4261. }
  4262. // The return value will not be used.
  4263. return nullptr;
  4264. }
  4265. }
  4266. // Other case will be lowered in later pass.
  4267. return EmitHLSLMatrixOperationCallImp(Builder, group, opcode, RetType,
  4268. paramList, M);
  4269. }
  4270. void CGMSHLSLRuntime::FlattenValToInitList(CodeGenFunction &CGF, SmallVector<Value *, 4> &elts,
  4271. SmallVector<QualType, 4> &eltTys,
  4272. QualType Ty, Value *val) {
  4273. CGBuilderTy &Builder = CGF.Builder;
  4274. llvm::Type *valTy = val->getType();
  4275. if (valTy->isPointerTy()) {
  4276. llvm::Type *valEltTy = valTy->getPointerElementType();
  4277. if (valEltTy->isVectorTy() ||
  4278. valEltTy->isSingleValueType()) {
  4279. Value *ldVal = Builder.CreateLoad(val);
  4280. FlattenValToInitList(CGF, elts, eltTys, Ty, ldVal);
  4281. } else if (HLMatrixLower::IsMatrixType(valEltTy)) {
  4282. Value *ldVal = EmitHLSLMatrixLoad(Builder, val, Ty);
  4283. FlattenValToInitList(CGF, elts, eltTys, Ty, ldVal);
  4284. } else {
  4285. llvm::Type *i32Ty = llvm::Type::getInt32Ty(valTy->getContext());
  4286. Value *zero = ConstantInt::get(i32Ty, 0);
  4287. if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(valEltTy)) {
  4288. QualType EltTy = Ty->getAsArrayTypeUnsafe()->getElementType();
  4289. for (unsigned i = 0; i < AT->getArrayNumElements(); i++) {
  4290. Value *gepIdx = ConstantInt::get(i32Ty, i);
  4291. Value *EltPtr = Builder.CreateInBoundsGEP(val, {zero, gepIdx});
  4292. FlattenValToInitList(CGF, elts, eltTys, EltTy,EltPtr);
  4293. }
  4294. } else {
  4295. // Struct.
  4296. StructType *ST = cast<StructType>(valEltTy);
  4297. if (HLModule::IsHLSLObjectType(ST)) {
  4298. // Save object directly like basic type.
  4299. elts.emplace_back(Builder.CreateLoad(val));
  4300. eltTys.emplace_back(Ty);
  4301. } else {
  4302. RecordDecl *RD = Ty->getAsStructureType()->getDecl();
  4303. const CGRecordLayout& RL = CGF.getTypes().getCGRecordLayout(RD);
  4304. // Take care base.
  4305. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  4306. if (CXXRD->getNumBases()) {
  4307. for (const auto &I : CXXRD->bases()) {
  4308. const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(
  4309. I.getType()->castAs<RecordType>()->getDecl());
  4310. if (BaseDecl->field_empty())
  4311. continue;
  4312. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  4313. unsigned i = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  4314. Value *gepIdx = ConstantInt::get(i32Ty, i);
  4315. Value *EltPtr = Builder.CreateInBoundsGEP(val, {zero, gepIdx});
  4316. FlattenValToInitList(CGF, elts, eltTys, parentTy, EltPtr);
  4317. }
  4318. }
  4319. }
  4320. for (auto fieldIter = RD->field_begin(), fieldEnd = RD->field_end();
  4321. fieldIter != fieldEnd; ++fieldIter) {
  4322. unsigned i = RL.getLLVMFieldNo(*fieldIter);
  4323. Value *gepIdx = ConstantInt::get(i32Ty, i);
  4324. Value *EltPtr = Builder.CreateInBoundsGEP(val, {zero, gepIdx});
  4325. FlattenValToInitList(CGF, elts, eltTys, fieldIter->getType(), EltPtr);
  4326. }
  4327. }
  4328. }
  4329. }
  4330. } else {
  4331. if (HLMatrixLower::IsMatrixType(valTy)) {
  4332. unsigned col, row;
  4333. llvm::Type *EltTy = HLMatrixLower::GetMatrixInfo(valTy, col, row);
  4334. // All matrix Value should be row major.
  4335. // Init list is row major in scalar.
  4336. // So the order is match here, just cast to vector.
  4337. unsigned matSize = col * row;
  4338. bool isRowMajor = IsRowMajorMatrix(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  4339. HLCastOpcode opcode = isRowMajor ? HLCastOpcode::RowMatrixToVecCast
  4340. : HLCastOpcode::ColMatrixToVecCast;
  4341. // Cast to vector.
  4342. val = EmitHLSLMatrixOperationCallImp(
  4343. Builder, HLOpcodeGroup::HLCast,
  4344. static_cast<unsigned>(opcode),
  4345. llvm::VectorType::get(EltTy, matSize), {val}, TheModule);
  4346. valTy = val->getType();
  4347. }
  4348. if (valTy->isVectorTy()) {
  4349. QualType EltTy = GetHLSLVecMatElementType(Ty);
  4350. unsigned vecSize = valTy->getVectorNumElements();
  4351. for (unsigned i = 0; i < vecSize; i++) {
  4352. Value *Elt = Builder.CreateExtractElement(val, i);
  4353. elts.emplace_back(Elt);
  4354. eltTys.emplace_back(EltTy);
  4355. }
  4356. } else {
  4357. DXASSERT(valTy->isSingleValueType(), "must be single value type here");
  4358. elts.emplace_back(val);
  4359. eltTys.emplace_back(Ty);
  4360. }
  4361. }
  4362. }
  4363. // Cast elements in initlist if not match the target type.
  4364. // idx is current element index in initlist, Ty is target type.
  4365. static void AddMissingCastOpsInInitList(SmallVector<Value *, 4> &elts, SmallVector<QualType, 4> &eltTys, unsigned &idx, QualType Ty, CodeGenFunction &CGF) {
  4366. if (Ty->isArrayType()) {
  4367. const clang::ArrayType *AT = Ty->getAsArrayTypeUnsafe();
  4368. // Must be ConstantArrayType here.
  4369. unsigned arraySize = cast<ConstantArrayType>(AT)->getSize().getLimitedValue();
  4370. QualType EltTy = AT->getElementType();
  4371. for (unsigned i = 0; i < arraySize; i++)
  4372. AddMissingCastOpsInInitList(elts, eltTys, idx, EltTy, CGF);
  4373. } else if (IsHLSLVecType(Ty)) {
  4374. QualType EltTy = GetHLSLVecElementType(Ty);
  4375. unsigned vecSize = GetHLSLVecSize(Ty);
  4376. for (unsigned i=0;i< vecSize;i++)
  4377. AddMissingCastOpsInInitList(elts, eltTys, idx, EltTy, CGF);
  4378. } else if (IsHLSLMatType(Ty)) {
  4379. QualType EltTy = GetHLSLMatElementType(Ty);
  4380. unsigned row, col;
  4381. GetHLSLMatRowColCount(Ty, row, col);
  4382. unsigned matSize = row*col;
  4383. for (unsigned i = 0; i < matSize; i++)
  4384. AddMissingCastOpsInInitList(elts, eltTys, idx, EltTy, CGF);
  4385. } else if (Ty->isRecordType()) {
  4386. if (HLModule::IsHLSLObjectType(CGF.ConvertType(Ty))) {
  4387. // Skip hlsl object.
  4388. idx++;
  4389. } else {
  4390. const RecordType *RT = Ty->getAsStructureType();
  4391. // For CXXRecord.
  4392. if (!RT)
  4393. RT = Ty->getAs<RecordType>();
  4394. RecordDecl *RD = RT->getDecl();
  4395. // Take care base.
  4396. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  4397. if (CXXRD->getNumBases()) {
  4398. for (const auto &I : CXXRD->bases()) {
  4399. const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(
  4400. I.getType()->castAs<RecordType>()->getDecl());
  4401. if (BaseDecl->field_empty())
  4402. continue;
  4403. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  4404. AddMissingCastOpsInInitList(elts, eltTys, idx, parentTy, CGF);
  4405. }
  4406. }
  4407. }
  4408. for (FieldDecl *field : RD->fields())
  4409. AddMissingCastOpsInInitList(elts, eltTys, idx, field->getType(), CGF);
  4410. }
  4411. }
  4412. else {
  4413. // Basic type.
  4414. Value *val = elts[idx];
  4415. llvm::Type *srcTy = val->getType();
  4416. llvm::Type *dstTy = CGF.ConvertType(Ty);
  4417. if (srcTy != dstTy) {
  4418. Instruction::CastOps castOp =
  4419. static_cast<Instruction::CastOps>(HLModule::FindCastOp(
  4420. IsUnsigned(eltTys[idx]), IsUnsigned(Ty), srcTy, dstTy));
  4421. elts[idx] = CGF.Builder.CreateCast(castOp, val, dstTy);
  4422. }
  4423. idx++;
  4424. }
  4425. }
  4426. static void StoreInitListToDestPtr(Value *DestPtr,
  4427. SmallVector<Value *, 4> &elts, unsigned &idx,
  4428. QualType Type, CodeGenTypes &Types, bool bDefaultRowMajor,
  4429. CGBuilderTy &Builder, llvm::Module &M) {
  4430. llvm::Type *Ty = DestPtr->getType()->getPointerElementType();
  4431. llvm::Type *i32Ty = llvm::Type::getInt32Ty(Ty->getContext());
  4432. if (Ty->isVectorTy()) {
  4433. Value *Result = UndefValue::get(Ty);
  4434. for (unsigned i = 0; i < Ty->getVectorNumElements(); i++)
  4435. Result = Builder.CreateInsertElement(Result, elts[idx + i], i);
  4436. Builder.CreateStore(Result, DestPtr);
  4437. idx += Ty->getVectorNumElements();
  4438. } else if (HLMatrixLower::IsMatrixType(Ty)) {
  4439. bool isRowMajor =
  4440. IsRowMajorMatrix(Type, bDefaultRowMajor);
  4441. unsigned row, col;
  4442. HLMatrixLower::GetMatrixInfo(Ty, col, row);
  4443. std::vector<Value *> matInitList(col * row);
  4444. for (unsigned i = 0; i < col; i++) {
  4445. for (unsigned r = 0; r < row; r++) {
  4446. unsigned matIdx = i * row + r;
  4447. matInitList[matIdx] = elts[idx + matIdx];
  4448. }
  4449. }
  4450. idx += row * col;
  4451. Value *matVal =
  4452. EmitHLSLMatrixOperationCallImp(Builder, HLOpcodeGroup::HLInit,
  4453. /*opcode*/ 0, Ty, matInitList, M);
  4454. // matVal return from HLInit is row major.
  4455. // If DestPtr is row major, just store it directly.
  4456. if (!isRowMajor) {
  4457. // ColMatStore need a col major value.
  4458. // Cast row major matrix into col major.
  4459. // Then store it.
  4460. Value *colMatVal = EmitHLSLMatrixOperationCallImp(
  4461. Builder, HLOpcodeGroup::HLCast,
  4462. static_cast<unsigned>(HLCastOpcode::RowMatrixToColMatrix), Ty,
  4463. {matVal}, M);
  4464. EmitHLSLMatrixOperationCallImp(
  4465. Builder, HLOpcodeGroup::HLMatLoadStore,
  4466. static_cast<unsigned>(HLMatLoadStoreOpcode::ColMatStore), Ty,
  4467. {DestPtr, colMatVal}, M);
  4468. } else {
  4469. EmitHLSLMatrixOperationCallImp(
  4470. Builder, HLOpcodeGroup::HLMatLoadStore,
  4471. static_cast<unsigned>(HLMatLoadStoreOpcode::RowMatStore), Ty,
  4472. {DestPtr, matVal}, M);
  4473. }
  4474. } else if (Ty->isStructTy()) {
  4475. if (HLModule::IsHLSLObjectType(Ty)) {
  4476. Builder.CreateStore(elts[idx], DestPtr);
  4477. idx++;
  4478. } else {
  4479. Constant *zero = ConstantInt::get(i32Ty, 0);
  4480. const RecordType *RT = Type->getAsStructureType();
  4481. // For CXXRecord.
  4482. if (!RT)
  4483. RT = Type->getAs<RecordType>();
  4484. RecordDecl *RD = RT->getDecl();
  4485. const CGRecordLayout &RL = Types.getCGRecordLayout(RD);
  4486. // Take care base.
  4487. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  4488. if (CXXRD->getNumBases()) {
  4489. for (const auto &I : CXXRD->bases()) {
  4490. const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(
  4491. I.getType()->castAs<RecordType>()->getDecl());
  4492. if (BaseDecl->field_empty())
  4493. continue;
  4494. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  4495. unsigned i = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  4496. Constant *gepIdx = ConstantInt::get(i32Ty, i);
  4497. Value *GEP = Builder.CreateInBoundsGEP(DestPtr, {zero, gepIdx});
  4498. StoreInitListToDestPtr(GEP, elts, idx, parentTy, Types,
  4499. bDefaultRowMajor, Builder, M);
  4500. }
  4501. }
  4502. }
  4503. for (FieldDecl *field : RD->fields()) {
  4504. unsigned i = RL.getLLVMFieldNo(field);
  4505. Constant *gepIdx = ConstantInt::get(i32Ty, i);
  4506. Value *GEP = Builder.CreateInBoundsGEP(DestPtr, {zero, gepIdx});
  4507. StoreInitListToDestPtr(GEP, elts, idx, field->getType(), Types,
  4508. bDefaultRowMajor, Builder, M);
  4509. }
  4510. }
  4511. } else if (Ty->isArrayTy()) {
  4512. Constant *zero = ConstantInt::get(i32Ty, 0);
  4513. QualType EltType = Type->getAsArrayTypeUnsafe()->getElementType();
  4514. for (unsigned i = 0; i < Ty->getArrayNumElements(); i++) {
  4515. Constant *gepIdx = ConstantInt::get(i32Ty, i);
  4516. Value *GEP = Builder.CreateInBoundsGEP(DestPtr, {zero, gepIdx});
  4517. StoreInitListToDestPtr(GEP, elts, idx, EltType, Types, bDefaultRowMajor,
  4518. Builder, M);
  4519. }
  4520. } else {
  4521. DXASSERT(Ty->isSingleValueType(), "invalid type");
  4522. llvm::Type *i1Ty = Builder.getInt1Ty();
  4523. Value *V = elts[idx];
  4524. if (V->getType() == i1Ty &&
  4525. DestPtr->getType()->getPointerElementType() != i1Ty) {
  4526. V = Builder.CreateZExt(V, DestPtr->getType()->getPointerElementType());
  4527. }
  4528. Builder.CreateStore(V, DestPtr);
  4529. idx++;
  4530. }
  4531. }
  4532. void CGMSHLSLRuntime::ScanInitList(CodeGenFunction &CGF, InitListExpr *E,
  4533. SmallVector<Value *, 4> &EltValList,
  4534. SmallVector<QualType, 4> &EltTyList) {
  4535. unsigned NumInitElements = E->getNumInits();
  4536. for (unsigned i = 0; i != NumInitElements; ++i) {
  4537. Expr *init = E->getInit(i);
  4538. QualType iType = init->getType();
  4539. if (InitListExpr *initList = dyn_cast<InitListExpr>(init)) {
  4540. ScanInitList(CGF, initList, EltValList, EltTyList);
  4541. } else if (CodeGenFunction::hasScalarEvaluationKind(iType)) {
  4542. llvm::Value *initVal = CGF.EmitScalarExpr(init);
  4543. FlattenValToInitList(CGF, EltValList, EltTyList, iType, initVal);
  4544. } else {
  4545. AggValueSlot Slot =
  4546. CGF.CreateAggTemp(init->getType(), "Agg.InitList.tmp");
  4547. CGF.EmitAggExpr(init, Slot);
  4548. llvm::Value *aggPtr = Slot.getAddr();
  4549. FlattenValToInitList(CGF, EltValList, EltTyList, iType, aggPtr);
  4550. }
  4551. }
  4552. }
  4553. // Is Type of E match Ty.
  4554. static bool ExpTypeMatch(Expr *E, QualType Ty, ASTContext &Ctx, CodeGenTypes &Types) {
  4555. if (InitListExpr *initList = dyn_cast<InitListExpr>(E)) {
  4556. unsigned NumInitElements = initList->getNumInits();
  4557. // Skip vector and matrix type.
  4558. if (Ty->isVectorType())
  4559. return false;
  4560. if (hlsl::IsHLSLVecMatType(Ty))
  4561. return false;
  4562. if (Ty->isStructureOrClassType()) {
  4563. RecordDecl *record = Ty->castAs<RecordType>()->getDecl();
  4564. bool bMatch = true;
  4565. auto It = record->field_begin();
  4566. auto ItEnd = record->field_end();
  4567. unsigned i = 0;
  4568. for (auto it = record->field_begin(), end = record->field_end();
  4569. it != end; it++) {
  4570. if (i == NumInitElements) {
  4571. bMatch = false;
  4572. break;
  4573. }
  4574. Expr *init = initList->getInit(i++);
  4575. QualType EltTy = it->getType();
  4576. bMatch &= ExpTypeMatch(init, EltTy, Ctx, Types);
  4577. if (!bMatch)
  4578. break;
  4579. }
  4580. bMatch &= i == NumInitElements;
  4581. if (bMatch && initList->getType()->isVoidType()) {
  4582. initList->setType(Ty);
  4583. }
  4584. return bMatch;
  4585. } else if (Ty->isArrayType() && !Ty->isIncompleteArrayType()) {
  4586. const ConstantArrayType *AT = Ctx.getAsConstantArrayType(Ty);
  4587. QualType EltTy = AT->getElementType();
  4588. unsigned size = AT->getSize().getZExtValue();
  4589. if (size != NumInitElements)
  4590. return false;
  4591. bool bMatch = true;
  4592. for (unsigned i = 0; i != NumInitElements; ++i) {
  4593. Expr *init = initList->getInit(i);
  4594. bMatch &= ExpTypeMatch(init, EltTy, Ctx, Types);
  4595. if (!bMatch)
  4596. break;
  4597. }
  4598. if (bMatch && initList->getType()->isVoidType()) {
  4599. initList->setType(Ty);
  4600. }
  4601. return bMatch;
  4602. } else {
  4603. return false;
  4604. }
  4605. } else {
  4606. llvm::Type *ExpTy = Types.ConvertType(E->getType());
  4607. llvm::Type *TargetTy = Types.ConvertType(Ty);
  4608. return ExpTy == TargetTy;
  4609. }
  4610. }
  4611. bool CGMSHLSLRuntime::IsTrivalInitListExpr(CodeGenFunction &CGF,
  4612. InitListExpr *E) {
  4613. QualType Ty = E->getType();
  4614. bool result = ExpTypeMatch(E, Ty, CGF.getContext(), CGF.getTypes());
  4615. if (result) {
  4616. auto iter = staticConstGlobalInitMap.find(E);
  4617. if (iter != staticConstGlobalInitMap.end()) {
  4618. GlobalVariable * GV = iter->second;
  4619. auto &InitConstants = staticConstGlobalInitListMap[GV];
  4620. // Add Constant to InitList.
  4621. for (unsigned i=0;i<E->getNumInits();i++) {
  4622. Expr *Expr = E->getInit(i);
  4623. LValue LV = CGF.EmitLValue(Expr);
  4624. if (LV.isSimple()) {
  4625. Constant *SrcPtr = dyn_cast<Constant>(LV.getAddress());
  4626. if (SrcPtr && !isa<UndefValue>(SrcPtr)) {
  4627. InitConstants.emplace_back(SrcPtr);
  4628. continue;
  4629. }
  4630. }
  4631. // Only support simple LV and Constant Ptr case.
  4632. // Other case just go normal path.
  4633. InitConstants.clear();
  4634. break;
  4635. }
  4636. if (InitConstants.empty())
  4637. staticConstGlobalInitListMap.erase(GV);
  4638. else
  4639. staticConstGlobalCtorMap[GV] = CGF.CurFn;
  4640. }
  4641. }
  4642. return result;
  4643. }
  4644. Value *CGMSHLSLRuntime::EmitHLSLInitListExpr(CodeGenFunction &CGF, InitListExpr *E,
  4645. // The destPtr when emiting aggregate init, for normal case, it will be null.
  4646. Value *DestPtr) {
  4647. if (DestPtr && E->getNumInits() == 1) {
  4648. llvm::Type *ExpTy = CGF.ConvertType(E->getType());
  4649. llvm::Type *TargetTy = CGF.ConvertType(E->getInit(0)->getType());
  4650. if (ExpTy == TargetTy) {
  4651. Expr *Expr = E->getInit(0);
  4652. LValue LV = CGF.EmitLValue(Expr);
  4653. if (LV.isSimple()) {
  4654. Value *SrcPtr = LV.getAddress();
  4655. SmallVector<Value *, 4> idxList;
  4656. EmitHLSLAggregateCopy(CGF, SrcPtr, DestPtr, idxList, Expr->getType(),
  4657. E->getType(), SrcPtr->getType());
  4658. return nullptr;
  4659. }
  4660. }
  4661. }
  4662. SmallVector<Value *, 4> EltValList;
  4663. SmallVector<QualType, 4> EltTyList;
  4664. ScanInitList(CGF, E, EltValList, EltTyList);
  4665. QualType ResultTy = E->getType();
  4666. unsigned idx = 0;
  4667. // Create cast if need.
  4668. AddMissingCastOpsInInitList(EltValList, EltTyList, idx, ResultTy, CGF);
  4669. DXASSERT(idx == EltValList.size(), "size must match");
  4670. llvm::Type *RetTy = CGF.ConvertType(ResultTy);
  4671. if (DestPtr) {
  4672. SmallVector<Value *, 4> ParamList;
  4673. DXASSERT(RetTy->isAggregateType(), "");
  4674. ParamList.emplace_back(DestPtr);
  4675. ParamList.append(EltValList.begin(), EltValList.end());
  4676. idx = 0;
  4677. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  4678. StoreInitListToDestPtr(DestPtr, EltValList, idx, ResultTy, CGF.getTypes(),
  4679. bDefaultRowMajor, CGF.Builder, TheModule);
  4680. return nullptr;
  4681. }
  4682. if (IsHLSLVecType(ResultTy)) {
  4683. Value *Result = UndefValue::get(RetTy);
  4684. for (unsigned i = 0; i < RetTy->getVectorNumElements(); i++)
  4685. Result = CGF.Builder.CreateInsertElement(Result, EltValList[i], i);
  4686. return Result;
  4687. } else {
  4688. // Must be matrix here.
  4689. DXASSERT(IsHLSLMatType(ResultTy), "must be matrix type here.");
  4690. return EmitHLSLMatrixOperationCallImp(CGF.Builder, HLOpcodeGroup::HLInit,
  4691. /*opcode*/ 0, RetTy, EltValList,
  4692. TheModule);
  4693. }
  4694. }
  4695. static void FlatConstToList(Constant *C, SmallVector<Constant *, 4> &EltValList,
  4696. QualType Type, CodeGenTypes &Types,
  4697. bool bDefaultRowMajor) {
  4698. llvm::Type *Ty = C->getType();
  4699. if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(Ty)) {
  4700. // Type is only for matrix. Keep use Type to next level.
  4701. for (unsigned i = 0; i < VT->getNumElements(); i++) {
  4702. FlatConstToList(C->getAggregateElement(i), EltValList, Type, Types,
  4703. bDefaultRowMajor);
  4704. }
  4705. } else if (HLMatrixLower::IsMatrixType(Ty)) {
  4706. bool isRowMajor = IsRowMajorMatrix(Type, bDefaultRowMajor);
  4707. // matrix type is struct { vector<Ty, row> [col] };
  4708. // Strip the struct level here.
  4709. Constant *matVal = C->getAggregateElement((unsigned)0);
  4710. const RecordType *RT = Type->getAs<RecordType>();
  4711. RecordDecl *RD = RT->getDecl();
  4712. QualType EltTy = RD->field_begin()->getType();
  4713. // When scan, init list scalars is row major.
  4714. if (isRowMajor) {
  4715. // Don't change the major for row major value.
  4716. FlatConstToList(matVal, EltValList, EltTy, Types, bDefaultRowMajor);
  4717. } else {
  4718. // Save to tmp list.
  4719. SmallVector<Constant *, 4> matEltList;
  4720. FlatConstToList(matVal, matEltList, EltTy, Types, bDefaultRowMajor);
  4721. unsigned row, col;
  4722. HLMatrixLower::GetMatrixInfo(Ty, col, row);
  4723. // Change col major value to row major.
  4724. for (unsigned r = 0; r < row; r++)
  4725. for (unsigned c = 0; c < col; c++) {
  4726. unsigned colMajorIdx = c * row + r;
  4727. EltValList.emplace_back(matEltList[colMajorIdx]);
  4728. }
  4729. }
  4730. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty)) {
  4731. QualType EltTy = Type->getAsArrayTypeUnsafe()->getElementType();
  4732. for (unsigned i = 0; i < AT->getNumElements(); i++) {
  4733. FlatConstToList(C->getAggregateElement(i), EltValList, EltTy, Types,
  4734. bDefaultRowMajor);
  4735. }
  4736. } else if (llvm::StructType *ST = dyn_cast<llvm::StructType>(Ty)) {
  4737. RecordDecl *RD = Type->getAsStructureType()->getDecl();
  4738. const CGRecordLayout &RL = Types.getCGRecordLayout(RD);
  4739. // Take care base.
  4740. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  4741. if (CXXRD->getNumBases()) {
  4742. for (const auto &I : CXXRD->bases()) {
  4743. const CXXRecordDecl *BaseDecl =
  4744. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  4745. if (BaseDecl->field_empty())
  4746. continue;
  4747. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  4748. unsigned i = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  4749. FlatConstToList(C->getAggregateElement(i), EltValList, parentTy,
  4750. Types, bDefaultRowMajor);
  4751. }
  4752. }
  4753. }
  4754. for (auto fieldIter = RD->field_begin(), fieldEnd = RD->field_end();
  4755. fieldIter != fieldEnd; ++fieldIter) {
  4756. unsigned i = RL.getLLVMFieldNo(*fieldIter);
  4757. FlatConstToList(C->getAggregateElement(i), EltValList,
  4758. fieldIter->getType(), Types, bDefaultRowMajor);
  4759. }
  4760. } else {
  4761. EltValList.emplace_back(C);
  4762. }
  4763. }
  4764. static bool ScanConstInitList(CodeGenModule &CGM, InitListExpr *E,
  4765. SmallVector<Constant *, 4> &EltValList,
  4766. CodeGenTypes &Types, bool bDefaultRowMajor) {
  4767. unsigned NumInitElements = E->getNumInits();
  4768. for (unsigned i = 0; i != NumInitElements; ++i) {
  4769. Expr *init = E->getInit(i);
  4770. QualType iType = init->getType();
  4771. if (InitListExpr *initList = dyn_cast<InitListExpr>(init)) {
  4772. if (!ScanConstInitList(CGM, initList, EltValList, Types,
  4773. bDefaultRowMajor))
  4774. return false;
  4775. } else if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(init)) {
  4776. if (VarDecl *D = dyn_cast<VarDecl>(ref->getDecl())) {
  4777. if (!D->hasInit())
  4778. return false;
  4779. if (Constant *initVal = CGM.EmitConstantInit(*D)) {
  4780. FlatConstToList(initVal, EltValList, iType, Types, bDefaultRowMajor);
  4781. } else {
  4782. return false;
  4783. }
  4784. } else {
  4785. return false;
  4786. }
  4787. } else if (hlsl::IsHLSLMatType(iType)) {
  4788. return false;
  4789. } else if (CodeGenFunction::hasScalarEvaluationKind(iType)) {
  4790. if (Constant *initVal = CGM.EmitConstantExpr(init, iType)) {
  4791. FlatConstToList(initVal, EltValList, iType, Types, bDefaultRowMajor);
  4792. } else {
  4793. return false;
  4794. }
  4795. } else {
  4796. return false;
  4797. }
  4798. }
  4799. return true;
  4800. }
  4801. static Constant *BuildConstInitializer(QualType Type, unsigned &offset,
  4802. SmallVector<Constant *, 4> &EltValList,
  4803. CodeGenTypes &Types,
  4804. bool bDefaultRowMajor);
  4805. static Constant *BuildConstVector(llvm::VectorType *VT, unsigned &offset,
  4806. SmallVector<Constant *, 4> &EltValList,
  4807. QualType Type, CodeGenTypes &Types) {
  4808. SmallVector<Constant *, 4> Elts;
  4809. QualType EltTy = hlsl::GetHLSLVecElementType(Type);
  4810. for (unsigned i = 0; i < VT->getNumElements(); i++) {
  4811. Elts.emplace_back(BuildConstInitializer(EltTy, offset, EltValList, Types,
  4812. // Vector don't need major.
  4813. /*bDefaultRowMajor*/ false));
  4814. }
  4815. return llvm::ConstantVector::get(Elts);
  4816. }
  4817. static Constant *BuildConstMatrix(llvm::Type *Ty, unsigned &offset,
  4818. SmallVector<Constant *, 4> &EltValList,
  4819. QualType Type, CodeGenTypes &Types,
  4820. bool bDefaultRowMajor) {
  4821. QualType EltTy = hlsl::GetHLSLMatElementType(Type);
  4822. unsigned col, row;
  4823. HLMatrixLower::GetMatrixInfo(Ty, col, row);
  4824. llvm::ArrayType *AT = cast<llvm::ArrayType>(Ty->getStructElementType(0));
  4825. // Save initializer elements first.
  4826. // Matrix initializer is row major.
  4827. SmallVector<Constant *, 16> elts;
  4828. for (unsigned i = 0; i < col * row; i++) {
  4829. elts.emplace_back(BuildConstInitializer(EltTy, offset, EltValList, Types,
  4830. bDefaultRowMajor));
  4831. }
  4832. bool isRowMajor = IsRowMajorMatrix(Type, bDefaultRowMajor);
  4833. SmallVector<Constant *, 16> majorElts(elts.begin(), elts.end());
  4834. if (!isRowMajor) {
  4835. // cast row major to col major.
  4836. for (unsigned c = 0; c < col; c++) {
  4837. SmallVector<Constant *, 4> rows;
  4838. for (unsigned r = 0; r < row; r++) {
  4839. unsigned rowMajorIdx = r * col + c;
  4840. unsigned colMajorIdx = c * row + r;
  4841. majorElts[colMajorIdx] = elts[rowMajorIdx];
  4842. }
  4843. }
  4844. }
  4845. // The type is vector<element, col>[row].
  4846. SmallVector<Constant *, 4> rows;
  4847. unsigned idx = 0;
  4848. for (unsigned r = 0; r < row; r++) {
  4849. SmallVector<Constant *, 4> cols;
  4850. for (unsigned c = 0; c < col; c++) {
  4851. cols.emplace_back(majorElts[idx++]);
  4852. }
  4853. rows.emplace_back(llvm::ConstantVector::get(cols));
  4854. }
  4855. Constant *mat = llvm::ConstantArray::get(AT, rows);
  4856. return llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), mat);
  4857. }
  4858. static Constant *BuildConstArray(llvm::ArrayType *AT, unsigned &offset,
  4859. SmallVector<Constant *, 4> &EltValList,
  4860. QualType Type, CodeGenTypes &Types,
  4861. bool bDefaultRowMajor) {
  4862. SmallVector<Constant *, 4> Elts;
  4863. QualType EltType = QualType(Type->getArrayElementTypeNoTypeQual(), 0);
  4864. for (unsigned i = 0; i < AT->getNumElements(); i++) {
  4865. Elts.emplace_back(BuildConstInitializer(EltType, offset, EltValList, Types,
  4866. bDefaultRowMajor));
  4867. }
  4868. return llvm::ConstantArray::get(AT, Elts);
  4869. }
  4870. static Constant *BuildConstStruct(llvm::StructType *ST, unsigned &offset,
  4871. SmallVector<Constant *, 4> &EltValList,
  4872. QualType Type, CodeGenTypes &Types,
  4873. bool bDefaultRowMajor) {
  4874. SmallVector<Constant *, 4> Elts;
  4875. const RecordType *RT = Type->getAsStructureType();
  4876. if (!RT)
  4877. RT = Type->getAs<RecordType>();
  4878. const RecordDecl *RD = RT->getDecl();
  4879. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  4880. if (CXXRD->getNumBases()) {
  4881. // Add base as field.
  4882. for (const auto &I : CXXRD->bases()) {
  4883. const CXXRecordDecl *BaseDecl =
  4884. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  4885. // Skip empty struct.
  4886. if (BaseDecl->field_empty())
  4887. continue;
  4888. // Add base as a whole constant. Not as element.
  4889. Elts.emplace_back(BuildConstInitializer(I.getType(), offset, EltValList,
  4890. Types, bDefaultRowMajor));
  4891. }
  4892. }
  4893. }
  4894. for (auto fieldIter = RD->field_begin(), fieldEnd = RD->field_end();
  4895. fieldIter != fieldEnd; ++fieldIter) {
  4896. Elts.emplace_back(BuildConstInitializer(
  4897. fieldIter->getType(), offset, EltValList, Types, bDefaultRowMajor));
  4898. }
  4899. return llvm::ConstantStruct::get(ST, Elts);
  4900. }
  4901. static Constant *BuildConstInitializer(QualType Type, unsigned &offset,
  4902. SmallVector<Constant *, 4> &EltValList,
  4903. CodeGenTypes &Types,
  4904. bool bDefaultRowMajor) {
  4905. llvm::Type *Ty = Types.ConvertType(Type);
  4906. if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(Ty)) {
  4907. return BuildConstVector(VT, offset, EltValList, Type, Types);
  4908. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty)) {
  4909. return BuildConstArray(AT, offset, EltValList, Type, Types,
  4910. bDefaultRowMajor);
  4911. } else if (HLMatrixLower::IsMatrixType(Ty)) {
  4912. return BuildConstMatrix(Ty, offset, EltValList, Type, Types,
  4913. bDefaultRowMajor);
  4914. } else if (StructType *ST = dyn_cast<llvm::StructType>(Ty)) {
  4915. return BuildConstStruct(ST, offset, EltValList, Type, Types,
  4916. bDefaultRowMajor);
  4917. } else {
  4918. // Scalar basic types.
  4919. Constant *Val = EltValList[offset++];
  4920. if (Val->getType() == Ty) {
  4921. return Val;
  4922. } else {
  4923. IRBuilder<> Builder(Ty->getContext());
  4924. // Don't cast int to bool. bool only for scalar.
  4925. if (Ty == Builder.getInt1Ty() && Val->getType() == Builder.getInt32Ty())
  4926. return Val;
  4927. Instruction::CastOps castOp =
  4928. static_cast<Instruction::CastOps>(HLModule::FindCastOp(
  4929. IsUnsigned(Type), IsUnsigned(Type), Val->getType(), Ty));
  4930. return cast<Constant>(Builder.CreateCast(castOp, Val, Ty));
  4931. }
  4932. }
  4933. }
  4934. Constant *CGMSHLSLRuntime::EmitHLSLConstInitListExpr(CodeGenModule &CGM,
  4935. InitListExpr *E) {
  4936. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  4937. SmallVector<Constant *, 4> EltValList;
  4938. if (!ScanConstInitList(CGM, E, EltValList, CGM.getTypes(), bDefaultRowMajor))
  4939. return nullptr;
  4940. QualType Type = E->getType();
  4941. unsigned offset = 0;
  4942. return BuildConstInitializer(Type, offset, EltValList, CGM.getTypes(),
  4943. bDefaultRowMajor);
  4944. }
  4945. Value *CGMSHLSLRuntime::EmitHLSLMatrixOperationCall(
  4946. CodeGenFunction &CGF, const clang::Expr *E, llvm::Type *RetType,
  4947. ArrayRef<Value *> paramList) {
  4948. HLOpcodeGroup group = GetHLOpcodeGroup(E->getStmtClass());
  4949. unsigned opcode = GetHLOpcode(E);
  4950. if (group == HLOpcodeGroup::HLInit)
  4951. return EmitHLSLArrayInit(CGF.Builder, group, opcode, RetType, paramList,
  4952. TheModule);
  4953. else
  4954. return EmitHLSLMatrixOperationCallImp(CGF.Builder, group, opcode, RetType,
  4955. paramList, TheModule);
  4956. }
  4957. void CGMSHLSLRuntime::EmitHLSLDiscard(CodeGenFunction &CGF) {
  4958. EmitHLSLMatrixOperationCallImp(
  4959. CGF.Builder, HLOpcodeGroup::HLIntrinsic,
  4960. static_cast<unsigned>(IntrinsicOp::IOP_clip),
  4961. llvm::Type::getVoidTy(CGF.getLLVMContext()),
  4962. {ConstantFP::get(llvm::Type::getFloatTy(CGF.getLLVMContext()), -1.0f)},
  4963. TheModule);
  4964. }
  4965. static llvm::Type *MergeIntType(llvm::IntegerType *T0, llvm::IntegerType *T1) {
  4966. if (T0->getBitWidth() > T1->getBitWidth())
  4967. return T0;
  4968. else
  4969. return T1;
  4970. }
  4971. static Value *CreateExt(CGBuilderTy &Builder, Value *Src, llvm::Type *DstTy,
  4972. bool bSigned) {
  4973. if (bSigned)
  4974. return Builder.CreateSExt(Src, DstTy);
  4975. else
  4976. return Builder.CreateZExt(Src, DstTy);
  4977. }
  4978. // For integer literal, try to get lowest precision.
  4979. static Value *CalcHLSLLiteralToLowestPrecision(CGBuilderTy &Builder, Value *Src,
  4980. bool bSigned) {
  4981. if (ConstantInt *CI = dyn_cast<ConstantInt>(Src)) {
  4982. APInt v = CI->getValue();
  4983. switch (v.getActiveWords()) {
  4984. case 4:
  4985. return Builder.getInt32(v.getLimitedValue());
  4986. case 8:
  4987. return Builder.getInt64(v.getLimitedValue());
  4988. case 2:
  4989. // TODO: use low precision type when support it in dxil.
  4990. // return Builder.getInt16(v.getLimitedValue());
  4991. return Builder.getInt32(v.getLimitedValue());
  4992. case 1:
  4993. // TODO: use precision type when support it in dxil.
  4994. // return Builder.getInt8(v.getLimitedValue());
  4995. return Builder.getInt32(v.getLimitedValue());
  4996. default:
  4997. return nullptr;
  4998. }
  4999. } else if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
  5000. if (SI->getType()->isIntegerTy()) {
  5001. Value *T = SI->getTrueValue();
  5002. Value *F = SI->getFalseValue();
  5003. Value *lowT = CalcHLSLLiteralToLowestPrecision(Builder, T, bSigned);
  5004. Value *lowF = CalcHLSLLiteralToLowestPrecision(Builder, F, bSigned);
  5005. if (lowT && lowF && lowT != T && lowF != F) {
  5006. llvm::IntegerType *TTy = cast<llvm::IntegerType>(lowT->getType());
  5007. llvm::IntegerType *FTy = cast<llvm::IntegerType>(lowF->getType());
  5008. llvm::Type *Ty = MergeIntType(TTy, FTy);
  5009. if (TTy != Ty) {
  5010. lowT = CreateExt(Builder, lowT, Ty, bSigned);
  5011. }
  5012. if (FTy != Ty) {
  5013. lowF = CreateExt(Builder, lowF, Ty, bSigned);
  5014. }
  5015. Value *Cond = SI->getCondition();
  5016. return Builder.CreateSelect(Cond, lowT, lowF);
  5017. }
  5018. }
  5019. } else if (llvm::BinaryOperator *BO = dyn_cast<llvm::BinaryOperator>(Src)) {
  5020. Value *Src0 = BO->getOperand(0);
  5021. Value *Src1 = BO->getOperand(1);
  5022. Value *CastSrc0 = CalcHLSLLiteralToLowestPrecision(Builder, Src0, bSigned);
  5023. Value *CastSrc1 = CalcHLSLLiteralToLowestPrecision(Builder, Src1, bSigned);
  5024. if (Src0 != CastSrc0 && Src1 != CastSrc1 && CastSrc0 && CastSrc1 &&
  5025. CastSrc0->getType() == CastSrc1->getType()) {
  5026. llvm::IntegerType *Ty0 = cast<llvm::IntegerType>(CastSrc0->getType());
  5027. llvm::IntegerType *Ty1 = cast<llvm::IntegerType>(CastSrc0->getType());
  5028. llvm::Type *Ty = MergeIntType(Ty0, Ty1);
  5029. if (Ty0 != Ty) {
  5030. CastSrc0 = CreateExt(Builder, CastSrc0, Ty, bSigned);
  5031. }
  5032. if (Ty1 != Ty) {
  5033. CastSrc1 = CreateExt(Builder, CastSrc1, Ty, bSigned);
  5034. }
  5035. return Builder.CreateBinOp(BO->getOpcode(), CastSrc0, CastSrc1);
  5036. }
  5037. }
  5038. return nullptr;
  5039. }
  5040. Value *CGMSHLSLRuntime::EmitHLSLLiteralCast(CodeGenFunction &CGF, Value *Src,
  5041. QualType SrcType,
  5042. QualType DstType) {
  5043. auto &Builder = CGF.Builder;
  5044. llvm::Type *DstTy = CGF.ConvertType(DstType);
  5045. bool bDstSigned = DstType->isSignedIntegerType();
  5046. if (ConstantInt *CI = dyn_cast<ConstantInt>(Src)) {
  5047. APInt v = CI->getValue();
  5048. if (llvm::IntegerType *IT = dyn_cast<llvm::IntegerType>(DstTy)) {
  5049. v = v.trunc(IT->getBitWidth());
  5050. switch (IT->getBitWidth()) {
  5051. case 32:
  5052. return Builder.getInt32(v.getLimitedValue());
  5053. case 64:
  5054. return Builder.getInt64(v.getLimitedValue());
  5055. case 16:
  5056. return Builder.getInt16(v.getLimitedValue());
  5057. case 8:
  5058. return Builder.getInt8(v.getLimitedValue());
  5059. default:
  5060. return nullptr;
  5061. }
  5062. } else {
  5063. DXASSERT_NOMSG(DstTy->isFloatingPointTy());
  5064. int64_t val = v.getLimitedValue();
  5065. if (v.isNegative())
  5066. val = 0-v.abs().getLimitedValue();
  5067. if (DstTy->isDoubleTy())
  5068. return ConstantFP::get(DstTy, (double)val);
  5069. else if (DstTy->isFloatTy())
  5070. return ConstantFP::get(DstTy, (float)val);
  5071. else {
  5072. if (bDstSigned)
  5073. return Builder.CreateSIToFP(Src, DstTy);
  5074. else
  5075. return Builder.CreateUIToFP(Src, DstTy);
  5076. }
  5077. }
  5078. } else if (ConstantFP *CF = dyn_cast<ConstantFP>(Src)) {
  5079. APFloat v = CF->getValueAPF();
  5080. double dv = v.convertToDouble();
  5081. if (llvm::IntegerType *IT = dyn_cast<llvm::IntegerType>(DstTy)) {
  5082. switch (IT->getBitWidth()) {
  5083. case 32:
  5084. return Builder.getInt32(dv);
  5085. case 64:
  5086. return Builder.getInt64(dv);
  5087. case 16:
  5088. return Builder.getInt16(dv);
  5089. case 8:
  5090. return Builder.getInt8(dv);
  5091. default:
  5092. return nullptr;
  5093. }
  5094. } else {
  5095. if (DstTy->isFloatTy()) {
  5096. float fv = dv;
  5097. return ConstantFP::get(DstTy->getContext(), APFloat(fv));
  5098. } else {
  5099. return Builder.CreateFPTrunc(Src, DstTy);
  5100. }
  5101. }
  5102. } else if (UndefValue *UV = dyn_cast<UndefValue>(Src)) {
  5103. return UndefValue::get(DstTy);
  5104. } else {
  5105. Instruction *I = cast<Instruction>(Src);
  5106. if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
  5107. Value *T = SI->getTrueValue();
  5108. Value *F = SI->getFalseValue();
  5109. Value *Cond = SI->getCondition();
  5110. if (isa<llvm::ConstantInt>(T) && isa<llvm::ConstantInt>(F)) {
  5111. llvm::APInt lhs = cast<llvm::ConstantInt>(T)->getValue();
  5112. llvm::APInt rhs = cast<llvm::ConstantInt>(F)->getValue();
  5113. if (DstTy == Builder.getInt32Ty()) {
  5114. T = Builder.getInt32(lhs.getLimitedValue());
  5115. F = Builder.getInt32(rhs.getLimitedValue());
  5116. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  5117. return Sel;
  5118. } else if (DstTy->isFloatingPointTy()) {
  5119. T = ConstantFP::get(DstTy, int64_t(lhs.getLimitedValue()));
  5120. F = ConstantFP::get(DstTy, int64_t(rhs.getLimitedValue()));
  5121. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  5122. return Sel;
  5123. }
  5124. } else if (isa<llvm::ConstantFP>(T) && isa<llvm::ConstantFP>(F)) {
  5125. llvm::APFloat lhs = cast<llvm::ConstantFP>(T)->getValueAPF();
  5126. llvm::APFloat rhs = cast<llvm::ConstantFP>(F)->getValueAPF();
  5127. double ld = lhs.convertToDouble();
  5128. double rd = rhs.convertToDouble();
  5129. if (DstTy->isFloatTy()) {
  5130. float lf = ld;
  5131. float rf = rd;
  5132. T = ConstantFP::get(DstTy->getContext(), APFloat(lf));
  5133. F = ConstantFP::get(DstTy->getContext(), APFloat(rf));
  5134. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  5135. return Sel;
  5136. } else if (DstTy == Builder.getInt32Ty()) {
  5137. T = Builder.getInt32(ld);
  5138. F = Builder.getInt32(rd);
  5139. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  5140. return Sel;
  5141. } else if (DstTy == Builder.getInt64Ty()) {
  5142. T = Builder.getInt64(ld);
  5143. F = Builder.getInt64(rd);
  5144. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  5145. return Sel;
  5146. }
  5147. }
  5148. } else if (llvm::BinaryOperator *BO = dyn_cast<llvm::BinaryOperator>(I)) {
  5149. // For integer binary operator, do the calc on lowest precision, then cast
  5150. // to dstTy.
  5151. if (I->getType()->isIntegerTy()) {
  5152. bool bSigned = DstType->isSignedIntegerType();
  5153. Value *CastResult =
  5154. CalcHLSLLiteralToLowestPrecision(Builder, BO, bSigned);
  5155. if (!CastResult)
  5156. return nullptr;
  5157. if (llvm::IntegerType *IT = dyn_cast<llvm::IntegerType>(DstTy)) {
  5158. if (DstTy == CastResult->getType()) {
  5159. return CastResult;
  5160. } else {
  5161. if (bSigned)
  5162. return Builder.CreateSExtOrTrunc(CastResult, DstTy);
  5163. else
  5164. return Builder.CreateZExtOrTrunc(CastResult, DstTy);
  5165. }
  5166. } else {
  5167. if (bDstSigned)
  5168. return Builder.CreateSIToFP(CastResult, DstTy);
  5169. else
  5170. return Builder.CreateUIToFP(CastResult, DstTy);
  5171. }
  5172. }
  5173. }
  5174. // TODO: support other opcode if need.
  5175. return nullptr;
  5176. }
  5177. }
  5178. Value *CGMSHLSLRuntime::EmitHLSLMatrixSubscript(CodeGenFunction &CGF,
  5179. llvm::Type *RetType,
  5180. llvm::Value *Ptr,
  5181. llvm::Value *Idx,
  5182. clang::QualType Ty) {
  5183. bool isRowMajor =
  5184. IsRowMajorMatrix(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  5185. unsigned opcode =
  5186. isRowMajor ? static_cast<unsigned>(HLSubscriptOpcode::RowMatSubscript)
  5187. : static_cast<unsigned>(HLSubscriptOpcode::ColMatSubscript);
  5188. Value *matBase = Ptr;
  5189. DXASSERT(matBase->getType()->isPointerTy(),
  5190. "matrix subscript should return pointer");
  5191. RetType =
  5192. llvm::PointerType::get(RetType->getPointerElementType(),
  5193. matBase->getType()->getPointerAddressSpace());
  5194. // Lower mat[Idx] into real idx.
  5195. SmallVector<Value *, 8> args;
  5196. args.emplace_back(Ptr);
  5197. unsigned row, col;
  5198. hlsl::GetHLSLMatRowColCount(Ty, row, col);
  5199. if (isRowMajor) {
  5200. Value *cCol = ConstantInt::get(Idx->getType(), col);
  5201. Value *Base = CGF.Builder.CreateMul(cCol, Idx);
  5202. for (unsigned i = 0; i < col; i++) {
  5203. Value *c = ConstantInt::get(Idx->getType(), i);
  5204. // r * col + c
  5205. Value *matIdx = CGF.Builder.CreateAdd(Base, c);
  5206. args.emplace_back(matIdx);
  5207. }
  5208. } else {
  5209. for (unsigned i = 0; i < col; i++) {
  5210. Value *cMulRow = ConstantInt::get(Idx->getType(), i * row);
  5211. // c * row + r
  5212. Value *matIdx = CGF.Builder.CreateAdd(cMulRow, Idx);
  5213. args.emplace_back(matIdx);
  5214. }
  5215. }
  5216. Value *matSub =
  5217. EmitHLSLMatrixOperationCallImp(CGF.Builder, HLOpcodeGroup::HLSubscript,
  5218. opcode, RetType, args, TheModule);
  5219. return matSub;
  5220. }
  5221. Value *CGMSHLSLRuntime::EmitHLSLMatrixElement(CodeGenFunction &CGF,
  5222. llvm::Type *RetType,
  5223. ArrayRef<Value *> paramList,
  5224. QualType Ty) {
  5225. bool isRowMajor =
  5226. IsRowMajorMatrix(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  5227. unsigned opcode =
  5228. isRowMajor ? static_cast<unsigned>(HLSubscriptOpcode::RowMatElement)
  5229. : static_cast<unsigned>(HLSubscriptOpcode::ColMatElement);
  5230. Value *matBase = paramList[0];
  5231. DXASSERT(matBase->getType()->isPointerTy(),
  5232. "matrix element should return pointer");
  5233. RetType =
  5234. llvm::PointerType::get(RetType->getPointerElementType(),
  5235. matBase->getType()->getPointerAddressSpace());
  5236. Value *idx = paramList[HLOperandIndex::kMatSubscriptSubOpIdx-1];
  5237. // Lower _m00 into real idx.
  5238. // -1 to avoid opcode param which is added in EmitHLSLMatrixOperationCallImp.
  5239. Value *args[] = {paramList[HLOperandIndex::kMatSubscriptMatOpIdx - 1],
  5240. paramList[HLOperandIndex::kMatSubscriptSubOpIdx - 1]};
  5241. // For all zero idx. Still all zero idx.
  5242. if (ConstantAggregateZero *zeros = dyn_cast<ConstantAggregateZero>(idx)) {
  5243. Constant *zero = zeros->getAggregateElement((unsigned)0);
  5244. std::vector<Constant *> elts(zeros->getNumElements() >> 1, zero);
  5245. args[HLOperandIndex::kMatSubscriptSubOpIdx - 1] = ConstantVector::get(elts);
  5246. } else {
  5247. ConstantDataSequential *elts = cast<ConstantDataSequential>(idx);
  5248. unsigned count = elts->getNumElements();
  5249. unsigned row, col;
  5250. hlsl::GetHLSLMatRowColCount(Ty, row, col);
  5251. std::vector<Constant *> idxs(count >> 1);
  5252. for (unsigned i = 0; i < count; i += 2) {
  5253. unsigned rowIdx = elts->getElementAsInteger(i);
  5254. unsigned colIdx = elts->getElementAsInteger(i + 1);
  5255. unsigned matIdx = 0;
  5256. if (isRowMajor) {
  5257. matIdx = rowIdx * col + colIdx;
  5258. } else {
  5259. matIdx = colIdx * row + rowIdx;
  5260. }
  5261. idxs[i >> 1] = CGF.Builder.getInt32(matIdx);
  5262. }
  5263. args[HLOperandIndex::kMatSubscriptSubOpIdx - 1] = ConstantVector::get(idxs);
  5264. }
  5265. return EmitHLSLMatrixOperationCallImp(CGF.Builder, HLOpcodeGroup::HLSubscript,
  5266. opcode, RetType, args, TheModule);
  5267. }
  5268. Value *CGMSHLSLRuntime::EmitHLSLMatrixLoad(CGBuilderTy &Builder, Value *Ptr,
  5269. QualType Ty) {
  5270. bool isRowMajor =
  5271. IsRowMajorMatrix(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  5272. unsigned opcode =
  5273. isRowMajor
  5274. ? static_cast<unsigned>(HLMatLoadStoreOpcode::RowMatLoad)
  5275. : static_cast<unsigned>(HLMatLoadStoreOpcode::ColMatLoad);
  5276. Value *matVal = EmitHLSLMatrixOperationCallImp(
  5277. Builder, HLOpcodeGroup::HLMatLoadStore, opcode,
  5278. Ptr->getType()->getPointerElementType(), {Ptr}, TheModule);
  5279. if (!isRowMajor) {
  5280. // ColMatLoad will return a col major matrix.
  5281. // All matrix Value should be row major.
  5282. // Cast it to row major.
  5283. matVal = EmitHLSLMatrixOperationCallImp(
  5284. Builder, HLOpcodeGroup::HLCast,
  5285. static_cast<unsigned>(HLCastOpcode::ColMatrixToRowMatrix),
  5286. matVal->getType(), {matVal}, TheModule);
  5287. }
  5288. return matVal;
  5289. }
  5290. void CGMSHLSLRuntime::EmitHLSLMatrixStore(CGBuilderTy &Builder, Value *Val,
  5291. Value *DestPtr, QualType Ty) {
  5292. bool isRowMajor =
  5293. IsRowMajorMatrix(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  5294. unsigned opcode =
  5295. isRowMajor
  5296. ? static_cast<unsigned>(HLMatLoadStoreOpcode::RowMatStore)
  5297. : static_cast<unsigned>(HLMatLoadStoreOpcode::ColMatStore);
  5298. if (!isRowMajor) {
  5299. Value *ColVal = nullptr;
  5300. // If Val is casted from col major. Just use the original col major val.
  5301. if (CallInst *CI = dyn_cast<CallInst>(Val)) {
  5302. hlsl::HLOpcodeGroup group =
  5303. hlsl::GetHLOpcodeGroupByName(CI->getCalledFunction());
  5304. if (group == HLOpcodeGroup::HLCast) {
  5305. HLCastOpcode castOp = static_cast<HLCastOpcode>(hlsl::GetHLOpcode(CI));
  5306. if (castOp == HLCastOpcode::ColMatrixToRowMatrix) {
  5307. ColVal = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  5308. }
  5309. }
  5310. }
  5311. if (ColVal) {
  5312. Val = ColVal;
  5313. } else {
  5314. // All matrix Value should be row major.
  5315. // ColMatStore need a col major value.
  5316. // Cast it to row major.
  5317. Val = EmitHLSLMatrixOperationCallImp(
  5318. Builder, HLOpcodeGroup::HLCast,
  5319. static_cast<unsigned>(HLCastOpcode::RowMatrixToColMatrix),
  5320. Val->getType(), {Val}, TheModule);
  5321. }
  5322. }
  5323. EmitHLSLMatrixOperationCallImp(Builder, HLOpcodeGroup::HLMatLoadStore, opcode,
  5324. Val->getType(), {DestPtr, Val}, TheModule);
  5325. }
  5326. Value *CGMSHLSLRuntime::EmitHLSLMatrixLoad(CodeGenFunction &CGF, Value *Ptr,
  5327. QualType Ty) {
  5328. return EmitHLSLMatrixLoad(CGF.Builder, Ptr, Ty);
  5329. }
  5330. void CGMSHLSLRuntime::EmitHLSLMatrixStore(CodeGenFunction &CGF, Value *Val,
  5331. Value *DestPtr, QualType Ty) {
  5332. EmitHLSLMatrixStore(CGF.Builder, Val, DestPtr, Ty);
  5333. }
  5334. // Copy data from srcPtr to destPtr.
  5335. static void SimplePtrCopy(Value *DestPtr, Value *SrcPtr,
  5336. ArrayRef<Value *> idxList, CGBuilderTy &Builder) {
  5337. if (idxList.size() > 1) {
  5338. DestPtr = Builder.CreateInBoundsGEP(DestPtr, idxList);
  5339. SrcPtr = Builder.CreateInBoundsGEP(SrcPtr, idxList);
  5340. }
  5341. llvm::LoadInst *ld = Builder.CreateLoad(SrcPtr);
  5342. Builder.CreateStore(ld, DestPtr);
  5343. }
  5344. // Get Element val from SrvVal with extract value.
  5345. static Value *GetEltVal(Value *SrcVal, ArrayRef<Value*> idxList,
  5346. CGBuilderTy &Builder) {
  5347. Value *Val = SrcVal;
  5348. // Skip beginning pointer type.
  5349. for (unsigned i = 1; i < idxList.size(); i++) {
  5350. ConstantInt *idx = cast<ConstantInt>(idxList[i]);
  5351. llvm::Type *Ty = Val->getType();
  5352. if (Ty->isAggregateType()) {
  5353. Val = Builder.CreateExtractValue(Val, idx->getLimitedValue());
  5354. }
  5355. }
  5356. return Val;
  5357. }
  5358. // Copy srcVal to destPtr.
  5359. static void SimpleValCopy(Value *DestPtr, Value *SrcVal,
  5360. ArrayRef<Value*> idxList,
  5361. CGBuilderTy &Builder) {
  5362. Value *DestGEP = Builder.CreateInBoundsGEP(DestPtr, idxList);
  5363. Value *Val = GetEltVal(SrcVal, idxList, Builder);
  5364. Builder.CreateStore(Val, DestGEP);
  5365. }
  5366. static void SimpleCopy(Value *Dest, Value *Src,
  5367. ArrayRef<Value *> idxList,
  5368. CGBuilderTy &Builder) {
  5369. if (Src->getType()->isPointerTy())
  5370. SimplePtrCopy(Dest, Src, idxList, Builder);
  5371. else
  5372. SimpleValCopy(Dest, Src, idxList, Builder);
  5373. }
  5374. void CGMSHLSLRuntime::FlattenAggregatePtrToGepList(
  5375. CodeGenFunction &CGF, Value *Ptr, SmallVector<Value *, 4> &idxList,
  5376. clang::QualType Type, llvm::Type *Ty, SmallVector<Value *, 4> &GepList,
  5377. SmallVector<QualType, 4> &EltTyList) {
  5378. if (llvm::PointerType *PT = dyn_cast<llvm::PointerType>(Ty)) {
  5379. Constant *idx = Constant::getIntegerValue(
  5380. IntegerType::get(Ty->getContext(), 32), APInt(32, 0));
  5381. idxList.emplace_back(idx);
  5382. FlattenAggregatePtrToGepList(CGF, Ptr, idxList, Type, PT->getElementType(),
  5383. GepList, EltTyList);
  5384. idxList.pop_back();
  5385. } else if (HLMatrixLower::IsMatrixType(Ty)) {
  5386. // Use matLd/St for matrix.
  5387. unsigned col, row;
  5388. llvm::Type *EltTy = HLMatrixLower::GetMatrixInfo(Ty, col, row);
  5389. llvm::PointerType *EltPtrTy =
  5390. llvm::PointerType::get(EltTy, Ptr->getType()->getPointerAddressSpace());
  5391. QualType EltQualTy = hlsl::GetHLSLMatElementType(Type);
  5392. Value *matPtr = CGF.Builder.CreateInBoundsGEP(Ptr, idxList);
  5393. // Flatten matrix to elements.
  5394. for (unsigned r = 0; r < row; r++) {
  5395. for (unsigned c = 0; c < col; c++) {
  5396. ConstantInt *cRow = CGF.Builder.getInt32(r);
  5397. ConstantInt *cCol = CGF.Builder.getInt32(c);
  5398. Constant *CV = llvm::ConstantVector::get({cRow, cCol});
  5399. GepList.push_back(
  5400. EmitHLSLMatrixElement(CGF, EltPtrTy, {matPtr, CV}, Type));
  5401. EltTyList.push_back(EltQualTy);
  5402. }
  5403. }
  5404. } else if (StructType *ST = dyn_cast<StructType>(Ty)) {
  5405. if (HLModule::IsHLSLObjectType(ST)) {
  5406. // Avoid split HLSL object.
  5407. Value *GEP = CGF.Builder.CreateInBoundsGEP(Ptr, idxList);
  5408. GepList.push_back(GEP);
  5409. EltTyList.push_back(Type);
  5410. return;
  5411. }
  5412. const clang::RecordType *RT = Type->getAsStructureType();
  5413. RecordDecl *RD = RT->getDecl();
  5414. auto fieldIter = RD->field_begin();
  5415. const CGRecordLayout &RL = CGF.getTypes().getCGRecordLayout(RD);
  5416. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  5417. if (CXXRD->getNumBases()) {
  5418. // Add base as field.
  5419. for (const auto &I : CXXRD->bases()) {
  5420. const CXXRecordDecl *BaseDecl =
  5421. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  5422. // Skip empty struct.
  5423. if (BaseDecl->field_empty())
  5424. continue;
  5425. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  5426. llvm::Type *parentType = CGF.ConvertType(parentTy);
  5427. unsigned i = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  5428. Constant *idx = llvm::Constant::getIntegerValue(
  5429. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  5430. idxList.emplace_back(idx);
  5431. FlattenAggregatePtrToGepList(CGF, Ptr, idxList, parentTy, parentType,
  5432. GepList, EltTyList);
  5433. idxList.pop_back();
  5434. }
  5435. }
  5436. }
  5437. for (auto fieldIter = RD->field_begin(), fieldEnd = RD->field_end();
  5438. fieldIter != fieldEnd; ++fieldIter) {
  5439. unsigned i = RL.getLLVMFieldNo(*fieldIter);
  5440. llvm::Type *ET = ST->getElementType(i);
  5441. Constant *idx = llvm::Constant::getIntegerValue(
  5442. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  5443. idxList.emplace_back(idx);
  5444. FlattenAggregatePtrToGepList(CGF, Ptr, idxList, fieldIter->getType(), ET,
  5445. GepList, EltTyList);
  5446. idxList.pop_back();
  5447. }
  5448. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty)) {
  5449. llvm::Type *ET = AT->getElementType();
  5450. QualType EltType = CGF.getContext().getBaseElementType(Type);
  5451. for (uint32_t i = 0; i < AT->getNumElements(); i++) {
  5452. Constant *idx = Constant::getIntegerValue(
  5453. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  5454. idxList.emplace_back(idx);
  5455. FlattenAggregatePtrToGepList(CGF, Ptr, idxList, EltType, ET, GepList,
  5456. EltTyList);
  5457. idxList.pop_back();
  5458. }
  5459. } else if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(Ty)) {
  5460. // Flatten vector too.
  5461. QualType EltTy = hlsl::GetHLSLVecElementType(Type);
  5462. for (uint32_t i = 0; i < VT->getNumElements(); i++) {
  5463. Constant *idx = CGF.Builder.getInt32(i);
  5464. idxList.emplace_back(idx);
  5465. Value *GEP = CGF.Builder.CreateInBoundsGEP(Ptr, idxList);
  5466. GepList.push_back(GEP);
  5467. EltTyList.push_back(EltTy);
  5468. idxList.pop_back();
  5469. }
  5470. } else {
  5471. Value *GEP = CGF.Builder.CreateInBoundsGEP(Ptr, idxList);
  5472. GepList.push_back(GEP);
  5473. EltTyList.push_back(Type);
  5474. }
  5475. }
  5476. void CGMSHLSLRuntime::LoadFlattenedGepList(CodeGenFunction &CGF,
  5477. ArrayRef<Value *> GepList,
  5478. ArrayRef<QualType> EltTyList,
  5479. SmallVector<Value *, 4> &EltList) {
  5480. unsigned eltSize = GepList.size();
  5481. for (unsigned i = 0; i < eltSize; i++) {
  5482. Value *Ptr = GepList[i];
  5483. QualType Type = EltTyList[i];
  5484. // Everying is element type.
  5485. EltList.push_back(CGF.Builder.CreateLoad(Ptr));
  5486. }
  5487. }
  5488. void CGMSHLSLRuntime::StoreFlattenedGepList(CodeGenFunction &CGF, ArrayRef<Value *> GepList,
  5489. ArrayRef<QualType> GepTyList, ArrayRef<Value *> EltValList, ArrayRef<QualType> SrcTyList) {
  5490. unsigned eltSize = GepList.size();
  5491. for (unsigned i = 0; i < eltSize; i++) {
  5492. Value *Ptr = GepList[i];
  5493. QualType DestType = GepTyList[i];
  5494. Value *Val = EltValList[i];
  5495. QualType SrcType = SrcTyList[i];
  5496. llvm::Type *Ty = Ptr->getType()->getPointerElementType();
  5497. // Everything is element type.
  5498. if (Ty != Val->getType()) {
  5499. Instruction::CastOps castOp =
  5500. static_cast<Instruction::CastOps>(HLModule::FindCastOp(
  5501. IsUnsigned(SrcType), IsUnsigned(DestType), Val->getType(), Ty));
  5502. Val = CGF.Builder.CreateCast(castOp, Val, Ty);
  5503. }
  5504. CGF.Builder.CreateStore(Val, Ptr);
  5505. }
  5506. }
  5507. // Copy data from SrcPtr to DestPtr.
  5508. // For matrix, use MatLoad/MatStore.
  5509. // For matrix array, EmitHLSLAggregateCopy on each element.
  5510. // For struct or array, use memcpy.
  5511. // Other just load/store.
  5512. void CGMSHLSLRuntime::EmitHLSLAggregateCopy(
  5513. CodeGenFunction &CGF, llvm::Value *SrcPtr, llvm::Value *DestPtr,
  5514. SmallVector<Value *, 4> &idxList, clang::QualType SrcType,
  5515. clang::QualType DestType, llvm::Type *Ty) {
  5516. if (llvm::PointerType *PT = dyn_cast<llvm::PointerType>(Ty)) {
  5517. Constant *idx = Constant::getIntegerValue(
  5518. IntegerType::get(Ty->getContext(), 32), APInt(32, 0));
  5519. idxList.emplace_back(idx);
  5520. EmitHLSLAggregateCopy(CGF, SrcPtr, DestPtr, idxList, SrcType, DestType,
  5521. PT->getElementType());
  5522. idxList.pop_back();
  5523. } else if (HLMatrixLower::IsMatrixType(Ty)) {
  5524. // Use matLd/St for matrix.
  5525. Value *srcGEP = CGF.Builder.CreateInBoundsGEP(SrcPtr, idxList);
  5526. Value *dstGEP = CGF.Builder.CreateInBoundsGEP(DestPtr, idxList);
  5527. Value *ldMat = EmitHLSLMatrixLoad(CGF, srcGEP, SrcType);
  5528. EmitHLSLMatrixStore(CGF, ldMat, dstGEP, DestType);
  5529. } else if (StructType *ST = dyn_cast<StructType>(Ty)) {
  5530. if (HLModule::IsHLSLObjectType(ST)) {
  5531. // Avoid split HLSL object.
  5532. SimpleCopy(DestPtr, SrcPtr, idxList, CGF.Builder);
  5533. return;
  5534. }
  5535. Value *srcGEP = CGF.Builder.CreateInBoundsGEP(SrcPtr, idxList);
  5536. Value *dstGEP = CGF.Builder.CreateInBoundsGEP(DestPtr, idxList);
  5537. unsigned size = this->TheModule.getDataLayout().getTypeAllocSize(ST);
  5538. // Memcpy struct.
  5539. CGF.Builder.CreateMemCpy(dstGEP, srcGEP, size, 1);
  5540. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty)) {
  5541. if (!HLMatrixLower::IsMatrixArrayPointer(llvm::PointerType::get(Ty,0))) {
  5542. Value *srcGEP = CGF.Builder.CreateInBoundsGEP(SrcPtr, idxList);
  5543. Value *dstGEP = CGF.Builder.CreateInBoundsGEP(DestPtr, idxList);
  5544. unsigned size = this->TheModule.getDataLayout().getTypeAllocSize(AT);
  5545. // Memcpy non-matrix array.
  5546. CGF.Builder.CreateMemCpy(dstGEP, srcGEP, size, 1);
  5547. } else {
  5548. llvm::Type *ET = AT->getElementType();
  5549. QualType EltDestType = CGF.getContext().getBaseElementType(DestType);
  5550. QualType EltSrcType = CGF.getContext().getBaseElementType(SrcType);
  5551. for (uint32_t i = 0; i < AT->getNumElements(); i++) {
  5552. Constant *idx = Constant::getIntegerValue(
  5553. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  5554. idxList.emplace_back(idx);
  5555. EmitHLSLAggregateCopy(CGF, SrcPtr, DestPtr, idxList, EltSrcType,
  5556. EltDestType, ET);
  5557. idxList.pop_back();
  5558. }
  5559. }
  5560. } else {
  5561. SimpleCopy(DestPtr, SrcPtr, idxList, CGF.Builder);
  5562. }
  5563. }
  5564. void CGMSHLSLRuntime::EmitHLSLAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  5565. llvm::Value *DestPtr,
  5566. clang::QualType Ty) {
  5567. SmallVector<Value *, 4> idxList;
  5568. EmitHLSLAggregateCopy(CGF, SrcPtr, DestPtr, idxList, Ty, Ty, SrcPtr->getType());
  5569. }
  5570. void CGMSHLSLRuntime::EmitHLSLFlatConversionAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  5571. clang::QualType SrcTy,
  5572. llvm::Value *DestPtr,
  5573. clang::QualType DestTy) {
  5574. llvm::Type *SrcPtrTy = SrcPtr->getType()->getPointerElementType();
  5575. llvm::Type *DestPtrTy = DestPtr->getType()->getPointerElementType();
  5576. if (SrcPtrTy == DestPtrTy) {
  5577. // Memcpy if type is match.
  5578. unsigned size = TheModule.getDataLayout().getTypeAllocSize(SrcPtrTy);
  5579. CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, size, 1);
  5580. return;
  5581. } else if (HLModule::IsHLSLObjectType(dxilutil::GetArrayEltTy(SrcPtrTy)) &&
  5582. HLModule::IsHLSLObjectType(dxilutil::GetArrayEltTy(DestPtrTy))) {
  5583. unsigned sizeSrc = TheModule.getDataLayout().getTypeAllocSize(SrcPtrTy);
  5584. unsigned sizeDest = TheModule.getDataLayout().getTypeAllocSize(DestPtrTy);
  5585. CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, std::max(sizeSrc, sizeDest), 1);
  5586. return;
  5587. }
  5588. // It is possiable to implement EmitHLSLAggregateCopy, EmitHLSLAggregateStore
  5589. // the same way. But split value to scalar will generate many instruction when
  5590. // src type is same as dest type.
  5591. SmallVector<Value *, 4> idxList;
  5592. SmallVector<Value *, 4> SrcGEPList;
  5593. SmallVector<QualType, 4> SrcEltTyList;
  5594. FlattenAggregatePtrToGepList(CGF, SrcPtr, idxList, SrcTy, SrcPtr->getType(),
  5595. SrcGEPList, SrcEltTyList);
  5596. SmallVector<Value *, 4> LdEltList;
  5597. LoadFlattenedGepList(CGF, SrcGEPList, SrcEltTyList, LdEltList);
  5598. idxList.clear();
  5599. SmallVector<Value *, 4> DestGEPList;
  5600. SmallVector<QualType, 4> DestEltTyList;
  5601. FlattenAggregatePtrToGepList(CGF, DestPtr, idxList, DestTy,
  5602. DestPtr->getType(), DestGEPList, DestEltTyList);
  5603. StoreFlattenedGepList(CGF, DestGEPList, DestEltTyList, LdEltList,
  5604. SrcEltTyList);
  5605. }
  5606. void CGMSHLSLRuntime::EmitHLSLAggregateStore(CodeGenFunction &CGF, llvm::Value *SrcVal,
  5607. llvm::Value *DestPtr,
  5608. clang::QualType Ty) {
  5609. DXASSERT(0, "aggregate return type will use SRet, no aggregate store should exist");
  5610. }
  5611. static void SimpleFlatValCopy(Value *DestPtr, Value *SrcVal, QualType Ty,
  5612. QualType SrcTy, ArrayRef<Value *> idxList,
  5613. CGBuilderTy &Builder) {
  5614. Value *DestGEP = Builder.CreateInBoundsGEP(DestPtr, idxList);
  5615. llvm::Type *ToTy = DestGEP->getType()->getPointerElementType();
  5616. llvm::Type *EltToTy = ToTy;
  5617. if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(ToTy)) {
  5618. EltToTy = VT->getElementType();
  5619. }
  5620. if (EltToTy != SrcVal->getType()) {
  5621. Instruction::CastOps castOp =
  5622. static_cast<Instruction::CastOps>(HLModule::FindCastOp(
  5623. IsUnsigned(SrcTy), IsUnsigned(Ty), SrcVal->getType(), ToTy));
  5624. SrcVal = Builder.CreateCast(castOp, SrcVal, EltToTy);
  5625. }
  5626. if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(ToTy)) {
  5627. llvm::VectorType *VT1 = llvm::VectorType::get(EltToTy, 1);
  5628. Value *V1 =
  5629. Builder.CreateInsertElement(UndefValue::get(VT1), SrcVal, (uint64_t)0);
  5630. std::vector<int> shufIdx(VT->getNumElements(), 0);
  5631. Value *Vec = Builder.CreateShuffleVector(V1, V1, shufIdx);
  5632. Builder.CreateStore(Vec, DestGEP);
  5633. } else
  5634. Builder.CreateStore(SrcVal, DestGEP);
  5635. }
  5636. void CGMSHLSLRuntime::EmitHLSLFlatConversionToAggregate(
  5637. CodeGenFunction &CGF, Value *SrcVal, llvm::Value *DestPtr,
  5638. SmallVector<Value *, 4> &idxList, QualType Type, QualType SrcType,
  5639. llvm::Type *Ty) {
  5640. if (llvm::PointerType *PT = dyn_cast<llvm::PointerType>(Ty)) {
  5641. Constant *idx = Constant::getIntegerValue(
  5642. IntegerType::get(Ty->getContext(), 32), APInt(32, 0));
  5643. idxList.emplace_back(idx);
  5644. EmitHLSLFlatConversionToAggregate(CGF, SrcVal, DestPtr, idxList, Type,
  5645. SrcType, PT->getElementType());
  5646. idxList.pop_back();
  5647. } else if (HLMatrixLower::IsMatrixType(Ty)) {
  5648. // Use matLd/St for matrix.
  5649. Value *dstGEP = CGF.Builder.CreateInBoundsGEP(DestPtr, idxList);
  5650. unsigned row, col;
  5651. llvm::Type *EltTy = HLMatrixLower::GetMatrixInfo(Ty, col, row);
  5652. llvm::VectorType *VT1 = llvm::VectorType::get(EltTy, 1);
  5653. if (EltTy != SrcVal->getType()) {
  5654. Instruction::CastOps castOp =
  5655. static_cast<Instruction::CastOps>(HLModule::FindCastOp(
  5656. IsUnsigned(SrcType), IsUnsigned(Type), SrcVal->getType(), EltTy));
  5657. SrcVal = CGF.Builder.CreateCast(castOp, SrcVal, EltTy);
  5658. }
  5659. Value *V1 = CGF.Builder.CreateInsertElement(UndefValue::get(VT1), SrcVal,
  5660. (uint64_t)0);
  5661. std::vector<int> shufIdx(col * row, 0);
  5662. Value *VecMat = CGF.Builder.CreateShuffleVector(V1, V1, shufIdx);
  5663. Value *MatInit = EmitHLSLMatrixOperationCallImp(
  5664. CGF.Builder, HLOpcodeGroup::HLInit, 0, Ty, {VecMat}, TheModule);
  5665. EmitHLSLMatrixStore(CGF, MatInit, dstGEP, Type);
  5666. } else if (StructType *ST = dyn_cast<StructType>(Ty)) {
  5667. DXASSERT(!HLModule::IsHLSLObjectType(ST), "cannot cast to hlsl object, Sema should reject");
  5668. const clang::RecordType *RT = Type->getAsStructureType();
  5669. RecordDecl *RD = RT->getDecl();
  5670. auto fieldIter = RD->field_begin();
  5671. const CGRecordLayout &RL = CGF.getTypes().getCGRecordLayout(RD);
  5672. // Take care base.
  5673. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  5674. if (CXXRD->getNumBases()) {
  5675. for (const auto &I : CXXRD->bases()) {
  5676. const CXXRecordDecl *BaseDecl =
  5677. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  5678. if (BaseDecl->field_empty())
  5679. continue;
  5680. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  5681. unsigned i = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  5682. llvm::Type *ET = ST->getElementType(i);
  5683. Constant *idx = llvm::Constant::getIntegerValue(
  5684. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  5685. idxList.emplace_back(idx);
  5686. EmitHLSLFlatConversionToAggregate(CGF, SrcVal, DestPtr, idxList,
  5687. parentTy, SrcType, ET);
  5688. idxList.pop_back();
  5689. }
  5690. }
  5691. }
  5692. for (auto fieldIter = RD->field_begin(), fieldEnd = RD->field_end();
  5693. fieldIter != fieldEnd; ++fieldIter) {
  5694. unsigned i = RL.getLLVMFieldNo(*fieldIter);
  5695. llvm::Type *ET = ST->getElementType(i);
  5696. Constant *idx = llvm::Constant::getIntegerValue(
  5697. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  5698. idxList.emplace_back(idx);
  5699. EmitHLSLFlatConversionToAggregate(CGF, SrcVal, DestPtr, idxList,
  5700. fieldIter->getType(), SrcType, ET);
  5701. idxList.pop_back();
  5702. }
  5703. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty)) {
  5704. llvm::Type *ET = AT->getElementType();
  5705. QualType EltType = CGF.getContext().getBaseElementType(Type);
  5706. for (uint32_t i = 0; i < AT->getNumElements(); i++) {
  5707. Constant *idx = Constant::getIntegerValue(
  5708. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  5709. idxList.emplace_back(idx);
  5710. EmitHLSLFlatConversionToAggregate(CGF, SrcVal, DestPtr, idxList, EltType,
  5711. SrcType, ET);
  5712. idxList.pop_back();
  5713. }
  5714. } else {
  5715. SimpleFlatValCopy(DestPtr, SrcVal, Type, SrcType, idxList, CGF.Builder);
  5716. }
  5717. }
  5718. void CGMSHLSLRuntime::EmitHLSLFlatConversionToAggregate(CodeGenFunction &CGF,
  5719. Value *Val,
  5720. Value *DestPtr,
  5721. QualType Ty,
  5722. QualType SrcTy) {
  5723. if (SrcTy->isBuiltinType()) {
  5724. SmallVector<Value *, 4> idxList;
  5725. // Add first 0 for DestPtr.
  5726. Constant *idx = Constant::getIntegerValue(
  5727. IntegerType::get(Val->getContext(), 32), APInt(32, 0));
  5728. idxList.emplace_back(idx);
  5729. EmitHLSLFlatConversionToAggregate(
  5730. CGF, Val, DestPtr, idxList, Ty, SrcTy,
  5731. DestPtr->getType()->getPointerElementType());
  5732. }
  5733. else {
  5734. SmallVector<Value *, 4> idxList;
  5735. SmallVector<Value *, 4> DestGEPList;
  5736. SmallVector<QualType, 4> DestEltTyList;
  5737. FlattenAggregatePtrToGepList(CGF, DestPtr, idxList, Ty, DestPtr->getType(), DestGEPList, DestEltTyList);
  5738. SmallVector<Value *, 4> EltList;
  5739. SmallVector<QualType, 4> EltTyList;
  5740. FlattenValToInitList(CGF, EltList, EltTyList, SrcTy, Val);
  5741. StoreFlattenedGepList(CGF, DestGEPList, DestEltTyList, EltList, EltTyList);
  5742. }
  5743. }
  5744. void CGMSHLSLRuntime::EmitHLSLRootSignature(CodeGenFunction &CGF,
  5745. HLSLRootSignatureAttr *RSA,
  5746. Function *Fn) {
  5747. // Only parse root signature for entry function.
  5748. if (Fn != Entry.Func)
  5749. return;
  5750. StringRef StrRef = RSA->getSignatureName();
  5751. DiagnosticsEngine &Diags = CGF.getContext().getDiagnostics();
  5752. SourceLocation SLoc = RSA->getLocation();
  5753. clang::CompileRootSignature(StrRef, Diags, SLoc, rootSigVer, &m_pHLModule->GetRootSignature());
  5754. }
  5755. void CGMSHLSLRuntime::EmitHLSLOutParamConversionInit(
  5756. CodeGenFunction &CGF, const FunctionDecl *FD, const CallExpr *E,
  5757. llvm::SmallVector<LValue, 8> &castArgList,
  5758. llvm::SmallVector<const Stmt *, 8> &argList,
  5759. const std::function<void(const VarDecl *, llvm::Value *)> &TmpArgMap) {
  5760. // Special case: skip first argument of CXXOperatorCall (it is "this").
  5761. unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(E) ? 1 : 0;
  5762. for (uint32_t i = 0; i < FD->getNumParams(); i++) {
  5763. const ParmVarDecl *Param = FD->getParamDecl(i);
  5764. const Expr *Arg = E->getArg(i+ArgsToSkip);
  5765. QualType ParamTy = Param->getType().getNonReferenceType();
  5766. bool RValOnRef = false;
  5767. if (!Param->isModifierOut()) {
  5768. if (!ParamTy->isAggregateType() || hlsl::IsHLSLMatType(ParamTy)) {
  5769. if (Arg->isRValue() && Param->getType()->isReferenceType()) {
  5770. // RValue on a reference type.
  5771. if (const CStyleCastExpr *cCast = dyn_cast<CStyleCastExpr>(Arg)) {
  5772. // TODO: Evolving this to warn then fail in future language versions.
  5773. // Allow special case like cast uint to uint for back-compat.
  5774. if (cCast->getCastKind() == CastKind::CK_NoOp) {
  5775. if (const ImplicitCastExpr *cast =
  5776. dyn_cast<ImplicitCastExpr>(cCast->getSubExpr())) {
  5777. if (cast->getCastKind() == CastKind::CK_LValueToRValue) {
  5778. // update the arg
  5779. argList[i] = cast->getSubExpr();
  5780. continue;
  5781. }
  5782. }
  5783. }
  5784. }
  5785. // EmitLValue will report error.
  5786. // Mark RValOnRef to create tmpArg for it.
  5787. RValOnRef = true;
  5788. } else {
  5789. continue;
  5790. }
  5791. }
  5792. }
  5793. // get original arg
  5794. LValue argLV = CGF.EmitLValue(Arg);
  5795. if (!Param->isModifierOut() && !RValOnRef) {
  5796. bool isDefaultAddrSpace = true;
  5797. if (argLV.isSimple()) {
  5798. isDefaultAddrSpace =
  5799. argLV.getAddress()->getType()->getPointerAddressSpace() ==
  5800. DXIL::kDefaultAddrSpace;
  5801. }
  5802. bool isHLSLIntrinsic = false;
  5803. if (const FunctionDecl *Callee = E->getDirectCallee()) {
  5804. isHLSLIntrinsic = Callee->hasAttr<HLSLIntrinsicAttr>();
  5805. }
  5806. // Copy in arg which is not default address space and not on hlsl intrinsic.
  5807. if (isDefaultAddrSpace || isHLSLIntrinsic)
  5808. continue;
  5809. }
  5810. // create temp Var
  5811. VarDecl *tmpArg =
  5812. VarDecl::Create(CGF.getContext(), const_cast<FunctionDecl *>(FD),
  5813. SourceLocation(), SourceLocation(),
  5814. /*IdentifierInfo*/ nullptr, ParamTy,
  5815. CGF.getContext().getTrivialTypeSourceInfo(ParamTy),
  5816. StorageClass::SC_Auto);
  5817. // Aggregate type will be indirect param convert to pointer type.
  5818. // So don't update to ReferenceType, use RValue for it.
  5819. bool isAggregateType = (ParamTy->isArrayType() || ParamTy->isRecordType()) &&
  5820. !hlsl::IsHLSLVecMatType(ParamTy);
  5821. const DeclRefExpr *tmpRef = DeclRefExpr::Create(
  5822. CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), tmpArg,
  5823. /*enclosing*/ false, tmpArg->getLocation(), ParamTy,
  5824. isAggregateType ? VK_RValue : VK_LValue);
  5825. // update the arg
  5826. argList[i] = tmpRef;
  5827. // create alloc for the tmp arg
  5828. Value *tmpArgAddr = nullptr;
  5829. BasicBlock *InsertBlock = CGF.Builder.GetInsertBlock();
  5830. Function *F = InsertBlock->getParent();
  5831. BasicBlock *EntryBlock = &F->getEntryBlock();
  5832. if (ParamTy->isBooleanType()) {
  5833. // Create i32 for bool.
  5834. ParamTy = CGM.getContext().IntTy;
  5835. }
  5836. // Make sure the alloca is in entry block to stop inline create stacksave.
  5837. IRBuilder<> Builder(EntryBlock->getFirstInsertionPt());
  5838. tmpArgAddr = Builder.CreateAlloca(CGF.ConvertType(ParamTy));
  5839. // add it to local decl map
  5840. TmpArgMap(tmpArg, tmpArgAddr);
  5841. LValue tmpLV = LValue::MakeAddr(tmpArgAddr, ParamTy, argLV.getAlignment(),
  5842. CGF.getContext());
  5843. // save for cast after call
  5844. if (Param->isModifierOut()) {
  5845. castArgList.emplace_back(tmpLV);
  5846. castArgList.emplace_back(argLV);
  5847. }
  5848. bool isObject = HLModule::IsHLSLObjectType(
  5849. tmpArgAddr->getType()->getPointerElementType());
  5850. // cast before the call
  5851. if (Param->isModifierIn() &&
  5852. // Don't copy object
  5853. !isObject) {
  5854. QualType ArgTy = Arg->getType();
  5855. Value *outVal = nullptr;
  5856. bool isAggrageteTy = ParamTy->isAggregateType();
  5857. isAggrageteTy &= !IsHLSLVecMatType(ParamTy);
  5858. if (!isAggrageteTy) {
  5859. if (!IsHLSLMatType(ParamTy)) {
  5860. RValue outRVal = CGF.EmitLoadOfLValue(argLV, SourceLocation());
  5861. outVal = outRVal.getScalarVal();
  5862. } else {
  5863. Value *argAddr = argLV.getAddress();
  5864. outVal = EmitHLSLMatrixLoad(CGF, argAddr, ArgTy);
  5865. }
  5866. llvm::Type *ToTy = tmpArgAddr->getType()->getPointerElementType();
  5867. Instruction::CastOps castOp =
  5868. static_cast<Instruction::CastOps>(HLModule::FindCastOp(
  5869. IsUnsigned(argLV.getType()), IsUnsigned(tmpLV.getType()),
  5870. outVal->getType(), ToTy));
  5871. Value *castVal = CGF.Builder.CreateCast(castOp, outVal, ToTy);
  5872. if (!HLMatrixLower::IsMatrixType(ToTy))
  5873. CGF.Builder.CreateStore(castVal, tmpArgAddr);
  5874. else
  5875. EmitHLSLMatrixStore(CGF, castVal, tmpArgAddr, ParamTy);
  5876. } else {
  5877. SmallVector<Value *, 4> idxList;
  5878. EmitHLSLAggregateCopy(CGF, argLV.getAddress(), tmpLV.getAddress(),
  5879. idxList, ArgTy, ParamTy,
  5880. argLV.getAddress()->getType());
  5881. }
  5882. }
  5883. }
  5884. }
  5885. void CGMSHLSLRuntime::EmitHLSLOutParamConversionCopyBack(
  5886. CodeGenFunction &CGF, llvm::SmallVector<LValue, 8> &castArgList) {
  5887. for (uint32_t i = 0; i < castArgList.size(); i += 2) {
  5888. // cast after the call
  5889. LValue tmpLV = castArgList[i];
  5890. LValue argLV = castArgList[i + 1];
  5891. QualType ArgTy = argLV.getType().getNonReferenceType();
  5892. QualType ParamTy = tmpLV.getType().getNonReferenceType();
  5893. Value *tmpArgAddr = tmpLV.getAddress();
  5894. Value *outVal = nullptr;
  5895. bool isAggrageteTy = ArgTy->isAggregateType();
  5896. isAggrageteTy &= !IsHLSLVecMatType(ArgTy);
  5897. bool isObject = HLModule::IsHLSLObjectType(
  5898. tmpArgAddr->getType()->getPointerElementType());
  5899. if (!isObject) {
  5900. if (!isAggrageteTy) {
  5901. if (!IsHLSLMatType(ParamTy))
  5902. outVal = CGF.Builder.CreateLoad(tmpArgAddr);
  5903. else
  5904. outVal = EmitHLSLMatrixLoad(CGF, tmpArgAddr, ParamTy);
  5905. llvm::Type *ToTy = CGF.ConvertType(ArgTy);
  5906. llvm::Type *FromTy = outVal->getType();
  5907. Value *castVal = outVal;
  5908. if (ToTy == FromTy) {
  5909. // Don't need cast.
  5910. } else if (ToTy->getScalarType() == FromTy->getScalarType()) {
  5911. if (ToTy->getScalarType() == ToTy) {
  5912. DXASSERT(FromTy->isVectorTy() &&
  5913. FromTy->getVectorNumElements() == 1,
  5914. "must be vector of 1 element");
  5915. castVal = CGF.Builder.CreateExtractElement(outVal, (uint64_t)0);
  5916. } else {
  5917. DXASSERT(!FromTy->isVectorTy(), "must be scalar type");
  5918. DXASSERT(ToTy->isVectorTy() && ToTy->getVectorNumElements() == 1,
  5919. "must be vector of 1 element");
  5920. castVal = UndefValue::get(ToTy);
  5921. castVal =
  5922. CGF.Builder.CreateInsertElement(castVal, outVal, (uint64_t)0);
  5923. }
  5924. } else {
  5925. Instruction::CastOps castOp =
  5926. static_cast<Instruction::CastOps>(HLModule::FindCastOp(
  5927. IsUnsigned(tmpLV.getType()), IsUnsigned(argLV.getType()),
  5928. outVal->getType(), ToTy));
  5929. castVal = CGF.Builder.CreateCast(castOp, outVal, ToTy);
  5930. }
  5931. if (!HLMatrixLower::IsMatrixType(ToTy))
  5932. CGF.EmitStoreThroughLValue(RValue::get(castVal), argLV);
  5933. else {
  5934. Value *destPtr = argLV.getAddress();
  5935. EmitHLSLMatrixStore(CGF, castVal, destPtr, ArgTy);
  5936. }
  5937. } else {
  5938. SmallVector<Value *, 4> idxList;
  5939. EmitHLSLAggregateCopy(CGF, tmpLV.getAddress(), argLV.getAddress(),
  5940. idxList, ParamTy, ArgTy,
  5941. argLV.getAddress()->getType());
  5942. }
  5943. } else
  5944. tmpArgAddr->replaceAllUsesWith(argLV.getAddress());
  5945. }
  5946. }
  5947. CGHLSLRuntime *CodeGen::CreateMSHLSLRuntime(CodeGenModule &CGM) {
  5948. return new CGMSHLSLRuntime(CGM);
  5949. }