2
0

CGHLSLMS.cpp 233 KB

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