CGHLSLMS.cpp 199 KB

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