CGHLSLMS.cpp 214 KB

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