CGHLSLMS.cpp 239 KB

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