CGHLSLMS.cpp 203 KB

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