CGHLSLMS.cpp 214 KB

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