CGHLSLMS.cpp 257 KB

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