CGHLSLMS.cpp 225 KB

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