CGHLSLMS.cpp 239 KB

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