CGHLSLMS.cpp 218 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722
  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/HLMatrixType.h"
  18. #include "dxc/HLSL/HLModule.h"
  19. #include "dxc/DXIL/DxilUtil.h"
  20. #include "dxc/HLSL/HLOperations.h"
  21. #include "dxc/DXIL/DxilOperations.h"
  22. #include "dxc/DXIL/DxilTypeSystem.h"
  23. #include "clang/AST/DeclTemplate.h"
  24. #include "clang/AST/HlslTypes.h"
  25. #include "clang/Frontend/CodeGenOptions.h"
  26. #include "clang/Lex/HLSLMacroExpander.h"
  27. #include "llvm/ADT/STLExtras.h"
  28. #include "llvm/ADT/StringSwitch.h"
  29. #include "llvm/ADT/StringSet.h"
  30. #include "llvm/ADT/SmallPtrSet.h"
  31. #include "llvm/ADT/StringSet.h"
  32. #include "llvm/IR/Constants.h"
  33. #include "llvm/IR/IRBuilder.h"
  34. #include "llvm/IR/GetElementPtrTypeIterator.h"
  35. #include "llvm/Transforms/Utils/Cloning.h"
  36. #include "llvm/IR/InstIterator.h"
  37. #include <memory>
  38. #include <unordered_map>
  39. #include <unordered_set>
  40. #include <set>
  41. #include "dxc/DxilRootSignature/DxilRootSignature.h"
  42. #include "dxc/DXIL/DxilCBuffer.h"
  43. #include "clang/Parse/ParseHLSL.h" // root sig would be in Parser if part of lang
  44. #include "dxc/Support/WinIncludes.h" // stream support
  45. #include "dxc/dxcapi.h" // stream support
  46. #include "dxc/HLSL/HLSLExtensionsCodegenHelper.h"
  47. #include "dxc/HLSL/DxilGenerationPass.h" // support pause/resume passes
  48. #include "dxc/HLSL/DxilExportMap.h"
  49. #include "dxc/DXIL/DxilResourceProperties.h"
  50. #include "CGHLSLMSHelper.h"
  51. using namespace clang;
  52. using namespace CodeGen;
  53. using namespace hlsl;
  54. using namespace llvm;
  55. using std::unique_ptr;
  56. using namespace CGHLSLMSHelper;
  57. static const bool KeepUndefinedTrue = true; // Keep interpolation mode undefined if not set explicitly.
  58. namespace {
  59. class CGMSHLSLRuntime : public CGHLSLRuntime {
  60. private:
  61. /// Convenience reference to LLVM Context
  62. llvm::LLVMContext &Context;
  63. /// Convenience reference to the current module
  64. llvm::Module &TheModule;
  65. HLModule *m_pHLModule;
  66. llvm::Type *CBufferType;
  67. uint32_t globalCBIndex;
  68. // TODO: make sure how minprec works
  69. llvm::DataLayout dataLayout;
  70. // decl map to constant id for program
  71. llvm::DenseMap<HLSLBufferDecl *, uint32_t> constantBufMap;
  72. // Map for resource type to resource metadata value.
  73. std::unordered_map<llvm::Type *, MDNode*> resMetadataMap;
  74. // Map from Constant to register bindings.
  75. llvm::DenseMap<llvm::Constant *,
  76. llvm::SmallVector<std::pair<DXIL::ResourceClass, unsigned>, 1>>
  77. constantRegBindingMap;
  78. // Map from value to resource properties.
  79. // This only collect object variables(global/local/parameter), not object fields inside struct.
  80. // Object fields inside struct is saved by TypeAnnotation.
  81. DenseMap<Value *, DxilResourceProperties> valToResPropertiesMap;
  82. bool m_bDebugInfo;
  83. bool m_bIsLib;
  84. // For library, m_ExportMap maps from internal name to zero or more renames
  85. dxilutil::ExportMap m_ExportMap;
  86. HLCBuffer &GetGlobalCBuffer() {
  87. return *static_cast<HLCBuffer*>(&(m_pHLModule->GetCBuffer(globalCBIndex)));
  88. }
  89. void AddConstant(VarDecl *constDecl, HLCBuffer &CB);
  90. uint32_t AddSampler(VarDecl *samplerDecl);
  91. uint32_t AddUAVSRV(VarDecl *decl, hlsl::DxilResourceBase::Class resClass);
  92. bool SetUAVSRV(SourceLocation loc, hlsl::DxilResourceBase::Class resClass,
  93. DxilResource *hlslRes, QualType QualTy);
  94. uint32_t AddCBuffer(HLSLBufferDecl *D);
  95. hlsl::DxilResourceBase::Class TypeToClass(clang::QualType Ty);
  96. void CreateSubobject(DXIL::SubobjectKind kind, const StringRef name, clang::Expr **args,
  97. unsigned int argCount, DXIL::HitGroupType hgType = (DXIL::HitGroupType)(-1));
  98. bool GetAsConstantString(clang::Expr *expr, StringRef *value, bool failWhenEmpty = false);
  99. bool GetAsConstantUInt32(clang::Expr *expr, uint32_t *value);
  100. std::vector<StringRef> ParseSubobjectExportsAssociations(StringRef exports);
  101. EntryFunctionInfo Entry;
  102. StringMap<PatchConstantInfo> patchConstantFunctionMap;
  103. std::unordered_map<Function *, std::unique_ptr<DxilFunctionProps>>
  104. patchConstantFunctionPropsMap;
  105. std::unordered_map<Function *, const clang::HLSLPatchConstantFuncAttr *>
  106. HSEntryPatchConstantFuncAttr;
  107. // Map to save entry functions.
  108. StringMap<EntryFunctionInfo> entryFunctionMap;
  109. // Map to save static global init exp.
  110. std::unordered_map<Expr *, GlobalVariable *> staticConstGlobalInitMap;
  111. std::unordered_map<GlobalVariable *, std::vector<Constant *>>
  112. staticConstGlobalInitListMap;
  113. std::unordered_map<GlobalVariable *, Function *> staticConstGlobalCtorMap;
  114. // List for functions with clip plane.
  115. std::vector<Function *> clipPlaneFuncList;
  116. std::unordered_map<Value *, DebugLoc> debugInfoMap;
  117. DxilRootSignatureVersion rootSigVer;
  118. Value *EmitHLSLMatrixLoad(CGBuilderTy &Builder, Value *Ptr, QualType Ty);
  119. void EmitHLSLMatrixStore(CGBuilderTy &Builder, Value *Val, Value *DestPtr,
  120. QualType Ty);
  121. // Flatten the val into scalar val and push into elts and eltTys.
  122. void FlattenValToInitList(CodeGenFunction &CGF, SmallVector<Value *, 4> &elts,
  123. SmallVector<QualType, 4> &eltTys, QualType Ty,
  124. Value *val);
  125. // Push every value on InitListExpr into EltValList and EltTyList.
  126. void ScanInitList(CodeGenFunction &CGF, InitListExpr *E,
  127. SmallVector<Value *, 4> &EltValList,
  128. SmallVector<QualType, 4> &EltTyList);
  129. void FlattenAggregatePtrToGepList(CodeGenFunction &CGF, Value *Ptr,
  130. SmallVector<Value *, 4> &idxList,
  131. clang::QualType Type, llvm::Type *Ty,
  132. SmallVector<Value *, 4> &GepList,
  133. SmallVector<QualType, 4> &EltTyList);
  134. void LoadElements(CodeGenFunction &CGF,
  135. ArrayRef<Value *> Ptrs, ArrayRef<QualType> QualTys,
  136. SmallVector<Value *, 4> &Vals);
  137. void ConvertAndStoreElements(CodeGenFunction &CGF,
  138. ArrayRef<Value *> SrcVals, ArrayRef<QualType> SrcQualTys,
  139. ArrayRef<Value *> DstPtrs, ArrayRef<QualType> DstQualTys);
  140. void EmitHLSLAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  141. llvm::Value *DestPtr,
  142. SmallVector<Value *, 4> &idxList,
  143. clang::QualType SrcType,
  144. clang::QualType DestType,
  145. llvm::Type *Ty);
  146. void EmitHLSLSplat(CodeGenFunction &CGF, Value *SrcVal,
  147. llvm::Value *DestPtr,
  148. SmallVector<Value *, 4> &idxList,
  149. QualType Type, QualType SrcType,
  150. llvm::Type *Ty);
  151. void EmitHLSLRootSignature(CodeGenFunction &CGF, HLSLRootSignatureAttr *RSA,
  152. llvm::Function *Fn) override;
  153. void CheckParameterAnnotation(SourceLocation SLoc,
  154. const DxilParameterAnnotation &paramInfo,
  155. bool isPatchConstantFunction);
  156. void CheckParameterAnnotation(SourceLocation SLoc,
  157. DxilParamInputQual paramQual,
  158. llvm::StringRef semFullName,
  159. bool isPatchConstantFunction);
  160. void RemapObsoleteSemantic(DxilParameterAnnotation &paramInfo,
  161. bool isPatchConstantFunction);
  162. SourceLocation SetSemantic(const NamedDecl *decl,
  163. DxilParameterAnnotation &paramInfo);
  164. hlsl::InterpolationMode GetInterpMode(const Decl *decl, CompType compType,
  165. bool bKeepUndefined);
  166. hlsl::CompType GetCompType(const BuiltinType *BT);
  167. // save intrinsic opcode
  168. std::vector<std::pair<Function *, unsigned>> m_IntrinsicMap;
  169. void AddHLSLIntrinsicOpcodeToFunction(Function *, unsigned opcode);
  170. // Type annotation related.
  171. unsigned ConstructStructAnnotation(DxilStructAnnotation *annotation,
  172. const RecordDecl *RD,
  173. DxilTypeSystem &dxilTypeSys);
  174. unsigned AddTypeAnnotation(QualType Ty, DxilTypeSystem &dxilTypeSys,
  175. unsigned &arrayEltSize);
  176. MDNode *GetOrAddResTypeMD(QualType resTy, bool bCreate);
  177. DxilResourceProperties BuildResourceProperty(QualType resTy);
  178. void ConstructFieldAttributedAnnotation(DxilFieldAnnotation &fieldAnnotation,
  179. QualType fieldTy,
  180. bool bDefaultRowMajor);
  181. std::unordered_map<Constant*, DxilFieldAnnotation> m_ConstVarAnnotationMap;
  182. StringSet<> m_PreciseOutputSet;
  183. DenseMap<Function*, ScopeInfo> m_ScopeMap;
  184. ScopeInfo *GetScopeInfo(Function *F);
  185. public:
  186. CGMSHLSLRuntime(CodeGenModule &CGM);
  187. /// Add resouce to the program
  188. void addResource(Decl *D) override;
  189. void addSubobject(Decl *D) override;
  190. void FinishCodeGen() override;
  191. bool IsTrivalInitListExpr(CodeGenFunction &CGF, InitListExpr *E) override;
  192. Value *EmitHLSLInitListExpr(CodeGenFunction &CGF, InitListExpr *E, Value *DestPtr) override;
  193. Constant *EmitHLSLConstInitListExpr(CodeGenModule &CGM, InitListExpr *E) override;
  194. RValue EmitHLSLBuiltinCallExpr(CodeGenFunction &CGF, const FunctionDecl *FD,
  195. const CallExpr *E,
  196. ReturnValueSlot ReturnValue) override;
  197. void EmitHLSLOutParamConversionInit(
  198. CodeGenFunction &CGF, const FunctionDecl *FD, const CallExpr *E,
  199. llvm::SmallVector<LValue, 8> &castArgList,
  200. llvm::SmallVector<const Stmt *, 8> &argList,
  201. const std::function<void(const VarDecl *, llvm::Value *)> &TmpArgMap)
  202. override;
  203. void EmitHLSLOutParamConversionCopyBack(
  204. CodeGenFunction &CGF, llvm::SmallVector<LValue, 8> &castArgList) override;
  205. Value *EmitHLSLMatrixOperationCall(CodeGenFunction &CGF, const clang::Expr *E,
  206. llvm::Type *RetType,
  207. ArrayRef<Value *> paramList) override;
  208. void EmitHLSLDiscard(CodeGenFunction &CGF) override;
  209. void EmitHLSLCondBreak(CodeGenFunction &CGF, llvm::Function *F, llvm::BasicBlock *DestBB, llvm::BasicBlock *AltBB) override;
  210. Value *EmitHLSLMatrixSubscript(CodeGenFunction &CGF, llvm::Type *RetType,
  211. Value *Ptr, Value *Idx, QualType Ty) override;
  212. Value *EmitHLSLMatrixElement(CodeGenFunction &CGF, llvm::Type *RetType,
  213. ArrayRef<Value *> paramList,
  214. QualType Ty) override;
  215. Value *EmitHLSLMatrixLoad(CodeGenFunction &CGF, Value *Ptr,
  216. QualType Ty) override;
  217. void EmitHLSLMatrixStore(CodeGenFunction &CGF, Value *Val, Value *DestPtr,
  218. QualType Ty) override;
  219. void EmitHLSLAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  220. llvm::Value *DestPtr,
  221. clang::QualType Ty) override;
  222. void EmitHLSLAggregateStore(CodeGenFunction &CGF, llvm::Value *Val,
  223. llvm::Value *DestPtr,
  224. clang::QualType Ty) override;
  225. void EmitHLSLFlatConversion(CodeGenFunction &CGF, Value *Val,
  226. Value *DestPtr,
  227. QualType Ty,
  228. QualType SrcTy) override;
  229. Value *EmitHLSLLiteralCast(CodeGenFunction &CGF, Value *Src, QualType SrcType,
  230. QualType DstType) override;
  231. void EmitHLSLFlatConversionAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  232. clang::QualType SrcTy,
  233. llvm::Value *DestPtr,
  234. clang::QualType DestTy) override;
  235. void AddHLSLFunctionInfo(llvm::Function *, const FunctionDecl *FD) override;
  236. void EmitHLSLFunctionProlog(llvm::Function *, const FunctionDecl *FD) override;
  237. void AddControlFlowHint(CodeGenFunction &CGF, const Stmt &S,
  238. llvm::TerminatorInst *TI,
  239. ArrayRef<const Attr *> Attrs) override;
  240. void MarkRetTemp(CodeGenFunction &CGF, llvm::Value *V,
  241. clang::QualType QaulTy) override;
  242. void FinishAutoVar(CodeGenFunction &CGF, const VarDecl &D, llvm::Value *V) override;
  243. void MarkIfStmt(CodeGenFunction &CGF, BasicBlock *endIfBB) override;
  244. void MarkSwitchStmt(CodeGenFunction &CGF, SwitchInst *switchInst,
  245. BasicBlock *endSwitch) override;
  246. void MarkReturnStmt(CodeGenFunction &CGF, BasicBlock *bbWithRet) override;
  247. void MarkLoopStmt(CodeGenFunction &CGF, BasicBlock *loopContinue,
  248. BasicBlock *loopExit) override;
  249. void MarkScopeEnd(CodeGenFunction &CGF) override;
  250. /// Get or add constant to the program
  251. HLCBuffer &GetOrCreateCBuffer(HLSLBufferDecl *D);
  252. };
  253. }
  254. //------------------------------------------------------------------------------
  255. //
  256. // CGMSHLSLRuntime methods.
  257. //
  258. CGMSHLSLRuntime::CGMSHLSLRuntime(CodeGenModule &CGM)
  259. : CGHLSLRuntime(CGM), Context(CGM.getLLVMContext()),
  260. TheModule(CGM.getModule()),
  261. CBufferType(
  262. llvm::StructType::create(TheModule.getContext(), "ConstantBuffer")),
  263. dataLayout(CGM.getLangOpts().UseMinPrecision
  264. ? hlsl::DXIL::kLegacyLayoutString
  265. : hlsl::DXIL::kNewLayoutString), Entry() {
  266. const hlsl::ShaderModel *SM =
  267. hlsl::ShaderModel::GetByName(CGM.getCodeGenOpts().HLSLProfile.c_str());
  268. // Only accept valid, 6.0 shader model.
  269. if (!SM->IsValid() || SM->GetMajor() != 6) {
  270. DiagnosticsEngine &Diags = CGM.getDiags();
  271. unsigned DiagID =
  272. Diags.getCustomDiagID(DiagnosticsEngine::Error, "invalid profile %0");
  273. Diags.Report(DiagID) << CGM.getCodeGenOpts().HLSLProfile;
  274. return;
  275. }
  276. if (CGM.getCodeGenOpts().HLSLValidatorMajorVer != 0) {
  277. // Check validator version against minimum for target profile:
  278. unsigned MinMajor, MinMinor;
  279. SM->GetMinValidatorVersion(MinMajor, MinMinor);
  280. if (DXIL::CompareVersions(CGM.getCodeGenOpts().HLSLValidatorMajorVer,
  281. CGM.getCodeGenOpts().HLSLValidatorMinorVer,
  282. MinMajor, MinMinor) < 0) {
  283. DiagnosticsEngine &Diags = CGM.getDiags();
  284. unsigned DiagID =
  285. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  286. "validator version %0,%1 does not support target profile.");
  287. Diags.Report(DiagID) << CGM.getCodeGenOpts().HLSLValidatorMajorVer
  288. << CGM.getCodeGenOpts().HLSLValidatorMinorVer;
  289. return;
  290. }
  291. }
  292. m_bIsLib = SM->IsLib();
  293. // TODO: add AllResourceBound.
  294. if (CGM.getCodeGenOpts().HLSLAvoidControlFlow && !CGM.getCodeGenOpts().HLSLAllResourcesBound) {
  295. if (SM->IsSM51Plus()) {
  296. DiagnosticsEngine &Diags = CGM.getDiags();
  297. unsigned DiagID =
  298. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  299. "Gfa option cannot be used in SM_5_1+ unless "
  300. "all_resources_bound flag is specified");
  301. Diags.Report(DiagID);
  302. }
  303. }
  304. // Create HLModule.
  305. const bool skipInit = true;
  306. m_pHLModule = &TheModule.GetOrCreateHLModule(skipInit);
  307. // Precise Output.
  308. for (auto &preciseOutput : CGM.getCodeGenOpts().HLSLPreciseOutputs) {
  309. m_PreciseOutputSet.insert(StringRef(preciseOutput).lower());
  310. }
  311. // Set Option.
  312. HLOptions opts;
  313. opts.bIEEEStrict = CGM.getCodeGenOpts().UnsafeFPMath;
  314. opts.bDefaultRowMajor = CGM.getCodeGenOpts().HLSLDefaultRowMajor;
  315. opts.bDisableOptimizations = CGM.getCodeGenOpts().DisableLLVMOpts;
  316. opts.bLegacyCBufferLoad = !CGM.getCodeGenOpts().HLSLNotUseLegacyCBufLoad;
  317. opts.bAllResourcesBound = CGM.getCodeGenOpts().HLSLAllResourcesBound;
  318. opts.PackingStrategy = CGM.getCodeGenOpts().HLSLSignaturePackingStrategy;
  319. opts.bLegacyResourceReservation = CGM.getCodeGenOpts().HLSLLegacyResourceReservation;
  320. opts.bUseMinPrecision = CGM.getLangOpts().UseMinPrecision;
  321. opts.bDX9CompatMode = CGM.getLangOpts().EnableDX9CompatMode;
  322. opts.bFXCCompatMode = CGM.getLangOpts().EnableFXCCompatMode;
  323. m_pHLModule->SetHLOptions(opts);
  324. m_pHLModule->GetOP()->SetMinPrecision(opts.bUseMinPrecision);
  325. m_pHLModule->GetTypeSystem().SetMinPrecision(opts.bUseMinPrecision);
  326. m_pHLModule->SetAutoBindingSpace(CGM.getCodeGenOpts().HLSLDefaultSpace);
  327. m_pHLModule->SetValidatorVersion(CGM.getCodeGenOpts().HLSLValidatorMajorVer, CGM.getCodeGenOpts().HLSLValidatorMinorVer);
  328. m_bDebugInfo = CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::FullDebugInfo;
  329. // set profile
  330. m_pHLModule->SetShaderModel(SM);
  331. // set entry name
  332. if (!SM->IsLib())
  333. m_pHLModule->SetEntryFunctionName(CGM.getCodeGenOpts().HLSLEntryFunction);
  334. // set root signature version.
  335. if (CGM.getLangOpts().RootSigMinor == 0) {
  336. rootSigVer = hlsl::DxilRootSignatureVersion::Version_1_0;
  337. }
  338. else {
  339. DXASSERT(CGM.getLangOpts().RootSigMinor == 1,
  340. "else CGMSHLSLRuntime Constructor needs to be updated");
  341. rootSigVer = hlsl::DxilRootSignatureVersion::Version_1_1;
  342. }
  343. DXASSERT(CGM.getLangOpts().RootSigMajor == 1,
  344. "else CGMSHLSLRuntime Constructor needs to be updated");
  345. // add globalCB
  346. unique_ptr<HLCBuffer> CB = llvm::make_unique<HLCBuffer>();
  347. std::string globalCBName = "$Globals";
  348. CB->SetGlobalSymbol(nullptr);
  349. CB->SetGlobalName(globalCBName);
  350. globalCBIndex = m_pHLModule->GetCBuffers().size();
  351. CB->SetID(globalCBIndex);
  352. CB->SetRangeSize(1);
  353. CB->SetLowerBound(UINT_MAX);
  354. DXVERIFY_NOMSG(globalCBIndex == m_pHLModule->AddCBuffer(std::move(CB)));
  355. // set Float Denorm Mode
  356. m_pHLModule->SetFloat32DenormMode(CGM.getCodeGenOpts().HLSLFloat32DenormMode);
  357. // set DefaultLinkage
  358. m_pHLModule->SetDefaultLinkage(CGM.getCodeGenOpts().DefaultLinkage);
  359. // Fill in m_ExportMap, which maps from internal name to zero or more renames
  360. m_ExportMap.clear();
  361. std::string errors;
  362. llvm::raw_string_ostream os(errors);
  363. if (!m_ExportMap.ParseExports(CGM.getCodeGenOpts().HLSLLibraryExports, os)) {
  364. DiagnosticsEngine &Diags = CGM.getDiags();
  365. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "Error parsing -exports options: %0");
  366. Diags.Report(DiagID) << os.str();
  367. }
  368. }
  369. void CGMSHLSLRuntime::AddHLSLIntrinsicOpcodeToFunction(Function *F,
  370. unsigned opcode) {
  371. m_IntrinsicMap.emplace_back(F,opcode);
  372. }
  373. void CGMSHLSLRuntime::CheckParameterAnnotation(
  374. SourceLocation SLoc, const DxilParameterAnnotation &paramInfo,
  375. bool isPatchConstantFunction) {
  376. if (!paramInfo.HasSemanticString()) {
  377. return;
  378. }
  379. llvm::StringRef semFullName = paramInfo.GetSemanticStringRef();
  380. DxilParamInputQual paramQual = paramInfo.GetParamInputQual();
  381. if (paramQual == DxilParamInputQual::Inout) {
  382. CheckParameterAnnotation(SLoc, DxilParamInputQual::In, semFullName, isPatchConstantFunction);
  383. CheckParameterAnnotation(SLoc, DxilParamInputQual::Out, semFullName, isPatchConstantFunction);
  384. return;
  385. }
  386. CheckParameterAnnotation(SLoc, paramQual, semFullName, isPatchConstantFunction);
  387. }
  388. void CGMSHLSLRuntime::CheckParameterAnnotation(
  389. SourceLocation SLoc, DxilParamInputQual paramQual, llvm::StringRef semFullName,
  390. bool isPatchConstantFunction) {
  391. const ShaderModel *SM = m_pHLModule->GetShaderModel();
  392. DXIL::SigPointKind sigPoint = SigPointFromInputQual(
  393. paramQual, SM->GetKind(), isPatchConstantFunction);
  394. llvm::StringRef semName;
  395. unsigned semIndex;
  396. Semantic::DecomposeNameAndIndex(semFullName, &semName, &semIndex);
  397. const Semantic *pSemantic =
  398. Semantic::GetByName(semName, sigPoint, SM->GetMajor(), SM->GetMinor());
  399. if (pSemantic->IsInvalid()) {
  400. DiagnosticsEngine &Diags = CGM.getDiags();
  401. unsigned DiagID =
  402. Diags.getCustomDiagID(DiagnosticsEngine::Error, "invalid semantic '%0' for %1 %2.%3");
  403. Diags.Report(SLoc, DiagID) << semName << SM->GetKindName() << SM->GetMajor() << SM->GetMinor();
  404. }
  405. }
  406. SourceLocation
  407. CGMSHLSLRuntime::SetSemantic(const NamedDecl *decl,
  408. DxilParameterAnnotation &paramInfo) {
  409. for (const hlsl::UnusualAnnotation *it : decl->getUnusualAnnotations()) {
  410. if (it->getKind() == hlsl::UnusualAnnotation::UA_SemanticDecl) {
  411. const hlsl::SemanticDecl *sd = cast<hlsl::SemanticDecl>(it);
  412. paramInfo.SetSemanticString(sd->SemanticName);
  413. if (m_PreciseOutputSet.count(StringRef(sd->SemanticName).lower()))
  414. paramInfo.SetPrecise();
  415. return it->Loc;
  416. }
  417. }
  418. return SourceLocation();
  419. }
  420. static DXIL::TessellatorDomain StringToDomain(StringRef domain) {
  421. if (domain == "isoline")
  422. return DXIL::TessellatorDomain::IsoLine;
  423. if (domain == "tri")
  424. return DXIL::TessellatorDomain::Tri;
  425. if (domain == "quad")
  426. return DXIL::TessellatorDomain::Quad;
  427. return DXIL::TessellatorDomain::Undefined;
  428. }
  429. static DXIL::TessellatorPartitioning StringToPartitioning(StringRef partition) {
  430. if (partition == "integer")
  431. return DXIL::TessellatorPartitioning::Integer;
  432. if (partition == "pow2")
  433. return DXIL::TessellatorPartitioning::Pow2;
  434. if (partition == "fractional_even")
  435. return DXIL::TessellatorPartitioning::FractionalEven;
  436. if (partition == "fractional_odd")
  437. return DXIL::TessellatorPartitioning::FractionalOdd;
  438. return DXIL::TessellatorPartitioning::Undefined;
  439. }
  440. static DXIL::TessellatorOutputPrimitive
  441. StringToTessOutputPrimitive(StringRef primitive) {
  442. if (primitive == "point")
  443. return DXIL::TessellatorOutputPrimitive::Point;
  444. if (primitive == "line")
  445. return DXIL::TessellatorOutputPrimitive::Line;
  446. if (primitive == "triangle_cw")
  447. return DXIL::TessellatorOutputPrimitive::TriangleCW;
  448. if (primitive == "triangle_ccw")
  449. return DXIL::TessellatorOutputPrimitive::TriangleCCW;
  450. return DXIL::TessellatorOutputPrimitive::Undefined;
  451. }
  452. static DXIL::MeshOutputTopology
  453. StringToMeshOutputTopology(StringRef topology) {
  454. if (topology == "line")
  455. return DXIL::MeshOutputTopology::Line;
  456. if (topology == "triangle")
  457. return DXIL::MeshOutputTopology::Triangle;
  458. return DXIL::MeshOutputTopology::Undefined;
  459. }
  460. static unsigned GetMatrixSizeInCB(QualType Ty, bool defaultRowMajor,
  461. bool b64Bit) {
  462. bool bRowMajor;
  463. if (!hlsl::HasHLSLMatOrientation(Ty, &bRowMajor))
  464. bRowMajor = defaultRowMajor;
  465. unsigned row, col;
  466. hlsl::GetHLSLMatRowColCount(Ty, row, col);
  467. unsigned EltSize = b64Bit ? 8 : 4;
  468. // Align to 4 * 4bytes.
  469. unsigned alignment = 4 * 4;
  470. if (bRowMajor) {
  471. unsigned rowSize = EltSize * col;
  472. // 3x64bit or 4x64bit align to 32 bytes.
  473. if (rowSize > alignment)
  474. alignment <<= 1;
  475. return alignment * (row - 1) + col * EltSize;
  476. } else {
  477. unsigned rowSize = EltSize * row;
  478. // 3x64bit or 4x64bit align to 32 bytes.
  479. if (rowSize > alignment)
  480. alignment <<= 1;
  481. return alignment * (col - 1) + row * EltSize;
  482. }
  483. }
  484. static CompType::Kind BuiltinTyToCompTy(const BuiltinType *BTy, bool bSNorm,
  485. bool bUNorm) {
  486. CompType::Kind kind = CompType::Kind::Invalid;
  487. switch (BTy->getKind()) {
  488. case BuiltinType::UInt:
  489. kind = CompType::Kind::U32;
  490. break;
  491. case BuiltinType::Min16UInt: // HLSL Change
  492. case BuiltinType::UShort:
  493. kind = CompType::Kind::U16;
  494. break;
  495. case BuiltinType::ULongLong:
  496. kind = CompType::Kind::U64;
  497. break;
  498. case BuiltinType::Int:
  499. kind = CompType::Kind::I32;
  500. break;
  501. // HLSL Changes begin
  502. case BuiltinType::Min12Int:
  503. case BuiltinType::Min16Int:
  504. // HLSL Changes end
  505. case BuiltinType::Short:
  506. kind = CompType::Kind::I16;
  507. break;
  508. case BuiltinType::LongLong:
  509. kind = CompType::Kind::I64;
  510. break;
  511. // HLSL Changes begin
  512. case BuiltinType::Min10Float:
  513. case BuiltinType::Min16Float:
  514. // HLSL Changes end
  515. case BuiltinType::Half:
  516. if (bSNorm)
  517. kind = CompType::Kind::SNormF16;
  518. else if (bUNorm)
  519. kind = CompType::Kind::UNormF16;
  520. else
  521. kind = CompType::Kind::F16;
  522. break;
  523. case BuiltinType::HalfFloat: // HLSL Change
  524. case BuiltinType::Float:
  525. if (bSNorm)
  526. kind = CompType::Kind::SNormF32;
  527. else if (bUNorm)
  528. kind = CompType::Kind::UNormF32;
  529. else
  530. kind = CompType::Kind::F32;
  531. break;
  532. case BuiltinType::Double:
  533. if (bSNorm)
  534. kind = CompType::Kind::SNormF64;
  535. else if (bUNorm)
  536. kind = CompType::Kind::UNormF64;
  537. else
  538. kind = CompType::Kind::F64;
  539. break;
  540. case BuiltinType::Bool:
  541. kind = CompType::Kind::I1;
  542. break;
  543. default:
  544. // Other types not used by HLSL.
  545. break;
  546. }
  547. return kind;
  548. }
  549. static DxilSampler::SamplerKind KeywordToSamplerKind(llvm::StringRef keyword) {
  550. // TODO: refactor for faster search (switch by 1/2/3 first letters, then
  551. // compare)
  552. return llvm::StringSwitch<DxilSampler::SamplerKind>(keyword)
  553. .Case("SamplerState", DxilSampler::SamplerKind::Default)
  554. .Case("SamplerComparisonState", DxilSampler::SamplerKind::Comparison)
  555. .Default(DxilSampler::SamplerKind::Invalid);
  556. }
  557. MDNode *CGMSHLSLRuntime::GetOrAddResTypeMD(QualType resTy, bool bCreate) {
  558. const RecordType *RT = resTy->getAs<RecordType>();
  559. if (!RT)
  560. return nullptr;
  561. RecordDecl *RD = RT->getDecl();
  562. SourceLocation loc = RD->getLocation();
  563. hlsl::DxilResourceBase::Class resClass = TypeToClass(resTy);
  564. llvm::Type *Ty = CGM.getTypes().ConvertType(resTy);
  565. auto it = resMetadataMap.find(Ty);
  566. if (!bCreate && it != resMetadataMap.end())
  567. return it->second;
  568. // Save resource type metadata.
  569. switch (resClass) {
  570. case DXIL::ResourceClass::UAV: {
  571. DxilResource UAV;
  572. // TODO: save globalcoherent to variable in EmitHLSLBuiltinCallExpr.
  573. SetUAVSRV(loc, resClass, &UAV, resTy);
  574. // Set global symbol to save type.
  575. UAV.SetGlobalSymbol(UndefValue::get(Ty->getPointerTo()));
  576. MDNode *MD = m_pHLModule->DxilUAVToMDNode(UAV);
  577. resMetadataMap[Ty] = MD;
  578. return MD;
  579. } break;
  580. case DXIL::ResourceClass::SRV: {
  581. DxilResource SRV;
  582. SetUAVSRV(loc, resClass, &SRV, resTy);
  583. // Set global symbol to save type.
  584. SRV.SetGlobalSymbol(UndefValue::get(Ty->getPointerTo()));
  585. MDNode *MD = m_pHLModule->DxilSRVToMDNode(SRV);
  586. resMetadataMap[Ty] = MD;
  587. return MD;
  588. } break;
  589. case DXIL::ResourceClass::Sampler: {
  590. DxilSampler S;
  591. DxilSampler::SamplerKind kind = KeywordToSamplerKind(RD->getName());
  592. S.SetSamplerKind(kind);
  593. // Set global symbol to save type.
  594. S.SetGlobalSymbol(UndefValue::get(Ty->getPointerTo()));
  595. MDNode *MD = m_pHLModule->DxilSamplerToMDNode(S);
  596. resMetadataMap[Ty] = MD;
  597. return MD;
  598. }
  599. default:
  600. // Skip OutputStream for GS.
  601. return nullptr;
  602. }
  603. }
  604. namespace {
  605. MatrixOrientation GetMatrixMajor(QualType Ty, bool bDefaultRowMajor) {
  606. DXASSERT_NOMSG(hlsl::IsHLSLMatType(Ty));
  607. bool bIsRowMajor = bDefaultRowMajor;
  608. HasHLSLMatOrientation(Ty, &bIsRowMajor);
  609. return bIsRowMajor ? MatrixOrientation::RowMajor
  610. : MatrixOrientation::ColumnMajor;
  611. }
  612. QualType GetArrayEltType(ASTContext &Context, QualType Ty) {
  613. while (const clang::ArrayType *ArrayTy = Context.getAsArrayType(Ty))
  614. Ty = ArrayTy->getElementType();
  615. return Ty;
  616. }
  617. } // namespace
  618. DxilResourceProperties CGMSHLSLRuntime::BuildResourceProperty(QualType resTy) {
  619. resTy = GetArrayEltType(CGM.getContext(), resTy);
  620. const RecordType *RT = resTy->getAs<RecordType>();
  621. DxilResourceProperties RP;
  622. if (!RT) {
  623. RP.Class = DXIL::ResourceClass::Invalid;
  624. return RP;
  625. }
  626. RecordDecl *RD = RT->getDecl();
  627. SourceLocation loc = RD->getLocation();
  628. hlsl::DxilResourceBase::Class resClass = TypeToClass(resTy);
  629. RP.Class = resClass;
  630. if (resClass == DXIL::ResourceClass::Invalid)
  631. return RP;
  632. llvm::Type *Ty = CGM.getTypes().ConvertType(resTy);
  633. switch (resClass) {
  634. case DXIL::ResourceClass::UAV: {
  635. DxilResource UAV;
  636. // TODO: save globalcoherent to variable in EmitHLSLBuiltinCallExpr.
  637. SetUAVSRV(loc, resClass, &UAV, resTy);
  638. UAV.SetGlobalSymbol(UndefValue::get(Ty->getPointerTo()));
  639. RP = resource_helper::loadFromResourceBase(&UAV);
  640. } break;
  641. case DXIL::ResourceClass::SRV: {
  642. DxilResource SRV;
  643. SetUAVSRV(loc, resClass, &SRV, resTy);
  644. SRV.SetGlobalSymbol(UndefValue::get(Ty->getPointerTo()));
  645. RP = resource_helper::loadFromResourceBase(&SRV);
  646. } break;
  647. case DXIL::ResourceClass::Sampler: {
  648. DxilSampler::SamplerKind kind = KeywordToSamplerKind(RD->getName());
  649. DxilSampler Sampler;
  650. Sampler.SetSamplerKind(kind);
  651. RP = resource_helper::loadFromResourceBase(&Sampler);
  652. }
  653. default:
  654. break;
  655. }
  656. return RP;
  657. }
  658. void CGMSHLSLRuntime::ConstructFieldAttributedAnnotation(
  659. DxilFieldAnnotation &fieldAnnotation, QualType fieldTy,
  660. bool bDefaultRowMajor) {
  661. QualType Ty = fieldTy;
  662. if (Ty->isReferenceType())
  663. Ty = Ty.getNonReferenceType();
  664. // Get element type.
  665. Ty = GetArrayEltType(CGM.getContext(), Ty);
  666. QualType EltTy = Ty;
  667. if (hlsl::IsHLSLMatType(Ty)) {
  668. DxilMatrixAnnotation Matrix;
  669. Matrix.Orientation = GetMatrixMajor(Ty, bDefaultRowMajor);
  670. hlsl::GetHLSLMatRowColCount(Ty, Matrix.Rows, Matrix.Cols);
  671. fieldAnnotation.SetMatrixAnnotation(Matrix);
  672. EltTy = hlsl::GetHLSLMatElementType(Ty);
  673. }
  674. if (hlsl::IsHLSLVecType(Ty))
  675. EltTy = hlsl::GetHLSLVecElementType(Ty);
  676. if (IsHLSLResourceType(Ty)) {
  677. // Always create for llvm::Type could be same for different QualType.
  678. // TODO: change to DxilProperties.
  679. MDNode *MD = GetOrAddResTypeMD(Ty, /*bCreate*/ true);
  680. fieldAnnotation.SetResourceAttribute(MD);
  681. }
  682. bool bSNorm = false;
  683. bool bUNorm = false;
  684. if (HasHLSLUNormSNorm(Ty, &bSNorm) && !bSNorm)
  685. bUNorm = true;
  686. if (EltTy->isBuiltinType()) {
  687. const BuiltinType *BTy = EltTy->getAs<BuiltinType>();
  688. CompType::Kind kind = BuiltinTyToCompTy(BTy, bSNorm, bUNorm);
  689. fieldAnnotation.SetCompType(kind);
  690. } else if (EltTy->isEnumeralType()) {
  691. const EnumType *ETy = EltTy->getAs<EnumType>();
  692. QualType type = ETy->getDecl()->getIntegerType();
  693. if (const BuiltinType *BTy =
  694. dyn_cast<BuiltinType>(type->getCanonicalTypeInternal()))
  695. fieldAnnotation.SetCompType(BuiltinTyToCompTy(BTy, bSNorm, bUNorm));
  696. } else {
  697. DXASSERT(!bSNorm && !bUNorm,
  698. "snorm/unorm on invalid type, validate at handleHLSLTypeAttr");
  699. }
  700. }
  701. static void ConstructFieldInterpolation(DxilFieldAnnotation &fieldAnnotation,
  702. FieldDecl *fieldDecl) {
  703. // Keep undefined for interpMode here.
  704. InterpolationMode InterpMode = {fieldDecl->hasAttr<HLSLNoInterpolationAttr>(),
  705. fieldDecl->hasAttr<HLSLLinearAttr>(),
  706. fieldDecl->hasAttr<HLSLNoPerspectiveAttr>(),
  707. fieldDecl->hasAttr<HLSLCentroidAttr>(),
  708. fieldDecl->hasAttr<HLSLSampleAttr>()};
  709. if (InterpMode.GetKind() != InterpolationMode::Kind::Undefined)
  710. fieldAnnotation.SetInterpolationMode(InterpMode);
  711. }
  712. static unsigned AlignBaseOffset(unsigned baseOffset, unsigned size, QualType Ty,
  713. bool bDefaultRowMajor) {
  714. bool needNewAlign = Ty->isArrayType();
  715. if (IsHLSLMatType(Ty)) {
  716. bool bRowMajor = false;
  717. if (!hlsl::HasHLSLMatOrientation(Ty, &bRowMajor))
  718. bRowMajor = bDefaultRowMajor;
  719. unsigned row, col;
  720. hlsl::GetHLSLMatRowColCount(Ty, row, col);
  721. needNewAlign |= !bRowMajor && col > 1;
  722. needNewAlign |= bRowMajor && row > 1;
  723. } else if (Ty->isStructureOrClassType() && !hlsl::IsHLSLVecType(Ty)) {
  724. needNewAlign = true;
  725. }
  726. unsigned scalarSizeInBytes = 4;
  727. const clang::BuiltinType *BT = Ty->getAs<clang::BuiltinType>();
  728. if (hlsl::IsHLSLVecMatType(Ty)) {
  729. BT = hlsl::GetElementTypeOrType(Ty)->getAs<clang::BuiltinType>();
  730. }
  731. if (BT) {
  732. if (BT->getKind() == clang::BuiltinType::Kind::Double ||
  733. BT->getKind() == clang::BuiltinType::Kind::LongLong)
  734. scalarSizeInBytes = 8;
  735. else if (BT->getKind() == clang::BuiltinType::Kind::Half ||
  736. BT->getKind() == clang::BuiltinType::Kind::Short ||
  737. BT->getKind() == clang::BuiltinType::Kind::UShort)
  738. scalarSizeInBytes = 2;
  739. }
  740. return AlignBufferOffsetInLegacy(baseOffset, size, scalarSizeInBytes,
  741. needNewAlign);
  742. }
  743. static unsigned AlignBaseOffset(QualType Ty, unsigned baseOffset,
  744. bool bDefaultRowMajor,
  745. CodeGen::CodeGenModule &CGM,
  746. llvm::DataLayout &layout) {
  747. QualType paramTy = Ty.getCanonicalType();
  748. if (const ReferenceType *RefType = dyn_cast<ReferenceType>(paramTy))
  749. paramTy = RefType->getPointeeType();
  750. // Get size.
  751. llvm::Type *Type = CGM.getTypes().ConvertType(paramTy);
  752. unsigned size = layout.getTypeAllocSize(Type);
  753. return AlignBaseOffset(baseOffset, size, paramTy, bDefaultRowMajor);
  754. }
  755. unsigned CGMSHLSLRuntime::ConstructStructAnnotation(DxilStructAnnotation *annotation,
  756. const RecordDecl *RD,
  757. DxilTypeSystem &dxilTypeSys) {
  758. unsigned fieldIdx = 0;
  759. unsigned offset = 0;
  760. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  761. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  762. // If template, save template args
  763. if (const ClassTemplateSpecializationDecl *templateSpecializationDecl =
  764. dyn_cast<ClassTemplateSpecializationDecl>(CXXRD)) {
  765. const clang::TemplateArgumentList &args = templateSpecializationDecl->getTemplateInstantiationArgs();
  766. for (unsigned i = 0; i < args.size(); ++i) {
  767. DxilTemplateArgAnnotation &argAnnotation = annotation->GetTemplateArgAnnotation(i);
  768. const clang::TemplateArgument &arg = args[i];
  769. switch (arg.getKind()) {
  770. case clang::TemplateArgument::ArgKind::Type:
  771. argAnnotation.SetType(CGM.getTypes().ConvertType(arg.getAsType()));
  772. break;
  773. case clang::TemplateArgument::ArgKind::Integral:
  774. argAnnotation.SetIntegral(arg.getAsIntegral().getExtValue());
  775. break;
  776. default:
  777. break;
  778. }
  779. }
  780. }
  781. if (CXXRD->getNumBases()) {
  782. // Add base as field.
  783. for (const auto &I : CXXRD->bases()) {
  784. const CXXRecordDecl *BaseDecl =
  785. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  786. std::string fieldSemName = "";
  787. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  788. // Align offset.
  789. offset = AlignBaseOffset(parentTy, offset, bDefaultRowMajor, CGM,
  790. dataLayout);
  791. unsigned CBufferOffset = offset;
  792. unsigned arrayEltSize = 0;
  793. // Process field to make sure the size of field is ready.
  794. unsigned size =
  795. AddTypeAnnotation(parentTy, dxilTypeSys, arrayEltSize);
  796. // Update offset.
  797. offset += size;
  798. if (size > 0) {
  799. DxilFieldAnnotation &fieldAnnotation =
  800. annotation->GetFieldAnnotation(fieldIdx++);
  801. fieldAnnotation.SetCBufferOffset(CBufferOffset);
  802. fieldAnnotation.SetFieldName(BaseDecl->getNameAsString());
  803. }
  804. }
  805. }
  806. }
  807. for (auto fieldDecl : RD->fields()) {
  808. std::string fieldSemName = "";
  809. QualType fieldTy = fieldDecl->getType();
  810. DXASSERT(!fieldDecl->isBitField(), "We should have already ensured we have no bitfields.");
  811. // Align offset.
  812. offset = AlignBaseOffset(fieldTy, offset, bDefaultRowMajor, CGM, dataLayout);
  813. unsigned CBufferOffset = offset;
  814. // Try to get info from fieldDecl.
  815. for (const hlsl::UnusualAnnotation *it :
  816. fieldDecl->getUnusualAnnotations()) {
  817. switch (it->getKind()) {
  818. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  819. const hlsl::SemanticDecl *sd = cast<hlsl::SemanticDecl>(it);
  820. fieldSemName = sd->SemanticName;
  821. } break;
  822. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  823. const hlsl::ConstantPacking *cp = cast<hlsl::ConstantPacking>(it);
  824. CBufferOffset = cp->Subcomponent << 2;
  825. CBufferOffset += cp->ComponentOffset;
  826. // Change to byte.
  827. CBufferOffset <<= 2;
  828. } break;
  829. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  830. // register assignment only works on global constant.
  831. DiagnosticsEngine &Diags = CGM.getDiags();
  832. unsigned DiagID = Diags.getCustomDiagID(
  833. DiagnosticsEngine::Error,
  834. "location semantics cannot be specified on members.");
  835. Diags.Report(it->Loc, DiagID);
  836. return 0;
  837. } break;
  838. default:
  839. llvm_unreachable("only semantic for input/output");
  840. break;
  841. }
  842. }
  843. unsigned arrayEltSize = 0;
  844. // Process field to make sure the size of field is ready.
  845. unsigned size = AddTypeAnnotation(fieldDecl->getType(), dxilTypeSys, arrayEltSize);
  846. // Update offset.
  847. offset += size;
  848. DxilFieldAnnotation &fieldAnnotation = annotation->GetFieldAnnotation(fieldIdx++);
  849. ConstructFieldAttributedAnnotation(fieldAnnotation, fieldTy, bDefaultRowMajor);
  850. ConstructFieldInterpolation(fieldAnnotation, fieldDecl);
  851. if (fieldDecl->hasAttr<HLSLPreciseAttr>())
  852. fieldAnnotation.SetPrecise();
  853. fieldAnnotation.SetCBufferOffset(CBufferOffset);
  854. fieldAnnotation.SetFieldName(fieldDecl->getName());
  855. if (!fieldSemName.empty()) {
  856. fieldAnnotation.SetSemanticString(fieldSemName);
  857. if (m_PreciseOutputSet.count(StringRef(fieldSemName).lower()))
  858. fieldAnnotation.SetPrecise();
  859. }
  860. }
  861. annotation->SetCBufferSize(offset);
  862. if (offset == 0) {
  863. annotation->MarkEmptyStruct();
  864. }
  865. return offset;
  866. }
  867. static bool IsElementInputOutputType(QualType Ty) {
  868. return Ty->isBuiltinType() || hlsl::IsHLSLVecMatType(Ty) || Ty->isEnumeralType();
  869. }
  870. static unsigned GetNumTemplateArgsForRecordDecl(const RecordDecl *RD) {
  871. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  872. if (const ClassTemplateSpecializationDecl *templateSpecializationDecl =
  873. dyn_cast<ClassTemplateSpecializationDecl>(CXXRD)) {
  874. const clang::TemplateArgumentList &args = templateSpecializationDecl->getTemplateInstantiationArgs();
  875. return args.size();
  876. }
  877. }
  878. return 0;
  879. }
  880. // Return the size for constant buffer of each decl.
  881. unsigned CGMSHLSLRuntime::AddTypeAnnotation(QualType Ty,
  882. DxilTypeSystem &dxilTypeSys,
  883. unsigned &arrayEltSize) {
  884. QualType paramTy = Ty.getCanonicalType();
  885. if (const ReferenceType *RefType = dyn_cast<ReferenceType>(paramTy))
  886. paramTy = RefType->getPointeeType();
  887. // Get size.
  888. llvm::Type *Type = CGM.getTypes().ConvertType(paramTy);
  889. unsigned size = dataLayout.getTypeAllocSize(Type);
  890. if (IsHLSLMatType(Ty)) {
  891. llvm::Type *EltTy = HLMatrixType::cast(Type).getElementTypeForReg();
  892. bool b64Bit = dataLayout.getTypeAllocSize(EltTy) == 8;
  893. size = GetMatrixSizeInCB(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor,
  894. b64Bit);
  895. }
  896. // Skip element types.
  897. if (IsElementInputOutputType(paramTy))
  898. return size;
  899. else if (IsHLSLStreamOutputType(Ty)) {
  900. return AddTypeAnnotation(GetHLSLOutputPatchElementType(Ty), dxilTypeSys,
  901. arrayEltSize);
  902. } else if (IsHLSLInputPatchType(Ty))
  903. return AddTypeAnnotation(GetHLSLInputPatchElementType(Ty), dxilTypeSys,
  904. arrayEltSize);
  905. else if (IsHLSLOutputPatchType(Ty))
  906. return AddTypeAnnotation(GetHLSLOutputPatchElementType(Ty), dxilTypeSys,
  907. arrayEltSize);
  908. else if (const RecordType *RT = paramTy->getAsStructureType()) {
  909. RecordDecl *RD = RT->getDecl();
  910. llvm::StructType *ST = CGM.getTypes().ConvertRecordDeclType(RD);
  911. // Skip if already created.
  912. if (DxilStructAnnotation *annotation = dxilTypeSys.GetStructAnnotation(ST)) {
  913. unsigned structSize = annotation->GetCBufferSize();
  914. return structSize;
  915. }
  916. DxilStructAnnotation *annotation = dxilTypeSys.AddStructAnnotation(ST,
  917. GetNumTemplateArgsForRecordDecl(RT->getDecl()));
  918. return ConstructStructAnnotation(annotation, RD, dxilTypeSys);
  919. } else if (const RecordType *RT = dyn_cast<RecordType>(paramTy)) {
  920. // For this pointer.
  921. RecordDecl *RD = RT->getDecl();
  922. llvm::StructType *ST = CGM.getTypes().ConvertRecordDeclType(RD);
  923. // Skip if already created.
  924. if (DxilStructAnnotation *annotation = dxilTypeSys.GetStructAnnotation(ST)) {
  925. unsigned structSize = annotation->GetCBufferSize();
  926. return structSize;
  927. }
  928. DxilStructAnnotation *annotation = dxilTypeSys.AddStructAnnotation(ST,
  929. GetNumTemplateArgsForRecordDecl(RT->getDecl()));
  930. return ConstructStructAnnotation(annotation, RD, dxilTypeSys);
  931. } else if (IsHLSLResourceType(Ty)) {
  932. // Save result type info.
  933. AddTypeAnnotation(GetHLSLResourceResultType(Ty), dxilTypeSys, arrayEltSize);
  934. // Resource don't count for cbuffer size.
  935. return 0;
  936. } else if (IsStringType(Ty)) {
  937. // string won't be included in cbuffer
  938. return 0;
  939. } else {
  940. unsigned arraySize = 0;
  941. QualType arrayElementTy = Ty;
  942. if (Ty->isConstantArrayType()) {
  943. const ConstantArrayType *arrayTy =
  944. CGM.getContext().getAsConstantArrayType(Ty);
  945. DXASSERT(arrayTy != nullptr, "Must array type here");
  946. arraySize = arrayTy->getSize().getLimitedValue();
  947. arrayElementTy = arrayTy->getElementType();
  948. }
  949. else if (Ty->isIncompleteArrayType()) {
  950. const IncompleteArrayType *arrayTy = CGM.getContext().getAsIncompleteArrayType(Ty);
  951. arrayElementTy = arrayTy->getElementType();
  952. } else {
  953. DXASSERT(0, "Must array type here");
  954. }
  955. unsigned elementSize = AddTypeAnnotation(arrayElementTy, dxilTypeSys, arrayEltSize);
  956. // Only set arrayEltSize once.
  957. if (arrayEltSize == 0)
  958. arrayEltSize = elementSize;
  959. // Align to 4 * 4bytes.
  960. unsigned alignedSize = (elementSize + 15) & 0xfffffff0;
  961. return alignedSize * (arraySize - 1) + elementSize;
  962. }
  963. }
  964. static DxilResource::Kind KeywordToKind(StringRef keyword) {
  965. // TODO: refactor for faster search (switch by 1/2/3 first letters, then
  966. // compare)
  967. if (keyword == "Texture1D" || keyword == "RWTexture1D" || keyword == "RasterizerOrderedTexture1D")
  968. return DxilResource::Kind::Texture1D;
  969. if (keyword == "Texture2D" || keyword == "RWTexture2D" || keyword == "RasterizerOrderedTexture2D")
  970. return DxilResource::Kind::Texture2D;
  971. if (keyword == "Texture2DMS" || keyword == "RWTexture2DMS")
  972. return DxilResource::Kind::Texture2DMS;
  973. if (keyword == "FeedbackTexture2D")
  974. return DxilResource::Kind::FeedbackTexture2D;
  975. if (keyword == "Texture3D" || keyword == "RWTexture3D" || keyword == "RasterizerOrderedTexture3D")
  976. return DxilResource::Kind::Texture3D;
  977. if (keyword == "TextureCube" || keyword == "RWTextureCube")
  978. return DxilResource::Kind::TextureCube;
  979. if (keyword == "Texture1DArray" || keyword == "RWTexture1DArray" || keyword == "RasterizerOrderedTexture1DArray")
  980. return DxilResource::Kind::Texture1DArray;
  981. if (keyword == "Texture2DArray" || keyword == "RWTexture2DArray" || keyword == "RasterizerOrderedTexture2DArray")
  982. return DxilResource::Kind::Texture2DArray;
  983. if (keyword == "FeedbackTexture2DArray")
  984. return DxilResource::Kind::FeedbackTexture2DArray;
  985. if (keyword == "Texture2DMSArray" || keyword == "RWTexture2DMSArray")
  986. return DxilResource::Kind::Texture2DMSArray;
  987. if (keyword == "TextureCubeArray" || keyword == "RWTextureCubeArray")
  988. return DxilResource::Kind::TextureCubeArray;
  989. if (keyword == "ByteAddressBuffer" || keyword == "RWByteAddressBuffer" || keyword == "RasterizerOrderedByteAddressBuffer")
  990. return DxilResource::Kind::RawBuffer;
  991. if (keyword == "StructuredBuffer" || keyword == "RWStructuredBuffer" || keyword == "RasterizerOrderedStructuredBuffer")
  992. return DxilResource::Kind::StructuredBuffer;
  993. if (keyword == "AppendStructuredBuffer" || keyword == "ConsumeStructuredBuffer")
  994. return DxilResource::Kind::StructuredBuffer;
  995. // TODO: this is not efficient.
  996. bool isBuffer = keyword == "Buffer";
  997. isBuffer |= keyword == "RWBuffer";
  998. isBuffer |= keyword == "RasterizerOrderedBuffer";
  999. if (isBuffer)
  1000. return DxilResource::Kind::TypedBuffer;
  1001. if (keyword == "RaytracingAccelerationStructure")
  1002. return DxilResource::Kind::RTAccelerationStructure;
  1003. return DxilResource::Kind::Invalid;
  1004. }
  1005. void CGMSHLSLRuntime::AddHLSLFunctionInfo(Function *F, const FunctionDecl *FD) {
  1006. // Add hlsl intrinsic attr
  1007. unsigned intrinsicOpcode;
  1008. StringRef intrinsicGroup;
  1009. if (hlsl::GetIntrinsicOp(FD, intrinsicOpcode, intrinsicGroup)) {
  1010. AddHLSLIntrinsicOpcodeToFunction(F, intrinsicOpcode);
  1011. F->addFnAttr(hlsl::HLPrefix, intrinsicGroup);
  1012. StringRef lower;
  1013. if (hlsl::GetIntrinsicLowering(FD, lower))
  1014. hlsl::SetHLLowerStrategy(F, lower);
  1015. if (FD->hasAttr<HLSLWaveSensitiveAttr>())
  1016. hlsl::SetHLWaveSensitive(F);
  1017. // Don't need to add FunctionQual for intrinsic function.
  1018. return;
  1019. }
  1020. if (m_pHLModule->GetFloat32DenormMode() == DXIL::Float32DenormMode::FTZ) {
  1021. F->addFnAttr(DXIL::kFP32DenormKindString, DXIL::kFP32DenormValueFtzString);
  1022. }
  1023. else if (m_pHLModule->GetFloat32DenormMode() == DXIL::Float32DenormMode::Preserve) {
  1024. F->addFnAttr(DXIL::kFP32DenormKindString, DXIL::kFP32DenormValuePreserveString);
  1025. }
  1026. else if (m_pHLModule->GetFloat32DenormMode() == DXIL::Float32DenormMode::Any) {
  1027. F->addFnAttr(DXIL::kFP32DenormKindString, DXIL::kFP32DenormValueAnyString);
  1028. }
  1029. // Set entry function
  1030. const std::string &entryName = m_pHLModule->GetEntryFunctionName();
  1031. bool isEntry = FD->getNameAsString() == entryName;
  1032. if (isEntry) {
  1033. Entry.Func = F;
  1034. Entry.SL = FD->getLocation();
  1035. }
  1036. DiagnosticsEngine &Diags = CGM.getDiags();
  1037. std::unique_ptr<DxilFunctionProps> funcProps =
  1038. llvm::make_unique<DxilFunctionProps>();
  1039. funcProps->shaderKind = DXIL::ShaderKind::Invalid;
  1040. bool isCS = false;
  1041. bool isGS = false;
  1042. bool isHS = false;
  1043. bool isDS = false;
  1044. bool isVS = false;
  1045. bool isPS = false;
  1046. bool isRay = false;
  1047. bool isMS = false;
  1048. bool isAS = false;
  1049. if (const HLSLShaderAttr *Attr = FD->getAttr<HLSLShaderAttr>()) {
  1050. // Stage is already validate in HandleDeclAttributeForHLSL.
  1051. // Here just check first letter (or two).
  1052. switch (Attr->getStage()[0]) {
  1053. case 'c':
  1054. switch (Attr->getStage()[1]) {
  1055. case 'o':
  1056. isCS = true;
  1057. funcProps->shaderKind = DXIL::ShaderKind::Compute;
  1058. break;
  1059. case 'l':
  1060. isRay = true;
  1061. funcProps->shaderKind = DXIL::ShaderKind::ClosestHit;
  1062. break;
  1063. case 'a':
  1064. isRay = true;
  1065. funcProps->shaderKind = DXIL::ShaderKind::Callable;
  1066. break;
  1067. default:
  1068. break;
  1069. }
  1070. break;
  1071. case 'v':
  1072. isVS = true;
  1073. funcProps->shaderKind = DXIL::ShaderKind::Vertex;
  1074. break;
  1075. case 'h':
  1076. isHS = true;
  1077. funcProps->shaderKind = DXIL::ShaderKind::Hull;
  1078. break;
  1079. case 'd':
  1080. isDS = true;
  1081. funcProps->shaderKind = DXIL::ShaderKind::Domain;
  1082. break;
  1083. case 'g':
  1084. isGS = true;
  1085. funcProps->shaderKind = DXIL::ShaderKind::Geometry;
  1086. break;
  1087. case 'p':
  1088. isPS = true;
  1089. funcProps->shaderKind = DXIL::ShaderKind::Pixel;
  1090. break;
  1091. case 'r':
  1092. isRay = true;
  1093. funcProps->shaderKind = DXIL::ShaderKind::RayGeneration;
  1094. break;
  1095. case 'i':
  1096. isRay = true;
  1097. funcProps->shaderKind = DXIL::ShaderKind::Intersection;
  1098. break;
  1099. case 'a':
  1100. switch (Attr->getStage()[1]) {
  1101. case 'm':
  1102. isAS = true;
  1103. funcProps->shaderKind = DXIL::ShaderKind::Amplification;
  1104. break;
  1105. case 'n':
  1106. isRay = true;
  1107. funcProps->shaderKind = DXIL::ShaderKind::AnyHit;
  1108. break;
  1109. default:
  1110. break;
  1111. }
  1112. break;
  1113. case 'm':
  1114. switch (Attr->getStage()[1]) {
  1115. case 'e':
  1116. isMS = true;
  1117. funcProps->shaderKind = DXIL::ShaderKind::Mesh;
  1118. break;
  1119. case 'i':
  1120. isRay = true;
  1121. funcProps->shaderKind = DXIL::ShaderKind::Miss;
  1122. break;
  1123. default:
  1124. break;
  1125. }
  1126. break;
  1127. default:
  1128. break;
  1129. }
  1130. if (funcProps->shaderKind == DXIL::ShaderKind::Invalid) {
  1131. unsigned DiagID = Diags.getCustomDiagID(
  1132. DiagnosticsEngine::Error, "Invalid profile for shader attribute");
  1133. Diags.Report(Attr->getLocation(), DiagID);
  1134. }
  1135. if (isEntry && isRay) {
  1136. unsigned DiagID = Diags.getCustomDiagID(
  1137. DiagnosticsEngine::Error, "Ray function cannot be used as a global entry point");
  1138. Diags.Report(Attr->getLocation(), DiagID);
  1139. }
  1140. }
  1141. // Save patch constant function to patchConstantFunctionMap.
  1142. bool isPatchConstantFunction = false;
  1143. if (!isEntry && CGM.getContext().IsPatchConstantFunctionDecl(FD)) {
  1144. isPatchConstantFunction = true;
  1145. auto &PCI = patchConstantFunctionMap[FD->getName()];
  1146. PCI.SL = FD->getLocation();
  1147. PCI.Func = F;
  1148. ++PCI.NumOverloads;
  1149. for (ParmVarDecl *parmDecl : FD->parameters()) {
  1150. QualType Ty = parmDecl->getType();
  1151. if (IsHLSLOutputPatchType(Ty)) {
  1152. funcProps->ShaderProps.HS.outputControlPoints =
  1153. GetHLSLOutputPatchCount(parmDecl->getType());
  1154. } else if (IsHLSLInputPatchType(Ty)) {
  1155. funcProps->ShaderProps.HS.inputControlPoints =
  1156. GetHLSLInputPatchCount(parmDecl->getType());
  1157. }
  1158. }
  1159. // Mark patch constant functions that cannot be linked as exports
  1160. // InternalLinkage. Patch constant functions that are actually used
  1161. // will be set back to ExternalLinkage in FinishCodeGen.
  1162. if (funcProps->ShaderProps.HS.outputControlPoints ||
  1163. funcProps->ShaderProps.HS.inputControlPoints) {
  1164. PCI.Func->setLinkage(GlobalValue::InternalLinkage);
  1165. }
  1166. funcProps->shaderKind = DXIL::ShaderKind::Hull;
  1167. }
  1168. const ShaderModel *SM = m_pHLModule->GetShaderModel();
  1169. if (isEntry) {
  1170. funcProps->shaderKind = SM->GetKind();
  1171. if (funcProps->shaderKind == DXIL::ShaderKind::Mesh) {
  1172. isMS = true;
  1173. }
  1174. else if (funcProps->shaderKind == DXIL::ShaderKind::Amplification) {
  1175. isAS = true;
  1176. }
  1177. }
  1178. // Geometry shader.
  1179. if (const HLSLMaxVertexCountAttr *Attr =
  1180. FD->getAttr<HLSLMaxVertexCountAttr>()) {
  1181. isGS = true;
  1182. funcProps->shaderKind = DXIL::ShaderKind::Geometry;
  1183. funcProps->ShaderProps.GS.maxVertexCount = Attr->getCount();
  1184. funcProps->ShaderProps.GS.inputPrimitive = DXIL::InputPrimitive::Undefined;
  1185. if (isEntry && !SM->IsGS()) {
  1186. unsigned DiagID =
  1187. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1188. "attribute maxvertexcount only valid for GS.");
  1189. Diags.Report(Attr->getLocation(), DiagID);
  1190. return;
  1191. }
  1192. }
  1193. if (const HLSLInstanceAttr *Attr = FD->getAttr<HLSLInstanceAttr>()) {
  1194. unsigned instanceCount = Attr->getCount();
  1195. funcProps->ShaderProps.GS.instanceCount = instanceCount;
  1196. if (isEntry && !SM->IsGS()) {
  1197. unsigned DiagID =
  1198. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1199. "attribute maxvertexcount only valid for GS.");
  1200. Diags.Report(Attr->getLocation(), DiagID);
  1201. return;
  1202. }
  1203. } else {
  1204. // Set default instance count.
  1205. if (isGS)
  1206. funcProps->ShaderProps.GS.instanceCount = 1;
  1207. }
  1208. // Compute shader
  1209. if (const HLSLNumThreadsAttr *Attr = FD->getAttr<HLSLNumThreadsAttr>()) {
  1210. if (isMS) {
  1211. funcProps->ShaderProps.MS.numThreads[0] = Attr->getX();
  1212. funcProps->ShaderProps.MS.numThreads[1] = Attr->getY();
  1213. funcProps->ShaderProps.MS.numThreads[2] = Attr->getZ();
  1214. } else if (isAS) {
  1215. funcProps->ShaderProps.AS.numThreads[0] = Attr->getX();
  1216. funcProps->ShaderProps.AS.numThreads[1] = Attr->getY();
  1217. funcProps->ShaderProps.AS.numThreads[2] = Attr->getZ();
  1218. } else {
  1219. isCS = true;
  1220. funcProps->shaderKind = DXIL::ShaderKind::Compute;
  1221. funcProps->ShaderProps.CS.numThreads[0] = Attr->getX();
  1222. funcProps->ShaderProps.CS.numThreads[1] = Attr->getY();
  1223. funcProps->ShaderProps.CS.numThreads[2] = Attr->getZ();
  1224. }
  1225. if (isEntry && !SM->IsCS() && !SM->IsMS() && !SM->IsAS()) {
  1226. unsigned DiagID = Diags.getCustomDiagID(
  1227. DiagnosticsEngine::Error, "attribute numthreads only valid for CS/MS/AS.");
  1228. Diags.Report(Attr->getLocation(), DiagID);
  1229. return;
  1230. }
  1231. }
  1232. // Hull shader.
  1233. if (const HLSLPatchConstantFuncAttr *Attr =
  1234. FD->getAttr<HLSLPatchConstantFuncAttr>()) {
  1235. if (isEntry && !SM->IsHS()) {
  1236. unsigned DiagID = Diags.getCustomDiagID(
  1237. DiagnosticsEngine::Error,
  1238. "attribute patchconstantfunc only valid for HS.");
  1239. Diags.Report(Attr->getLocation(), DiagID);
  1240. return;
  1241. }
  1242. isHS = true;
  1243. funcProps->shaderKind = DXIL::ShaderKind::Hull;
  1244. HSEntryPatchConstantFuncAttr[F] = Attr;
  1245. } else {
  1246. // TODO: This is a duplicate check. We also have this check in
  1247. // hlsl::DiagnoseTranslationUnit(clang::Sema*).
  1248. if (isEntry && SM->IsHS()) {
  1249. unsigned DiagID = Diags.getCustomDiagID(
  1250. DiagnosticsEngine::Error,
  1251. "HS entry point must have the patchconstantfunc attribute");
  1252. Diags.Report(FD->getLocation(), DiagID);
  1253. return;
  1254. }
  1255. }
  1256. if (const HLSLOutputControlPointsAttr *Attr =
  1257. FD->getAttr<HLSLOutputControlPointsAttr>()) {
  1258. if (isHS) {
  1259. funcProps->ShaderProps.HS.outputControlPoints = Attr->getCount();
  1260. } else if (isEntry && !SM->IsHS()) {
  1261. unsigned DiagID = Diags.getCustomDiagID(
  1262. DiagnosticsEngine::Error,
  1263. "attribute outputcontrolpoints only valid for HS.");
  1264. Diags.Report(Attr->getLocation(), DiagID);
  1265. return;
  1266. }
  1267. }
  1268. if (const HLSLPartitioningAttr *Attr = FD->getAttr<HLSLPartitioningAttr>()) {
  1269. if (isHS) {
  1270. DXIL::TessellatorPartitioning partition =
  1271. StringToPartitioning(Attr->getScheme());
  1272. funcProps->ShaderProps.HS.partition = partition;
  1273. } else if (isEntry && !SM->IsHS()) {
  1274. unsigned DiagID =
  1275. Diags.getCustomDiagID(DiagnosticsEngine::Warning,
  1276. "attribute partitioning only valid for HS.");
  1277. Diags.Report(Attr->getLocation(), DiagID);
  1278. }
  1279. }
  1280. if (const HLSLOutputTopologyAttr *Attr =
  1281. FD->getAttr<HLSLOutputTopologyAttr>()) {
  1282. if (isHS) {
  1283. DXIL::TessellatorOutputPrimitive primitive =
  1284. StringToTessOutputPrimitive(Attr->getTopology());
  1285. funcProps->ShaderProps.HS.outputPrimitive = primitive;
  1286. }
  1287. else if (isMS) {
  1288. DXIL::MeshOutputTopology topology =
  1289. StringToMeshOutputTopology(Attr->getTopology());
  1290. funcProps->ShaderProps.MS.outputTopology = topology;
  1291. }
  1292. else if (isEntry && !SM->IsHS() && !SM->IsMS()) {
  1293. unsigned DiagID =
  1294. Diags.getCustomDiagID(DiagnosticsEngine::Warning,
  1295. "attribute outputtopology only valid for HS and MS.");
  1296. Diags.Report(Attr->getLocation(), DiagID);
  1297. }
  1298. }
  1299. if (isHS) {
  1300. funcProps->ShaderProps.HS.maxTessFactor = DXIL::kHSMaxTessFactorUpperBound;
  1301. funcProps->ShaderProps.HS.inputControlPoints = DXIL::kHSDefaultInputControlPointCount;
  1302. }
  1303. if (const HLSLMaxTessFactorAttr *Attr =
  1304. FD->getAttr<HLSLMaxTessFactorAttr>()) {
  1305. if (isHS) {
  1306. // TODO: change getFactor to return float.
  1307. llvm::APInt intV(32, Attr->getFactor());
  1308. funcProps->ShaderProps.HS.maxTessFactor = intV.bitsToFloat();
  1309. } else if (isEntry && !SM->IsHS()) {
  1310. unsigned DiagID =
  1311. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1312. "attribute maxtessfactor only valid for HS.");
  1313. Diags.Report(Attr->getLocation(), DiagID);
  1314. return;
  1315. }
  1316. }
  1317. // Hull or domain shader.
  1318. if (const HLSLDomainAttr *Attr = FD->getAttr<HLSLDomainAttr>()) {
  1319. if (isEntry && !SM->IsHS() && !SM->IsDS()) {
  1320. unsigned DiagID =
  1321. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1322. "attribute domain only valid for HS or DS.");
  1323. Diags.Report(Attr->getLocation(), DiagID);
  1324. return;
  1325. }
  1326. isDS = !isHS;
  1327. if (isDS)
  1328. funcProps->shaderKind = DXIL::ShaderKind::Domain;
  1329. DXIL::TessellatorDomain domain = StringToDomain(Attr->getDomainType());
  1330. if (isHS)
  1331. funcProps->ShaderProps.HS.domain = domain;
  1332. else
  1333. funcProps->ShaderProps.DS.domain = domain;
  1334. }
  1335. // Vertex shader.
  1336. if (const HLSLClipPlanesAttr *Attr = FD->getAttr<HLSLClipPlanesAttr>()) {
  1337. if (isEntry && !SM->IsVS()) {
  1338. unsigned DiagID = Diags.getCustomDiagID(
  1339. DiagnosticsEngine::Error, "attribute clipplane only valid for VS.");
  1340. Diags.Report(Attr->getLocation(), DiagID);
  1341. return;
  1342. }
  1343. isVS = true;
  1344. // The real job is done at EmitHLSLFunctionProlog where debug info is
  1345. // available. Only set shader kind here.
  1346. funcProps->shaderKind = DXIL::ShaderKind::Vertex;
  1347. }
  1348. // Pixel shader.
  1349. if (const HLSLEarlyDepthStencilAttr *Attr =
  1350. FD->getAttr<HLSLEarlyDepthStencilAttr>()) {
  1351. if (isEntry && !SM->IsPS()) {
  1352. unsigned DiagID = Diags.getCustomDiagID(
  1353. DiagnosticsEngine::Error,
  1354. "attribute earlydepthstencil only valid for PS.");
  1355. Diags.Report(Attr->getLocation(), DiagID);
  1356. return;
  1357. }
  1358. isPS = true;
  1359. funcProps->ShaderProps.PS.EarlyDepthStencil = true;
  1360. funcProps->shaderKind = DXIL::ShaderKind::Pixel;
  1361. }
  1362. const unsigned profileAttributes = isCS + isHS + isDS + isGS + isVS + isPS + isRay + isMS + isAS;
  1363. // TODO: check this in front-end and report error.
  1364. DXASSERT(profileAttributes < 2, "profile attributes are mutual exclusive");
  1365. if (isEntry) {
  1366. switch (funcProps->shaderKind) {
  1367. case ShaderModel::Kind::Compute:
  1368. case ShaderModel::Kind::Hull:
  1369. case ShaderModel::Kind::Domain:
  1370. case ShaderModel::Kind::Geometry:
  1371. case ShaderModel::Kind::Vertex:
  1372. case ShaderModel::Kind::Pixel:
  1373. case ShaderModel::Kind::Mesh:
  1374. case ShaderModel::Kind::Amplification:
  1375. DXASSERT(funcProps->shaderKind == SM->GetKind(),
  1376. "attribute profile not match entry function profile");
  1377. break;
  1378. case ShaderModel::Kind::Library:
  1379. case ShaderModel::Kind::Invalid:
  1380. // Non-shader stage shadermodels don't have entry points.
  1381. break;
  1382. }
  1383. }
  1384. DxilFunctionAnnotation *FuncAnnotation =
  1385. m_pHLModule->AddFunctionAnnotation(F);
  1386. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  1387. // Param Info
  1388. unsigned streamIndex = 0;
  1389. unsigned inputPatchCount = 0;
  1390. unsigned outputPatchCount = 0;
  1391. unsigned ArgNo = 0;
  1392. unsigned ParmIdx = 0;
  1393. auto ArgIt = F->arg_begin();
  1394. if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FD)) {
  1395. if (MethodDecl->isInstance()) {
  1396. QualType ThisTy = MethodDecl->getThisType(FD->getASTContext());
  1397. DxilParameterAnnotation &paramAnnotation =
  1398. FuncAnnotation->GetParameterAnnotation(ArgNo++);
  1399. ++ArgIt;
  1400. // Construct annoation for this pointer.
  1401. ConstructFieldAttributedAnnotation(paramAnnotation, ThisTy,
  1402. bDefaultRowMajor);
  1403. if (MethodDecl->isConst()) {
  1404. paramAnnotation.SetParamInputQual(DxilParamInputQual::In);
  1405. } else {
  1406. paramAnnotation.SetParamInputQual(DxilParamInputQual::Inout);
  1407. }
  1408. }
  1409. }
  1410. // Ret Info
  1411. QualType retTy = FD->getReturnType();
  1412. DxilParameterAnnotation *pRetTyAnnotation = nullptr;
  1413. if (F->getReturnType()->isVoidTy() && !retTy->isVoidType()) {
  1414. // SRet.
  1415. pRetTyAnnotation = &FuncAnnotation->GetParameterAnnotation(ArgNo++);
  1416. // Save resource properties for parameters.
  1417. DxilResourceProperties RP = BuildResourceProperty(retTy);
  1418. if (RP.Class != DXIL::ResourceClass::Invalid)
  1419. valToResPropertiesMap[ArgIt] = RP;
  1420. ++ArgIt;
  1421. } else {
  1422. pRetTyAnnotation = &FuncAnnotation->GetRetTypeAnnotation();
  1423. }
  1424. DxilParameterAnnotation &retTyAnnotation = *pRetTyAnnotation;
  1425. // keep Undefined here, we cannot decide for struct
  1426. retTyAnnotation.SetInterpolationMode(
  1427. GetInterpMode(FD, CompType::Kind::Invalid, /*bKeepUndefined*/ true)
  1428. .GetKind());
  1429. SourceLocation retTySemanticLoc = SetSemantic(FD, retTyAnnotation);
  1430. retTyAnnotation.SetParamInputQual(DxilParamInputQual::Out);
  1431. if (isEntry) {
  1432. if (CGM.getLangOpts().EnableDX9CompatMode && retTyAnnotation.HasSemanticString()) {
  1433. RemapObsoleteSemantic(retTyAnnotation, /*isPatchConstantFunction*/ false);
  1434. }
  1435. CheckParameterAnnotation(retTySemanticLoc, retTyAnnotation,
  1436. /*isPatchConstantFunction*/ false);
  1437. }
  1438. if (isRay && !retTy->isVoidType()) {
  1439. Diags.Report(FD->getLocation(), Diags.getCustomDiagID(
  1440. DiagnosticsEngine::Error, "return type for ray tracing shaders must be void"));
  1441. }
  1442. ConstructFieldAttributedAnnotation(retTyAnnotation, retTy, bDefaultRowMajor);
  1443. if (FD->hasAttr<HLSLPreciseAttr>())
  1444. retTyAnnotation.SetPrecise();
  1445. if (isRay) {
  1446. funcProps->ShaderProps.Ray.payloadSizeInBytes = 0;
  1447. funcProps->ShaderProps.Ray.attributeSizeInBytes = 0;
  1448. }
  1449. bool hasOutIndices = false;
  1450. bool hasOutVertices = false;
  1451. bool hasOutPrimitives = false;
  1452. bool hasInPayload = false;
  1453. for (; ArgNo < F->arg_size(); ++ArgNo, ++ParmIdx, ++ArgIt) {
  1454. DxilParameterAnnotation &paramAnnotation =
  1455. FuncAnnotation->GetParameterAnnotation(ArgNo);
  1456. const ParmVarDecl *parmDecl = FD->getParamDecl(ParmIdx);
  1457. QualType fieldTy = parmDecl->getType();
  1458. // Save resource properties for parameters.
  1459. DxilResourceProperties RP = BuildResourceProperty(fieldTy);
  1460. if (RP.Class != DXIL::ResourceClass::Invalid)
  1461. valToResPropertiesMap[ArgIt] = RP;
  1462. // if parameter type is a typedef, try to desugar it first.
  1463. if (isa<TypedefType>(fieldTy.getTypePtr()))
  1464. fieldTy = fieldTy.getDesugaredType(FD->getASTContext());
  1465. ConstructFieldAttributedAnnotation(paramAnnotation, fieldTy,
  1466. bDefaultRowMajor);
  1467. if (parmDecl->hasAttr<HLSLPreciseAttr>())
  1468. paramAnnotation.SetPrecise();
  1469. // keep Undefined here, we cannot decide for struct
  1470. InterpolationMode paramIM =
  1471. GetInterpMode(parmDecl, CompType::Kind::Invalid, KeepUndefinedTrue);
  1472. paramAnnotation.SetInterpolationMode(paramIM);
  1473. SourceLocation paramSemanticLoc = SetSemantic(parmDecl, paramAnnotation);
  1474. DxilParamInputQual dxilInputQ = DxilParamInputQual::In;
  1475. if (parmDecl->hasAttr<HLSLInOutAttr>())
  1476. dxilInputQ = DxilParamInputQual::Inout;
  1477. else if (parmDecl->hasAttr<HLSLOutAttr>())
  1478. dxilInputQ = DxilParamInputQual::Out;
  1479. if (parmDecl->hasAttr<HLSLOutAttr>() && parmDecl->hasAttr<HLSLInAttr>())
  1480. dxilInputQ = DxilParamInputQual::Inout;
  1481. if (parmDecl->hasAttr<HLSLOutAttr>() && parmDecl->hasAttr<HLSLIndicesAttr>()) {
  1482. if (hasOutIndices) {
  1483. unsigned DiagID = Diags.getCustomDiagID(
  1484. DiagnosticsEngine::Error,
  1485. "multiple out indices parameters not allowed");
  1486. Diags.Report(parmDecl->getLocation(), DiagID);
  1487. continue;
  1488. }
  1489. const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(fieldTy.getCanonicalType());
  1490. if (CAT == nullptr) {
  1491. unsigned DiagID = Diags.getCustomDiagID(
  1492. DiagnosticsEngine::Error,
  1493. "indices output is not an constant-length array");
  1494. Diags.Report(parmDecl->getLocation(), DiagID);
  1495. continue;
  1496. }
  1497. unsigned count = CAT->getSize().getZExtValue();
  1498. if (count > DXIL::kMaxMSOutputPrimitiveCount) {
  1499. unsigned DiagID = Diags.getCustomDiagID(
  1500. DiagnosticsEngine::Error,
  1501. "max primitive count should not exceed %0");
  1502. Diags.Report(parmDecl->getLocation(), DiagID) << DXIL::kMaxMSOutputPrimitiveCount;
  1503. continue;
  1504. }
  1505. if (funcProps->ShaderProps.MS.maxPrimitiveCount != 0 &&
  1506. funcProps->ShaderProps.MS.maxPrimitiveCount != count) {
  1507. unsigned DiagID = Diags.getCustomDiagID(
  1508. DiagnosticsEngine::Error,
  1509. "max primitive count mismatch");
  1510. Diags.Report(parmDecl->getLocation(), DiagID);
  1511. continue;
  1512. }
  1513. // Get element type.
  1514. QualType arrayEleTy = CAT->getElementType();
  1515. if (hlsl::IsHLSLVecType(arrayEleTy)) {
  1516. QualType vecEltTy = hlsl::GetHLSLVecElementType(arrayEleTy);
  1517. if (!vecEltTy->isUnsignedIntegerType() || CGM.getContext().getTypeSize(vecEltTy) != 32) {
  1518. unsigned DiagID = Diags.getCustomDiagID(
  1519. DiagnosticsEngine::Error,
  1520. "the element of out_indices array must be uint2 for line output or uint3 for triangle output");
  1521. Diags.Report(parmDecl->getLocation(), DiagID);
  1522. continue;
  1523. }
  1524. unsigned vecEltCount = hlsl::GetHLSLVecSize(arrayEleTy);
  1525. if (funcProps->ShaderProps.MS.outputTopology == DXIL::MeshOutputTopology::Line && vecEltCount != 2) {
  1526. unsigned DiagID = Diags.getCustomDiagID(
  1527. DiagnosticsEngine::Error,
  1528. "the element of out_indices array in a mesh shader whose output topology is line must be uint2");
  1529. Diags.Report(parmDecl->getLocation(), DiagID);
  1530. continue;
  1531. }
  1532. if (funcProps->ShaderProps.MS.outputTopology == DXIL::MeshOutputTopology::Triangle && vecEltCount != 3) {
  1533. unsigned DiagID = Diags.getCustomDiagID(
  1534. DiagnosticsEngine::Error,
  1535. "the element of out_indices array in a mesh shader whose output topology is triangle must be uint3");
  1536. Diags.Report(parmDecl->getLocation(), DiagID);
  1537. continue;
  1538. }
  1539. } else {
  1540. unsigned DiagID = Diags.getCustomDiagID(
  1541. DiagnosticsEngine::Error,
  1542. "the element of out_indices array must be uint2 for line output or uint3 for triangle output");
  1543. Diags.Report(parmDecl->getLocation(), DiagID);
  1544. continue;
  1545. }
  1546. dxilInputQ = DxilParamInputQual::OutIndices;
  1547. funcProps->ShaderProps.MS.maxPrimitiveCount = count;
  1548. hasOutIndices = true;
  1549. }
  1550. if (parmDecl->hasAttr<HLSLOutAttr>() && parmDecl->hasAttr<HLSLVerticesAttr>()) {
  1551. if (hasOutVertices) {
  1552. unsigned DiagID = Diags.getCustomDiagID(
  1553. DiagnosticsEngine::Error,
  1554. "multiple out vertices parameters not allowed");
  1555. Diags.Report(parmDecl->getLocation(), DiagID);
  1556. continue;
  1557. }
  1558. const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(fieldTy.getCanonicalType());
  1559. if (CAT == nullptr) {
  1560. unsigned DiagID = Diags.getCustomDiagID(
  1561. DiagnosticsEngine::Error,
  1562. "vertices output is not an constant-length array");
  1563. Diags.Report(parmDecl->getLocation(), DiagID);
  1564. continue;
  1565. }
  1566. unsigned count = CAT->getSize().getZExtValue();
  1567. if (count > DXIL::kMaxMSOutputVertexCount) {
  1568. unsigned DiagID = Diags.getCustomDiagID(
  1569. DiagnosticsEngine::Error,
  1570. "max vertex count should not exceed %0");
  1571. Diags.Report(parmDecl->getLocation(), DiagID) << DXIL::kMaxMSOutputVertexCount;
  1572. continue;
  1573. }
  1574. dxilInputQ = DxilParamInputQual::OutVertices;
  1575. funcProps->ShaderProps.MS.maxVertexCount = count;
  1576. hasOutVertices = true;
  1577. }
  1578. if (parmDecl->hasAttr<HLSLOutAttr>() && parmDecl->hasAttr<HLSLPrimitivesAttr>()) {
  1579. if (hasOutPrimitives) {
  1580. unsigned DiagID = Diags.getCustomDiagID(
  1581. DiagnosticsEngine::Error,
  1582. "multiple out primitives parameters not allowed");
  1583. Diags.Report(parmDecl->getLocation(), DiagID);
  1584. continue;
  1585. }
  1586. const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(fieldTy.getCanonicalType());
  1587. if (CAT == nullptr) {
  1588. unsigned DiagID = Diags.getCustomDiagID(
  1589. DiagnosticsEngine::Error,
  1590. "primitives output is not an constant-length array");
  1591. Diags.Report(parmDecl->getLocation(), DiagID);
  1592. continue;
  1593. }
  1594. unsigned count = CAT->getSize().getZExtValue();
  1595. if (count > DXIL::kMaxMSOutputPrimitiveCount) {
  1596. unsigned DiagID = Diags.getCustomDiagID(
  1597. DiagnosticsEngine::Error,
  1598. "max primitive count should not exceed %0");
  1599. Diags.Report(parmDecl->getLocation(), DiagID) << DXIL::kMaxMSOutputPrimitiveCount;
  1600. continue;
  1601. }
  1602. if (funcProps->ShaderProps.MS.maxPrimitiveCount != 0 &&
  1603. funcProps->ShaderProps.MS.maxPrimitiveCount != count) {
  1604. unsigned DiagID = Diags.getCustomDiagID(
  1605. DiagnosticsEngine::Error,
  1606. "max primitive count mismatch");
  1607. Diags.Report(parmDecl->getLocation(), DiagID);
  1608. continue;
  1609. }
  1610. dxilInputQ = DxilParamInputQual::OutPrimitives;
  1611. funcProps->ShaderProps.MS.maxPrimitiveCount = count;
  1612. hasOutPrimitives = true;
  1613. }
  1614. if (parmDecl->hasAttr<HLSLInAttr>() && parmDecl->hasAttr<HLSLPayloadAttr>()) {
  1615. if (hasInPayload) {
  1616. unsigned DiagID = Diags.getCustomDiagID(
  1617. DiagnosticsEngine::Error,
  1618. "multiple in payload parameters not allowed");
  1619. Diags.Report(parmDecl->getLocation(), DiagID);
  1620. continue;
  1621. }
  1622. dxilInputQ = DxilParamInputQual::InPayload;
  1623. DataLayout DL(&this->TheModule);
  1624. funcProps->ShaderProps.MS.payloadSizeInBytes = DL.getTypeAllocSize(
  1625. F->getFunctionType()->getFunctionParamType(ArgNo)->getPointerElementType());
  1626. hasInPayload = true;
  1627. }
  1628. DXIL::InputPrimitive inputPrimitive = DXIL::InputPrimitive::Undefined;
  1629. if (IsHLSLOutputPatchType(parmDecl->getType())) {
  1630. outputPatchCount++;
  1631. if (dxilInputQ != DxilParamInputQual::In) {
  1632. unsigned DiagID = Diags.getCustomDiagID(
  1633. DiagnosticsEngine::Error,
  1634. "OutputPatch should not be out/inout parameter");
  1635. Diags.Report(parmDecl->getLocation(), DiagID);
  1636. continue;
  1637. }
  1638. dxilInputQ = DxilParamInputQual::OutputPatch;
  1639. if (isDS)
  1640. funcProps->ShaderProps.DS.inputControlPoints =
  1641. GetHLSLOutputPatchCount(parmDecl->getType());
  1642. } else if (IsHLSLInputPatchType(parmDecl->getType())) {
  1643. inputPatchCount++;
  1644. if (dxilInputQ != DxilParamInputQual::In) {
  1645. unsigned DiagID = Diags.getCustomDiagID(
  1646. DiagnosticsEngine::Error,
  1647. "InputPatch should not be out/inout parameter");
  1648. Diags.Report(parmDecl->getLocation(), DiagID);
  1649. continue;
  1650. }
  1651. dxilInputQ = DxilParamInputQual::InputPatch;
  1652. if (isHS) {
  1653. funcProps->ShaderProps.HS.inputControlPoints =
  1654. GetHLSLInputPatchCount(parmDecl->getType());
  1655. } else if (isGS) {
  1656. inputPrimitive = (DXIL::InputPrimitive)(
  1657. (unsigned)DXIL::InputPrimitive::ControlPointPatch1 +
  1658. GetHLSLInputPatchCount(parmDecl->getType()) - 1);
  1659. }
  1660. } else if (IsHLSLStreamOutputType(parmDecl->getType())) {
  1661. // TODO: validation this at ASTContext::getFunctionType in
  1662. // AST/ASTContext.cpp
  1663. DXASSERT(dxilInputQ == DxilParamInputQual::Inout,
  1664. "stream output parameter must be inout");
  1665. switch (streamIndex) {
  1666. case 0:
  1667. dxilInputQ = DxilParamInputQual::OutStream0;
  1668. break;
  1669. case 1:
  1670. dxilInputQ = DxilParamInputQual::OutStream1;
  1671. break;
  1672. case 2:
  1673. dxilInputQ = DxilParamInputQual::OutStream2;
  1674. break;
  1675. case 3:
  1676. default:
  1677. // TODO: validation this at ASTContext::getFunctionType in
  1678. // AST/ASTContext.cpp
  1679. DXASSERT(streamIndex == 3, "stream number out of bound");
  1680. dxilInputQ = DxilParamInputQual::OutStream3;
  1681. break;
  1682. }
  1683. DXIL::PrimitiveTopology &streamTopology =
  1684. funcProps->ShaderProps.GS.streamPrimitiveTopologies[streamIndex];
  1685. if (IsHLSLPointStreamType(parmDecl->getType()))
  1686. streamTopology = DXIL::PrimitiveTopology::PointList;
  1687. else if (IsHLSLLineStreamType(parmDecl->getType()))
  1688. streamTopology = DXIL::PrimitiveTopology::LineStrip;
  1689. else {
  1690. DXASSERT(IsHLSLTriangleStreamType(parmDecl->getType()),
  1691. "invalid StreamType");
  1692. streamTopology = DXIL::PrimitiveTopology::TriangleStrip;
  1693. }
  1694. if (streamIndex > 0) {
  1695. bool bAllPoint =
  1696. streamTopology == DXIL::PrimitiveTopology::PointList &&
  1697. funcProps->ShaderProps.GS.streamPrimitiveTopologies[0] ==
  1698. DXIL::PrimitiveTopology::PointList;
  1699. if (!bAllPoint) {
  1700. unsigned DiagID = Diags.getCustomDiagID(
  1701. DiagnosticsEngine::Error, "when multiple GS output streams are "
  1702. "used they must be pointlists.");
  1703. Diags.Report(FD->getLocation(), DiagID);
  1704. }
  1705. }
  1706. streamIndex++;
  1707. }
  1708. unsigned GsInputArrayDim = 0;
  1709. if (parmDecl->hasAttr<HLSLTriangleAttr>()) {
  1710. inputPrimitive = DXIL::InputPrimitive::Triangle;
  1711. GsInputArrayDim = 3;
  1712. } else if (parmDecl->hasAttr<HLSLTriangleAdjAttr>()) {
  1713. inputPrimitive = DXIL::InputPrimitive::TriangleWithAdjacency;
  1714. GsInputArrayDim = 6;
  1715. } else if (parmDecl->hasAttr<HLSLPointAttr>()) {
  1716. inputPrimitive = DXIL::InputPrimitive::Point;
  1717. GsInputArrayDim = 1;
  1718. } else if (parmDecl->hasAttr<HLSLLineAdjAttr>()) {
  1719. inputPrimitive = DXIL::InputPrimitive::LineWithAdjacency;
  1720. GsInputArrayDim = 4;
  1721. } else if (parmDecl->hasAttr<HLSLLineAttr>()) {
  1722. inputPrimitive = DXIL::InputPrimitive::Line;
  1723. GsInputArrayDim = 2;
  1724. }
  1725. if (inputPrimitive != DXIL::InputPrimitive::Undefined) {
  1726. // Set to InputPrimitive for GS.
  1727. dxilInputQ = DxilParamInputQual::InputPrimitive;
  1728. if (funcProps->ShaderProps.GS.inputPrimitive ==
  1729. DXIL::InputPrimitive::Undefined) {
  1730. funcProps->ShaderProps.GS.inputPrimitive = inputPrimitive;
  1731. } else if (funcProps->ShaderProps.GS.inputPrimitive != inputPrimitive) {
  1732. unsigned DiagID = Diags.getCustomDiagID(
  1733. DiagnosticsEngine::Error, "input parameter conflicts with geometry "
  1734. "specifier of previous input parameters");
  1735. Diags.Report(parmDecl->getLocation(), DiagID);
  1736. }
  1737. }
  1738. if (GsInputArrayDim != 0) {
  1739. QualType Ty = parmDecl->getType();
  1740. if (!Ty->isConstantArrayType()) {
  1741. unsigned DiagID = Diags.getCustomDiagID(
  1742. DiagnosticsEngine::Error,
  1743. "input types for geometry shader must be constant size arrays");
  1744. Diags.Report(parmDecl->getLocation(), DiagID);
  1745. } else {
  1746. const ConstantArrayType *CAT = cast<ConstantArrayType>(Ty);
  1747. if (CAT->getSize().getLimitedValue() != GsInputArrayDim) {
  1748. StringRef primtiveNames[] = {
  1749. "invalid", // 0
  1750. "point", // 1
  1751. "line", // 2
  1752. "triangle", // 3
  1753. "lineadj", // 4
  1754. "invalid", // 5
  1755. "triangleadj", // 6
  1756. };
  1757. DXASSERT(GsInputArrayDim < llvm::array_lengthof(primtiveNames),
  1758. "Invalid array dim");
  1759. unsigned DiagID = Diags.getCustomDiagID(
  1760. DiagnosticsEngine::Error, "array dimension for %0 must be %1");
  1761. Diags.Report(parmDecl->getLocation(), DiagID)
  1762. << primtiveNames[GsInputArrayDim] << GsInputArrayDim;
  1763. }
  1764. }
  1765. }
  1766. // Validate Ray Tracing function parameter (some validation may be pushed into front end)
  1767. if (isRay) {
  1768. switch (funcProps->shaderKind) {
  1769. case DXIL::ShaderKind::RayGeneration:
  1770. case DXIL::ShaderKind::Intersection:
  1771. // RayGeneration and Intersection shaders are not allowed to have any input parameters
  1772. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1773. DiagnosticsEngine::Error, "parameters are not allowed for %0 shader"))
  1774. << (funcProps->shaderKind == DXIL::ShaderKind::RayGeneration ?
  1775. "raygeneration" : "intersection");
  1776. break;
  1777. case DXIL::ShaderKind::AnyHit:
  1778. case DXIL::ShaderKind::ClosestHit:
  1779. if (0 == ArgNo && dxilInputQ != DxilParamInputQual::Inout) {
  1780. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1781. DiagnosticsEngine::Error,
  1782. "ray payload parameter must be inout"));
  1783. } else if (1 == ArgNo && dxilInputQ != DxilParamInputQual::In) {
  1784. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1785. DiagnosticsEngine::Error,
  1786. "intersection attributes parameter must be in"));
  1787. } else if (ArgNo > 1) {
  1788. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1789. DiagnosticsEngine::Error,
  1790. "too many parameters, expected payload and attributes parameters only."));
  1791. }
  1792. if (ArgNo < 2) {
  1793. if (!IsHLSLNumericUserDefinedType(parmDecl->getType())) {
  1794. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1795. DiagnosticsEngine::Error,
  1796. "payload and attribute structures must be user defined types with only numeric contents."));
  1797. } else {
  1798. DataLayout DL(&this->TheModule);
  1799. unsigned size = DL.getTypeAllocSize(F->getFunctionType()->getFunctionParamType(ArgNo)->getPointerElementType());
  1800. if (0 == ArgNo)
  1801. funcProps->ShaderProps.Ray.payloadSizeInBytes = size;
  1802. else
  1803. funcProps->ShaderProps.Ray.attributeSizeInBytes = size;
  1804. }
  1805. }
  1806. break;
  1807. case DXIL::ShaderKind::Miss:
  1808. if (ArgNo > 0) {
  1809. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1810. DiagnosticsEngine::Error,
  1811. "only one parameter (ray payload) allowed for miss shader"));
  1812. } else if (dxilInputQ != DxilParamInputQual::Inout) {
  1813. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1814. DiagnosticsEngine::Error,
  1815. "ray payload parameter must be declared inout"));
  1816. }
  1817. if (ArgNo < 1) {
  1818. if (!IsHLSLNumericUserDefinedType(parmDecl->getType())) {
  1819. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1820. DiagnosticsEngine::Error,
  1821. "ray payload parameter must be a user defined type with only numeric contents."));
  1822. } else {
  1823. DataLayout DL(&this->TheModule);
  1824. unsigned size = DL.getTypeAllocSize(F->getFunctionType()->getFunctionParamType(ArgNo)->getPointerElementType());
  1825. funcProps->ShaderProps.Ray.payloadSizeInBytes = size;
  1826. }
  1827. }
  1828. break;
  1829. case DXIL::ShaderKind::Callable:
  1830. if (ArgNo > 0) {
  1831. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1832. DiagnosticsEngine::Error,
  1833. "only one parameter allowed for callable shader"));
  1834. } else if (dxilInputQ != DxilParamInputQual::Inout) {
  1835. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1836. DiagnosticsEngine::Error,
  1837. "callable parameter must be declared inout"));
  1838. }
  1839. if (ArgNo < 1) {
  1840. if (!IsHLSLNumericUserDefinedType(parmDecl->getType())) {
  1841. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1842. DiagnosticsEngine::Error,
  1843. "callable parameter must be a user defined type with only numeric contents."));
  1844. } else {
  1845. DataLayout DL(&this->TheModule);
  1846. unsigned size = DL.getTypeAllocSize(F->getFunctionType()->getFunctionParamType(ArgNo)->getPointerElementType());
  1847. funcProps->ShaderProps.Ray.paramSizeInBytes = size;
  1848. }
  1849. }
  1850. break;
  1851. }
  1852. }
  1853. paramAnnotation.SetParamInputQual(dxilInputQ);
  1854. if (isEntry) {
  1855. if (CGM.getLangOpts().EnableDX9CompatMode && paramAnnotation.HasSemanticString()) {
  1856. RemapObsoleteSemantic(paramAnnotation, /*isPatchConstantFunction*/ false);
  1857. }
  1858. CheckParameterAnnotation(paramSemanticLoc, paramAnnotation,
  1859. /*isPatchConstantFunction*/ false);
  1860. }
  1861. }
  1862. if (inputPatchCount > 1) {
  1863. unsigned DiagID = Diags.getCustomDiagID(
  1864. DiagnosticsEngine::Error, "may only have one InputPatch parameter");
  1865. Diags.Report(FD->getLocation(), DiagID);
  1866. }
  1867. if (outputPatchCount > 1) {
  1868. unsigned DiagID = Diags.getCustomDiagID(
  1869. DiagnosticsEngine::Error, "may only have one OutputPatch parameter");
  1870. Diags.Report(FD->getLocation(), DiagID);
  1871. }
  1872. // If Shader is a ray shader that requires parameters, make sure size is non-zero
  1873. if (isRay) {
  1874. bool bNeedsAttributes = false;
  1875. bool bNeedsPayload = false;
  1876. switch (funcProps->shaderKind) {
  1877. case DXIL::ShaderKind::AnyHit:
  1878. case DXIL::ShaderKind::ClosestHit:
  1879. bNeedsAttributes = true;
  1880. case DXIL::ShaderKind::Miss:
  1881. bNeedsPayload = true;
  1882. case DXIL::ShaderKind::Callable:
  1883. if (0 == funcProps->ShaderProps.Ray.payloadSizeInBytes) {
  1884. unsigned DiagID = bNeedsPayload ?
  1885. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1886. "shader must include inout payload structure parameter.") :
  1887. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1888. "shader must include inout parameter structure.");
  1889. Diags.Report(FD->getLocation(), DiagID);
  1890. }
  1891. }
  1892. if (bNeedsAttributes &&
  1893. 0 == funcProps->ShaderProps.Ray.attributeSizeInBytes) {
  1894. Diags.Report(FD->getLocation(), Diags.getCustomDiagID(
  1895. DiagnosticsEngine::Error,
  1896. "shader must include attributes structure parameter."));
  1897. }
  1898. }
  1899. // Type annotation for parameters and return type.
  1900. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  1901. unsigned arrayEltSize = 0;
  1902. AddTypeAnnotation(FD->getReturnType(), dxilTypeSys, arrayEltSize);
  1903. // Type annotation for this pointer.
  1904. if (const CXXMethodDecl *MFD = dyn_cast<CXXMethodDecl>(FD)) {
  1905. const CXXRecordDecl *RD = MFD->getParent();
  1906. QualType Ty = CGM.getContext().getTypeDeclType(RD);
  1907. AddTypeAnnotation(Ty, dxilTypeSys, arrayEltSize);
  1908. }
  1909. for (const ValueDecl *param : FD->params()) {
  1910. QualType Ty = param->getType();
  1911. AddTypeAnnotation(Ty, dxilTypeSys, arrayEltSize);
  1912. }
  1913. // clear isExportedEntry if not exporting entry
  1914. bool isExportedEntry = profileAttributes != 0;
  1915. if (isExportedEntry) {
  1916. // use unmangled or mangled name depending on which is used for final entry function
  1917. StringRef name = isRay ? F->getName() : FD->getName();
  1918. if (!m_ExportMap.IsExported(name)) {
  1919. isExportedEntry = false;
  1920. }
  1921. }
  1922. // Only add functionProps when exist.
  1923. if (isExportedEntry || isEntry)
  1924. m_pHLModule->AddDxilFunctionProps(F, funcProps);
  1925. if (isPatchConstantFunction)
  1926. patchConstantFunctionPropsMap[F] = std::move(funcProps);
  1927. // Save F to entry map.
  1928. if (isExportedEntry) {
  1929. if (entryFunctionMap.count(FD->getName())) {
  1930. DiagnosticsEngine &Diags = CGM.getDiags();
  1931. unsigned DiagID = Diags.getCustomDiagID(
  1932. DiagnosticsEngine::Error,
  1933. "redefinition of %0");
  1934. Diags.Report(FD->getLocStart(), DiagID) << FD->getName();
  1935. }
  1936. auto &Entry = entryFunctionMap[FD->getNameAsString()];
  1937. Entry.SL = FD->getLocation();
  1938. Entry.Func= F;
  1939. }
  1940. // Add target-dependent experimental function attributes
  1941. for (const auto &Attr : FD->specific_attrs<HLSLExperimentalAttr>()) {
  1942. F->addFnAttr(Twine("exp-", Attr->getName()).str(), Attr->getValue());
  1943. }
  1944. m_ScopeMap[F] = ScopeInfo(F);
  1945. }
  1946. void CGMSHLSLRuntime::RemapObsoleteSemantic(DxilParameterAnnotation &paramInfo, bool isPatchConstantFunction) {
  1947. DXASSERT(CGM.getLangOpts().EnableDX9CompatMode, "should be used only in back-compat mode");
  1948. const ShaderModel *SM = m_pHLModule->GetShaderModel();
  1949. DXIL::SigPointKind sigPointKind = SigPointFromInputQual(paramInfo.GetParamInputQual(), SM->GetKind(), isPatchConstantFunction);
  1950. hlsl::RemapObsoleteSemantic(paramInfo, sigPointKind, CGM.getLLVMContext());
  1951. }
  1952. void CGMSHLSLRuntime::EmitHLSLFunctionProlog(Function *F, const FunctionDecl *FD) {
  1953. // Support clip plane need debug info which not available when create function attribute.
  1954. if (const HLSLClipPlanesAttr *Attr = FD->getAttr<HLSLClipPlanesAttr>()) {
  1955. DxilFunctionProps &funcProps = m_pHLModule->GetDxilFunctionProps(F);
  1956. // Initialize to null.
  1957. memset(funcProps.ShaderProps.VS.clipPlanes, 0, sizeof(funcProps.ShaderProps.VS.clipPlanes));
  1958. // Create global for each clip plane, and use the clip plane val as init val.
  1959. auto AddClipPlane = [&](Expr *clipPlane, unsigned idx) {
  1960. if (DeclRefExpr *decl = dyn_cast<DeclRefExpr>(clipPlane)) {
  1961. const VarDecl *VD = cast<VarDecl>(decl->getDecl());
  1962. Constant *clipPlaneVal = CGM.GetAddrOfGlobalVar(VD);
  1963. funcProps.ShaderProps.VS.clipPlanes[idx] = clipPlaneVal;
  1964. if (m_bDebugInfo) {
  1965. CodeGenFunction CGF(CGM);
  1966. ApplyDebugLocation applyDebugLoc(CGF, clipPlane);
  1967. debugInfoMap[clipPlaneVal] = CGF.Builder.getCurrentDebugLocation();
  1968. }
  1969. } else {
  1970. // Must be a MemberExpr.
  1971. const MemberExpr *ME = cast<MemberExpr>(clipPlane);
  1972. CodeGenFunction CGF(CGM);
  1973. CodeGen::LValue LV = CGF.EmitMemberExpr(ME);
  1974. Value *addr = LV.getAddress();
  1975. funcProps.ShaderProps.VS.clipPlanes[idx] = cast<Constant>(addr);
  1976. if (m_bDebugInfo) {
  1977. CodeGenFunction CGF(CGM);
  1978. ApplyDebugLocation applyDebugLoc(CGF, clipPlane);
  1979. debugInfoMap[addr] = CGF.Builder.getCurrentDebugLocation();
  1980. }
  1981. }
  1982. };
  1983. if (Expr *clipPlane = Attr->getClipPlane1())
  1984. AddClipPlane(clipPlane, 0);
  1985. if (Expr *clipPlane = Attr->getClipPlane2())
  1986. AddClipPlane(clipPlane, 1);
  1987. if (Expr *clipPlane = Attr->getClipPlane3())
  1988. AddClipPlane(clipPlane, 2);
  1989. if (Expr *clipPlane = Attr->getClipPlane4())
  1990. AddClipPlane(clipPlane, 3);
  1991. if (Expr *clipPlane = Attr->getClipPlane5())
  1992. AddClipPlane(clipPlane, 4);
  1993. if (Expr *clipPlane = Attr->getClipPlane6())
  1994. AddClipPlane(clipPlane, 5);
  1995. clipPlaneFuncList.emplace_back(F);
  1996. }
  1997. // Update function linkage based on DefaultLinkage
  1998. // We will take care of patch constant functions later, once identified for certain.
  1999. if (!m_pHLModule->HasDxilFunctionProps(F)) {
  2000. if (F->getLinkage() == GlobalValue::LinkageTypes::ExternalLinkage) {
  2001. if (!FD->hasAttr<HLSLExportAttr>()) {
  2002. switch (CGM.getCodeGenOpts().DefaultLinkage) {
  2003. case DXIL::DefaultLinkage::Default:
  2004. if (m_pHLModule->GetShaderModel()->GetMinor() != ShaderModel::kOfflineMinor)
  2005. F->setLinkage(GlobalValue::LinkageTypes::InternalLinkage);
  2006. break;
  2007. case DXIL::DefaultLinkage::Internal:
  2008. F->setLinkage(GlobalValue::LinkageTypes::InternalLinkage);
  2009. break;
  2010. }
  2011. }
  2012. }
  2013. }
  2014. }
  2015. void CGMSHLSLRuntime::AddControlFlowHint(CodeGenFunction &CGF, const Stmt &S,
  2016. llvm::TerminatorInst *TI,
  2017. ArrayRef<const Attr *> Attrs) {
  2018. // Build hints.
  2019. bool bNoBranchFlatten = true;
  2020. bool bBranch = false;
  2021. bool bFlatten = false;
  2022. std::vector<DXIL::ControlFlowHint> hints;
  2023. for (const auto *Attr : Attrs) {
  2024. if (isa<HLSLBranchAttr>(Attr)) {
  2025. hints.emplace_back(DXIL::ControlFlowHint::Branch);
  2026. bNoBranchFlatten = false;
  2027. bBranch = true;
  2028. }
  2029. else if (isa<HLSLFlattenAttr>(Attr)) {
  2030. hints.emplace_back(DXIL::ControlFlowHint::Flatten);
  2031. bNoBranchFlatten = false;
  2032. bFlatten = true;
  2033. } else if (isa<HLSLForceCaseAttr>(Attr)) {
  2034. if (isa<SwitchStmt>(&S)) {
  2035. hints.emplace_back(DXIL::ControlFlowHint::ForceCase);
  2036. }
  2037. }
  2038. // Ignore fastopt, allow_uav_condition and call for now.
  2039. }
  2040. if (bNoBranchFlatten) {
  2041. // CHECK control flow option.
  2042. if (CGF.CGM.getCodeGenOpts().HLSLPreferControlFlow)
  2043. hints.emplace_back(DXIL::ControlFlowHint::Branch);
  2044. else if (CGF.CGM.getCodeGenOpts().HLSLAvoidControlFlow)
  2045. hints.emplace_back(DXIL::ControlFlowHint::Flatten);
  2046. }
  2047. if (bFlatten && bBranch) {
  2048. DiagnosticsEngine &Diags = CGM.getDiags();
  2049. unsigned DiagID = Diags.getCustomDiagID(
  2050. DiagnosticsEngine::Error,
  2051. "can't use branch and flatten attributes together");
  2052. Diags.Report(S.getLocStart(), DiagID);
  2053. }
  2054. if (hints.size()) {
  2055. // Add meta data to the instruction.
  2056. MDNode *hintsNode = DxilMDHelper::EmitControlFlowHints(Context, hints);
  2057. TI->setMetadata(DxilMDHelper::kDxilControlFlowHintMDName, hintsNode);
  2058. }
  2059. }
  2060. void CGMSHLSLRuntime::MarkRetTemp(CodeGenFunction &CGF, Value *V,
  2061. QualType QualTy) {
  2062. // Save resource properties for ret temp.
  2063. DxilResourceProperties RP = BuildResourceProperty(QualTy);
  2064. if (RP.Class != DXIL::ResourceClass::Invalid)
  2065. valToResPropertiesMap[V] = RP;
  2066. }
  2067. void CGMSHLSLRuntime::FinishAutoVar(CodeGenFunction &CGF, const VarDecl &D,
  2068. llvm::Value *V) {
  2069. if (D.hasAttr<HLSLPreciseAttr>()) {
  2070. AllocaInst *AI = cast<AllocaInst>(V);
  2071. HLModule::MarkPreciseAttributeWithMetadata(AI);
  2072. }
  2073. // Add type annotation for local variable.
  2074. DxilTypeSystem &typeSys = m_pHLModule->GetTypeSystem();
  2075. unsigned arrayEltSize = 0;
  2076. AddTypeAnnotation(D.getType(), typeSys, arrayEltSize);
  2077. // Save resource properties for local variables.
  2078. DxilResourceProperties RP = BuildResourceProperty(D.getType());
  2079. if (RP.Class != DXIL::ResourceClass::Invalid)
  2080. valToResPropertiesMap[V] = RP;
  2081. }
  2082. hlsl::InterpolationMode CGMSHLSLRuntime::GetInterpMode(const Decl *decl,
  2083. CompType compType,
  2084. bool bKeepUndefined) {
  2085. InterpolationMode Interp(
  2086. decl->hasAttr<HLSLNoInterpolationAttr>(), decl->hasAttr<HLSLLinearAttr>(),
  2087. decl->hasAttr<HLSLNoPerspectiveAttr>(), decl->hasAttr<HLSLCentroidAttr>(),
  2088. decl->hasAttr<HLSLSampleAttr>());
  2089. DXASSERT(Interp.IsValid(), "otherwise front-end missing validation");
  2090. if (Interp.IsUndefined() && !bKeepUndefined) {
  2091. // Type-based default: linear for floats, constant for others.
  2092. if (compType.IsFloatTy())
  2093. Interp = InterpolationMode::Kind::Linear;
  2094. else
  2095. Interp = InterpolationMode::Kind::Constant;
  2096. }
  2097. return Interp;
  2098. }
  2099. hlsl::CompType CGMSHLSLRuntime::GetCompType(const BuiltinType *BT) {
  2100. hlsl::CompType ElementType = hlsl::CompType::getInvalid();
  2101. switch (BT->getKind()) {
  2102. case BuiltinType::Bool:
  2103. ElementType = hlsl::CompType::getI1();
  2104. break;
  2105. case BuiltinType::Double:
  2106. ElementType = hlsl::CompType::getF64();
  2107. break;
  2108. case BuiltinType::HalfFloat: // HLSL Change
  2109. case BuiltinType::Float:
  2110. ElementType = hlsl::CompType::getF32();
  2111. break;
  2112. // HLSL Changes begin
  2113. case BuiltinType::Min10Float:
  2114. case BuiltinType::Min16Float:
  2115. // HLSL Changes end
  2116. case BuiltinType::Half:
  2117. ElementType = hlsl::CompType::getF16();
  2118. break;
  2119. case BuiltinType::Int:
  2120. ElementType = hlsl::CompType::getI32();
  2121. break;
  2122. case BuiltinType::LongLong:
  2123. ElementType = hlsl::CompType::getI64();
  2124. break;
  2125. // HLSL Changes begin
  2126. case BuiltinType::Min12Int:
  2127. case BuiltinType::Min16Int:
  2128. // HLSL Changes end
  2129. case BuiltinType::Short:
  2130. ElementType = hlsl::CompType::getI16();
  2131. break;
  2132. case BuiltinType::UInt:
  2133. ElementType = hlsl::CompType::getU32();
  2134. break;
  2135. case BuiltinType::ULongLong:
  2136. ElementType = hlsl::CompType::getU64();
  2137. break;
  2138. case BuiltinType::Min16UInt: // HLSL Change
  2139. case BuiltinType::UShort:
  2140. ElementType = hlsl::CompType::getU16();
  2141. break;
  2142. default:
  2143. llvm_unreachable("unsupported type");
  2144. break;
  2145. }
  2146. return ElementType;
  2147. }
  2148. /// Add resource to the program
  2149. void CGMSHLSLRuntime::addResource(Decl *D) {
  2150. if (HLSLBufferDecl *BD = dyn_cast<HLSLBufferDecl>(D))
  2151. GetOrCreateCBuffer(BD);
  2152. else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  2153. hlsl::DxilResourceBase::Class resClass = TypeToClass(VD->getType());
  2154. // Save resource properties for global variables.
  2155. if (resClass != DXIL::ResourceClass::Invalid) {
  2156. GlobalVariable *GV = cast<GlobalVariable>(CGM.GetAddrOfGlobalVar(VD));
  2157. DxilResourceProperties RP = BuildResourceProperty(VD->getType());
  2158. if (RP.Class != DXIL::ResourceClass::Invalid)
  2159. valToResPropertiesMap[GV] = RP;
  2160. }
  2161. // skip decl has init which is resource.
  2162. if (VD->hasInit() && resClass != DXIL::ResourceClass::Invalid)
  2163. return;
  2164. // skip static global.
  2165. if (!VD->hasExternalFormalLinkage()) {
  2166. if (VD->hasInit() && VD->getType().isConstQualified()) {
  2167. Expr* InitExp = VD->getInit();
  2168. GlobalVariable *GV = cast<GlobalVariable>(CGM.GetAddrOfGlobalVar(VD));
  2169. // Only save const static global of struct type.
  2170. if (GV->getType()->getElementType()->isStructTy()) {
  2171. staticConstGlobalInitMap[InitExp] = GV;
  2172. }
  2173. }
  2174. // Add type annotation for static global variable.
  2175. DxilTypeSystem &typeSys = m_pHLModule->GetTypeSystem();
  2176. unsigned arrayEltSize = 0;
  2177. AddTypeAnnotation(VD->getType(), typeSys, arrayEltSize);
  2178. return;
  2179. }
  2180. if (D->hasAttr<HLSLGroupSharedAttr>()) {
  2181. GlobalVariable *GV = cast<GlobalVariable>(CGM.GetAddrOfGlobalVar(VD));
  2182. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  2183. unsigned arraySize = 0;
  2184. AddTypeAnnotation(VD->getType(), dxilTypeSys, arraySize);
  2185. m_pHLModule->AddGroupSharedVariable(GV);
  2186. return;
  2187. }
  2188. switch (resClass) {
  2189. case hlsl::DxilResourceBase::Class::Sampler:
  2190. AddSampler(VD);
  2191. break;
  2192. case hlsl::DxilResourceBase::Class::UAV:
  2193. case hlsl::DxilResourceBase::Class::SRV:
  2194. AddUAVSRV(VD, resClass);
  2195. break;
  2196. case hlsl::DxilResourceBase::Class::Invalid: {
  2197. // normal global constant, add to global CB
  2198. HLCBuffer &globalCB = GetGlobalCBuffer();
  2199. AddConstant(VD, globalCB);
  2200. break;
  2201. }
  2202. case DXIL::ResourceClass::CBuffer:
  2203. DXASSERT(0, "cbuffer should not be here");
  2204. break;
  2205. }
  2206. }
  2207. }
  2208. /// Add subobject to the module
  2209. void CGMSHLSLRuntime::addSubobject(Decl *D) {
  2210. VarDecl *VD = dyn_cast<VarDecl>(D);
  2211. DXASSERT(VD != nullptr, "must be a global variable");
  2212. DXIL::SubobjectKind subobjKind;
  2213. DXIL::HitGroupType hgType;
  2214. if (!hlsl::GetHLSLSubobjectKind(VD->getType(), subobjKind, hgType)) {
  2215. DXASSERT(false, "not a valid subobject declaration");
  2216. return;
  2217. }
  2218. Expr *initExpr = const_cast<Expr*>(VD->getAnyInitializer());
  2219. if (!initExpr) {
  2220. DiagnosticsEngine &Diags = CGM.getDiags();
  2221. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "subobject needs to be initialized");
  2222. Diags.Report(D->getLocStart(), DiagID);
  2223. return;
  2224. }
  2225. if (InitListExpr *initListExpr = dyn_cast<InitListExpr>(initExpr)) {
  2226. try {
  2227. CreateSubobject(subobjKind, VD->getName(), initListExpr->getInits(), initListExpr->getNumInits(), hgType);
  2228. } catch (hlsl::Exception&) {
  2229. DiagnosticsEngine &Diags = CGM.getDiags();
  2230. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "internal error creating subobject");
  2231. Diags.Report(initExpr->getLocStart(), DiagID);
  2232. return;
  2233. }
  2234. }
  2235. else {
  2236. DiagnosticsEngine &Diags = CGM.getDiags();
  2237. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "expected initialization list");
  2238. Diags.Report(initExpr->getLocStart(), DiagID);
  2239. return;
  2240. }
  2241. }
  2242. // TODO: collect such helper utility functions in one place.
  2243. static DxilResourceBase::Class KeywordToClass(const std::string &keyword) {
  2244. // TODO: refactor for faster search (switch by 1/2/3 first letters, then
  2245. // compare)
  2246. if (keyword == "SamplerState")
  2247. return DxilResourceBase::Class::Sampler;
  2248. if (keyword == "SamplerComparisonState")
  2249. return DxilResourceBase::Class::Sampler;
  2250. if (keyword == "ConstantBuffer")
  2251. return DxilResourceBase::Class::CBuffer;
  2252. if (keyword == "TextureBuffer")
  2253. return DxilResourceBase::Class::SRV;
  2254. bool isSRV = keyword == "Buffer";
  2255. isSRV |= keyword == "ByteAddressBuffer";
  2256. isSRV |= keyword == "RaytracingAccelerationStructure";
  2257. isSRV |= keyword == "StructuredBuffer";
  2258. isSRV |= keyword == "Texture1D";
  2259. isSRV |= keyword == "Texture1DArray";
  2260. isSRV |= keyword == "Texture2D";
  2261. isSRV |= keyword == "Texture2DArray";
  2262. isSRV |= keyword == "Texture3D";
  2263. isSRV |= keyword == "TextureCube";
  2264. isSRV |= keyword == "TextureCubeArray";
  2265. isSRV |= keyword == "Texture2DMS";
  2266. isSRV |= keyword == "Texture2DMSArray";
  2267. if (isSRV)
  2268. return DxilResourceBase::Class::SRV;
  2269. bool isUAV = keyword == "RWBuffer";
  2270. isUAV |= keyword == "RWByteAddressBuffer";
  2271. isUAV |= keyword == "RWStructuredBuffer";
  2272. isUAV |= keyword == "RWTexture1D";
  2273. isUAV |= keyword == "RWTexture1DArray";
  2274. isUAV |= keyword == "RWTexture2D";
  2275. isUAV |= keyword == "RWTexture2DArray";
  2276. isUAV |= keyword == "RWTexture3D";
  2277. isUAV |= keyword == "RWTextureCube";
  2278. isUAV |= keyword == "RWTextureCubeArray";
  2279. isUAV |= keyword == "RWTexture2DMS";
  2280. isUAV |= keyword == "RWTexture2DMSArray";
  2281. isUAV |= keyword == "AppendStructuredBuffer";
  2282. isUAV |= keyword == "ConsumeStructuredBuffer";
  2283. isUAV |= keyword == "RasterizerOrderedBuffer";
  2284. isUAV |= keyword == "RasterizerOrderedByteAddressBuffer";
  2285. isUAV |= keyword == "RasterizerOrderedStructuredBuffer";
  2286. isUAV |= keyword == "RasterizerOrderedTexture1D";
  2287. isUAV |= keyword == "RasterizerOrderedTexture1DArray";
  2288. isUAV |= keyword == "RasterizerOrderedTexture2D";
  2289. isUAV |= keyword == "RasterizerOrderedTexture2DArray";
  2290. isUAV |= keyword == "RasterizerOrderedTexture3D";
  2291. isUAV |= keyword == "FeedbackTexture2D";
  2292. isUAV |= keyword == "FeedbackTexture2DArray";
  2293. if (isUAV)
  2294. return DxilResourceBase::Class::UAV;
  2295. return DxilResourceBase::Class::Invalid;
  2296. }
  2297. // This should probably be refactored to ASTContextHLSL, and follow types
  2298. // rather than do string comparisons.
  2299. DXIL::ResourceClass
  2300. hlsl::GetResourceClassForType(const clang::ASTContext &context,
  2301. clang::QualType Ty) {
  2302. Ty = Ty.getCanonicalType();
  2303. if (const clang::ArrayType *arrayType = context.getAsArrayType(Ty)) {
  2304. return GetResourceClassForType(context, arrayType->getElementType());
  2305. } else if (const RecordType *RT = Ty->getAsStructureType()) {
  2306. return KeywordToClass(RT->getDecl()->getName());
  2307. } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
  2308. if (const ClassTemplateSpecializationDecl *templateDecl =
  2309. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl())) {
  2310. return KeywordToClass(templateDecl->getName());
  2311. }
  2312. }
  2313. return hlsl::DxilResourceBase::Class::Invalid;
  2314. }
  2315. hlsl::DxilResourceBase::Class CGMSHLSLRuntime::TypeToClass(clang::QualType Ty) {
  2316. return hlsl::GetResourceClassForType(CGM.getContext(), Ty);
  2317. }
  2318. namespace {
  2319. void GetResourceDeclElemTypeAndRangeSize(CodeGenModule &CGM, HLModule &HL, VarDecl &VD,
  2320. QualType &ElemType, unsigned& rangeSize) {
  2321. // We can't canonicalize nor desugar the type without losing the 'snorm' in Buffer<snorm float>
  2322. ElemType = VD.getType();
  2323. rangeSize = 1;
  2324. while (const clang::ArrayType *arrayType = CGM.getContext().getAsArrayType(ElemType)) {
  2325. if (rangeSize != UINT_MAX) {
  2326. if (arrayType->isConstantArrayType()) {
  2327. rangeSize *= cast<ConstantArrayType>(arrayType)->getSize().getLimitedValue();
  2328. }
  2329. else {
  2330. if (HL.GetHLOptions().bLegacyResourceReservation) {
  2331. DiagnosticsEngine &Diags = CGM.getDiags();
  2332. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2333. "unbounded resources are not supported with -flegacy-resource-reservation");
  2334. Diags.Report(VD.getLocation(), DiagID);
  2335. }
  2336. rangeSize = UINT_MAX;
  2337. }
  2338. }
  2339. ElemType = arrayType->getElementType();
  2340. }
  2341. }
  2342. }
  2343. static void InitFromUnusualAnnotations(DxilResourceBase &Resource, NamedDecl &Decl) {
  2344. for (hlsl::UnusualAnnotation* It : Decl.getUnusualAnnotations()) {
  2345. switch (It->getKind()) {
  2346. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  2347. hlsl::RegisterAssignment* RegAssign = cast<hlsl::RegisterAssignment>(It);
  2348. if (RegAssign->RegisterType) {
  2349. Resource.SetLowerBound(RegAssign->RegisterNumber);
  2350. // For backcompat, don't auto-assign the register space if there's an
  2351. // explicit register type.
  2352. Resource.SetSpaceID(RegAssign->RegisterSpace.getValueOr(0));
  2353. }
  2354. else {
  2355. Resource.SetSpaceID(RegAssign->RegisterSpace.getValueOr(UINT_MAX));
  2356. }
  2357. break;
  2358. }
  2359. case hlsl::UnusualAnnotation::UA_SemanticDecl:
  2360. // Ignore Semantics
  2361. break;
  2362. case hlsl::UnusualAnnotation::UA_ConstantPacking:
  2363. // Should be handled by front-end
  2364. llvm_unreachable("packoffset on resource");
  2365. break;
  2366. default:
  2367. llvm_unreachable("unknown UnusualAnnotation on resource");
  2368. break;
  2369. }
  2370. }
  2371. }
  2372. uint32_t CGMSHLSLRuntime::AddSampler(VarDecl *samplerDecl) {
  2373. llvm::GlobalVariable *val =
  2374. cast<llvm::GlobalVariable>(CGM.GetAddrOfGlobalVar(samplerDecl));
  2375. unique_ptr<DxilSampler> hlslRes(new DxilSampler);
  2376. hlslRes->SetLowerBound(UINT_MAX);
  2377. hlslRes->SetSpaceID(UINT_MAX);
  2378. hlslRes->SetGlobalSymbol(val);
  2379. hlslRes->SetGlobalName(samplerDecl->getName());
  2380. QualType VarTy;
  2381. unsigned rangeSize;
  2382. GetResourceDeclElemTypeAndRangeSize(CGM, *m_pHLModule, *samplerDecl,
  2383. VarTy, rangeSize);
  2384. hlslRes->SetRangeSize(rangeSize);
  2385. const RecordType *RT = VarTy->getAs<RecordType>();
  2386. DxilSampler::SamplerKind kind = KeywordToSamplerKind(RT->getDecl()->getName());
  2387. hlslRes->SetSamplerKind(kind);
  2388. InitFromUnusualAnnotations(*hlslRes, *samplerDecl);
  2389. hlslRes->SetID(m_pHLModule->GetSamplers().size());
  2390. return m_pHLModule->AddSampler(std::move(hlslRes));
  2391. }
  2392. bool CGMSHLSLRuntime::GetAsConstantUInt32(clang::Expr *expr, uint32_t *value) {
  2393. APSInt result;
  2394. if (!expr->EvaluateAsInt(result, CGM.getContext())) {
  2395. DiagnosticsEngine &Diags = CGM.getDiags();
  2396. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2397. "cannot convert to constant unsigned int");
  2398. Diags.Report(expr->getLocStart(), DiagID);
  2399. return false;
  2400. }
  2401. *value = result.getLimitedValue(UINT32_MAX);
  2402. return true;
  2403. }
  2404. bool CGMSHLSLRuntime::GetAsConstantString(clang::Expr *expr, StringRef *value, bool failWhenEmpty /*=false*/) {
  2405. Expr::EvalResult result;
  2406. DiagnosticsEngine &Diags = CGM.getDiags();
  2407. unsigned DiagID = 0;
  2408. if (expr->EvaluateAsRValue(result, CGM.getContext())) {
  2409. if (result.Val.isLValue()) {
  2410. DXASSERT_NOMSG(result.Val.getLValueOffset().isZero());
  2411. DXASSERT_NOMSG(result.Val.getLValueCallIndex() == 0);
  2412. const Expr *evExpr = result.Val.getLValueBase().get<const Expr *>();
  2413. if (const StringLiteral *strLit = dyn_cast<const StringLiteral>(evExpr)) {
  2414. *value = strLit->getBytes();
  2415. if (!failWhenEmpty || !(*value).empty()) {
  2416. return true;
  2417. }
  2418. DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "empty string not expected here");
  2419. }
  2420. }
  2421. }
  2422. if (!DiagID)
  2423. DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "cannot convert to constant string");
  2424. Diags.Report(expr->getLocStart(), DiagID);
  2425. return false;
  2426. }
  2427. std::vector<StringRef> CGMSHLSLRuntime::ParseSubobjectExportsAssociations(StringRef exports) {
  2428. std::vector<StringRef> parsedExports;
  2429. const char *pData = exports.data();
  2430. const char *pEnd = pData + exports.size();
  2431. const char *pLast = pData;
  2432. while (pData < pEnd) {
  2433. if (*pData == ';') {
  2434. if (pLast < pData) {
  2435. parsedExports.emplace_back(StringRef(pLast, pData - pLast));
  2436. }
  2437. pLast = pData + 1;
  2438. }
  2439. pData++;
  2440. }
  2441. if (pLast < pData) {
  2442. parsedExports.emplace_back(StringRef(pLast, pData - pLast));
  2443. }
  2444. return parsedExports;
  2445. }
  2446. void CGMSHLSLRuntime::CreateSubobject(DXIL::SubobjectKind kind, const StringRef name,
  2447. clang::Expr **args, unsigned int argCount,
  2448. DXIL::HitGroupType hgType /*= (DXIL::HitGroupType)(-1)*/) {
  2449. DxilSubobjects *subobjects = m_pHLModule->GetSubobjects();
  2450. if (!subobjects) {
  2451. subobjects = new DxilSubobjects();
  2452. m_pHLModule->ResetSubobjects(subobjects);
  2453. }
  2454. DxilRootSignatureCompilationFlags flags = DxilRootSignatureCompilationFlags::GlobalRootSignature;
  2455. switch (kind) {
  2456. case DXIL::SubobjectKind::StateObjectConfig: {
  2457. uint32_t flags;
  2458. DXASSERT_NOMSG(argCount == 1);
  2459. if (GetAsConstantUInt32(args[0], &flags)) {
  2460. subobjects->CreateStateObjectConfig(name, flags);
  2461. }
  2462. break;
  2463. }
  2464. case DXIL::SubobjectKind::LocalRootSignature:
  2465. flags = DxilRootSignatureCompilationFlags::LocalRootSignature;
  2466. __fallthrough;
  2467. case DXIL::SubobjectKind::GlobalRootSignature: {
  2468. DXASSERT_NOMSG(argCount == 1);
  2469. StringRef signature;
  2470. if (!GetAsConstantString(args[0], &signature, true))
  2471. return;
  2472. RootSignatureHandle RootSigHandle;
  2473. CompileRootSignature(signature, CGM.getDiags(), args[0]->getLocStart(), rootSigVer, flags, &RootSigHandle);
  2474. if (!RootSigHandle.IsEmpty()) {
  2475. RootSigHandle.EnsureSerializedAvailable();
  2476. subobjects->CreateRootSignature(name, kind == DXIL::SubobjectKind::LocalRootSignature,
  2477. RootSigHandle.GetSerializedBytes(), RootSigHandle.GetSerializedSize(), &signature);
  2478. }
  2479. break;
  2480. }
  2481. case DXIL::SubobjectKind::SubobjectToExportsAssociation: {
  2482. DXASSERT_NOMSG(argCount == 2);
  2483. StringRef subObjName, exports;
  2484. if (!GetAsConstantString(args[0], &subObjName, true) ||
  2485. !GetAsConstantString(args[1], &exports, false))
  2486. return;
  2487. std::vector<StringRef> exportList = ParseSubobjectExportsAssociations(exports);
  2488. subobjects->CreateSubobjectToExportsAssociation(name, subObjName, exportList.data(), exportList.size());
  2489. break;
  2490. }
  2491. case DXIL::SubobjectKind::RaytracingShaderConfig: {
  2492. DXASSERT_NOMSG(argCount == 2);
  2493. uint32_t maxPayloadSize;
  2494. uint32_t MaxAttributeSize;
  2495. if (!GetAsConstantUInt32(args[0], &maxPayloadSize) ||
  2496. !GetAsConstantUInt32(args[1], &MaxAttributeSize))
  2497. return;
  2498. subobjects->CreateRaytracingShaderConfig(name, maxPayloadSize, MaxAttributeSize);
  2499. break;
  2500. }
  2501. case DXIL::SubobjectKind::RaytracingPipelineConfig: {
  2502. DXASSERT_NOMSG(argCount == 1);
  2503. uint32_t maxTraceRecursionDepth;
  2504. if (!GetAsConstantUInt32(args[0], &maxTraceRecursionDepth))
  2505. return;
  2506. subobjects->CreateRaytracingPipelineConfig(name, maxTraceRecursionDepth);
  2507. break;
  2508. }
  2509. case DXIL::SubobjectKind::HitGroup: {
  2510. switch (hgType) {
  2511. case DXIL::HitGroupType::Triangle: {
  2512. DXASSERT_NOMSG(argCount == 2);
  2513. StringRef anyhit, closesthit;
  2514. if (!GetAsConstantString(args[0], &anyhit) ||
  2515. !GetAsConstantString(args[1], &closesthit))
  2516. return;
  2517. subobjects->CreateHitGroup(name, DXIL::HitGroupType::Triangle, anyhit, closesthit, llvm::StringRef(""));
  2518. break;
  2519. }
  2520. case DXIL::HitGroupType::ProceduralPrimitive: {
  2521. DXASSERT_NOMSG(argCount == 3);
  2522. StringRef anyhit, closesthit, intersection;
  2523. if (!GetAsConstantString(args[0], &anyhit) ||
  2524. !GetAsConstantString(args[1], &closesthit) ||
  2525. !GetAsConstantString(args[2], &intersection, true))
  2526. return;
  2527. subobjects->CreateHitGroup(name, DXIL::HitGroupType::ProceduralPrimitive, anyhit, closesthit, intersection);
  2528. break;
  2529. }
  2530. default:
  2531. llvm_unreachable("unknown HitGroupType");
  2532. }
  2533. break;
  2534. }
  2535. case DXIL::SubobjectKind::RaytracingPipelineConfig1: {
  2536. DXASSERT_NOMSG(argCount == 2);
  2537. uint32_t maxTraceRecursionDepth;
  2538. uint32_t raytracingPipelineFlags;
  2539. if (!GetAsConstantUInt32(args[0], &maxTraceRecursionDepth))
  2540. return;
  2541. if (!GetAsConstantUInt32(args[1], &raytracingPipelineFlags))
  2542. return;
  2543. subobjects->CreateRaytracingPipelineConfig1(name, maxTraceRecursionDepth, raytracingPipelineFlags);
  2544. break;
  2545. }
  2546. default:
  2547. llvm_unreachable("unknown SubobjectKind");
  2548. break;
  2549. }
  2550. }
  2551. static void CollectScalarTypes(std::vector<QualType> &ScalarTys, QualType Ty) {
  2552. if (Ty->isRecordType()) {
  2553. if (hlsl::IsHLSLMatType(Ty)) {
  2554. QualType EltTy = hlsl::GetHLSLMatElementType(Ty);
  2555. unsigned row = 0;
  2556. unsigned col = 0;
  2557. hlsl::GetRowsAndCols(Ty, row, col);
  2558. unsigned size = col*row;
  2559. for (unsigned i = 0; i < size; i++) {
  2560. CollectScalarTypes(ScalarTys, EltTy);
  2561. }
  2562. } else if (hlsl::IsHLSLVecType(Ty)) {
  2563. QualType EltTy = hlsl::GetHLSLVecElementType(Ty);
  2564. unsigned row = 0;
  2565. unsigned col = 0;
  2566. hlsl::GetRowsAndColsForAny(Ty, row, col);
  2567. unsigned size = col;
  2568. for (unsigned i = 0; i < size; i++) {
  2569. CollectScalarTypes(ScalarTys, EltTy);
  2570. }
  2571. } else {
  2572. const RecordType *RT = Ty->getAsStructureType();
  2573. // For CXXRecord.
  2574. if (!RT)
  2575. RT = Ty->getAs<RecordType>();
  2576. RecordDecl *RD = RT->getDecl();
  2577. for (FieldDecl *field : RD->fields())
  2578. CollectScalarTypes(ScalarTys, field->getType());
  2579. }
  2580. } else if (Ty->isArrayType()) {
  2581. const clang::ArrayType *AT = Ty->getAsArrayTypeUnsafe();
  2582. QualType EltTy = AT->getElementType();
  2583. // Set it to 5 for unsized array.
  2584. unsigned size = 5;
  2585. if (AT->isConstantArrayType()) {
  2586. size = cast<ConstantArrayType>(AT)->getSize().getLimitedValue();
  2587. }
  2588. for (unsigned i=0;i<size;i++) {
  2589. CollectScalarTypes(ScalarTys, EltTy);
  2590. }
  2591. } else {
  2592. ScalarTys.emplace_back(Ty);
  2593. }
  2594. }
  2595. bool CGMSHLSLRuntime::SetUAVSRV(SourceLocation loc,
  2596. hlsl::DxilResourceBase::Class resClass,
  2597. DxilResource *hlslRes, QualType QualTy) {
  2598. RecordDecl *RD = QualTy->getAs<RecordType>()->getDecl();
  2599. hlsl::DxilResource::Kind kind = KeywordToKind(RD->getName());
  2600. DXASSERT_NOMSG(kind != hlsl::DxilResource::Kind::Invalid);
  2601. hlslRes->SetKind(kind);
  2602. // Type annotation for result type of resource.
  2603. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  2604. unsigned arrayEltSize = 0;
  2605. AddTypeAnnotation(QualType(RD->getTypeForDecl(),0), dxilTypeSys, arrayEltSize);
  2606. if (kind == hlsl::DxilResource::Kind::Texture2DMS ||
  2607. kind == hlsl::DxilResource::Kind::Texture2DMSArray) {
  2608. const ClassTemplateSpecializationDecl *templateDecl =
  2609. cast<ClassTemplateSpecializationDecl>(RD);
  2610. const clang::TemplateArgument &sampleCountArg =
  2611. templateDecl->getTemplateArgs()[1];
  2612. uint32_t sampleCount = sampleCountArg.getAsIntegral().getLimitedValue();
  2613. hlslRes->SetSampleCount(sampleCount);
  2614. }
  2615. if (hlsl::DxilResource::IsAnyTexture(kind)) {
  2616. const ClassTemplateSpecializationDecl *templateDecl = cast<ClassTemplateSpecializationDecl>(RD);
  2617. const clang::TemplateArgument &texelTyArg = templateDecl->getTemplateArgs()[0];
  2618. llvm::Type *texelTy = CGM.getTypes().ConvertType(texelTyArg.getAsType());
  2619. if (!texelTy->isFloatingPointTy() && !texelTy->isIntegerTy()
  2620. && !hlsl::IsHLSLVecType(texelTyArg.getAsType())) {
  2621. DiagnosticsEngine &Diags = CGM.getDiags();
  2622. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2623. "texture resource texel type must be scalar or vector");
  2624. Diags.Report(loc, DiagID);
  2625. return false;
  2626. }
  2627. }
  2628. QualType resultTy = hlsl::GetHLSLResourceResultType(QualTy);
  2629. if (kind != hlsl::DxilResource::Kind::StructuredBuffer && !resultTy.isNull()) {
  2630. QualType Ty = resultTy;
  2631. QualType EltTy = Ty;
  2632. if (hlsl::IsHLSLVecType(Ty)) {
  2633. EltTy = hlsl::GetHLSLVecElementType(Ty);
  2634. } else if (hlsl::IsHLSLMatType(Ty)) {
  2635. EltTy = hlsl::GetHLSLMatElementType(Ty);
  2636. } else if (hlsl::IsHLSLAggregateType(resultTy)) {
  2637. // Struct or array in a none-struct resource.
  2638. std::vector<QualType> ScalarTys;
  2639. CollectScalarTypes(ScalarTys, resultTy);
  2640. unsigned size = ScalarTys.size();
  2641. if (size == 0) {
  2642. DiagnosticsEngine &Diags = CGM.getDiags();
  2643. unsigned DiagID = Diags.getCustomDiagID(
  2644. DiagnosticsEngine::Error,
  2645. "object's templated type must have at least one element");
  2646. Diags.Report(loc, DiagID);
  2647. return false;
  2648. }
  2649. if (size > 4) {
  2650. DiagnosticsEngine &Diags = CGM.getDiags();
  2651. unsigned DiagID = Diags.getCustomDiagID(
  2652. DiagnosticsEngine::Error, "elements of typed buffers and textures "
  2653. "must fit in four 32-bit quantities");
  2654. Diags.Report(loc, DiagID);
  2655. return false;
  2656. }
  2657. EltTy = ScalarTys[0];
  2658. for (QualType ScalarTy : ScalarTys) {
  2659. if (ScalarTy != EltTy) {
  2660. DiagnosticsEngine &Diags = CGM.getDiags();
  2661. unsigned DiagID = Diags.getCustomDiagID(
  2662. DiagnosticsEngine::Error,
  2663. "all template type components must have the same type");
  2664. Diags.Report(loc, DiagID);
  2665. return false;
  2666. }
  2667. }
  2668. }
  2669. bool bSNorm = false;
  2670. bool bHasNormAttribute = hlsl::HasHLSLUNormSNorm(Ty, &bSNorm);
  2671. if (const BuiltinType *BTy = EltTy->getAs<BuiltinType>()) {
  2672. CompType::Kind kind = BuiltinTyToCompTy(BTy, bHasNormAttribute && bSNorm, bHasNormAttribute && !bSNorm);
  2673. // 64bits types are implemented with u32.
  2674. if (kind == CompType::Kind::U64 || kind == CompType::Kind::I64 ||
  2675. kind == CompType::Kind::SNormF64 ||
  2676. kind == CompType::Kind::UNormF64 || kind == CompType::Kind::F64) {
  2677. kind = CompType::Kind::U32;
  2678. }
  2679. hlslRes->SetCompType(kind);
  2680. } else {
  2681. DXASSERT(!bHasNormAttribute, "snorm/unorm on invalid type");
  2682. }
  2683. }
  2684. if (hlslRes->IsFeedbackTexture()) {
  2685. hlslRes->SetSamplerFeedbackType(
  2686. static_cast<DXIL::SamplerFeedbackType>(hlsl::GetHLSLResourceTemplateUInt(QualTy)));
  2687. }
  2688. hlslRes->SetROV(RD->getName().startswith("RasterizerOrdered"));
  2689. if (kind == hlsl::DxilResource::Kind::TypedBuffer ||
  2690. kind == hlsl::DxilResource::Kind::StructuredBuffer) {
  2691. const ClassTemplateSpecializationDecl *templateDecl =
  2692. cast<ClassTemplateSpecializationDecl>(RD);
  2693. const clang::TemplateArgument &retTyArg =
  2694. templateDecl->getTemplateArgs()[0];
  2695. llvm::Type *retTy = CGM.getTypes().ConvertType(retTyArg.getAsType());
  2696. uint32_t strideInBytes = dataLayout.getTypeAllocSize(retTy);
  2697. hlslRes->SetElementStride(strideInBytes);
  2698. }
  2699. if (HasHLSLGloballyCoherent(QualTy)) {
  2700. hlslRes->SetGloballyCoherent(true);
  2701. }
  2702. if (resClass == hlsl::DxilResourceBase::Class::SRV) {
  2703. if (hlslRes->IsGloballyCoherent()) {
  2704. DiagnosticsEngine &Diags = CGM.getDiags();
  2705. unsigned DiagID = Diags.getCustomDiagID(
  2706. DiagnosticsEngine::Error, "globallycoherent can only be used with "
  2707. "Unordered Access View buffers.");
  2708. Diags.Report(loc, DiagID);
  2709. return false;
  2710. }
  2711. hlslRes->SetRW(false);
  2712. hlslRes->SetID(m_pHLModule->GetSRVs().size());
  2713. } else {
  2714. hlslRes->SetRW(true);
  2715. hlslRes->SetID(m_pHLModule->GetUAVs().size());
  2716. }
  2717. return true;
  2718. }
  2719. uint32_t CGMSHLSLRuntime::AddUAVSRV(VarDecl *decl,
  2720. hlsl::DxilResourceBase::Class resClass) {
  2721. llvm::GlobalVariable *val =
  2722. cast<llvm::GlobalVariable>(CGM.GetAddrOfGlobalVar(decl));
  2723. unique_ptr<HLResource> hlslRes(new HLResource);
  2724. hlslRes->SetLowerBound(UINT_MAX);
  2725. hlslRes->SetSpaceID(UINT_MAX);
  2726. hlslRes->SetGlobalSymbol(val);
  2727. hlslRes->SetGlobalName(decl->getName());
  2728. QualType VarTy;
  2729. unsigned rangeSize;
  2730. GetResourceDeclElemTypeAndRangeSize(CGM, *m_pHLModule, *decl,
  2731. VarTy, rangeSize);
  2732. hlslRes->SetRangeSize(rangeSize);
  2733. InitFromUnusualAnnotations(*hlslRes, *decl);
  2734. if (decl->hasAttr<HLSLGloballyCoherentAttr>()) {
  2735. hlslRes->SetGloballyCoherent(true);
  2736. }
  2737. if (!SetUAVSRV(decl->getLocation(), resClass, hlslRes.get(), VarTy))
  2738. return 0;
  2739. if (resClass == hlsl::DxilResourceBase::Class::SRV) {
  2740. return m_pHLModule->AddSRV(std::move(hlslRes));
  2741. } else {
  2742. return m_pHLModule->AddUAV(std::move(hlslRes));
  2743. }
  2744. }
  2745. static bool IsResourceInType(const clang::ASTContext &context,
  2746. clang::QualType Ty) {
  2747. Ty = Ty.getCanonicalType();
  2748. if (const clang::ArrayType *arrayType = context.getAsArrayType(Ty)) {
  2749. return IsResourceInType(context, arrayType->getElementType());
  2750. } else if (const RecordType *RT = Ty->getAsStructureType()) {
  2751. if (KeywordToClass(RT->getDecl()->getName()) != DxilResourceBase::Class::Invalid)
  2752. return true;
  2753. const CXXRecordDecl* typeRecordDecl = RT->getAsCXXRecordDecl();
  2754. if (typeRecordDecl && !typeRecordDecl->isImplicit()) {
  2755. for (auto field : typeRecordDecl->fields()) {
  2756. if (IsResourceInType(context, field->getType()))
  2757. return true;
  2758. }
  2759. }
  2760. } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
  2761. if (const ClassTemplateSpecializationDecl *templateDecl =
  2762. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl())) {
  2763. if (KeywordToClass(templateDecl->getName()) != DxilResourceBase::Class::Invalid)
  2764. return true;
  2765. }
  2766. }
  2767. return false; // no resources found
  2768. }
  2769. void CGMSHLSLRuntime::AddConstant(VarDecl *constDecl, HLCBuffer &CB) {
  2770. if (constDecl->getStorageClass() == SC_Static) {
  2771. // For static inside cbuffer, take as global static.
  2772. // Don't add to cbuffer.
  2773. CGM.EmitGlobal(constDecl);
  2774. // Add type annotation for static global types.
  2775. // May need it when cast from cbuf.
  2776. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  2777. unsigned arraySize = 0;
  2778. AddTypeAnnotation(constDecl->getType(), dxilTypeSys, arraySize);
  2779. return;
  2780. }
  2781. // Search defined structure for resource objects and fail
  2782. if (CB.GetRangeSize() > 1 &&
  2783. IsResourceInType(CGM.getContext(), constDecl->getType())) {
  2784. DiagnosticsEngine &Diags = CGM.getDiags();
  2785. unsigned DiagID = Diags.getCustomDiagID(
  2786. DiagnosticsEngine::Error,
  2787. "object types not supported in cbuffer/tbuffer view arrays.");
  2788. Diags.Report(constDecl->getLocation(), DiagID);
  2789. return;
  2790. }
  2791. llvm::Constant *constVal = CGM.GetAddrOfGlobalVar(constDecl);
  2792. // Add debug info for constVal.
  2793. if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
  2794. if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
  2795. DI->EmitGlobalVariable(cast<GlobalVariable>(constVal), constDecl);
  2796. }
  2797. auto &regBindings = constantRegBindingMap[constVal];
  2798. // Save resource properties for cbuffer variables.
  2799. DxilResourceProperties RP = BuildResourceProperty(constDecl->getType());
  2800. if (RP.Class != DXIL::ResourceClass::Invalid)
  2801. valToResPropertiesMap[constVal] = RP;
  2802. bool isGlobalCB = CB.GetID() == globalCBIndex;
  2803. uint32_t offset = 0;
  2804. bool userOffset = false;
  2805. for (hlsl::UnusualAnnotation *it : constDecl->getUnusualAnnotations()) {
  2806. switch (it->getKind()) {
  2807. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  2808. if (!isGlobalCB) {
  2809. // TODO: check cannot mix packoffset elements with nonpackoffset
  2810. // elements in a cbuffer.
  2811. hlsl::ConstantPacking *cp = cast<hlsl::ConstantPacking>(it);
  2812. offset = cp->Subcomponent << 2;
  2813. offset += cp->ComponentOffset;
  2814. // Change to byte.
  2815. offset <<= 2;
  2816. userOffset = true;
  2817. } else {
  2818. DiagnosticsEngine &Diags = CGM.getDiags();
  2819. unsigned DiagID = Diags.getCustomDiagID(
  2820. DiagnosticsEngine::Error,
  2821. "packoffset is only allowed in a constant buffer.");
  2822. Diags.Report(it->Loc, DiagID);
  2823. }
  2824. break;
  2825. }
  2826. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  2827. RegisterAssignment *ra = cast<RegisterAssignment>(it);
  2828. if (isGlobalCB) {
  2829. if (ra->RegisterSpace.hasValue()) {
  2830. DiagnosticsEngine& Diags = CGM.getDiags();
  2831. unsigned DiagID = Diags.getCustomDiagID(
  2832. DiagnosticsEngine::Error,
  2833. "register space cannot be specified on global constants.");
  2834. Diags.Report(it->Loc, DiagID);
  2835. }
  2836. offset = ra->RegisterNumber << 2;
  2837. // Change to byte.
  2838. offset <<= 2;
  2839. userOffset = true;
  2840. }
  2841. switch (ra->RegisterType) {
  2842. default:
  2843. break;
  2844. case 't':
  2845. regBindings.emplace_back(
  2846. std::make_pair(DXIL::ResourceClass::SRV, ra->RegisterNumber));
  2847. break;
  2848. case 'u':
  2849. regBindings.emplace_back(
  2850. std::make_pair(DXIL::ResourceClass::UAV, ra->RegisterNumber));
  2851. break;
  2852. case 's':
  2853. regBindings.emplace_back(
  2854. std::make_pair(DXIL::ResourceClass::Sampler, ra->RegisterNumber));
  2855. break;
  2856. }
  2857. break;
  2858. }
  2859. case hlsl::UnusualAnnotation::UA_SemanticDecl:
  2860. // skip semantic on constant
  2861. break;
  2862. }
  2863. }
  2864. std::unique_ptr<DxilResourceBase> pHlslConst = llvm::make_unique<DxilResourceBase>(DXIL::ResourceClass::Invalid);
  2865. pHlslConst->SetLowerBound(UINT_MAX);
  2866. pHlslConst->SetSpaceID(0);
  2867. pHlslConst->SetGlobalSymbol(cast<llvm::GlobalVariable>(constVal));
  2868. pHlslConst->SetGlobalName(constDecl->getName());
  2869. if (userOffset) {
  2870. pHlslConst->SetLowerBound(offset);
  2871. }
  2872. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  2873. // Just add type annotation here.
  2874. // Offset will be allocated later.
  2875. QualType Ty = constDecl->getType();
  2876. if (CB.GetRangeSize() != 1) {
  2877. while (Ty->isArrayType()) {
  2878. Ty = Ty->getAsArrayTypeUnsafe()->getElementType();
  2879. }
  2880. }
  2881. unsigned arrayEltSize = 0;
  2882. unsigned size = AddTypeAnnotation(Ty, dxilTypeSys, arrayEltSize);
  2883. pHlslConst->SetRangeSize(size);
  2884. CB.AddConst(pHlslConst);
  2885. // Save fieldAnnotation for the const var.
  2886. DxilFieldAnnotation fieldAnnotation;
  2887. if (userOffset)
  2888. fieldAnnotation.SetCBufferOffset(offset);
  2889. // Get the nested element type.
  2890. if (Ty->isArrayType()) {
  2891. while (const ConstantArrayType *arrayTy =
  2892. CGM.getContext().getAsConstantArrayType(Ty)) {
  2893. Ty = arrayTy->getElementType();
  2894. }
  2895. }
  2896. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  2897. ConstructFieldAttributedAnnotation(fieldAnnotation, Ty, bDefaultRowMajor);
  2898. m_ConstVarAnnotationMap[constVal] = fieldAnnotation;
  2899. }
  2900. uint32_t CGMSHLSLRuntime::AddCBuffer(HLSLBufferDecl *D) {
  2901. unique_ptr<HLCBuffer> CB = llvm::make_unique<HLCBuffer>();
  2902. // setup the CB
  2903. CB->SetGlobalSymbol(nullptr);
  2904. CB->SetGlobalName(D->getNameAsString());
  2905. CB->SetSpaceID(UINT_MAX);
  2906. CB->SetLowerBound(UINT_MAX);
  2907. if (!D->isCBuffer()) {
  2908. CB->SetKind(DXIL::ResourceKind::TBuffer);
  2909. }
  2910. // the global variable will only used once by the createHandle?
  2911. // SetHandle(llvm::Value *pHandle);
  2912. InitFromUnusualAnnotations(*CB, *D);
  2913. // Add constant
  2914. if (D->isConstantBufferView()) {
  2915. VarDecl *constDecl = cast<VarDecl>(*D->decls_begin());
  2916. CB->SetRangeSize(1);
  2917. QualType Ty = constDecl->getType();
  2918. if (Ty->isArrayType()) {
  2919. if (!Ty->isIncompleteArrayType()) {
  2920. unsigned arraySize = 1;
  2921. while (Ty->isArrayType()) {
  2922. Ty = Ty->getCanonicalTypeUnqualified();
  2923. const ConstantArrayType *AT = cast<ConstantArrayType>(Ty);
  2924. arraySize *= AT->getSize().getLimitedValue();
  2925. Ty = AT->getElementType();
  2926. }
  2927. CB->SetRangeSize(arraySize);
  2928. } else {
  2929. CB->SetRangeSize(UINT_MAX);
  2930. }
  2931. }
  2932. AddConstant(constDecl, *CB.get());
  2933. } else {
  2934. auto declsEnds = D->decls_end();
  2935. CB->SetRangeSize(1);
  2936. for (auto it = D->decls_begin(); it != declsEnds; it++) {
  2937. if (VarDecl *constDecl = dyn_cast<VarDecl>(*it)) {
  2938. AddConstant(constDecl, *CB.get());
  2939. } else if (isa<EmptyDecl>(*it)) {
  2940. // Nothing to do for this declaration.
  2941. } else if (isa<CXXRecordDecl>(*it)) {
  2942. // Nothing to do for this declaration.
  2943. } else if (isa<FunctionDecl>(*it)) {
  2944. // A function within an cbuffer is effectively a top-level function,
  2945. // as it only refers to globally scoped declarations.
  2946. this->CGM.EmitTopLevelDecl(*it);
  2947. } else {
  2948. HLSLBufferDecl *inner = cast<HLSLBufferDecl>(*it);
  2949. GetOrCreateCBuffer(inner);
  2950. }
  2951. }
  2952. }
  2953. CB->SetID(m_pHLModule->GetCBuffers().size());
  2954. return m_pHLModule->AddCBuffer(std::move(CB));
  2955. }
  2956. HLCBuffer &CGMSHLSLRuntime::GetOrCreateCBuffer(HLSLBufferDecl *D) {
  2957. if (constantBufMap.count(D) != 0) {
  2958. uint32_t cbIndex = constantBufMap[D];
  2959. return *static_cast<HLCBuffer*>(&(m_pHLModule->GetCBuffer(cbIndex)));
  2960. }
  2961. uint32_t cbID = AddCBuffer(D);
  2962. constantBufMap[D] = cbID;
  2963. return *static_cast<HLCBuffer*>(&(m_pHLModule->GetCBuffer(cbID)));
  2964. }
  2965. void CGMSHLSLRuntime::FinishCodeGen() {
  2966. HLModule &HLM = *m_pHLModule;
  2967. llvm::Module &M = TheModule;
  2968. // Do this before CloneShaderEntry and TranslateRayQueryConstructor to avoid
  2969. // update valToResPropertiesMap for cloned inst.
  2970. FinishIntrinsics(HLM, m_IntrinsicMap, valToResPropertiesMap);
  2971. bool bWaveEnabledStage = m_pHLModule->GetShaderModel()->IsPS() ||
  2972. m_pHLModule->GetShaderModel()->IsCS() ||
  2973. m_pHLModule->GetShaderModel()->IsLib();
  2974. // Handle lang extensions if provided.
  2975. if (CGM.getCodeGenOpts().HLSLExtensionsCodegen) {
  2976. ExtensionCodeGen(HLM, CGM);
  2977. }
  2978. StructurizeMultiRet(M, CGM, m_ScopeMap, bWaveEnabledStage, m_DxBreaks);
  2979. FinishEntries(HLM, Entry, CGM, entryFunctionMap, HSEntryPatchConstantFuncAttr,
  2980. patchConstantFunctionMap, patchConstantFunctionPropsMap);
  2981. ReplaceConstStaticGlobals(staticConstGlobalInitListMap,
  2982. staticConstGlobalCtorMap);
  2983. // Create copy for clip plane.
  2984. if (!clipPlaneFuncList.empty()) {
  2985. FinishClipPlane(HLM, clipPlaneFuncList, debugInfoMap, CGM);
  2986. }
  2987. // Add Reg bindings for resource in cb.
  2988. AddRegBindingsForResourceInConstantBuffer(HLM, constantRegBindingMap);
  2989. // Allocate constant buffers.
  2990. // Create Global variable and type annotation for each CBuffer.
  2991. FinishCBuffer(HLM, CBufferType, m_ConstVarAnnotationMap);
  2992. // Translate calls to RayQuery constructor into hl Allocate calls
  2993. TranslateRayQueryConstructor(HLM);
  2994. bool bIsLib = HLM.GetShaderModel()->IsLib();
  2995. if (!bIsLib) {
  2996. // need this for "llvm.global_dtors"?
  2997. ProcessCtorFunctions(M, "llvm.global_ctors",
  2998. Entry.Func->getEntryBlock().getFirstInsertionPt());
  2999. }
  3000. UpdateLinkage(HLM, CGM, m_ExportMap, entryFunctionMap,
  3001. patchConstantFunctionMap);
  3002. // Do simple transform to make later lower pass easier.
  3003. SimpleTransformForHLDXIR(&M);
  3004. // Add dx.break function and make appropriate breaks conditional on it.
  3005. AddDxBreak(M, m_DxBreaks);
  3006. // At this point, we have a high-level DXIL module - record this.
  3007. SetPauseResumePasses(*m_pHLModule->GetModule(), "hlsl-hlemit",
  3008. "hlsl-hlensure");
  3009. }
  3010. RValue CGMSHLSLRuntime::EmitHLSLBuiltinCallExpr(CodeGenFunction &CGF,
  3011. const FunctionDecl *FD,
  3012. const CallExpr *E,
  3013. ReturnValueSlot ReturnValue) {
  3014. const Decl *TargetDecl = E->getCalleeDecl();
  3015. llvm::Value *Callee = CGF.EmitScalarExpr(E->getCallee());
  3016. RValue RV = CGF.EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue,
  3017. TargetDecl);
  3018. if (RV.isScalar() && RV.getScalarVal() != nullptr) {
  3019. if (CallInst *CI = dyn_cast<CallInst>(RV.getScalarVal())) {
  3020. Function *F = CI->getCalledFunction();
  3021. HLOpcodeGroup group = hlsl::GetHLOpcodeGroup(F);
  3022. if (group == HLOpcodeGroup::HLIntrinsic) {
  3023. bool allOperandImm = true;
  3024. for (auto &operand : CI->arg_operands()) {
  3025. bool isImm = isa<ConstantInt>(operand) || isa<ConstantFP>(operand) ||
  3026. isa<ConstantAggregateZero>(operand) || isa<ConstantDataVector>(operand);
  3027. if (!isImm) {
  3028. allOperandImm = false;
  3029. break;
  3030. } else if (operand->getType()->isHalfTy()) {
  3031. // Not support half Eval yet.
  3032. allOperandImm = false;
  3033. break;
  3034. }
  3035. }
  3036. if (allOperandImm) {
  3037. unsigned intrinsicOpcode;
  3038. StringRef intrinsicGroup;
  3039. hlsl::GetIntrinsicOp(FD, intrinsicOpcode, intrinsicGroup);
  3040. IntrinsicOp opcode = static_cast<IntrinsicOp>(intrinsicOpcode);
  3041. if (Value *Result = TryEvalIntrinsic(CI, opcode, CGM.getLangOpts().HLSLVersion)) {
  3042. RV = RValue::get(Result);
  3043. }
  3044. }
  3045. }
  3046. }
  3047. }
  3048. return RV;
  3049. }
  3050. static HLOpcodeGroup GetHLOpcodeGroup(const clang::Stmt::StmtClass stmtClass) {
  3051. switch (stmtClass) {
  3052. case Stmt::CStyleCastExprClass:
  3053. case Stmt::ImplicitCastExprClass:
  3054. case Stmt::CXXFunctionalCastExprClass:
  3055. return HLOpcodeGroup::HLCast;
  3056. case Stmt::InitListExprClass:
  3057. return HLOpcodeGroup::HLInit;
  3058. case Stmt::BinaryOperatorClass:
  3059. case Stmt::CompoundAssignOperatorClass:
  3060. return HLOpcodeGroup::HLBinOp;
  3061. case Stmt::UnaryOperatorClass:
  3062. return HLOpcodeGroup::HLUnOp;
  3063. case Stmt::ExtMatrixElementExprClass:
  3064. return HLOpcodeGroup::HLSubscript;
  3065. case Stmt::CallExprClass:
  3066. return HLOpcodeGroup::HLIntrinsic;
  3067. case Stmt::ConditionalOperatorClass:
  3068. return HLOpcodeGroup::HLSelect;
  3069. default:
  3070. llvm_unreachable("not support operation");
  3071. }
  3072. }
  3073. // NOTE: This table must match BinaryOperator::Opcode
  3074. static const HLBinaryOpcode BinaryOperatorKindMap[] = {
  3075. HLBinaryOpcode::Invalid, // PtrMemD
  3076. HLBinaryOpcode::Invalid, // PtrMemI
  3077. HLBinaryOpcode::Mul, HLBinaryOpcode::Div, HLBinaryOpcode::Rem,
  3078. HLBinaryOpcode::Add, HLBinaryOpcode::Sub, HLBinaryOpcode::Shl,
  3079. HLBinaryOpcode::Shr, HLBinaryOpcode::LT, HLBinaryOpcode::GT,
  3080. HLBinaryOpcode::LE, HLBinaryOpcode::GE, HLBinaryOpcode::EQ,
  3081. HLBinaryOpcode::NE, HLBinaryOpcode::And, HLBinaryOpcode::Xor,
  3082. HLBinaryOpcode::Or, HLBinaryOpcode::LAnd, HLBinaryOpcode::LOr,
  3083. HLBinaryOpcode::Invalid, // Assign,
  3084. // The assign part is done by matrix store
  3085. HLBinaryOpcode::Mul, // MulAssign
  3086. HLBinaryOpcode::Div, // DivAssign
  3087. HLBinaryOpcode::Rem, // RemAssign
  3088. HLBinaryOpcode::Add, // AddAssign
  3089. HLBinaryOpcode::Sub, // SubAssign
  3090. HLBinaryOpcode::Shl, // ShlAssign
  3091. HLBinaryOpcode::Shr, // ShrAssign
  3092. HLBinaryOpcode::And, // AndAssign
  3093. HLBinaryOpcode::Xor, // XorAssign
  3094. HLBinaryOpcode::Or, // OrAssign
  3095. HLBinaryOpcode::Invalid, // Comma
  3096. };
  3097. // NOTE: This table must match UnaryOperator::Opcode
  3098. static const HLUnaryOpcode UnaryOperatorKindMap[] = {
  3099. HLUnaryOpcode::PostInc, HLUnaryOpcode::PostDec,
  3100. HLUnaryOpcode::PreInc, HLUnaryOpcode::PreDec,
  3101. HLUnaryOpcode::Invalid, // AddrOf,
  3102. HLUnaryOpcode::Invalid, // Deref,
  3103. HLUnaryOpcode::Plus, HLUnaryOpcode::Minus,
  3104. HLUnaryOpcode::Not, HLUnaryOpcode::LNot,
  3105. HLUnaryOpcode::Invalid, // Real,
  3106. HLUnaryOpcode::Invalid, // Imag,
  3107. HLUnaryOpcode::Invalid, // Extension
  3108. };
  3109. static unsigned GetHLOpcode(const Expr *E) {
  3110. switch (E->getStmtClass()) {
  3111. case Stmt::CompoundAssignOperatorClass:
  3112. case Stmt::BinaryOperatorClass: {
  3113. const clang::BinaryOperator *binOp = cast<clang::BinaryOperator>(E);
  3114. HLBinaryOpcode binOpcode = BinaryOperatorKindMap[binOp->getOpcode()];
  3115. if (HasUnsignedOpcode(binOpcode)) {
  3116. if (hlsl::IsHLSLUnsigned(binOp->getLHS()->getType())) {
  3117. binOpcode = GetUnsignedOpcode(binOpcode);
  3118. }
  3119. }
  3120. return static_cast<unsigned>(binOpcode);
  3121. }
  3122. case Stmt::UnaryOperatorClass: {
  3123. const UnaryOperator *unOp = cast<clang::UnaryOperator>(E);
  3124. HLUnaryOpcode unOpcode = UnaryOperatorKindMap[unOp->getOpcode()];
  3125. return static_cast<unsigned>(unOpcode);
  3126. }
  3127. case Stmt::ImplicitCastExprClass:
  3128. case Stmt::CStyleCastExprClass: {
  3129. const CastExpr *CE = cast<CastExpr>(E);
  3130. bool toUnsigned = hlsl::IsHLSLUnsigned(E->getType());
  3131. bool fromUnsigned = hlsl::IsHLSLUnsigned(CE->getSubExpr()->getType());
  3132. if (toUnsigned && fromUnsigned)
  3133. return static_cast<unsigned>(HLCastOpcode::UnsignedUnsignedCast);
  3134. else if (toUnsigned)
  3135. return static_cast<unsigned>(HLCastOpcode::ToUnsignedCast);
  3136. else if (fromUnsigned)
  3137. return static_cast<unsigned>(HLCastOpcode::FromUnsignedCast);
  3138. else
  3139. return static_cast<unsigned>(HLCastOpcode::DefaultCast);
  3140. }
  3141. default:
  3142. return 0;
  3143. }
  3144. }
  3145. static Value *
  3146. EmitHLSLMatrixOperationCallImp(CGBuilderTy &Builder, HLOpcodeGroup group,
  3147. unsigned opcode, llvm::Type *RetType,
  3148. ArrayRef<Value *> paramList, llvm::Module &M) {
  3149. SmallVector<llvm::Type *, 4> paramTyList;
  3150. // Add the opcode param
  3151. llvm::Type *opcodeTy = llvm::Type::getInt32Ty(M.getContext());
  3152. paramTyList.emplace_back(opcodeTy);
  3153. for (Value *param : paramList) {
  3154. paramTyList.emplace_back(param->getType());
  3155. }
  3156. llvm::FunctionType *funcTy =
  3157. llvm::FunctionType::get(RetType, paramTyList, false);
  3158. Function *opFunc = GetOrCreateHLFunction(M, funcTy, group, opcode);
  3159. SmallVector<Value *, 4> opcodeParamList;
  3160. Value *opcodeConst = Constant::getIntegerValue(opcodeTy, APInt(32, opcode));
  3161. opcodeParamList.emplace_back(opcodeConst);
  3162. opcodeParamList.append(paramList.begin(), paramList.end());
  3163. return Builder.CreateCall(opFunc, opcodeParamList);
  3164. }
  3165. static Value *EmitHLSLArrayInit(CGBuilderTy &Builder, HLOpcodeGroup group,
  3166. unsigned opcode, llvm::Type *RetType,
  3167. ArrayRef<Value *> paramList, llvm::Module &M) {
  3168. // It's a matrix init.
  3169. if (!RetType->isVoidTy())
  3170. return EmitHLSLMatrixOperationCallImp(Builder, group, opcode, RetType,
  3171. paramList, M);
  3172. Value *arrayPtr = paramList[0];
  3173. llvm::ArrayType *AT =
  3174. cast<llvm::ArrayType>(arrayPtr->getType()->getPointerElementType());
  3175. // Avoid the arrayPtr.
  3176. unsigned paramSize = paramList.size() - 1;
  3177. // Support simple case here.
  3178. if (paramSize == AT->getArrayNumElements()) {
  3179. bool typeMatch = true;
  3180. llvm::Type *EltTy = AT->getArrayElementType();
  3181. if (EltTy->isAggregateType()) {
  3182. // Aggregate Type use pointer in initList.
  3183. EltTy = llvm::PointerType::get(EltTy, 0);
  3184. }
  3185. for (unsigned i = 1; i < paramList.size(); i++) {
  3186. if (paramList[i]->getType() != EltTy) {
  3187. typeMatch = false;
  3188. break;
  3189. }
  3190. }
  3191. // Both size and type match.
  3192. if (typeMatch) {
  3193. bool isPtr = EltTy->isPointerTy();
  3194. llvm::Type *i32Ty = llvm::Type::getInt32Ty(EltTy->getContext());
  3195. Constant *zero = ConstantInt::get(i32Ty, 0);
  3196. for (unsigned i = 1; i < paramList.size(); i++) {
  3197. Constant *idx = ConstantInt::get(i32Ty, i - 1);
  3198. Value *GEP = Builder.CreateInBoundsGEP(arrayPtr, {zero, idx});
  3199. Value *Elt = paramList[i];
  3200. if (isPtr) {
  3201. Elt = Builder.CreateLoad(Elt);
  3202. }
  3203. Builder.CreateStore(Elt, GEP);
  3204. }
  3205. // The return value will not be used.
  3206. return nullptr;
  3207. }
  3208. }
  3209. // Other case will be lowered in later pass.
  3210. return EmitHLSLMatrixOperationCallImp(Builder, group, opcode, RetType,
  3211. paramList, M);
  3212. }
  3213. void CGMSHLSLRuntime::FlattenValToInitList(CodeGenFunction &CGF, SmallVector<Value *, 4> &elts,
  3214. SmallVector<QualType, 4> &eltTys,
  3215. QualType Ty, Value *val) {
  3216. CGBuilderTy &Builder = CGF.Builder;
  3217. llvm::Type *valTy = val->getType();
  3218. if (valTy->isPointerTy()) {
  3219. llvm::Type *valEltTy = valTy->getPointerElementType();
  3220. if (valEltTy->isVectorTy() ||
  3221. valEltTy->isSingleValueType()) {
  3222. Value *ldVal = Builder.CreateLoad(val);
  3223. FlattenValToInitList(CGF, elts, eltTys, Ty, ldVal);
  3224. } else if (HLMatrixType::isa(valEltTy)) {
  3225. Value *ldVal = EmitHLSLMatrixLoad(Builder, val, Ty);
  3226. FlattenValToInitList(CGF, elts, eltTys, Ty, ldVal);
  3227. } else {
  3228. llvm::Type *i32Ty = llvm::Type::getInt32Ty(valTy->getContext());
  3229. Value *zero = ConstantInt::get(i32Ty, 0);
  3230. if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(valEltTy)) {
  3231. QualType EltTy = Ty->getAsArrayTypeUnsafe()->getElementType();
  3232. for (unsigned i = 0; i < AT->getArrayNumElements(); i++) {
  3233. Value *gepIdx = ConstantInt::get(i32Ty, i);
  3234. Value *EltPtr = Builder.CreateInBoundsGEP(val, {zero, gepIdx});
  3235. FlattenValToInitList(CGF, elts, eltTys, EltTy,EltPtr);
  3236. }
  3237. } else {
  3238. // Struct.
  3239. StructType *ST = cast<StructType>(valEltTy);
  3240. if (dxilutil::IsHLSLObjectType(ST)) {
  3241. // Save object directly like basic type.
  3242. elts.emplace_back(Builder.CreateLoad(val));
  3243. eltTys.emplace_back(Ty);
  3244. } else {
  3245. RecordDecl *RD = Ty->getAsStructureType()->getDecl();
  3246. const CGRecordLayout& RL = CGF.getTypes().getCGRecordLayout(RD);
  3247. // Take care base.
  3248. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  3249. if (CXXRD->getNumBases()) {
  3250. for (const auto &I : CXXRD->bases()) {
  3251. const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(
  3252. I.getType()->castAs<RecordType>()->getDecl());
  3253. if (BaseDecl->field_empty())
  3254. continue;
  3255. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  3256. unsigned i = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  3257. Value *gepIdx = ConstantInt::get(i32Ty, i);
  3258. Value *EltPtr = Builder.CreateInBoundsGEP(val, {zero, gepIdx});
  3259. FlattenValToInitList(CGF, elts, eltTys, parentTy, EltPtr);
  3260. }
  3261. }
  3262. }
  3263. for (auto fieldIter = RD->field_begin(), fieldEnd = RD->field_end();
  3264. fieldIter != fieldEnd; ++fieldIter) {
  3265. unsigned i = RL.getLLVMFieldNo(*fieldIter);
  3266. Value *gepIdx = ConstantInt::get(i32Ty, i);
  3267. Value *EltPtr = Builder.CreateInBoundsGEP(val, {zero, gepIdx});
  3268. FlattenValToInitList(CGF, elts, eltTys, fieldIter->getType(), EltPtr);
  3269. }
  3270. }
  3271. }
  3272. }
  3273. } else {
  3274. if (HLMatrixType MatTy = HLMatrixType::dyn_cast(valTy)) {
  3275. llvm::Type *EltTy = MatTy.getElementTypeForReg();
  3276. // All matrix Value should be row major.
  3277. // Init list is row major in scalar.
  3278. // So the order is match here, just cast to vector.
  3279. unsigned matSize = MatTy.getNumElements();
  3280. bool isRowMajor = hlsl::IsHLSLMatRowMajor(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  3281. HLCastOpcode opcode = isRowMajor ? HLCastOpcode::RowMatrixToVecCast
  3282. : HLCastOpcode::ColMatrixToVecCast;
  3283. // Cast to vector.
  3284. val = EmitHLSLMatrixOperationCallImp(
  3285. Builder, HLOpcodeGroup::HLCast,
  3286. static_cast<unsigned>(opcode),
  3287. llvm::VectorType::get(EltTy, matSize), {val}, TheModule);
  3288. valTy = val->getType();
  3289. }
  3290. if (valTy->isVectorTy()) {
  3291. QualType EltTy = hlsl::GetElementTypeOrType(Ty);
  3292. unsigned vecSize = valTy->getVectorNumElements();
  3293. for (unsigned i = 0; i < vecSize; i++) {
  3294. Value *Elt = Builder.CreateExtractElement(val, i);
  3295. elts.emplace_back(Elt);
  3296. eltTys.emplace_back(EltTy);
  3297. }
  3298. } else {
  3299. DXASSERT(valTy->isSingleValueType(), "must be single value type here");
  3300. elts.emplace_back(val);
  3301. eltTys.emplace_back(Ty);
  3302. }
  3303. }
  3304. }
  3305. static Value* ConvertScalarOrVector(CGBuilderTy& Builder, CodeGenTypes &Types,
  3306. Value *Val, QualType SrcQualTy, QualType DstQualTy) {
  3307. llvm::Type *SrcTy = Val->getType();
  3308. llvm::Type *DstTy = Types.ConvertType(DstQualTy);
  3309. DXASSERT(Val->getType() == Types.ConvertType(SrcQualTy), "QualType/Value mismatch!");
  3310. DXASSERT((SrcTy->isIntOrIntVectorTy() || SrcTy->isFPOrFPVectorTy())
  3311. && (DstTy->isIntOrIntVectorTy() || DstTy->isFPOrFPVectorTy()),
  3312. "EmitNumericConversion can only be used with int/float scalars/vectors.");
  3313. if (SrcTy == DstTy) return Val; // Valid no-op, including uint to int / int to uint
  3314. DXASSERT(SrcTy->isVectorTy()
  3315. ? (DstTy->isVectorTy() && SrcTy->getVectorNumElements() == DstTy->getVectorNumElements())
  3316. : !DstTy->isVectorTy(),
  3317. "EmitNumericConversion can only cast between scalars or vectors of matching sizes");
  3318. // Conversions to bools are comparisons
  3319. if (DstTy->getScalarSizeInBits() == 1) {
  3320. // fcmp une is what regular clang uses in C++ for (bool)f;
  3321. return SrcTy->isIntOrIntVectorTy()
  3322. ? Builder.CreateICmpNE(Val, llvm::Constant::getNullValue(SrcTy), "tobool")
  3323. : Builder.CreateFCmpUNE(Val, llvm::Constant::getNullValue(SrcTy), "tobool");
  3324. }
  3325. // Cast necessary
  3326. auto CastOp = static_cast<Instruction::CastOps>(HLModule::GetNumericCastOp(
  3327. SrcTy, hlsl::IsHLSLUnsigned(SrcQualTy), DstTy, hlsl::IsHLSLUnsigned(DstQualTy)));
  3328. return Builder.CreateCast(CastOp, Val, DstTy);
  3329. }
  3330. static Value* ConvertScalarOrVector(CodeGenFunction &CGF,
  3331. Value *Val, QualType SrcQualTy, QualType DstQualTy) {
  3332. return ConvertScalarOrVector(CGF.Builder, CGF.getTypes(), Val, SrcQualTy, DstQualTy);
  3333. }
  3334. // Cast elements in initlist if not match the target type.
  3335. // idx is current element index in initlist, Ty is target type.
  3336. // TODO: Stop handling missing cast here. Handle the casting of non-scalar values
  3337. // to their destination type in init list expressions at AST level.
  3338. static void AddMissingCastOpsInInitList(SmallVector<Value *, 4> &elts, SmallVector<QualType, 4> &eltTys, unsigned &idx, QualType Ty, CodeGenFunction &CGF) {
  3339. if (Ty->isArrayType()) {
  3340. const clang::ArrayType *AT = Ty->getAsArrayTypeUnsafe();
  3341. // Must be ConstantArrayType here.
  3342. unsigned arraySize = cast<ConstantArrayType>(AT)->getSize().getLimitedValue();
  3343. QualType EltTy = AT->getElementType();
  3344. for (unsigned i = 0; i < arraySize; i++)
  3345. AddMissingCastOpsInInitList(elts, eltTys, idx, EltTy, CGF);
  3346. } else if (IsHLSLVecType(Ty)) {
  3347. QualType EltTy = GetHLSLVecElementType(Ty);
  3348. unsigned vecSize = GetHLSLVecSize(Ty);
  3349. for (unsigned i=0;i< vecSize;i++)
  3350. AddMissingCastOpsInInitList(elts, eltTys, idx, EltTy, CGF);
  3351. } else if (IsHLSLMatType(Ty)) {
  3352. QualType EltTy = GetHLSLMatElementType(Ty);
  3353. unsigned row, col;
  3354. GetHLSLMatRowColCount(Ty, row, col);
  3355. unsigned matSize = row*col;
  3356. for (unsigned i = 0; i < matSize; i++)
  3357. AddMissingCastOpsInInitList(elts, eltTys, idx, EltTy, CGF);
  3358. } else if (Ty->isRecordType()) {
  3359. if (dxilutil::IsHLSLObjectType(CGF.ConvertType(Ty))) {
  3360. // Skip hlsl object.
  3361. idx++;
  3362. } else {
  3363. const RecordType *RT = Ty->getAsStructureType();
  3364. // For CXXRecord.
  3365. if (!RT)
  3366. RT = Ty->getAs<RecordType>();
  3367. RecordDecl *RD = RT->getDecl();
  3368. // Take care base.
  3369. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  3370. if (CXXRD->getNumBases()) {
  3371. for (const auto &I : CXXRD->bases()) {
  3372. const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(
  3373. I.getType()->castAs<RecordType>()->getDecl());
  3374. if (BaseDecl->field_empty())
  3375. continue;
  3376. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  3377. AddMissingCastOpsInInitList(elts, eltTys, idx, parentTy, CGF);
  3378. }
  3379. }
  3380. }
  3381. for (FieldDecl *field : RD->fields())
  3382. AddMissingCastOpsInInitList(elts, eltTys, idx, field->getType(), CGF);
  3383. }
  3384. }
  3385. else {
  3386. // Basic type.
  3387. elts[idx] = ConvertScalarOrVector(CGF, elts[idx], eltTys[idx], Ty);
  3388. idx++;
  3389. }
  3390. }
  3391. static void StoreInitListToDestPtr(Value *DestPtr,
  3392. SmallVector<Value *, 4> &elts, unsigned &idx,
  3393. QualType Type, bool bDefaultRowMajor,
  3394. CodeGenFunction &CGF, llvm::Module &M) {
  3395. CodeGenTypes &Types = CGF.getTypes();
  3396. CGBuilderTy &Builder = CGF.Builder;
  3397. llvm::Type *Ty = DestPtr->getType()->getPointerElementType();
  3398. if (Ty->isVectorTy()) {
  3399. llvm::Type *RegTy = CGF.ConvertType(Type);
  3400. Value *Result = UndefValue::get(RegTy);
  3401. for (unsigned i = 0; i < RegTy->getVectorNumElements(); i++)
  3402. Result = Builder.CreateInsertElement(Result, elts[idx + i], i);
  3403. Result = CGF.EmitToMemory(Result, Type);
  3404. Builder.CreateStore(Result, DestPtr);
  3405. idx += Ty->getVectorNumElements();
  3406. } else if (HLMatrixType MatTy = HLMatrixType::dyn_cast(Ty)) {
  3407. bool isRowMajor = hlsl::IsHLSLMatRowMajor(Type, bDefaultRowMajor);
  3408. std::vector<Value *> matInitList(MatTy.getNumElements());
  3409. for (unsigned c = 0; c < MatTy.getNumColumns(); c++) {
  3410. for (unsigned r = 0; r < MatTy.getNumRows(); r++) {
  3411. unsigned matIdx = c * MatTy.getNumRows() + r;
  3412. matInitList[matIdx] = elts[idx + matIdx];
  3413. }
  3414. }
  3415. idx += MatTy.getNumElements();
  3416. Value *matVal =
  3417. EmitHLSLMatrixOperationCallImp(Builder, HLOpcodeGroup::HLInit,
  3418. /*opcode*/ 0, Ty, matInitList, M);
  3419. // matVal return from HLInit is row major.
  3420. // If DestPtr is row major, just store it directly.
  3421. if (!isRowMajor) {
  3422. // ColMatStore need a col major value.
  3423. // Cast row major matrix into col major.
  3424. // Then store it.
  3425. Value *colMatVal = EmitHLSLMatrixOperationCallImp(
  3426. Builder, HLOpcodeGroup::HLCast,
  3427. static_cast<unsigned>(HLCastOpcode::RowMatrixToColMatrix), Ty,
  3428. {matVal}, M);
  3429. EmitHLSLMatrixOperationCallImp(
  3430. Builder, HLOpcodeGroup::HLMatLoadStore,
  3431. static_cast<unsigned>(HLMatLoadStoreOpcode::ColMatStore), Ty,
  3432. {DestPtr, colMatVal}, M);
  3433. } else {
  3434. EmitHLSLMatrixOperationCallImp(
  3435. Builder, HLOpcodeGroup::HLMatLoadStore,
  3436. static_cast<unsigned>(HLMatLoadStoreOpcode::RowMatStore), Ty,
  3437. {DestPtr, matVal}, M);
  3438. }
  3439. } else if (Ty->isStructTy()) {
  3440. if (dxilutil::IsHLSLObjectType(Ty)) {
  3441. Builder.CreateStore(elts[idx], DestPtr);
  3442. idx++;
  3443. } else {
  3444. Constant *zero = Builder.getInt32(0);
  3445. const RecordType *RT = Type->getAsStructureType();
  3446. // For CXXRecord.
  3447. if (!RT)
  3448. RT = Type->getAs<RecordType>();
  3449. RecordDecl *RD = RT->getDecl();
  3450. const CGRecordLayout &RL = Types.getCGRecordLayout(RD);
  3451. // Take care base.
  3452. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  3453. if (CXXRD->getNumBases()) {
  3454. for (const auto &I : CXXRD->bases()) {
  3455. const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(
  3456. I.getType()->castAs<RecordType>()->getDecl());
  3457. if (BaseDecl->field_empty())
  3458. continue;
  3459. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  3460. unsigned i = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  3461. Constant *gepIdx = Builder.getInt32(i);
  3462. Value *GEP = Builder.CreateInBoundsGEP(DestPtr, {zero, gepIdx});
  3463. StoreInitListToDestPtr(GEP, elts, idx, parentTy,
  3464. bDefaultRowMajor, CGF, M);
  3465. }
  3466. }
  3467. }
  3468. for (FieldDecl *field : RD->fields()) {
  3469. unsigned i = RL.getLLVMFieldNo(field);
  3470. Constant *gepIdx = Builder.getInt32(i);
  3471. Value *GEP = Builder.CreateInBoundsGEP(DestPtr, {zero, gepIdx});
  3472. StoreInitListToDestPtr(GEP, elts, idx, field->getType(),
  3473. bDefaultRowMajor, CGF, M);
  3474. }
  3475. }
  3476. } else if (Ty->isArrayTy()) {
  3477. Constant *zero = Builder.getInt32(0);
  3478. QualType EltType = Type->getAsArrayTypeUnsafe()->getElementType();
  3479. for (unsigned i = 0; i < Ty->getArrayNumElements(); i++) {
  3480. Constant *gepIdx = Builder.getInt32(i);
  3481. Value *GEP = Builder.CreateInBoundsGEP(DestPtr, {zero, gepIdx});
  3482. StoreInitListToDestPtr(GEP, elts, idx, EltType, bDefaultRowMajor,
  3483. CGF, M);
  3484. }
  3485. } else {
  3486. DXASSERT(Ty->isSingleValueType(), "invalid type");
  3487. llvm::Type *i1Ty = Builder.getInt1Ty();
  3488. Value *V = elts[idx];
  3489. if (V->getType() == i1Ty &&
  3490. DestPtr->getType()->getPointerElementType() != i1Ty) {
  3491. V = Builder.CreateZExt(V, DestPtr->getType()->getPointerElementType());
  3492. }
  3493. Builder.CreateStore(V, DestPtr);
  3494. idx++;
  3495. }
  3496. }
  3497. void CGMSHLSLRuntime::ScanInitList(CodeGenFunction &CGF, InitListExpr *E,
  3498. SmallVector<Value *, 4> &EltValList,
  3499. SmallVector<QualType, 4> &EltTyList) {
  3500. unsigned NumInitElements = E->getNumInits();
  3501. for (unsigned i = 0; i != NumInitElements; ++i) {
  3502. Expr *init = E->getInit(i);
  3503. QualType iType = init->getType();
  3504. if (InitListExpr *initList = dyn_cast<InitListExpr>(init)) {
  3505. ScanInitList(CGF, initList, EltValList, EltTyList);
  3506. } else if (CodeGenFunction::hasScalarEvaluationKind(iType)) {
  3507. llvm::Value *initVal = CGF.EmitScalarExpr(init);
  3508. FlattenValToInitList(CGF, EltValList, EltTyList, iType, initVal);
  3509. } else {
  3510. AggValueSlot Slot =
  3511. CGF.CreateAggTemp(init->getType(), "Agg.InitList.tmp");
  3512. CGF.EmitAggExpr(init, Slot);
  3513. llvm::Value *aggPtr = Slot.getAddr();
  3514. FlattenValToInitList(CGF, EltValList, EltTyList, iType, aggPtr);
  3515. }
  3516. }
  3517. }
  3518. // Is Type of E match Ty.
  3519. static bool ExpTypeMatch(Expr *E, QualType Ty, ASTContext &Ctx, CodeGenTypes &Types) {
  3520. if (InitListExpr *initList = dyn_cast<InitListExpr>(E)) {
  3521. unsigned NumInitElements = initList->getNumInits();
  3522. // Skip vector and matrix type.
  3523. if (Ty->isVectorType())
  3524. return false;
  3525. if (hlsl::IsHLSLVecMatType(Ty))
  3526. return false;
  3527. if (Ty->isStructureOrClassType()) {
  3528. RecordDecl *record = Ty->castAs<RecordType>()->getDecl();
  3529. bool bMatch = true;
  3530. unsigned i = 0;
  3531. for (auto it = record->field_begin(), end = record->field_end();
  3532. it != end; it++) {
  3533. if (i == NumInitElements) {
  3534. bMatch = false;
  3535. break;
  3536. }
  3537. Expr *init = initList->getInit(i++);
  3538. QualType EltTy = it->getType();
  3539. bMatch &= ExpTypeMatch(init, EltTy, Ctx, Types);
  3540. if (!bMatch)
  3541. break;
  3542. }
  3543. bMatch &= i == NumInitElements;
  3544. if (bMatch && initList->getType()->isVoidType()) {
  3545. initList->setType(Ty);
  3546. }
  3547. return bMatch;
  3548. } else if (Ty->isArrayType() && !Ty->isIncompleteArrayType()) {
  3549. const ConstantArrayType *AT = Ctx.getAsConstantArrayType(Ty);
  3550. QualType EltTy = AT->getElementType();
  3551. unsigned size = AT->getSize().getZExtValue();
  3552. if (size != NumInitElements)
  3553. return false;
  3554. bool bMatch = true;
  3555. for (unsigned i = 0; i != NumInitElements; ++i) {
  3556. Expr *init = initList->getInit(i);
  3557. bMatch &= ExpTypeMatch(init, EltTy, Ctx, Types);
  3558. if (!bMatch)
  3559. break;
  3560. }
  3561. if (bMatch && initList->getType()->isVoidType()) {
  3562. initList->setType(Ty);
  3563. }
  3564. return bMatch;
  3565. } else {
  3566. return false;
  3567. }
  3568. } else {
  3569. llvm::Type *ExpTy = Types.ConvertType(E->getType());
  3570. llvm::Type *TargetTy = Types.ConvertType(Ty);
  3571. return ExpTy == TargetTy;
  3572. }
  3573. }
  3574. bool CGMSHLSLRuntime::IsTrivalInitListExpr(CodeGenFunction &CGF,
  3575. InitListExpr *E) {
  3576. QualType Ty = E->getType();
  3577. bool result = ExpTypeMatch(E, Ty, CGF.getContext(), CGF.getTypes());
  3578. if (result) {
  3579. auto iter = staticConstGlobalInitMap.find(E);
  3580. if (iter != staticConstGlobalInitMap.end()) {
  3581. GlobalVariable * GV = iter->second;
  3582. auto &InitConstants = staticConstGlobalInitListMap[GV];
  3583. // Add Constant to InitList.
  3584. for (unsigned i=0;i<E->getNumInits();i++) {
  3585. Expr *Expr = E->getInit(i);
  3586. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Expr)) {
  3587. if (Cast->getCastKind() == CK_LValueToRValue) {
  3588. Expr = Cast->getSubExpr();
  3589. }
  3590. }
  3591. // Only do this on lvalue, if not lvalue, it will not be constant
  3592. // anyway.
  3593. if (Expr->isLValue()) {
  3594. LValue LV = CGF.EmitLValue(Expr);
  3595. if (LV.isSimple()) {
  3596. Constant *SrcPtr = dyn_cast<Constant>(LV.getAddress());
  3597. if (SrcPtr && !isa<UndefValue>(SrcPtr)) {
  3598. InitConstants.emplace_back(SrcPtr);
  3599. continue;
  3600. }
  3601. }
  3602. }
  3603. // Only support simple LV and Constant Ptr case.
  3604. // Other case just go normal path.
  3605. InitConstants.clear();
  3606. break;
  3607. }
  3608. if (InitConstants.empty())
  3609. staticConstGlobalInitListMap.erase(GV);
  3610. else
  3611. staticConstGlobalCtorMap[GV] = CGF.CurFn;
  3612. }
  3613. }
  3614. return result;
  3615. }
  3616. Value *CGMSHLSLRuntime::EmitHLSLInitListExpr(CodeGenFunction &CGF, InitListExpr *E,
  3617. // The destPtr when emiting aggregate init, for normal case, it will be null.
  3618. Value *DestPtr) {
  3619. if (DestPtr && E->getNumInits() == 1) {
  3620. llvm::Type *ExpTy = CGF.ConvertType(E->getType());
  3621. llvm::Type *TargetTy = CGF.ConvertType(E->getInit(0)->getType());
  3622. if (ExpTy == TargetTy) {
  3623. Expr *Expr = E->getInit(0);
  3624. LValue LV = CGF.EmitLValue(Expr);
  3625. if (LV.isSimple()) {
  3626. Value *SrcPtr = LV.getAddress();
  3627. SmallVector<Value *, 4> idxList;
  3628. EmitHLSLAggregateCopy(CGF, SrcPtr, DestPtr, idxList, Expr->getType(),
  3629. E->getType(), SrcPtr->getType());
  3630. return nullptr;
  3631. }
  3632. }
  3633. }
  3634. SmallVector<Value *, 4> EltValList;
  3635. SmallVector<QualType, 4> EltTyList;
  3636. ScanInitList(CGF, E, EltValList, EltTyList);
  3637. QualType ResultTy = E->getType();
  3638. unsigned idx = 0;
  3639. // Create cast if need.
  3640. AddMissingCastOpsInInitList(EltValList, EltTyList, idx, ResultTy, CGF);
  3641. DXASSERT(idx == EltValList.size(), "size must match");
  3642. llvm::Type *RetTy = CGF.ConvertType(ResultTy);
  3643. if (DestPtr) {
  3644. SmallVector<Value *, 4> ParamList;
  3645. DXASSERT_NOMSG(RetTy->isAggregateType());
  3646. ParamList.emplace_back(DestPtr);
  3647. ParamList.append(EltValList.begin(), EltValList.end());
  3648. idx = 0;
  3649. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  3650. StoreInitListToDestPtr(DestPtr, EltValList, idx, ResultTy,
  3651. bDefaultRowMajor, CGF, TheModule);
  3652. return nullptr;
  3653. }
  3654. if (IsHLSLVecType(ResultTy)) {
  3655. Value *Result = UndefValue::get(RetTy);
  3656. for (unsigned i = 0; i < RetTy->getVectorNumElements(); i++)
  3657. Result = CGF.Builder.CreateInsertElement(Result, EltValList[i], i);
  3658. return Result;
  3659. } else {
  3660. // Must be matrix here.
  3661. DXASSERT(IsHLSLMatType(ResultTy), "must be matrix type here.");
  3662. return EmitHLSLMatrixOperationCallImp(CGF.Builder, HLOpcodeGroup::HLInit,
  3663. /*opcode*/ 0, RetTy, EltValList,
  3664. TheModule);
  3665. }
  3666. }
  3667. static void FlatConstToList(CodeGenTypes &Types, bool bDefaultRowMajor,
  3668. Constant *C, QualType QualTy,
  3669. SmallVectorImpl<Constant *> &EltVals, SmallVectorImpl<QualType> &EltQualTys) {
  3670. llvm::Type *Ty = C->getType();
  3671. DXASSERT(Types.ConvertTypeForMem(QualTy) == Ty, "QualType/Type mismatch!");
  3672. if (llvm::VectorType *VecTy = dyn_cast<llvm::VectorType>(Ty)) {
  3673. DXASSERT(hlsl::IsHLSLVecType(QualTy), "QualType/Type mismatch!");
  3674. QualType VecElemQualTy = hlsl::GetHLSLVecElementType(QualTy);
  3675. for (unsigned i = 0; i < VecTy->getNumElements(); i++) {
  3676. EltVals.emplace_back(C->getAggregateElement(i));
  3677. EltQualTys.emplace_back(VecElemQualTy);
  3678. }
  3679. } else if (HLMatrixType::isa(Ty)) {
  3680. DXASSERT(hlsl::IsHLSLMatType(QualTy), "QualType/Type mismatch!");
  3681. // matrix type is struct { [rowcount x <colcount x T>] };
  3682. // Strip the struct level here.
  3683. Constant *RowArrayVal = C->getAggregateElement((unsigned)0);
  3684. QualType MatEltQualTy = hlsl::GetHLSLMatElementType(QualTy);
  3685. unsigned RowCount, ColCount;
  3686. hlsl::GetHLSLMatRowColCount(QualTy, RowCount, ColCount);
  3687. // Get all the elements from the array of row vectors.
  3688. // Matrices are never in memory representation so convert as needed.
  3689. SmallVector<Constant *, 16> MatElts;
  3690. for (unsigned r = 0; r < RowCount; ++r) {
  3691. Constant *RowVec = RowArrayVal->getAggregateElement(r);
  3692. for (unsigned c = 0; c < ColCount; ++c) {
  3693. Constant *MatElt = RowVec->getAggregateElement(c);
  3694. if (MatEltQualTy->isBooleanType()) {
  3695. DXASSERT(MatElt->getType()->isIntegerTy(1),
  3696. "Matrix elements should be in their register representation.");
  3697. MatElt = llvm::ConstantExpr::getZExt(MatElt, Types.ConvertTypeForMem(MatEltQualTy));
  3698. }
  3699. MatElts.emplace_back(MatElt);
  3700. }
  3701. }
  3702. // Return the elements in the order respecting the orientation.
  3703. // Constant initializers are used as the initial value for static variables,
  3704. // which live in memory. This is why they have to respect memory packing order.
  3705. bool IsRowMajor = hlsl::IsHLSLMatRowMajor(QualTy, bDefaultRowMajor);
  3706. for (unsigned r = 0; r < RowCount; ++r) {
  3707. for (unsigned c = 0; c < ColCount; ++c) {
  3708. unsigned Idx = IsRowMajor ? (r * ColCount + c) : (c * RowCount + r);
  3709. EltVals.emplace_back(MatElts[Idx]);
  3710. EltQualTys.emplace_back(MatEltQualTy);
  3711. }
  3712. }
  3713. }
  3714. else if (const clang::ConstantArrayType *ClangArrayTy = Types.getContext().getAsConstantArrayType(QualTy)) {
  3715. QualType ArrayEltQualTy = ClangArrayTy->getElementType();
  3716. uint64_t ArraySize = ClangArrayTy->getSize().getLimitedValue();
  3717. DXASSERT(cast<llvm::ArrayType>(Ty)->getArrayNumElements() == ArraySize, "QualType/Type mismatch!");
  3718. for (unsigned i = 0; i < ArraySize; i++) {
  3719. FlatConstToList(Types, bDefaultRowMajor, C->getAggregateElement(i), ArrayEltQualTy,
  3720. EltVals, EltQualTys);
  3721. }
  3722. }
  3723. else if (const clang::RecordType* RecordTy = QualTy->getAs<clang::RecordType>()) {
  3724. DXASSERT(dyn_cast<llvm::StructType>(Ty) != nullptr, "QualType/Type mismatch!");
  3725. RecordDecl *RecordDecl = RecordTy->getDecl();
  3726. const CGRecordLayout &RL = Types.getCGRecordLayout(RecordDecl);
  3727. // Take care base.
  3728. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RecordDecl)) {
  3729. if (CXXRD->getNumBases()) {
  3730. for (const auto &I : CXXRD->bases()) {
  3731. const CXXRecordDecl *BaseDecl =
  3732. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  3733. if (BaseDecl->field_empty())
  3734. continue;
  3735. QualType BaseQualTy = QualType(BaseDecl->getTypeForDecl(), 0);
  3736. unsigned BaseFieldIdx = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  3737. FlatConstToList(Types, bDefaultRowMajor,
  3738. C->getAggregateElement(BaseFieldIdx), BaseQualTy, EltVals, EltQualTys);
  3739. }
  3740. }
  3741. }
  3742. for (auto FieldIt = RecordDecl->field_begin(), fieldEnd = RecordDecl->field_end();
  3743. FieldIt != fieldEnd; ++FieldIt) {
  3744. unsigned FieldIndex = RL.getLLVMFieldNo(*FieldIt);
  3745. FlatConstToList(Types, bDefaultRowMajor,
  3746. C->getAggregateElement(FieldIndex), FieldIt->getType(), EltVals, EltQualTys);
  3747. }
  3748. }
  3749. else {
  3750. // At this point, we should have scalars in their memory representation
  3751. DXASSERT_NOMSG(QualTy->isBuiltinType());
  3752. EltVals.emplace_back(C);
  3753. EltQualTys.emplace_back(QualTy);
  3754. }
  3755. }
  3756. static bool ScanConstInitList(CodeGenModule &CGM, bool bDefaultRowMajor,
  3757. InitListExpr *InitList,
  3758. SmallVectorImpl<Constant *> &EltVals,
  3759. SmallVectorImpl<QualType> &EltQualTys) {
  3760. unsigned NumInitElements = InitList->getNumInits();
  3761. for (unsigned i = 0; i != NumInitElements; ++i) {
  3762. Expr *InitExpr = InitList->getInit(i);
  3763. QualType InitQualTy = InitExpr->getType();
  3764. if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(InitExpr)) {
  3765. if (!ScanConstInitList(CGM, bDefaultRowMajor, SubInitList, EltVals, EltQualTys))
  3766. return false;
  3767. } else if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(InitExpr)) {
  3768. if (VarDecl *Var = dyn_cast<VarDecl>(DeclRef->getDecl())) {
  3769. if (!Var->hasInit())
  3770. return false;
  3771. if (Constant *InitVal = CGM.EmitConstantInit(*Var)) {
  3772. FlatConstToList(CGM.getTypes(), bDefaultRowMajor,
  3773. InitVal, InitQualTy, EltVals, EltQualTys);
  3774. } else {
  3775. return false;
  3776. }
  3777. } else {
  3778. return false;
  3779. }
  3780. } else if (hlsl::IsHLSLMatType(InitQualTy)) {
  3781. return false;
  3782. } else if (CodeGenFunction::hasScalarEvaluationKind(InitQualTy)) {
  3783. if (Constant *InitVal = CGM.EmitConstantExpr(InitExpr, InitQualTy)) {
  3784. FlatConstToList(CGM.getTypes(), bDefaultRowMajor, InitVal, InitQualTy, EltVals, EltQualTys);
  3785. } else {
  3786. return false;
  3787. }
  3788. } else {
  3789. return false;
  3790. }
  3791. }
  3792. return true;
  3793. }
  3794. static Constant *BuildConstInitializer(CodeGenTypes &Types, bool bDefaultRowMajor,
  3795. QualType QualTy, bool MemRepr,
  3796. SmallVectorImpl<Constant *> &EltVals, SmallVectorImpl<QualType> &EltQualTys, unsigned &EltIdx);
  3797. static Constant *BuildConstMatrix(CodeGenTypes &Types, bool bDefaultRowMajor, QualType QualTy,
  3798. SmallVectorImpl<Constant *> &EltVals, SmallVectorImpl<QualType> &EltQualTys, unsigned &EltIdx) {
  3799. QualType MatEltTy = hlsl::GetHLSLMatElementType(QualTy);
  3800. unsigned RowCount, ColCount;
  3801. hlsl::GetHLSLMatRowColCount(QualTy, RowCount, ColCount);
  3802. bool IsRowMajor = hlsl::IsHLSLMatRowMajor(QualTy, bDefaultRowMajor);
  3803. // Save initializer elements first.
  3804. // Matrix initializer is row major.
  3805. SmallVector<Constant *, 16> RowMajorMatElts;
  3806. for (unsigned i = 0; i < RowCount * ColCount; i++) {
  3807. // Matrix elements are never in their memory representation,
  3808. // to preserve type information for later lowering.
  3809. bool MemRepr = false;
  3810. RowMajorMatElts.emplace_back(BuildConstInitializer(
  3811. Types, bDefaultRowMajor, MatEltTy, MemRepr,
  3812. EltVals, EltQualTys, EltIdx));
  3813. }
  3814. SmallVector<Constant *, 16> FinalMatElts;
  3815. if (IsRowMajor) {
  3816. FinalMatElts = RowMajorMatElts;
  3817. }
  3818. else {
  3819. // Cast row major to col major.
  3820. for (unsigned c = 0; c < ColCount; c++) {
  3821. for (unsigned r = 0; r < RowCount; r++) {
  3822. FinalMatElts.emplace_back(RowMajorMatElts[r * ColCount + c]);
  3823. }
  3824. }
  3825. }
  3826. // The type is vector<element, col>[row].
  3827. SmallVector<Constant *, 4> Rows;
  3828. unsigned idx = 0;
  3829. for (unsigned r = 0; r < RowCount; r++) {
  3830. SmallVector<Constant *, 4> RowElts;
  3831. for (unsigned c = 0; c < ColCount; c++) {
  3832. RowElts.emplace_back(FinalMatElts[idx++]);
  3833. }
  3834. Rows.emplace_back(llvm::ConstantVector::get(RowElts));
  3835. }
  3836. Constant *RowArray = llvm::ConstantArray::get(
  3837. llvm::ArrayType::get(Rows[0]->getType(), Rows.size()), Rows);
  3838. return llvm::ConstantStruct::get(cast<llvm::StructType>(Types.ConvertType(QualTy)), RowArray);
  3839. }
  3840. static Constant *BuildConstStruct(CodeGenTypes &Types, bool bDefaultRowMajor, QualType QualTy,
  3841. SmallVectorImpl<Constant *> &EltVals, SmallVectorImpl<QualType> &EltQualTys, unsigned &EltIdx) {
  3842. const RecordDecl *Record = QualTy->castAs<RecordType>()->getDecl();
  3843. bool MemRepr = true; // Structs are always in their memory representation
  3844. SmallVector<Constant *, 4> FieldVals;
  3845. if (const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
  3846. if (CXXRecord->getNumBases()) {
  3847. // Add base as field.
  3848. for (const auto &BaseSpec : CXXRecord->bases()) {
  3849. const CXXRecordDecl *BaseDecl =
  3850. cast<CXXRecordDecl>(BaseSpec.getType()->castAs<RecordType>()->getDecl());
  3851. // Skip empty struct.
  3852. if (BaseDecl->field_empty())
  3853. continue;
  3854. // Add base as a whole constant. Not as element.
  3855. FieldVals.emplace_back(BuildConstInitializer(Types, bDefaultRowMajor,
  3856. BaseSpec.getType(), MemRepr, EltVals, EltQualTys, EltIdx));
  3857. }
  3858. }
  3859. }
  3860. for (auto FieldIt = Record->field_begin(), FieldEnd = Record->field_end();
  3861. FieldIt != FieldEnd; ++FieldIt) {
  3862. FieldVals.emplace_back(BuildConstInitializer(Types, bDefaultRowMajor,
  3863. FieldIt->getType(), MemRepr, EltVals, EltQualTys, EltIdx));
  3864. }
  3865. return llvm::ConstantStruct::get(cast<llvm::StructType>(Types.ConvertTypeForMem(QualTy)), FieldVals);
  3866. }
  3867. static Constant *BuildConstInitializer(CodeGenTypes &Types, bool bDefaultRowMajor,
  3868. QualType QualTy, bool MemRepr,
  3869. SmallVectorImpl<Constant *> &EltVals, SmallVectorImpl<QualType> &EltQualTys, unsigned &EltIdx) {
  3870. if (hlsl::IsHLSLVecType(QualTy)) {
  3871. QualType VecEltQualTy = hlsl::GetHLSLVecElementType(QualTy);
  3872. unsigned VecSize = hlsl::GetHLSLVecSize(QualTy);
  3873. SmallVector<Constant *, 4> VecElts;
  3874. for (unsigned i = 0; i < VecSize; i++) {
  3875. VecElts.emplace_back(BuildConstInitializer(Types, bDefaultRowMajor,
  3876. VecEltQualTy, MemRepr,
  3877. EltVals, EltQualTys, EltIdx));
  3878. }
  3879. return llvm::ConstantVector::get(VecElts);
  3880. }
  3881. else if (const clang::ConstantArrayType *ArrayTy = Types.getContext().getAsConstantArrayType(QualTy)) {
  3882. QualType ArrayEltQualTy = QualType(ArrayTy->getArrayElementTypeNoTypeQual(), 0);
  3883. uint64_t ArraySize = ArrayTy->getSize().getLimitedValue();
  3884. SmallVector<Constant *, 4> ArrayElts;
  3885. for (unsigned i = 0; i < ArraySize; i++) {
  3886. ArrayElts.emplace_back(BuildConstInitializer(Types, bDefaultRowMajor,
  3887. ArrayEltQualTy, true, // Array elements must be in their memory representation
  3888. EltVals, EltQualTys, EltIdx));
  3889. }
  3890. return llvm::ConstantArray::get(
  3891. cast<llvm::ArrayType>(Types.ConvertTypeForMem(QualTy)), ArrayElts);
  3892. }
  3893. else if (hlsl::IsHLSLMatType(QualTy)) {
  3894. return BuildConstMatrix(Types, bDefaultRowMajor, QualTy,
  3895. EltVals, EltQualTys, EltIdx);
  3896. }
  3897. else if (QualTy->getAs<clang::RecordType>() != nullptr) {
  3898. return BuildConstStruct(Types, bDefaultRowMajor, QualTy,
  3899. EltVals, EltQualTys, EltIdx);
  3900. } else {
  3901. DXASSERT_NOMSG(QualTy->isBuiltinType());
  3902. Constant *EltVal = EltVals[EltIdx];
  3903. QualType EltQualTy = EltQualTys[EltIdx];
  3904. EltIdx++;
  3905. // Initializer constants are in their memory representation.
  3906. if (EltQualTy == QualTy && MemRepr) return EltVal;
  3907. CGBuilderTy Builder(EltVal->getContext());
  3908. if (EltQualTy->isBooleanType()) {
  3909. // Convert to register representation
  3910. // We don't have access to CodeGenFunction::EmitFromMemory here
  3911. DXASSERT_NOMSG(!EltVal->getType()->isIntegerTy(1));
  3912. EltVal = cast<Constant>(Builder.CreateICmpNE(EltVal, Constant::getNullValue(EltVal->getType())));
  3913. }
  3914. Constant *Result = cast<Constant>(ConvertScalarOrVector(Builder, Types, EltVal, EltQualTy, QualTy));
  3915. if (QualTy->isBooleanType() && MemRepr) {
  3916. // Convert back to the memory representation
  3917. // We don't have access to CodeGenFunction::EmitToMemory here
  3918. DXASSERT_NOMSG(Result->getType()->isIntegerTy(1));
  3919. Result = cast<Constant>(Builder.CreateZExt(Result, Types.ConvertTypeForMem(QualTy)));
  3920. }
  3921. return Result;
  3922. }
  3923. }
  3924. Constant *CGMSHLSLRuntime::EmitHLSLConstInitListExpr(CodeGenModule &CGM,
  3925. InitListExpr *E) {
  3926. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  3927. SmallVector<Constant *, 4> EltVals;
  3928. SmallVector<QualType, 4> EltQualTys;
  3929. if (!ScanConstInitList(CGM, bDefaultRowMajor, E, EltVals, EltQualTys))
  3930. return nullptr;
  3931. QualType QualTy = E->getType();
  3932. unsigned EltIdx = 0;
  3933. bool MemRepr = true;
  3934. return BuildConstInitializer(CGM.getTypes(), bDefaultRowMajor,
  3935. QualTy, MemRepr, EltVals, EltQualTys, EltIdx);
  3936. }
  3937. Value *CGMSHLSLRuntime::EmitHLSLMatrixOperationCall(
  3938. CodeGenFunction &CGF, const clang::Expr *E, llvm::Type *RetType,
  3939. ArrayRef<Value *> paramList) {
  3940. HLOpcodeGroup group = GetHLOpcodeGroup(E->getStmtClass());
  3941. unsigned opcode = GetHLOpcode(E);
  3942. if (group == HLOpcodeGroup::HLInit)
  3943. return EmitHLSLArrayInit(CGF.Builder, group, opcode, RetType, paramList,
  3944. TheModule);
  3945. else
  3946. return EmitHLSLMatrixOperationCallImp(CGF.Builder, group, opcode, RetType,
  3947. paramList, TheModule);
  3948. }
  3949. void CGMSHLSLRuntime::EmitHLSLDiscard(CodeGenFunction &CGF) {
  3950. EmitHLSLMatrixOperationCallImp(
  3951. CGF.Builder, HLOpcodeGroup::HLIntrinsic,
  3952. static_cast<unsigned>(IntrinsicOp::IOP_clip),
  3953. llvm::Type::getVoidTy(CGF.getLLVMContext()),
  3954. {ConstantFP::get(llvm::Type::getFloatTy(CGF.getLLVMContext()), -1.0f)},
  3955. TheModule);
  3956. }
  3957. // Emit an artificially conditionalized branch for a break operation when in a potentially wave-enabled stage
  3958. // This allows the block containing what would have been an unconditional break to be included in the loop
  3959. // If the block uses values that are wave-sensitive, it needs to stay in the loop to prevent optimizations
  3960. // that might produce incorrect results by ignoring the volatile aspect of wave operation results.
  3961. void CGMSHLSLRuntime::EmitHLSLCondBreak(CodeGenFunction &CGF, Function *F, BasicBlock *DestBB, BasicBlock *AltBB) {
  3962. // If not a wave-enabled stage, we can keep everything unconditional as before
  3963. if (!m_pHLModule->GetShaderModel()->IsPS() && !m_pHLModule->GetShaderModel()->IsCS() &&
  3964. !m_pHLModule->GetShaderModel()->IsLib()) {
  3965. CGF.Builder.CreateBr(DestBB);
  3966. return;
  3967. }
  3968. // Create a branch that is temporarily conditional on a constant
  3969. // FinalizeCodeGen will turn this into a function, DxilFinalize will turn it into a global var
  3970. llvm::Type *boolTy = llvm::Type::getInt1Ty(Context);
  3971. BranchInst *BI = CGF.Builder.CreateCondBr(llvm::ConstantInt::get(boolTy,1), DestBB, AltBB);
  3972. m_DxBreaks.emplace_back(BI);
  3973. }
  3974. static llvm::Type *MergeIntType(llvm::IntegerType *T0, llvm::IntegerType *T1) {
  3975. if (T0->getBitWidth() > T1->getBitWidth())
  3976. return T0;
  3977. else
  3978. return T1;
  3979. }
  3980. static Value *CreateExt(CGBuilderTy &Builder, Value *Src, llvm::Type *DstTy,
  3981. bool bSigned) {
  3982. if (bSigned)
  3983. return Builder.CreateSExt(Src, DstTy);
  3984. else
  3985. return Builder.CreateZExt(Src, DstTy);
  3986. }
  3987. // For integer literal, try to get lowest precision.
  3988. static Value *CalcHLSLLiteralToLowestPrecision(CGBuilderTy &Builder, Value *Src,
  3989. bool bSigned) {
  3990. if (ConstantInt *CI = dyn_cast<ConstantInt>(Src)) {
  3991. APInt v = CI->getValue();
  3992. switch (v.getActiveWords()) {
  3993. case 4:
  3994. return Builder.getInt32(v.getLimitedValue());
  3995. case 8:
  3996. return Builder.getInt64(v.getLimitedValue());
  3997. case 2:
  3998. // TODO: use low precision type when support it in dxil.
  3999. // return Builder.getInt16(v.getLimitedValue());
  4000. return Builder.getInt32(v.getLimitedValue());
  4001. case 1:
  4002. // TODO: use precision type when support it in dxil.
  4003. // return Builder.getInt8(v.getLimitedValue());
  4004. return Builder.getInt32(v.getLimitedValue());
  4005. default:
  4006. return nullptr;
  4007. }
  4008. } else if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
  4009. if (SI->getType()->isIntegerTy()) {
  4010. Value *T = SI->getTrueValue();
  4011. Value *F = SI->getFalseValue();
  4012. Value *lowT = CalcHLSLLiteralToLowestPrecision(Builder, T, bSigned);
  4013. Value *lowF = CalcHLSLLiteralToLowestPrecision(Builder, F, bSigned);
  4014. if (lowT && lowF && lowT != T && lowF != F) {
  4015. llvm::IntegerType *TTy = cast<llvm::IntegerType>(lowT->getType());
  4016. llvm::IntegerType *FTy = cast<llvm::IntegerType>(lowF->getType());
  4017. llvm::Type *Ty = MergeIntType(TTy, FTy);
  4018. if (TTy != Ty) {
  4019. lowT = CreateExt(Builder, lowT, Ty, bSigned);
  4020. }
  4021. if (FTy != Ty) {
  4022. lowF = CreateExt(Builder, lowF, Ty, bSigned);
  4023. }
  4024. Value *Cond = SI->getCondition();
  4025. return Builder.CreateSelect(Cond, lowT, lowF);
  4026. }
  4027. }
  4028. } else if (llvm::BinaryOperator *BO = dyn_cast<llvm::BinaryOperator>(Src)) {
  4029. Value *Src0 = BO->getOperand(0);
  4030. Value *Src1 = BO->getOperand(1);
  4031. Value *CastSrc0 = CalcHLSLLiteralToLowestPrecision(Builder, Src0, bSigned);
  4032. Value *CastSrc1 = CalcHLSLLiteralToLowestPrecision(Builder, Src1, bSigned);
  4033. if (Src0 != CastSrc0 && Src1 != CastSrc1 && CastSrc0 && CastSrc1 &&
  4034. CastSrc0->getType() == CastSrc1->getType()) {
  4035. llvm::IntegerType *Ty0 = cast<llvm::IntegerType>(CastSrc0->getType());
  4036. llvm::IntegerType *Ty1 = cast<llvm::IntegerType>(CastSrc0->getType());
  4037. llvm::Type *Ty = MergeIntType(Ty0, Ty1);
  4038. if (Ty0 != Ty) {
  4039. CastSrc0 = CreateExt(Builder, CastSrc0, Ty, bSigned);
  4040. }
  4041. if (Ty1 != Ty) {
  4042. CastSrc1 = CreateExt(Builder, CastSrc1, Ty, bSigned);
  4043. }
  4044. return Builder.CreateBinOp(BO->getOpcode(), CastSrc0, CastSrc1);
  4045. }
  4046. }
  4047. return nullptr;
  4048. }
  4049. Value *CGMSHLSLRuntime::EmitHLSLLiteralCast(CodeGenFunction &CGF, Value *Src,
  4050. QualType SrcType,
  4051. QualType DstType) {
  4052. auto &Builder = CGF.Builder;
  4053. llvm::Type *DstTy = CGF.ConvertType(DstType);
  4054. bool bSrcSigned = SrcType->isSignedIntegerType();
  4055. if (ConstantInt *CI = dyn_cast<ConstantInt>(Src)) {
  4056. APInt v = CI->getValue();
  4057. if (llvm::IntegerType *IT = dyn_cast<llvm::IntegerType>(DstTy)) {
  4058. v = v.trunc(IT->getBitWidth());
  4059. switch (IT->getBitWidth()) {
  4060. case 32:
  4061. return Builder.getInt32(v.getLimitedValue());
  4062. case 64:
  4063. return Builder.getInt64(v.getLimitedValue());
  4064. case 16:
  4065. return Builder.getInt16(v.getLimitedValue());
  4066. case 8:
  4067. return Builder.getInt8(v.getLimitedValue());
  4068. default:
  4069. return nullptr;
  4070. }
  4071. } else {
  4072. DXASSERT_NOMSG(DstTy->isFloatingPointTy());
  4073. int64_t val = v.getLimitedValue();
  4074. if (v.isNegative())
  4075. val = 0-v.abs().getLimitedValue();
  4076. if (DstTy->isDoubleTy())
  4077. return ConstantFP::get(DstTy, (double)val);
  4078. else if (DstTy->isFloatTy())
  4079. return ConstantFP::get(DstTy, (float)val);
  4080. else {
  4081. if (bSrcSigned)
  4082. return Builder.CreateSIToFP(Src, DstTy);
  4083. else
  4084. return Builder.CreateUIToFP(Src, DstTy);
  4085. }
  4086. }
  4087. } else if (ConstantFP *CF = dyn_cast<ConstantFP>(Src)) {
  4088. APFloat v = CF->getValueAPF();
  4089. double dv = v.convertToDouble();
  4090. if (llvm::IntegerType *IT = dyn_cast<llvm::IntegerType>(DstTy)) {
  4091. switch (IT->getBitWidth()) {
  4092. case 32:
  4093. return Builder.getInt32(dv);
  4094. case 64:
  4095. return Builder.getInt64(dv);
  4096. case 16:
  4097. return Builder.getInt16(dv);
  4098. case 8:
  4099. return Builder.getInt8(dv);
  4100. default:
  4101. return nullptr;
  4102. }
  4103. } else {
  4104. if (DstTy->isFloatTy()) {
  4105. float fv = dv;
  4106. return ConstantFP::get(DstTy->getContext(), APFloat(fv));
  4107. } else {
  4108. return Builder.CreateFPTrunc(Src, DstTy);
  4109. }
  4110. }
  4111. } else if (dyn_cast<UndefValue>(Src)) {
  4112. return UndefValue::get(DstTy);
  4113. } else {
  4114. Instruction *I = cast<Instruction>(Src);
  4115. if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
  4116. Value *T = SI->getTrueValue();
  4117. Value *F = SI->getFalseValue();
  4118. Value *Cond = SI->getCondition();
  4119. if (isa<llvm::ConstantInt>(T) && isa<llvm::ConstantInt>(F)) {
  4120. llvm::APInt lhs = cast<llvm::ConstantInt>(T)->getValue();
  4121. llvm::APInt rhs = cast<llvm::ConstantInt>(F)->getValue();
  4122. if (DstTy == Builder.getInt32Ty()) {
  4123. T = Builder.getInt32(lhs.getLimitedValue());
  4124. F = Builder.getInt32(rhs.getLimitedValue());
  4125. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  4126. return Sel;
  4127. } else if (DstTy->isFloatingPointTy()) {
  4128. T = ConstantFP::get(DstTy, int64_t(lhs.getLimitedValue()));
  4129. F = ConstantFP::get(DstTy, int64_t(rhs.getLimitedValue()));
  4130. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  4131. return Sel;
  4132. }
  4133. } else if (isa<llvm::ConstantFP>(T) && isa<llvm::ConstantFP>(F)) {
  4134. llvm::APFloat lhs = cast<llvm::ConstantFP>(T)->getValueAPF();
  4135. llvm::APFloat rhs = cast<llvm::ConstantFP>(F)->getValueAPF();
  4136. double ld = lhs.convertToDouble();
  4137. double rd = rhs.convertToDouble();
  4138. if (DstTy->isFloatTy()) {
  4139. float lf = ld;
  4140. float rf = rd;
  4141. T = ConstantFP::get(DstTy->getContext(), APFloat(lf));
  4142. F = ConstantFP::get(DstTy->getContext(), APFloat(rf));
  4143. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  4144. return Sel;
  4145. } else if (DstTy == Builder.getInt32Ty()) {
  4146. T = Builder.getInt32(ld);
  4147. F = Builder.getInt32(rd);
  4148. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  4149. return Sel;
  4150. } else if (DstTy == Builder.getInt64Ty()) {
  4151. T = Builder.getInt64(ld);
  4152. F = Builder.getInt64(rd);
  4153. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  4154. return Sel;
  4155. }
  4156. }
  4157. } else if (llvm::BinaryOperator *BO = dyn_cast<llvm::BinaryOperator>(I)) {
  4158. // For integer binary operator, do the calc on lowest precision, then cast
  4159. // to dstTy.
  4160. if (I->getType()->isIntegerTy()) {
  4161. bool bSigned = DstType->isSignedIntegerType();
  4162. Value *CastResult =
  4163. CalcHLSLLiteralToLowestPrecision(Builder, BO, bSigned);
  4164. if (!CastResult)
  4165. return nullptr;
  4166. if (dyn_cast<llvm::IntegerType>(DstTy)) {
  4167. if (DstTy == CastResult->getType()) {
  4168. return CastResult;
  4169. } else {
  4170. if (bSigned)
  4171. return Builder.CreateSExtOrTrunc(CastResult, DstTy);
  4172. else
  4173. return Builder.CreateZExtOrTrunc(CastResult, DstTy);
  4174. }
  4175. } else {
  4176. if (bSrcSigned)
  4177. return Builder.CreateSIToFP(CastResult, DstTy);
  4178. else
  4179. return Builder.CreateUIToFP(CastResult, DstTy);
  4180. }
  4181. }
  4182. }
  4183. // TODO: support other opcode if need.
  4184. return nullptr;
  4185. }
  4186. }
  4187. // For case like ((float3xfloat3)mat4x4).m21 or ((float3xfloat3)mat4x4)[1], just
  4188. // treat it like mat4x4.m21 or mat4x4[1].
  4189. static Value *GetOriginMatrixOperandAndUpdateMatSize(Value *Ptr, unsigned &row,
  4190. unsigned &col) {
  4191. if (CallInst *Mat = dyn_cast<CallInst>(Ptr)) {
  4192. HLOpcodeGroup OpcodeGroup =
  4193. GetHLOpcodeGroupByName(Mat->getCalledFunction());
  4194. if (OpcodeGroup == HLOpcodeGroup::HLCast) {
  4195. HLCastOpcode castOpcode = static_cast<HLCastOpcode>(GetHLOpcode(Mat));
  4196. if (castOpcode == HLCastOpcode::DefaultCast) {
  4197. Ptr = Mat->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  4198. // Remove the cast which is useless now.
  4199. Mat->eraseFromParent();
  4200. // Update row and col.
  4201. HLMatrixType matTy =
  4202. HLMatrixType::cast(Ptr->getType()->getPointerElementType());
  4203. row = matTy.getNumRows();
  4204. col = matTy.getNumColumns();
  4205. // Don't update RetTy and DxilGeneration pass will do the right thing.
  4206. return Ptr;
  4207. }
  4208. }
  4209. }
  4210. return nullptr;
  4211. }
  4212. Value *CGMSHLSLRuntime::EmitHLSLMatrixSubscript(CodeGenFunction &CGF,
  4213. llvm::Type *RetType,
  4214. llvm::Value *Ptr,
  4215. llvm::Value *Idx,
  4216. clang::QualType Ty) {
  4217. bool isRowMajor =
  4218. hlsl::IsHLSLMatRowMajor(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  4219. unsigned opcode =
  4220. isRowMajor ? static_cast<unsigned>(HLSubscriptOpcode::RowMatSubscript)
  4221. : static_cast<unsigned>(HLSubscriptOpcode::ColMatSubscript);
  4222. Value *matBase = Ptr;
  4223. DXASSERT(matBase->getType()->isPointerTy(),
  4224. "matrix subscript should return pointer");
  4225. RetType =
  4226. llvm::PointerType::get(RetType->getPointerElementType(),
  4227. matBase->getType()->getPointerAddressSpace());
  4228. unsigned row, col;
  4229. hlsl::GetHLSLMatRowColCount(Ty, row, col);
  4230. unsigned resultCol = col;
  4231. if (Value *OriginPtr = GetOriginMatrixOperandAndUpdateMatSize(Ptr, row, col)) {
  4232. Ptr = OriginPtr;
  4233. // Update col to result col to get correct result size.
  4234. col = resultCol;
  4235. }
  4236. // Lower mat[Idx] into real idx.
  4237. SmallVector<Value *, 8> args;
  4238. args.emplace_back(Ptr);
  4239. if (isRowMajor) {
  4240. Value *cCol = ConstantInt::get(Idx->getType(), col);
  4241. Value *Base = CGF.Builder.CreateMul(cCol, Idx);
  4242. for (unsigned i = 0; i < col; i++) {
  4243. Value *c = ConstantInt::get(Idx->getType(), i);
  4244. // r * col + c
  4245. Value *matIdx = CGF.Builder.CreateAdd(Base, c);
  4246. args.emplace_back(matIdx);
  4247. }
  4248. } else {
  4249. for (unsigned i = 0; i < col; i++) {
  4250. Value *cMulRow = ConstantInt::get(Idx->getType(), i * row);
  4251. // c * row + r
  4252. Value *matIdx = CGF.Builder.CreateAdd(cMulRow, Idx);
  4253. args.emplace_back(matIdx);
  4254. }
  4255. }
  4256. Value *matSub =
  4257. EmitHLSLMatrixOperationCallImp(CGF.Builder, HLOpcodeGroup::HLSubscript,
  4258. opcode, RetType, args, TheModule);
  4259. return matSub;
  4260. }
  4261. Value *CGMSHLSLRuntime::EmitHLSLMatrixElement(CodeGenFunction &CGF,
  4262. llvm::Type *RetType,
  4263. ArrayRef<Value *> paramList,
  4264. QualType Ty) {
  4265. bool isRowMajor =
  4266. hlsl::IsHLSLMatRowMajor(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  4267. unsigned opcode =
  4268. isRowMajor ? static_cast<unsigned>(HLSubscriptOpcode::RowMatElement)
  4269. : static_cast<unsigned>(HLSubscriptOpcode::ColMatElement);
  4270. Value *matBase = paramList[0];
  4271. DXASSERT(matBase->getType()->isPointerTy(),
  4272. "matrix element should return pointer");
  4273. RetType =
  4274. llvm::PointerType::get(RetType->getPointerElementType(),
  4275. matBase->getType()->getPointerAddressSpace());
  4276. Value *idx = paramList[HLOperandIndex::kMatSubscriptSubOpIdx-1];
  4277. // Lower _m00 into real idx.
  4278. // -1 to avoid opcode param which is added in EmitHLSLMatrixOperationCallImp.
  4279. Value *args[] = {paramList[HLOperandIndex::kMatSubscriptMatOpIdx - 1],
  4280. paramList[HLOperandIndex::kMatSubscriptSubOpIdx - 1]};
  4281. unsigned row, col;
  4282. hlsl::GetHLSLMatRowColCount(Ty, row, col);
  4283. Value *Ptr = paramList[0];
  4284. if (Value *OriginPtr = GetOriginMatrixOperandAndUpdateMatSize(Ptr, row, col)) {
  4285. args[0] = OriginPtr;
  4286. }
  4287. // For all zero idx. Still all zero idx.
  4288. if (ConstantAggregateZero *zeros = dyn_cast<ConstantAggregateZero>(idx)) {
  4289. Constant *zero = zeros->getAggregateElement((unsigned)0);
  4290. std::vector<Constant *> elts(zeros->getNumElements() >> 1, zero);
  4291. args[HLOperandIndex::kMatSubscriptSubOpIdx - 1] = ConstantVector::get(elts);
  4292. } else {
  4293. ConstantDataSequential *elts = cast<ConstantDataSequential>(idx);
  4294. unsigned count = elts->getNumElements();
  4295. std::vector<Constant *> idxs(count >> 1);
  4296. for (unsigned i = 0; i < count; i += 2) {
  4297. unsigned rowIdx = elts->getElementAsInteger(i);
  4298. unsigned colIdx = elts->getElementAsInteger(i + 1);
  4299. unsigned matIdx = 0;
  4300. if (isRowMajor) {
  4301. matIdx = rowIdx * col + colIdx;
  4302. } else {
  4303. matIdx = colIdx * row + rowIdx;
  4304. }
  4305. idxs[i >> 1] = CGF.Builder.getInt32(matIdx);
  4306. }
  4307. args[HLOperandIndex::kMatSubscriptSubOpIdx - 1] = ConstantVector::get(idxs);
  4308. }
  4309. return EmitHLSLMatrixOperationCallImp(CGF.Builder, HLOpcodeGroup::HLSubscript,
  4310. opcode, RetType, args, TheModule);
  4311. }
  4312. Value *CGMSHLSLRuntime::EmitHLSLMatrixLoad(CGBuilderTy &Builder, Value *Ptr,
  4313. QualType Ty) {
  4314. bool isRowMajor =
  4315. hlsl::IsHLSLMatRowMajor(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  4316. unsigned opcode =
  4317. isRowMajor
  4318. ? static_cast<unsigned>(HLMatLoadStoreOpcode::RowMatLoad)
  4319. : static_cast<unsigned>(HLMatLoadStoreOpcode::ColMatLoad);
  4320. Value *matVal = EmitHLSLMatrixOperationCallImp(
  4321. Builder, HLOpcodeGroup::HLMatLoadStore, opcode,
  4322. Ptr->getType()->getPointerElementType(), {Ptr}, TheModule);
  4323. if (!isRowMajor) {
  4324. // ColMatLoad will return a col major matrix.
  4325. // All matrix Value should be row major.
  4326. // Cast it to row major.
  4327. matVal = EmitHLSLMatrixOperationCallImp(
  4328. Builder, HLOpcodeGroup::HLCast,
  4329. static_cast<unsigned>(HLCastOpcode::ColMatrixToRowMatrix),
  4330. matVal->getType(), {matVal}, TheModule);
  4331. }
  4332. return matVal;
  4333. }
  4334. void CGMSHLSLRuntime::EmitHLSLMatrixStore(CGBuilderTy &Builder, Value *Val,
  4335. Value *DestPtr, QualType Ty) {
  4336. bool isRowMajor =
  4337. hlsl::IsHLSLMatRowMajor(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  4338. unsigned opcode =
  4339. isRowMajor
  4340. ? static_cast<unsigned>(HLMatLoadStoreOpcode::RowMatStore)
  4341. : static_cast<unsigned>(HLMatLoadStoreOpcode::ColMatStore);
  4342. if (!isRowMajor) {
  4343. Value *ColVal = nullptr;
  4344. // If Val is casted from col major. Just use the original col major val.
  4345. if (CallInst *CI = dyn_cast<CallInst>(Val)) {
  4346. hlsl::HLOpcodeGroup group =
  4347. hlsl::GetHLOpcodeGroupByName(CI->getCalledFunction());
  4348. if (group == HLOpcodeGroup::HLCast) {
  4349. HLCastOpcode castOp = static_cast<HLCastOpcode>(hlsl::GetHLOpcode(CI));
  4350. if (castOp == HLCastOpcode::ColMatrixToRowMatrix) {
  4351. ColVal = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  4352. }
  4353. }
  4354. }
  4355. if (ColVal) {
  4356. Val = ColVal;
  4357. } else {
  4358. // All matrix Value should be row major.
  4359. // ColMatStore need a col major value.
  4360. // Cast it to row major.
  4361. Val = EmitHLSLMatrixOperationCallImp(
  4362. Builder, HLOpcodeGroup::HLCast,
  4363. static_cast<unsigned>(HLCastOpcode::RowMatrixToColMatrix),
  4364. Val->getType(), {Val}, TheModule);
  4365. }
  4366. }
  4367. EmitHLSLMatrixOperationCallImp(Builder, HLOpcodeGroup::HLMatLoadStore, opcode,
  4368. Val->getType(), {DestPtr, Val}, TheModule);
  4369. }
  4370. Value *CGMSHLSLRuntime::EmitHLSLMatrixLoad(CodeGenFunction &CGF, Value *Ptr,
  4371. QualType Ty) {
  4372. return EmitHLSLMatrixLoad(CGF.Builder, Ptr, Ty);
  4373. }
  4374. void CGMSHLSLRuntime::EmitHLSLMatrixStore(CodeGenFunction &CGF, Value *Val,
  4375. Value *DestPtr, QualType Ty) {
  4376. EmitHLSLMatrixStore(CGF.Builder, Val, DestPtr, Ty);
  4377. }
  4378. // Copy data from srcPtr to destPtr.
  4379. static void SimplePtrCopy(Value *DestPtr, Value *SrcPtr,
  4380. ArrayRef<Value *> idxList, CGBuilderTy &Builder) {
  4381. if (idxList.size() > 1) {
  4382. DestPtr = Builder.CreateInBoundsGEP(DestPtr, idxList);
  4383. SrcPtr = Builder.CreateInBoundsGEP(SrcPtr, idxList);
  4384. }
  4385. llvm::LoadInst *ld = Builder.CreateLoad(SrcPtr);
  4386. Builder.CreateStore(ld, DestPtr);
  4387. }
  4388. // Get Element val from SrvVal with extract value.
  4389. static Value *GetEltVal(Value *SrcVal, ArrayRef<Value*> idxList,
  4390. CGBuilderTy &Builder) {
  4391. Value *Val = SrcVal;
  4392. // Skip beginning pointer type.
  4393. for (unsigned i = 1; i < idxList.size(); i++) {
  4394. ConstantInt *idx = cast<ConstantInt>(idxList[i]);
  4395. llvm::Type *Ty = Val->getType();
  4396. if (Ty->isAggregateType()) {
  4397. Val = Builder.CreateExtractValue(Val, idx->getLimitedValue());
  4398. }
  4399. }
  4400. return Val;
  4401. }
  4402. // Copy srcVal to destPtr.
  4403. static void SimpleValCopy(Value *DestPtr, Value *SrcVal,
  4404. ArrayRef<Value*> idxList,
  4405. CGBuilderTy &Builder) {
  4406. Value *DestGEP = Builder.CreateInBoundsGEP(DestPtr, idxList);
  4407. Value *Val = GetEltVal(SrcVal, idxList, Builder);
  4408. Builder.CreateStore(Val, DestGEP);
  4409. }
  4410. static void SimpleCopy(Value *Dest, Value *Src,
  4411. ArrayRef<Value *> idxList,
  4412. CGBuilderTy &Builder) {
  4413. if (Src->getType()->isPointerTy())
  4414. SimplePtrCopy(Dest, Src, idxList, Builder);
  4415. else
  4416. SimpleValCopy(Dest, Src, idxList, Builder);
  4417. }
  4418. void CGMSHLSLRuntime::FlattenAggregatePtrToGepList(
  4419. CodeGenFunction &CGF, Value *Ptr, SmallVector<Value *, 4> &idxList,
  4420. clang::QualType Type, llvm::Type *Ty, SmallVector<Value *, 4> &GepList,
  4421. SmallVector<QualType, 4> &EltTyList) {
  4422. if (llvm::PointerType *PT = dyn_cast<llvm::PointerType>(Ty)) {
  4423. Constant *idx = Constant::getIntegerValue(
  4424. IntegerType::get(Ty->getContext(), 32), APInt(32, 0));
  4425. idxList.emplace_back(idx);
  4426. FlattenAggregatePtrToGepList(CGF, Ptr, idxList, Type, PT->getElementType(),
  4427. GepList, EltTyList);
  4428. idxList.pop_back();
  4429. } else if (HLMatrixType MatTy = HLMatrixType::dyn_cast(Ty)) {
  4430. // Use matLd/St for matrix.
  4431. llvm::Type *EltTy = MatTy.getElementTypeForReg();
  4432. llvm::PointerType *EltPtrTy =
  4433. llvm::PointerType::get(EltTy, Ptr->getType()->getPointerAddressSpace());
  4434. QualType EltQualTy = hlsl::GetHLSLMatElementType(Type);
  4435. Value *matPtr = CGF.Builder.CreateInBoundsGEP(Ptr, idxList);
  4436. // Flatten matrix to elements.
  4437. for (unsigned r = 0; r < MatTy.getNumRows(); r++) {
  4438. for (unsigned c = 0; c < MatTy.getNumColumns(); c++) {
  4439. ConstantInt *cRow = CGF.Builder.getInt32(r);
  4440. ConstantInt *cCol = CGF.Builder.getInt32(c);
  4441. Constant *CV = llvm::ConstantVector::get({cRow, cCol});
  4442. GepList.push_back(
  4443. EmitHLSLMatrixElement(CGF, EltPtrTy, {matPtr, CV}, Type));
  4444. EltTyList.push_back(EltQualTy);
  4445. }
  4446. }
  4447. } else if (StructType *ST = dyn_cast<StructType>(Ty)) {
  4448. if (dxilutil::IsHLSLObjectType(ST)) {
  4449. // Avoid split HLSL object.
  4450. Value *GEP = CGF.Builder.CreateInBoundsGEP(Ptr, idxList);
  4451. GepList.push_back(GEP);
  4452. EltTyList.push_back(Type);
  4453. return;
  4454. }
  4455. const clang::RecordType *RT = Type->getAsStructureType();
  4456. RecordDecl *RD = RT->getDecl();
  4457. const CGRecordLayout &RL = CGF.getTypes().getCGRecordLayout(RD);
  4458. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  4459. if (CXXRD->getNumBases()) {
  4460. // Add base as field.
  4461. for (const auto &I : CXXRD->bases()) {
  4462. const CXXRecordDecl *BaseDecl =
  4463. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  4464. // Skip empty struct.
  4465. if (BaseDecl->field_empty())
  4466. continue;
  4467. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  4468. llvm::Type *parentType = CGF.ConvertType(parentTy);
  4469. unsigned i = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  4470. Constant *idx = llvm::Constant::getIntegerValue(
  4471. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  4472. idxList.emplace_back(idx);
  4473. FlattenAggregatePtrToGepList(CGF, Ptr, idxList, parentTy, parentType,
  4474. GepList, EltTyList);
  4475. idxList.pop_back();
  4476. }
  4477. }
  4478. }
  4479. for (auto fieldIter = RD->field_begin(), fieldEnd = RD->field_end();
  4480. fieldIter != fieldEnd; ++fieldIter) {
  4481. unsigned i = RL.getLLVMFieldNo(*fieldIter);
  4482. llvm::Type *ET = ST->getElementType(i);
  4483. Constant *idx = llvm::Constant::getIntegerValue(
  4484. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  4485. idxList.emplace_back(idx);
  4486. FlattenAggregatePtrToGepList(CGF, Ptr, idxList, fieldIter->getType(), ET,
  4487. GepList, EltTyList);
  4488. idxList.pop_back();
  4489. }
  4490. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty)) {
  4491. llvm::Type *ET = AT->getElementType();
  4492. QualType EltType = CGF.getContext().getBaseElementType(Type);
  4493. for (uint32_t i = 0; i < AT->getNumElements(); i++) {
  4494. Constant *idx = Constant::getIntegerValue(
  4495. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  4496. idxList.emplace_back(idx);
  4497. FlattenAggregatePtrToGepList(CGF, Ptr, idxList, EltType, ET, GepList,
  4498. EltTyList);
  4499. idxList.pop_back();
  4500. }
  4501. } else if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(Ty)) {
  4502. // Flatten vector too.
  4503. QualType EltTy = hlsl::GetHLSLVecElementType(Type);
  4504. for (uint32_t i = 0; i < VT->getNumElements(); i++) {
  4505. Constant *idx = CGF.Builder.getInt32(i);
  4506. idxList.emplace_back(idx);
  4507. Value *GEP = CGF.Builder.CreateInBoundsGEP(Ptr, idxList);
  4508. GepList.push_back(GEP);
  4509. EltTyList.push_back(EltTy);
  4510. idxList.pop_back();
  4511. }
  4512. } else {
  4513. Value *GEP = CGF.Builder.CreateInBoundsGEP(Ptr, idxList);
  4514. GepList.push_back(GEP);
  4515. EltTyList.push_back(Type);
  4516. }
  4517. }
  4518. void CGMSHLSLRuntime::LoadElements(CodeGenFunction &CGF,
  4519. ArrayRef<Value *> Ptrs, ArrayRef<QualType> QualTys,
  4520. SmallVector<Value *, 4> &Vals) {
  4521. for (size_t i = 0, e = Ptrs.size(); i < e; i++) {
  4522. Value *Ptr = Ptrs[i];
  4523. llvm::Type *Ty = Ptr->getType()->getPointerElementType();
  4524. DXASSERT_LOCALVAR(Ty, Ty->isIntegerTy() || Ty->isFloatingPointTy(), "Expected only element types.");
  4525. Value *Val = CGF.Builder.CreateLoad(Ptr);
  4526. Val = CGF.EmitFromMemory(Val, QualTys[i]);
  4527. Vals.push_back(Val);
  4528. }
  4529. }
  4530. void CGMSHLSLRuntime::ConvertAndStoreElements(CodeGenFunction &CGF,
  4531. ArrayRef<Value *> SrcVals, ArrayRef<QualType> SrcQualTys,
  4532. ArrayRef<Value *> DstPtrs, ArrayRef<QualType> DstQualTys) {
  4533. for (size_t i = 0, e = DstPtrs.size(); i < e; i++) {
  4534. Value *DstPtr = DstPtrs[i];
  4535. QualType DstQualTy = DstQualTys[i];
  4536. Value *SrcVal = SrcVals[i];
  4537. QualType SrcQualTy = SrcQualTys[i];
  4538. DXASSERT(SrcVal->getType()->isIntegerTy() || SrcVal->getType()->isFloatingPointTy(),
  4539. "Expected only element types.");
  4540. llvm::Value *Result = ConvertScalarOrVector(CGF, SrcVal, SrcQualTy, DstQualTy);
  4541. Result = CGF.EmitToMemory(Result, DstQualTy);
  4542. CGF.Builder.CreateStore(Result, DstPtr);
  4543. }
  4544. }
  4545. static bool AreMatrixArrayOrientationMatching(ASTContext& Context,
  4546. HLModule &Module, QualType LhsTy, QualType RhsTy) {
  4547. while (const clang::ArrayType *LhsArrayTy = Context.getAsArrayType(LhsTy)) {
  4548. LhsTy = LhsArrayTy->getElementType();
  4549. RhsTy = Context.getAsArrayType(RhsTy)->getElementType();
  4550. }
  4551. bool LhsRowMajor, RhsRowMajor;
  4552. LhsRowMajor = RhsRowMajor = Module.GetHLOptions().bDefaultRowMajor;
  4553. HasHLSLMatOrientation(LhsTy, &LhsRowMajor);
  4554. HasHLSLMatOrientation(RhsTy, &RhsRowMajor);
  4555. return LhsRowMajor == RhsRowMajor;
  4556. }
  4557. static llvm::Value *CreateInBoundsGEPIfNeeded(llvm::Value *Ptr, ArrayRef<Value*> IdxList, CGBuilderTy &Builder) {
  4558. DXASSERT(IdxList.size() > 0, "Invalid empty GEP index list");
  4559. // If the GEP list is a single zero, it's a no-op, so save us the trouble.
  4560. if (IdxList.size() == 1) {
  4561. if (ConstantInt *FirstIdx = dyn_cast<ConstantInt>(IdxList[0])) {
  4562. if (FirstIdx->isZero()) return Ptr;
  4563. }
  4564. }
  4565. return Builder.CreateInBoundsGEP(Ptr, IdxList);
  4566. }
  4567. // Copy data from SrcPtr to DestPtr.
  4568. // For matrix, use MatLoad/MatStore.
  4569. // For matrix array, EmitHLSLAggregateCopy on each element.
  4570. // For struct or array, use memcpy.
  4571. // Other just load/store.
  4572. void CGMSHLSLRuntime::EmitHLSLAggregateCopy(
  4573. CodeGenFunction &CGF, llvm::Value *SrcPtr, llvm::Value *DestPtr,
  4574. SmallVector<Value *, 4> &idxList, clang::QualType SrcType,
  4575. clang::QualType DestType, llvm::Type *Ty) {
  4576. if (llvm::PointerType *PT = dyn_cast<llvm::PointerType>(Ty)) {
  4577. Constant *idx = Constant::getIntegerValue(
  4578. IntegerType::get(Ty->getContext(), 32), APInt(32, 0));
  4579. idxList.emplace_back(idx);
  4580. EmitHLSLAggregateCopy(CGF, SrcPtr, DestPtr, idxList, SrcType, DestType,
  4581. PT->getElementType());
  4582. idxList.pop_back();
  4583. } else if (HLMatrixType::isa(Ty)) {
  4584. // Use matLd/St for matrix.
  4585. Value *SrcMatPtr = CreateInBoundsGEPIfNeeded(SrcPtr, idxList, CGF.Builder);
  4586. Value *DestMatPtr = CreateInBoundsGEPIfNeeded(DestPtr, idxList, CGF.Builder);
  4587. Value *ldMat = EmitHLSLMatrixLoad(CGF, SrcMatPtr, SrcType);
  4588. EmitHLSLMatrixStore(CGF, ldMat, DestMatPtr, DestType);
  4589. } else if (StructType *ST = dyn_cast<StructType>(Ty)) {
  4590. if (dxilutil::IsHLSLObjectType(ST)) {
  4591. // Avoid split HLSL object.
  4592. SimpleCopy(DestPtr, SrcPtr, idxList, CGF.Builder);
  4593. return;
  4594. }
  4595. Value *SrcStructPtr = CreateInBoundsGEPIfNeeded(SrcPtr, idxList, CGF.Builder);
  4596. Value *DestStructPtr = CreateInBoundsGEPIfNeeded(DestPtr, idxList, CGF.Builder);
  4597. unsigned size = this->TheModule.getDataLayout().getTypeAllocSize(ST);
  4598. // Memcpy struct.
  4599. CGF.Builder.CreateMemCpy(DestStructPtr, SrcStructPtr, size, 1);
  4600. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty)) {
  4601. if (!HLMatrixType::isMatrixArray(Ty)
  4602. || AreMatrixArrayOrientationMatching(CGF.getContext(), *m_pHLModule, SrcType, DestType)) {
  4603. Value *SrcArrayPtr = CreateInBoundsGEPIfNeeded(SrcPtr, idxList, CGF.Builder);
  4604. Value *DestArrayPtr = CreateInBoundsGEPIfNeeded(DestPtr, idxList, CGF.Builder);
  4605. unsigned size = this->TheModule.getDataLayout().getTypeAllocSize(AT);
  4606. // Memcpy non-matrix array.
  4607. CGF.Builder.CreateMemCpy(DestArrayPtr, SrcArrayPtr, size, 1);
  4608. } else {
  4609. // Copy matrix arrays elementwise if orientation changes are needed.
  4610. llvm::Type *ET = AT->getElementType();
  4611. QualType EltDestType = CGF.getContext().getBaseElementType(DestType);
  4612. QualType EltSrcType = CGF.getContext().getBaseElementType(SrcType);
  4613. for (uint32_t i = 0; i < AT->getNumElements(); i++) {
  4614. Constant *idx = Constant::getIntegerValue(
  4615. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  4616. idxList.emplace_back(idx);
  4617. EmitHLSLAggregateCopy(CGF, SrcPtr, DestPtr, idxList, EltSrcType,
  4618. EltDestType, ET);
  4619. idxList.pop_back();
  4620. }
  4621. }
  4622. } else {
  4623. SimpleCopy(DestPtr, SrcPtr, idxList, CGF.Builder);
  4624. }
  4625. }
  4626. void CGMSHLSLRuntime::EmitHLSLAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  4627. llvm::Value *DestPtr,
  4628. clang::QualType Ty) {
  4629. SmallVector<Value *, 4> idxList;
  4630. EmitHLSLAggregateCopy(CGF, SrcPtr, DestPtr, idxList, Ty, Ty, SrcPtr->getType());
  4631. }
  4632. // Make sure all element type of struct is same type.
  4633. static bool IsStructWithSameElementType(llvm::StructType *ST, llvm::Type *Ty) {
  4634. for (llvm::Type *EltTy : ST->elements()) {
  4635. if (StructType *EltSt = dyn_cast<StructType>(EltTy)) {
  4636. if (!IsStructWithSameElementType(EltSt, Ty))
  4637. return false;
  4638. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(EltTy)) {
  4639. llvm::Type *ArrayEltTy = dxilutil::GetArrayEltTy(AT);
  4640. if (ArrayEltTy == Ty) {
  4641. continue;
  4642. } else if (StructType *EltSt = dyn_cast<StructType>(EltTy)) {
  4643. if (!IsStructWithSameElementType(EltSt, Ty))
  4644. return false;
  4645. } else {
  4646. return false;
  4647. }
  4648. } else if (EltTy != Ty)
  4649. return false;
  4650. }
  4651. return true;
  4652. }
  4653. // To memcpy, need element type match.
  4654. // For struct type, the layout should match in cbuffer layout.
  4655. // struct { float2 x; float3 y; } will not match struct { float3 x; float2 y; }.
  4656. // struct { float2 x; float3 y; } will not match array of float.
  4657. static bool IsTypeMatchForMemcpy(llvm::Type *SrcTy, llvm::Type *DestTy) {
  4658. llvm::Type *SrcEltTy = dxilutil::GetArrayEltTy(SrcTy);
  4659. llvm::Type *DestEltTy = dxilutil::GetArrayEltTy(DestTy);
  4660. if (SrcEltTy == DestEltTy)
  4661. return true;
  4662. llvm::StructType *SrcST = dyn_cast<llvm::StructType>(SrcEltTy);
  4663. llvm::StructType *DestST = dyn_cast<llvm::StructType>(DestEltTy);
  4664. if (SrcST && DestST) {
  4665. // Only allow identical struct.
  4666. return SrcST->isLayoutIdentical(DestST);
  4667. } else if (!SrcST && !DestST) {
  4668. // For basic type, if one is array, one is not array, layout is different.
  4669. // If both array, type mismatch. If both basic, copy should be fine.
  4670. // So all return false.
  4671. return false;
  4672. } else {
  4673. // One struct, one basic type.
  4674. // Make sure all struct element match the basic type and basic type is
  4675. // vector4.
  4676. llvm::StructType *ST = SrcST ? SrcST : DestST;
  4677. llvm::Type *Ty = SrcST ? DestEltTy : SrcEltTy;
  4678. if (!Ty->isVectorTy())
  4679. return false;
  4680. if (Ty->getVectorNumElements() != 4)
  4681. return false;
  4682. return IsStructWithSameElementType(ST, Ty);
  4683. }
  4684. }
  4685. void CGMSHLSLRuntime::EmitHLSLFlatConversionAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  4686. clang::QualType SrcTy,
  4687. llvm::Value *DestPtr,
  4688. clang::QualType DestTy) {
  4689. llvm::Type *SrcPtrTy = SrcPtr->getType()->getPointerElementType();
  4690. llvm::Type *DestPtrTy = DestPtr->getType()->getPointerElementType();
  4691. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  4692. if (SrcPtrTy == DestPtrTy) {
  4693. bool bMatArrayRotate = false;
  4694. if (HLMatrixType::isMatrixArrayPtr(SrcPtr->getType())) {
  4695. QualType SrcEltTy = GetArrayEltType(CGM.getContext(), SrcTy);
  4696. QualType DestEltTy = GetArrayEltType(CGM.getContext(), DestTy);
  4697. if (GetMatrixMajor(SrcEltTy, bDefaultRowMajor) !=
  4698. GetMatrixMajor(DestEltTy, bDefaultRowMajor)) {
  4699. bMatArrayRotate = true;
  4700. }
  4701. }
  4702. if (!bMatArrayRotate) {
  4703. // Memcpy if type is match.
  4704. unsigned size = TheModule.getDataLayout().getTypeAllocSize(SrcPtrTy);
  4705. CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, size, 1);
  4706. return;
  4707. }
  4708. } else if (dxilutil::IsHLSLResourceDescType(SrcPtrTy) &&
  4709. dxilutil::IsHLSLResourceType(DestPtrTy)) {
  4710. // Cast resource desc to resource.
  4711. Value *CastPtr = CGF.Builder.CreatePointerCast(SrcPtr, DestPtr->getType());
  4712. // Load resource.
  4713. Value *V = CGF.Builder.CreateLoad(CastPtr);
  4714. // Store to resource ptr.
  4715. CGF.Builder.CreateStore(V, DestPtr);
  4716. return;
  4717. } else if (dxilutil::IsHLSLObjectType(dxilutil::GetArrayEltTy(SrcPtrTy)) &&
  4718. dxilutil::IsHLSLObjectType(dxilutil::GetArrayEltTy(DestPtrTy))) {
  4719. unsigned sizeSrc = TheModule.getDataLayout().getTypeAllocSize(SrcPtrTy);
  4720. unsigned sizeDest = TheModule.getDataLayout().getTypeAllocSize(DestPtrTy);
  4721. CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, std::max(sizeSrc, sizeDest), 1);
  4722. return;
  4723. } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(DestPtr)) {
  4724. if (GV->isInternalLinkage(GV->getLinkage()) &&
  4725. IsTypeMatchForMemcpy(SrcPtrTy, DestPtrTy)) {
  4726. unsigned sizeSrc = TheModule.getDataLayout().getTypeAllocSize(SrcPtrTy);
  4727. unsigned sizeDest = TheModule.getDataLayout().getTypeAllocSize(DestPtrTy);
  4728. CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, std::min(sizeSrc, sizeDest), 1);
  4729. return;
  4730. }
  4731. }
  4732. // It is possible to implement EmitHLSLAggregateCopy, EmitHLSLAggregateStore
  4733. // the same way. But split value to scalar will generate many instruction when
  4734. // src type is same as dest type.
  4735. SmallVector<Value *, 4> GEPIdxStack;
  4736. SmallVector<Value *, 4> SrcPtrs;
  4737. SmallVector<QualType, 4> SrcQualTys;
  4738. FlattenAggregatePtrToGepList(CGF, SrcPtr, GEPIdxStack, SrcTy, SrcPtr->getType(),
  4739. SrcPtrs, SrcQualTys);
  4740. SmallVector<Value *, 4> SrcVals;
  4741. LoadElements(CGF, SrcPtrs, SrcQualTys, SrcVals);
  4742. GEPIdxStack.clear();
  4743. SmallVector<Value *, 4> DstPtrs;
  4744. SmallVector<QualType, 4> DstQualTys;
  4745. FlattenAggregatePtrToGepList(CGF, DestPtr, GEPIdxStack, DestTy,
  4746. DestPtr->getType(), DstPtrs, DstQualTys);
  4747. ConvertAndStoreElements(CGF, SrcVals, SrcQualTys, DstPtrs, DstQualTys);
  4748. }
  4749. void CGMSHLSLRuntime::EmitHLSLAggregateStore(CodeGenFunction &CGF, llvm::Value *SrcVal,
  4750. llvm::Value *DestPtr,
  4751. clang::QualType Ty) {
  4752. DXASSERT(0, "aggregate return type will use SRet, no aggregate store should exist");
  4753. }
  4754. // Either copies a scalar to a scalar, a scalar to a vector, or splats a scalar to a vector
  4755. static void SimpleFlatValCopy(CodeGenFunction &CGF,
  4756. Value *SrcVal, QualType SrcQualTy, Value *DstPtr, QualType DstQualTy) {
  4757. DXASSERT(SrcVal->getType() == CGF.ConvertType(SrcQualTy), "QualType/Type mismatch!");
  4758. llvm::Type *DstTy = DstPtr->getType()->getPointerElementType();
  4759. DXASSERT(DstTy == CGF.ConvertTypeForMem(DstQualTy), "QualType/Type mismatch!");
  4760. llvm::VectorType *DstVecTy = dyn_cast<llvm::VectorType>(DstTy);
  4761. QualType DstScalarQualTy = DstQualTy;
  4762. if (DstVecTy) {
  4763. DstScalarQualTy = hlsl::GetHLSLVecElementType(DstQualTy);
  4764. }
  4765. Value *ResultScalar = ConvertScalarOrVector(CGF, SrcVal, SrcQualTy, DstScalarQualTy);
  4766. ResultScalar = CGF.EmitToMemory(ResultScalar, DstScalarQualTy);
  4767. if (DstVecTy) {
  4768. llvm::VectorType *DstScalarVecTy = llvm::VectorType::get(ResultScalar->getType(), 1);
  4769. Value *ResultScalarVec = CGF.Builder.CreateInsertElement(
  4770. UndefValue::get(DstScalarVecTy), ResultScalar, (uint64_t)0);
  4771. std::vector<int> ShufIdx(DstVecTy->getNumElements(), 0);
  4772. Value *ResultVec = CGF.Builder.CreateShuffleVector(ResultScalarVec, ResultScalarVec, ShufIdx);
  4773. CGF.Builder.CreateStore(ResultVec, DstPtr);
  4774. } else
  4775. CGF.Builder.CreateStore(ResultScalar, DstPtr);
  4776. }
  4777. void CGMSHLSLRuntime::EmitHLSLSplat(
  4778. CodeGenFunction &CGF, Value *SrcVal, llvm::Value *DestPtr,
  4779. SmallVector<Value *, 4> &idxList, QualType Type, QualType SrcType,
  4780. llvm::Type *Ty) {
  4781. if (llvm::PointerType *PT = dyn_cast<llvm::PointerType>(Ty)) {
  4782. idxList.emplace_back(CGF.Builder.getInt32(0));
  4783. EmitHLSLSplat(CGF, SrcVal, DestPtr, idxList, Type,
  4784. SrcType, PT->getElementType());
  4785. idxList.pop_back();
  4786. } else if (HLMatrixType MatTy = HLMatrixType::dyn_cast(Ty)) {
  4787. // Use matLd/St for matrix.
  4788. Value *dstGEP = CGF.Builder.CreateInBoundsGEP(DestPtr, idxList);
  4789. llvm::Type *EltTy = MatTy.getElementTypeForReg();
  4790. llvm::VectorType *VT1 = llvm::VectorType::get(EltTy, 1);
  4791. SrcVal = ConvertScalarOrVector(CGF, SrcVal, SrcType, hlsl::GetHLSLMatElementType(Type));
  4792. // Splat the value
  4793. Value *V1 = CGF.Builder.CreateInsertElement(UndefValue::get(VT1), SrcVal,
  4794. (uint64_t)0);
  4795. std::vector<int> shufIdx(MatTy.getNumElements(), 0);
  4796. Value *VecMat = CGF.Builder.CreateShuffleVector(V1, V1, shufIdx);
  4797. Value *MatInit = EmitHLSLMatrixOperationCallImp(
  4798. CGF.Builder, HLOpcodeGroup::HLInit, 0, Ty, {VecMat}, TheModule);
  4799. EmitHLSLMatrixStore(CGF, MatInit, dstGEP, Type);
  4800. } else if (StructType *ST = dyn_cast<StructType>(Ty)) {
  4801. DXASSERT(!dxilutil::IsHLSLObjectType(ST), "cannot cast to hlsl object, Sema should reject");
  4802. const clang::RecordType *RT = Type->getAsStructureType();
  4803. RecordDecl *RD = RT->getDecl();
  4804. const CGRecordLayout &RL = CGF.getTypes().getCGRecordLayout(RD);
  4805. // Take care base.
  4806. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  4807. if (CXXRD->getNumBases()) {
  4808. for (const auto &I : CXXRD->bases()) {
  4809. const CXXRecordDecl *BaseDecl =
  4810. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  4811. if (BaseDecl->field_empty())
  4812. continue;
  4813. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  4814. unsigned i = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  4815. llvm::Type *ET = ST->getElementType(i);
  4816. Constant *idx = llvm::Constant::getIntegerValue(
  4817. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  4818. idxList.emplace_back(idx);
  4819. EmitHLSLSplat(CGF, SrcVal, DestPtr, idxList, parentTy, SrcType, ET);
  4820. idxList.pop_back();
  4821. }
  4822. }
  4823. }
  4824. for (auto fieldIter = RD->field_begin(), fieldEnd = RD->field_end();
  4825. fieldIter != fieldEnd; ++fieldIter) {
  4826. unsigned i = RL.getLLVMFieldNo(*fieldIter);
  4827. llvm::Type *ET = ST->getElementType(i);
  4828. Constant *idx = llvm::Constant::getIntegerValue(
  4829. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  4830. idxList.emplace_back(idx);
  4831. EmitHLSLSplat(CGF, SrcVal, DestPtr, idxList, fieldIter->getType(), SrcType, ET);
  4832. idxList.pop_back();
  4833. }
  4834. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty)) {
  4835. llvm::Type *ET = AT->getElementType();
  4836. QualType EltType = CGF.getContext().getBaseElementType(Type);
  4837. for (uint32_t i = 0; i < AT->getNumElements(); i++) {
  4838. Constant *idx = Constant::getIntegerValue(
  4839. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  4840. idxList.emplace_back(idx);
  4841. EmitHLSLSplat(CGF, SrcVal, DestPtr, idxList, EltType, SrcType, ET);
  4842. idxList.pop_back();
  4843. }
  4844. } else {
  4845. DestPtr = CGF.Builder.CreateInBoundsGEP(DestPtr, idxList);
  4846. SimpleFlatValCopy(CGF, SrcVal, SrcType, DestPtr, Type);
  4847. }
  4848. }
  4849. void CGMSHLSLRuntime::EmitHLSLFlatConversion(CodeGenFunction &CGF,
  4850. Value *Val,
  4851. Value *DestPtr,
  4852. QualType Ty,
  4853. QualType SrcTy) {
  4854. SmallVector<Value *, 4> SrcVals;
  4855. SmallVector<QualType, 4> SrcQualTys;
  4856. FlattenValToInitList(CGF, SrcVals, SrcQualTys, SrcTy, Val);
  4857. if (SrcVals.size() == 1) {
  4858. // Perform a splat
  4859. SmallVector<Value *, 4> GEPIdxStack;
  4860. GEPIdxStack.emplace_back(CGF.Builder.getInt32(0)); // Add first 0 for DestPtr.
  4861. EmitHLSLSplat(
  4862. CGF, SrcVals[0], DestPtr, GEPIdxStack, Ty, SrcQualTys[0],
  4863. DestPtr->getType()->getPointerElementType());
  4864. }
  4865. else {
  4866. SmallVector<Value *, 4> GEPIdxStack;
  4867. SmallVector<Value *, 4> DstPtrs;
  4868. SmallVector<QualType, 4> DstQualTys;
  4869. FlattenAggregatePtrToGepList(CGF, DestPtr, GEPIdxStack, Ty, DestPtr->getType(), DstPtrs, DstQualTys);
  4870. ConvertAndStoreElements(CGF, SrcVals, SrcQualTys, DstPtrs, DstQualTys);
  4871. }
  4872. }
  4873. void CGMSHLSLRuntime::EmitHLSLRootSignature(CodeGenFunction &CGF,
  4874. HLSLRootSignatureAttr *RSA,
  4875. Function *Fn) {
  4876. // Only parse root signature for entry function.
  4877. if (Fn != Entry.Func)
  4878. return;
  4879. StringRef StrRef = RSA->getSignatureName();
  4880. DiagnosticsEngine &Diags = CGF.getContext().getDiagnostics();
  4881. SourceLocation SLoc = RSA->getLocation();
  4882. RootSignatureHandle RootSigHandle;
  4883. clang::CompileRootSignature(StrRef, Diags, SLoc, rootSigVer, DxilRootSignatureCompilationFlags::GlobalRootSignature, &RootSigHandle);
  4884. if (!RootSigHandle.IsEmpty()) {
  4885. RootSigHandle.EnsureSerializedAvailable();
  4886. m_pHLModule->SetSerializedRootSignature(RootSigHandle.GetSerializedBytes(),
  4887. RootSigHandle.GetSerializedSize());
  4888. }
  4889. }
  4890. void CGMSHLSLRuntime::EmitHLSLOutParamConversionInit(
  4891. CodeGenFunction &CGF, const FunctionDecl *FD, const CallExpr *E,
  4892. llvm::SmallVector<LValue, 8> &castArgList,
  4893. llvm::SmallVector<const Stmt *, 8> &argList,
  4894. const std::function<void(const VarDecl *, llvm::Value *)> &TmpArgMap) {
  4895. // Special case: skip first argument of CXXOperatorCall (it is "this").
  4896. unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(E) ? 1 : 0;
  4897. for (uint32_t i = 0; i < FD->getNumParams(); i++) {
  4898. const ParmVarDecl *Param = FD->getParamDecl(i);
  4899. const Expr *Arg = E->getArg(i+ArgsToSkip);
  4900. QualType ParamTy = Param->getType().getNonReferenceType();
  4901. bool isObject = dxilutil::IsHLSLObjectType(CGF.ConvertTypeForMem(ParamTy));
  4902. bool isAggregateType = !isObject &&
  4903. (ParamTy->isArrayType() || ParamTy->isRecordType()) &&
  4904. !hlsl::IsHLSLVecMatType(ParamTy);
  4905. bool EmitRValueAgg = false;
  4906. bool RValOnRef = false;
  4907. if (!Param->isModifierOut()) {
  4908. if (!isAggregateType && !isObject) {
  4909. if (Arg->isRValue() && Param->getType()->isReferenceType()) {
  4910. // RValue on a reference type.
  4911. if (const CStyleCastExpr *cCast = dyn_cast<CStyleCastExpr>(Arg)) {
  4912. // TODO: Evolving this to warn then fail in future language versions.
  4913. // Allow special case like cast uint to uint for back-compat.
  4914. if (cCast->getCastKind() == CastKind::CK_NoOp) {
  4915. if (const ImplicitCastExpr *cast =
  4916. dyn_cast<ImplicitCastExpr>(cCast->getSubExpr())) {
  4917. if (cast->getCastKind() == CastKind::CK_LValueToRValue) {
  4918. // update the arg
  4919. argList[i] = cast->getSubExpr();
  4920. continue;
  4921. }
  4922. }
  4923. }
  4924. }
  4925. // EmitLValue will report error.
  4926. // Mark RValOnRef to create tmpArg for it.
  4927. RValOnRef = true;
  4928. } else {
  4929. continue;
  4930. }
  4931. } else if (isAggregateType) {
  4932. // aggregate in-only - emit RValue, unless LValueToRValue cast
  4933. EmitRValueAgg = true;
  4934. if (const ImplicitCastExpr *cast =
  4935. dyn_cast<ImplicitCastExpr>(Arg)) {
  4936. if (cast->getCastKind() == CastKind::CK_LValueToRValue) {
  4937. EmitRValueAgg = false;
  4938. }
  4939. }
  4940. } else {
  4941. // Must be object
  4942. DXASSERT(isObject, "otherwise, flow condition changed, breaking assumption");
  4943. // in-only objects should be skipped to preserve previous behavior.
  4944. continue;
  4945. }
  4946. }
  4947. // Skip unbounded array, since we cannot preserve copy-in copy-out
  4948. // semantics for these.
  4949. if (ParamTy->isIncompleteArrayType()) {
  4950. continue;
  4951. }
  4952. if (!Param->isModifierOut() && !RValOnRef) {
  4953. // No need to copy arg to in-only param for hlsl intrinsic.
  4954. if (const FunctionDecl *Callee = E->getDirectCallee()) {
  4955. if (Callee->hasAttr<HLSLIntrinsicAttr>())
  4956. continue;
  4957. }
  4958. }
  4959. // get original arg
  4960. // FIXME: This will not emit in correct argument order with the other
  4961. // arguments. This should be integrated into
  4962. // CodeGenFunction::EmitCallArg if possible.
  4963. RValue argRV; // emit this if aggregate arg on in-only param
  4964. LValue argLV; // otherwise, we may emit this
  4965. llvm::Value *argAddr = nullptr;
  4966. QualType argType = Arg->getType();
  4967. CharUnits argAlignment;
  4968. if (EmitRValueAgg) {
  4969. argRV = CGF.EmitAnyExprToTemp(Arg);
  4970. argAddr = argRV.getAggregateAddr(); // must be alloca
  4971. argAlignment = CharUnits::fromQuantity(cast<AllocaInst>(argAddr)->getAlignment());
  4972. argLV = LValue::MakeAddr(argAddr, ParamTy, argAlignment, CGF.getContext());
  4973. } else {
  4974. argLV = CGF.EmitLValue(Arg);
  4975. if (argLV.isSimple())
  4976. argAddr = argLV.getAddress();
  4977. // TODO: enable avoid copy for lib profile.
  4978. if (!m_bIsLib) {
  4979. // When there's argument need to lower like buffer/cbuffer load, need to
  4980. // copy to let the lower not happen on argument when calle is noinline
  4981. // or extern functions. Will do it in HLLegalizeParameter after known
  4982. // which functions are extern but before inline.
  4983. bool bConstGlobal = false;
  4984. Value *Ptr = argAddr;
  4985. while (GEPOperator *GEP = dyn_cast_or_null<GEPOperator>(Ptr)) {
  4986. Ptr = GEP->getPointerOperand();
  4987. }
  4988. if (GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(Ptr)) {
  4989. bConstGlobal = m_ConstVarAnnotationMap.count(GV) | GV->isConstant();
  4990. }
  4991. // Skip copy-in copy-out when safe.
  4992. // The unsafe case will be global variable alias with parameter.
  4993. // Then global variable is updated in the function, the parameter will
  4994. // be updated silently. For non global variable or constant global
  4995. // variable, it should be safe.
  4996. if (argAddr &&
  4997. (isa<AllocaInst>(Ptr) || isa<Argument>(Ptr) || bConstGlobal)) {
  4998. llvm::Type *ToTy = CGF.ConvertType(ParamTy.getNonReferenceType());
  4999. if (argAddr->getType()->getPointerElementType() == ToTy &&
  5000. // Check clang Type for case like int cast to unsigned.
  5001. ParamTy.getNonReferenceType().getCanonicalType().getTypePtr() ==
  5002. Arg->getType().getCanonicalType().getTypePtr())
  5003. continue;
  5004. }
  5005. }
  5006. argType = argLV.getType(); // TBD: Can this be different than Arg->getType()?
  5007. argAlignment = argLV.getAlignment();
  5008. }
  5009. // After emit Arg, we must update the argList[i],
  5010. // otherwise we get double emit of the expression.
  5011. // create temp Var
  5012. VarDecl *tmpArg =
  5013. VarDecl::Create(CGF.getContext(), const_cast<FunctionDecl *>(FD),
  5014. SourceLocation(), SourceLocation(),
  5015. /*IdentifierInfo*/ nullptr, ParamTy,
  5016. CGF.getContext().getTrivialTypeSourceInfo(ParamTy),
  5017. StorageClass::SC_Auto);
  5018. // Aggregate type will be indirect param convert to pointer type.
  5019. // So don't update to ReferenceType, use RValue for it.
  5020. const DeclRefExpr *tmpRef = DeclRefExpr::Create(
  5021. CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), tmpArg,
  5022. /*enclosing*/ false, tmpArg->getLocation(), ParamTy,
  5023. (isAggregateType || isObject) ? VK_RValue : VK_LValue);
  5024. // must update the arg, since we did emit Arg, else we get double emit.
  5025. argList[i] = tmpRef;
  5026. // create alloc for the tmp arg
  5027. Value *tmpArgAddr = nullptr;
  5028. BasicBlock *InsertBlock = CGF.Builder.GetInsertBlock();
  5029. Function *F = InsertBlock->getParent();
  5030. // Make sure the alloca is in entry block to stop inline create stacksave.
  5031. IRBuilder<> AllocaBuilder(dxilutil::FindAllocaInsertionPt(F));
  5032. tmpArgAddr = AllocaBuilder.CreateAlloca(CGF.ConvertTypeForMem(ParamTy));
  5033. // add it to local decl map
  5034. TmpArgMap(tmpArg, tmpArgAddr);
  5035. LValue tmpLV = LValue::MakeAddr(tmpArgAddr, ParamTy, argAlignment,
  5036. CGF.getContext());
  5037. // save for cast after call
  5038. if (Param->isModifierOut()) {
  5039. castArgList.emplace_back(tmpLV);
  5040. castArgList.emplace_back(argLV);
  5041. }
  5042. // cast before the call
  5043. if (Param->isModifierIn() &&
  5044. // Don't copy object
  5045. !isObject) {
  5046. QualType ArgTy = Arg->getType();
  5047. Value *outVal = nullptr;
  5048. if (!isAggregateType) {
  5049. if (!IsHLSLMatType(ParamTy)) {
  5050. RValue outRVal = CGF.EmitLoadOfLValue(argLV, SourceLocation());
  5051. outVal = outRVal.getScalarVal();
  5052. } else {
  5053. DXASSERT(argAddr, "should be RV or simple LV");
  5054. outVal = EmitHLSLMatrixLoad(CGF, argAddr, ArgTy);
  5055. }
  5056. llvm::Type *ToTy = tmpArgAddr->getType()->getPointerElementType();
  5057. if (HLMatrixType::isa(ToTy)) {
  5058. Value *castVal = CGF.Builder.CreateBitCast(outVal, ToTy);
  5059. EmitHLSLMatrixStore(CGF, castVal, tmpArgAddr, ParamTy);
  5060. }
  5061. else {
  5062. Value *castVal = ConvertScalarOrVector(CGF, outVal, argType, ParamTy);
  5063. castVal = CGF.EmitToMemory(castVal, ParamTy);
  5064. CGF.Builder.CreateStore(castVal, tmpArgAddr);
  5065. }
  5066. } else {
  5067. DXASSERT(argAddr, "should be RV or simple LV");
  5068. SmallVector<Value *, 4> idxList;
  5069. EmitHLSLAggregateCopy(CGF, argAddr, tmpArgAddr,
  5070. idxList, ArgTy, ParamTy,
  5071. argAddr->getType());
  5072. }
  5073. }
  5074. }
  5075. }
  5076. void CGMSHLSLRuntime::EmitHLSLOutParamConversionCopyBack(
  5077. CodeGenFunction &CGF, llvm::SmallVector<LValue, 8> &castArgList) {
  5078. for (uint32_t i = 0; i < castArgList.size(); i += 2) {
  5079. // cast after the call
  5080. LValue tmpLV = castArgList[i];
  5081. LValue argLV = castArgList[i + 1];
  5082. QualType ArgTy = argLV.getType().getNonReferenceType();
  5083. QualType ParamTy = tmpLV.getType().getNonReferenceType();
  5084. Value *tmpArgAddr = tmpLV.getAddress();
  5085. Value *outVal = nullptr;
  5086. bool isAggregateTy = hlsl::IsHLSLAggregateType(ArgTy);
  5087. bool isObject = dxilutil::IsHLSLObjectType(
  5088. tmpArgAddr->getType()->getPointerElementType());
  5089. if (!isObject) {
  5090. if (!isAggregateTy) {
  5091. if (!IsHLSLMatType(ParamTy))
  5092. outVal = CGF.Builder.CreateLoad(tmpArgAddr);
  5093. else
  5094. outVal = EmitHLSLMatrixLoad(CGF, tmpArgAddr, ParamTy);
  5095. outVal = CGF.EmitFromMemory(outVal, ParamTy);
  5096. llvm::Type *ToTy = CGF.ConvertType(ArgTy);
  5097. llvm::Type *FromTy = outVal->getType();
  5098. Value *castVal = outVal;
  5099. if (ToTy == FromTy) {
  5100. // Don't need cast.
  5101. } else if (ToTy->getScalarType() == FromTy->getScalarType()) {
  5102. if (ToTy->getScalarType() == ToTy) {
  5103. DXASSERT(FromTy->isVectorTy() &&
  5104. FromTy->getVectorNumElements() == 1,
  5105. "must be vector of 1 element");
  5106. castVal = CGF.Builder.CreateExtractElement(outVal, (uint64_t)0);
  5107. } else {
  5108. DXASSERT(!FromTy->isVectorTy(), "must be scalar type");
  5109. DXASSERT(ToTy->isVectorTy() && ToTy->getVectorNumElements() == 1,
  5110. "must be vector of 1 element");
  5111. castVal = UndefValue::get(ToTy);
  5112. castVal =
  5113. CGF.Builder.CreateInsertElement(castVal, outVal, (uint64_t)0);
  5114. }
  5115. } else {
  5116. castVal = ConvertScalarOrVector(CGF,
  5117. outVal, tmpLV.getType(), argLV.getType());
  5118. }
  5119. if (!HLMatrixType::isa(ToTy))
  5120. CGF.EmitStoreThroughLValue(RValue::get(castVal), argLV);
  5121. else {
  5122. Value *destPtr = argLV.getAddress();
  5123. EmitHLSLMatrixStore(CGF, castVal, destPtr, ArgTy);
  5124. }
  5125. } else {
  5126. SmallVector<Value *, 4> idxList;
  5127. EmitHLSLAggregateCopy(CGF, tmpLV.getAddress(), argLV.getAddress(),
  5128. idxList, ParamTy, ArgTy,
  5129. argLV.getAddress()->getType());
  5130. }
  5131. } else
  5132. tmpArgAddr->replaceAllUsesWith(argLV.getAddress());
  5133. }
  5134. }
  5135. ScopeInfo *CGMSHLSLRuntime::GetScopeInfo(Function *F) {
  5136. auto it = m_ScopeMap.find(F);
  5137. if (it == m_ScopeMap.end())
  5138. return nullptr;
  5139. return &it->second;
  5140. }
  5141. void CGMSHLSLRuntime::MarkIfStmt(CodeGenFunction &CGF, BasicBlock *endIfBB) {
  5142. if (ScopeInfo *Scope = GetScopeInfo(CGF.CurFn))
  5143. Scope->AddIf(endIfBB);
  5144. }
  5145. void CGMSHLSLRuntime::MarkSwitchStmt(CodeGenFunction &CGF,
  5146. SwitchInst *switchInst,
  5147. BasicBlock *endSwitch) {
  5148. if (ScopeInfo *Scope = GetScopeInfo(CGF.CurFn))
  5149. Scope->AddSwitch(endSwitch);
  5150. }
  5151. void CGMSHLSLRuntime::MarkReturnStmt(CodeGenFunction &CGF,
  5152. BasicBlock *bbWithRet) {
  5153. if (ScopeInfo *Scope = GetScopeInfo(CGF.CurFn))
  5154. Scope->AddRet(bbWithRet);
  5155. }
  5156. void CGMSHLSLRuntime::MarkLoopStmt(CodeGenFunction &CGF,
  5157. BasicBlock *loopContinue,
  5158. BasicBlock *loopExit) {
  5159. if (ScopeInfo *Scope = GetScopeInfo(CGF.CurFn))
  5160. Scope->AddLoop(loopContinue, loopExit);
  5161. }
  5162. void CGMSHLSLRuntime::MarkScopeEnd(CodeGenFunction &CGF) {
  5163. if (ScopeInfo *Scope = GetScopeInfo(CGF.CurFn)) {
  5164. llvm::BasicBlock *CurBB = CGF.Builder.GetInsertBlock();
  5165. bool bScopeFinishedWithRet = !CurBB || CurBB->getTerminator();
  5166. Scope->EndScope(bScopeFinishedWithRet);
  5167. }
  5168. }
  5169. CGHLSLRuntime *CodeGen::CreateMSHLSLRuntime(CodeGenModule &CGM) {
  5170. return new CGMSHLSLRuntime(CGM);
  5171. }