CGHLSLMS.cpp 213 KB

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