CGHLSLMS.cpp 245 KB

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