CGHLSLMS.cpp 192 KB

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