CGHLSLMS.cpp 233 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116
  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/HLMatrixType.h"
  18. #include "dxc/HLSL/HLModule.h"
  19. #include "dxc/DXIL/DxilUtil.h"
  20. #include "dxc/HLSL/HLOperations.h"
  21. #include "dxc/DXIL/DxilOperations.h"
  22. #include "dxc/DXIL/DxilTypeSystem.h"
  23. #include "clang/AST/DeclTemplate.h"
  24. #include "clang/AST/HlslTypes.h"
  25. #include "clang/Frontend/CodeGenOptions.h"
  26. #include "clang/Lex/HLSLMacroExpander.h"
  27. #include "clang/Sema/SemaDiagnostic.h"
  28. #include "llvm/ADT/STLExtras.h"
  29. #include "llvm/ADT/StringSwitch.h"
  30. #include "llvm/ADT/StringSet.h"
  31. #include "llvm/ADT/SmallPtrSet.h"
  32. #include "llvm/ADT/StringSet.h"
  33. #include "llvm/IR/Constants.h"
  34. #include "llvm/IR/IRBuilder.h"
  35. #include "llvm/IR/GetElementPtrTypeIterator.h"
  36. #include "llvm/Transforms/Utils/Cloning.h"
  37. #include "llvm/IR/InstIterator.h"
  38. #include <memory>
  39. #include <unordered_map>
  40. #include <unordered_set>
  41. #include <set>
  42. #include "dxc/DxilRootSignature/DxilRootSignature.h"
  43. #include "dxc/DXIL/DxilCBuffer.h"
  44. #include "clang/Parse/ParseHLSL.h" // root sig would be in Parser if part of lang
  45. #include "dxc/Support/WinIncludes.h" // stream support
  46. #include "dxc/dxcapi.h" // stream support
  47. #include "dxc/HLSL/HLSLExtensionsCodegenHelper.h"
  48. #include "dxc/HLSL/DxilGenerationPass.h" // support pause/resume passes
  49. #include "dxc/HLSL/DxilExportMap.h"
  50. #include "dxc/DXIL/DxilResourceProperties.h"
  51. #include "CGHLSLMSHelper.h"
  52. using namespace clang;
  53. using namespace CodeGen;
  54. using namespace hlsl;
  55. using namespace llvm;
  56. using std::unique_ptr;
  57. using namespace CGHLSLMSHelper;
  58. static const bool KeepUndefinedTrue = true; // Keep interpolation mode undefined if not set explicitly.
  59. namespace {
  60. class CGMSHLSLRuntime : public CGHLSLRuntime {
  61. private:
  62. /// Convenience reference to LLVM Context
  63. llvm::LLVMContext &Context;
  64. /// Convenience reference to the current module
  65. llvm::Module &TheModule;
  66. HLModule *m_pHLModule;
  67. llvm::Type *CBufferType;
  68. uint32_t globalCBIndex;
  69. // TODO: make sure how minprec works
  70. llvm::DataLayout dataLayout;
  71. // decl map to constant id for program
  72. llvm::DenseMap<HLSLBufferDecl *, uint32_t> constantBufMap;
  73. // Map for resource type to resource metadata value.
  74. std::unordered_map<llvm::Type *, MDNode*> resMetadataMap;
  75. // Map from Constant to register bindings.
  76. llvm::DenseMap<llvm::Constant *,
  77. llvm::SmallVector<std::pair<DXIL::ResourceClass, unsigned>, 1>>
  78. constantRegBindingMap;
  79. // Map from value to resource properties.
  80. // This only collect object variables(global/local/parameter), not object fields inside struct.
  81. // Object fields inside struct is saved by TypeAnnotation.
  82. // Returns true if added to one.
  83. bool AddValToPropertyMap(Value *V, QualType Ty);
  84. CGHLSLMSHelper::DxilObjectProperties objectProperties;
  85. bool m_bDebugInfo;
  86. bool m_bIsLib;
  87. // For library, m_ExportMap maps from internal name to zero or more renames
  88. dxilutil::ExportMap m_ExportMap;
  89. HLCBuffer &GetGlobalCBuffer() {
  90. return *static_cast<HLCBuffer*>(&(m_pHLModule->GetCBuffer(globalCBIndex)));
  91. }
  92. void AddConstantToCB(GlobalVariable *CV, StringRef Name, QualType Ty,
  93. unsigned LowerBound, HLCBuffer &CB);
  94. void AddConstant(VarDecl *constDecl, HLCBuffer &CB);
  95. uint32_t AddSampler(VarDecl *samplerDecl);
  96. uint32_t AddUAVSRV(VarDecl *decl, hlsl::DxilResourceBase::Class resClass);
  97. bool SetUAVSRV(SourceLocation loc, hlsl::DxilResourceBase::Class resClass,
  98. DxilResource *hlslRes, QualType QualTy);
  99. uint32_t AddCBuffer(HLSLBufferDecl *D);
  100. uint32_t AddConstantBufferView(VarDecl *D);
  101. hlsl::DxilResourceBase::Class TypeToClass(clang::QualType Ty);
  102. void CreateSubobject(DXIL::SubobjectKind kind, const StringRef name, clang::Expr **args,
  103. unsigned int argCount, DXIL::HitGroupType hgType = (DXIL::HitGroupType)(-1));
  104. bool GetAsConstantString(clang::Expr *expr, StringRef *value, bool failWhenEmpty = false);
  105. bool GetAsConstantUInt32(clang::Expr *expr, uint32_t *value);
  106. std::vector<StringRef> ParseSubobjectExportsAssociations(StringRef exports);
  107. EntryFunctionInfo Entry;
  108. StringMap<PatchConstantInfo> patchConstantFunctionMap;
  109. std::unordered_map<Function *, std::unique_ptr<DxilFunctionProps>>
  110. patchConstantFunctionPropsMap;
  111. std::unordered_map<Function *, const clang::HLSLPatchConstantFuncAttr *>
  112. HSEntryPatchConstantFuncAttr;
  113. // Map to save entry functions.
  114. StringMap<EntryFunctionInfo> entryFunctionMap;
  115. // Map to save static global init exp.
  116. std::unordered_map<Expr *, GlobalVariable *> staticConstGlobalInitMap;
  117. std::unordered_map<GlobalVariable *, std::vector<Constant *>>
  118. staticConstGlobalInitListMap;
  119. std::unordered_map<GlobalVariable *, Function *> staticConstGlobalCtorMap;
  120. // List for functions with clip plane.
  121. std::vector<Function *> clipPlaneFuncList;
  122. std::unordered_map<Value *, DebugLoc> debugInfoMap;
  123. DxilRootSignatureVersion rootSigVer;
  124. Value *EmitHLSLMatrixLoad(CGBuilderTy &Builder, Value *Ptr, QualType Ty);
  125. void EmitHLSLMatrixStore(CGBuilderTy &Builder, Value *Val, Value *DestPtr,
  126. QualType Ty);
  127. // Flatten the val into scalar val and push into elts and eltTys.
  128. void FlattenValToInitList(CodeGenFunction &CGF, SmallVector<Value *, 4> &elts,
  129. SmallVector<QualType, 4> &eltTys, QualType Ty,
  130. Value *val);
  131. // Push every value on InitListExpr into EltValList and EltTyList.
  132. void ScanInitList(CodeGenFunction &CGF, InitListExpr *E,
  133. SmallVector<Value *, 4> &EltValList,
  134. SmallVector<QualType, 4> &EltTyList);
  135. void FlattenAggregatePtrToGepList(CodeGenFunction &CGF, Value *Ptr,
  136. SmallVector<Value *, 4> &idxList,
  137. clang::QualType Type, llvm::Type *Ty,
  138. SmallVector<Value *, 4> &GepList,
  139. SmallVector<QualType, 4> &EltTyList);
  140. void LoadElements(CodeGenFunction &CGF,
  141. ArrayRef<Value *> Ptrs, ArrayRef<QualType> QualTys,
  142. SmallVector<Value *, 4> &Vals);
  143. void ConvertAndStoreElements(CodeGenFunction &CGF,
  144. ArrayRef<Value *> SrcVals, ArrayRef<QualType> SrcQualTys,
  145. ArrayRef<Value *> DstPtrs, ArrayRef<QualType> DstQualTys);
  146. void EmitHLSLAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  147. llvm::Value *DestPtr,
  148. SmallVector<Value *, 4> &idxList,
  149. clang::QualType SrcType,
  150. clang::QualType DestType,
  151. llvm::Type *Ty);
  152. void EmitHLSLSplat(CodeGenFunction &CGF, Value *SrcVal,
  153. llvm::Value *DestPtr,
  154. SmallVector<Value *, 4> &idxList,
  155. QualType Type, QualType SrcType,
  156. llvm::Type *Ty);
  157. void EmitHLSLRootSignature(CodeGenFunction &CGF, HLSLRootSignatureAttr *RSA,
  158. llvm::Function *Fn) override;
  159. void CheckParameterAnnotation(SourceLocation SLoc,
  160. const DxilParameterAnnotation &paramInfo,
  161. bool isPatchConstantFunction);
  162. void CheckParameterAnnotation(SourceLocation SLoc,
  163. DxilParamInputQual paramQual,
  164. llvm::StringRef semFullName,
  165. bool isPatchConstantFunction);
  166. void RemapObsoleteSemantic(DxilParameterAnnotation &paramInfo,
  167. bool isPatchConstantFunction);
  168. SourceLocation SetSemantic(const NamedDecl *decl,
  169. DxilParameterAnnotation &paramInfo);
  170. hlsl::InterpolationMode GetInterpMode(const Decl *decl, CompType compType,
  171. bool bKeepUndefined);
  172. hlsl::CompType GetCompType(const BuiltinType *BT);
  173. // save intrinsic opcode
  174. std::vector<std::pair<Function *, unsigned>> m_IntrinsicMap;
  175. void AddHLSLIntrinsicOpcodeToFunction(Function *, unsigned opcode);
  176. // Type annotation related.
  177. unsigned ConstructStructAnnotation(DxilStructAnnotation *annotation,
  178. DxilPayloadAnnotation* payloadAnnotation,
  179. const RecordDecl *RD,
  180. DxilTypeSystem &dxilTypeSys);
  181. unsigned AddTypeAnnotation(QualType Ty, DxilTypeSystem &dxilTypeSys,
  182. unsigned &arrayEltSize);
  183. MDNode *GetOrAddResTypeMD(QualType resTy, bool bCreate);
  184. DxilResourceProperties BuildResourceProperty(QualType resTy);
  185. void ConstructFieldAttributedAnnotation(DxilFieldAnnotation &fieldAnnotation,
  186. QualType fieldTy,
  187. bool bDefaultRowMajor);
  188. std::unordered_map<Constant*, DxilFieldAnnotation> m_ConstVarAnnotationMap;
  189. StringSet<> m_PreciseOutputSet;
  190. DenseMap<Function*, ScopeInfo> m_ScopeMap;
  191. ScopeInfo *GetScopeInfo(Function *F);
  192. public:
  193. CGMSHLSLRuntime(CodeGenModule &CGM);
  194. /// Add resouce to the program
  195. void addResource(Decl *D) override;
  196. void addSubobject(Decl *D) override;
  197. void FinishCodeGen() override;
  198. bool IsTrivalInitListExpr(CodeGenFunction &CGF, InitListExpr *E) override;
  199. Value *EmitHLSLInitListExpr(CodeGenFunction &CGF, InitListExpr *E, Value *DestPtr) override;
  200. Constant *EmitHLSLConstInitListExpr(CodeGenModule &CGM, InitListExpr *E) override;
  201. RValue EmitHLSLBuiltinCallExpr(CodeGenFunction &CGF, const FunctionDecl *FD,
  202. const CallExpr *E,
  203. ReturnValueSlot ReturnValue) override;
  204. void EmitHLSLOutParamConversionInit(
  205. CodeGenFunction &CGF, const FunctionDecl *FD, const CallExpr *E,
  206. llvm::SmallVector<LValue, 8> &castArgList,
  207. llvm::SmallVector<const Stmt *, 8> &argList,
  208. llvm::SmallVector<LValue, 8> &lifetimeCleanupList,
  209. const std::function<void(const VarDecl *, llvm::Value *)> &TmpArgMap)
  210. override;
  211. void EmitHLSLOutParamConversionCopyBack(
  212. CodeGenFunction &CGF, llvm::SmallVector<LValue, 8> &castArgList,
  213. llvm::SmallVector<LValue, 8> &lifetimeCleanupList) override;
  214. Value *EmitHLSLMatrixOperationCall(CodeGenFunction &CGF, const clang::Expr *E,
  215. llvm::Type *RetType,
  216. ArrayRef<Value *> paramList) override;
  217. void EmitHLSLDiscard(CodeGenFunction &CGF) override;
  218. BranchInst *EmitHLSLCondBreak(CodeGenFunction &CGF, llvm::Function *F, llvm::BasicBlock *DestBB, llvm::BasicBlock *AltBB) override;
  219. Value *EmitHLSLMatrixSubscript(CodeGenFunction &CGF, llvm::Type *RetType,
  220. Value *Ptr, Value *Idx, QualType Ty) override;
  221. Value *EmitHLSLMatrixElement(CodeGenFunction &CGF, llvm::Type *RetType,
  222. ArrayRef<Value *> paramList,
  223. QualType Ty) override;
  224. Value *EmitHLSLMatrixLoad(CodeGenFunction &CGF, Value *Ptr,
  225. QualType Ty) override;
  226. void EmitHLSLMatrixStore(CodeGenFunction &CGF, Value *Val, Value *DestPtr,
  227. QualType Ty) override;
  228. void EmitHLSLAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  229. llvm::Value *DestPtr,
  230. clang::QualType Ty) override;
  231. void EmitHLSLAggregateStore(CodeGenFunction &CGF, llvm::Value *Val,
  232. llvm::Value *DestPtr,
  233. clang::QualType Ty) override;
  234. void EmitHLSLFlatConversion(CodeGenFunction &CGF, Value *Val,
  235. Value *DestPtr,
  236. QualType Ty,
  237. QualType SrcTy) override;
  238. Value *EmitHLSLLiteralCast(CodeGenFunction &CGF, Value *Src, QualType SrcType,
  239. QualType DstType) override;
  240. void EmitHLSLFlatConversionAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  241. clang::QualType SrcTy,
  242. llvm::Value *DestPtr,
  243. clang::QualType DestTy) override;
  244. void AddHLSLFunctionInfo(llvm::Function *, const FunctionDecl *FD) override;
  245. void EmitHLSLFunctionProlog(llvm::Function *, const FunctionDecl *FD) override;
  246. void AddControlFlowHint(CodeGenFunction &CGF, const Stmt &S,
  247. llvm::TerminatorInst *TI,
  248. ArrayRef<const Attr *> Attrs) override;
  249. void MarkRetTemp(CodeGenFunction &CGF, llvm::Value *V,
  250. clang::QualType QaulTy) override;
  251. void MarkCallArgumentTemp(CodeGenFunction &CGF, llvm::Value *V,
  252. clang::QualType QaulTy) override;
  253. void FinishAutoVar(CodeGenFunction &CGF, const VarDecl &D, llvm::Value *V) override;
  254. void MarkIfStmt(CodeGenFunction &CGF, BasicBlock *endIfBB) override;
  255. void MarkSwitchStmt(CodeGenFunction &CGF, SwitchInst *switchInst,
  256. BasicBlock *endSwitch) override;
  257. void MarkReturnStmt(CodeGenFunction &CGF, BasicBlock *bbWithRet) override;
  258. void MarkLoopStmt(CodeGenFunction &CGF, BasicBlock *loopContinue,
  259. BasicBlock *loopExit) override;
  260. void MarkScopeEnd(CodeGenFunction &CGF) override;
  261. bool NeedHLSLMartrixCastForStoreOp(const clang::Decl* TD,
  262. llvm::SmallVector<llvm::Value*, 16>& IRCallArgs) override;
  263. void EmitHLSLMartrixCastForStoreOp(CodeGenFunction& CGF,
  264. SmallVector<llvm::Value*, 16>& IRCallArgs,
  265. llvm::SmallVector<clang::QualType, 16>& ArgTys) override;
  266. /// Get or add constant to the program
  267. HLCBuffer &GetOrCreateCBuffer(HLSLBufferDecl *D);
  268. };
  269. }
  270. //------------------------------------------------------------------------------
  271. //
  272. // CGMSHLSLRuntime methods.
  273. //
  274. CGMSHLSLRuntime::CGMSHLSLRuntime(CodeGenModule &CGM)
  275. : CGHLSLRuntime(CGM), Context(CGM.getLLVMContext()),
  276. TheModule(CGM.getModule()),
  277. CBufferType(
  278. llvm::StructType::create(TheModule.getContext(), "ConstantBuffer")),
  279. dataLayout(CGM.getLangOpts().UseMinPrecision
  280. ? hlsl::DXIL::kLegacyLayoutString
  281. : hlsl::DXIL::kNewLayoutString), Entry() {
  282. const hlsl::ShaderModel *SM =
  283. hlsl::ShaderModel::GetByName(CGM.getCodeGenOpts().HLSLProfile.c_str());
  284. // Only accept valid, 6.0 shader model.
  285. if (!SM->IsValid() || SM->GetMajor() != 6) {
  286. DiagnosticsEngine &Diags = CGM.getDiags();
  287. unsigned DiagID =
  288. Diags.getCustomDiagID(DiagnosticsEngine::Error, "invalid profile %0");
  289. Diags.Report(DiagID) << CGM.getCodeGenOpts().HLSLProfile;
  290. return;
  291. }
  292. if (CGM.getCodeGenOpts().HLSLValidatorMajorVer != 0) {
  293. // Check validator version against minimum for target profile:
  294. unsigned MinMajor, MinMinor;
  295. SM->GetMinValidatorVersion(MinMajor, MinMinor);
  296. if (DXIL::CompareVersions(CGM.getCodeGenOpts().HLSLValidatorMajorVer,
  297. CGM.getCodeGenOpts().HLSLValidatorMinorVer,
  298. MinMajor, MinMinor) < 0) {
  299. DiagnosticsEngine &Diags = CGM.getDiags();
  300. unsigned DiagID =
  301. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  302. "validator version %0,%1 does not support target profile.");
  303. Diags.Report(DiagID) << CGM.getCodeGenOpts().HLSLValidatorMajorVer
  304. << CGM.getCodeGenOpts().HLSLValidatorMinorVer;
  305. return;
  306. }
  307. }
  308. m_bIsLib = SM->IsLib();
  309. // TODO: add AllResourceBound.
  310. if (CGM.getCodeGenOpts().HLSLAvoidControlFlow && !CGM.getCodeGenOpts().HLSLAllResourcesBound) {
  311. if (SM->IsSM51Plus()) {
  312. DiagnosticsEngine &Diags = CGM.getDiags();
  313. unsigned DiagID =
  314. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  315. "Gfa option cannot be used in SM_5_1+ unless "
  316. "all_resources_bound flag is specified");
  317. Diags.Report(DiagID);
  318. }
  319. }
  320. // Create HLModule.
  321. const bool skipInit = true;
  322. m_pHLModule = &TheModule.GetOrCreateHLModule(skipInit);
  323. // Precise Output.
  324. for (auto &preciseOutput : CGM.getCodeGenOpts().HLSLPreciseOutputs) {
  325. m_PreciseOutputSet.insert(StringRef(preciseOutput).lower());
  326. }
  327. // Set Option.
  328. HLOptions opts;
  329. opts.bIEEEStrict = CGM.getCodeGenOpts().UnsafeFPMath;
  330. opts.bDefaultRowMajor = CGM.getCodeGenOpts().HLSLDefaultRowMajor;
  331. opts.bDisableOptimizations = CGM.getCodeGenOpts().DisableLLVMOpts;
  332. opts.bLegacyCBufferLoad = !CGM.getCodeGenOpts().HLSLNotUseLegacyCBufLoad;
  333. opts.bAllResourcesBound = CGM.getCodeGenOpts().HLSLAllResourcesBound;
  334. opts.PackingStrategy = CGM.getCodeGenOpts().HLSLSignaturePackingStrategy;
  335. opts.bLegacyResourceReservation = CGM.getCodeGenOpts().HLSLLegacyResourceReservation;
  336. opts.bForceZeroStoreLifetimes = CGM.getCodeGenOpts().HLSLForceZeroStoreLifetimes;
  337. opts.bUseMinPrecision = CGM.getLangOpts().UseMinPrecision;
  338. opts.bDX9CompatMode = CGM.getLangOpts().EnableDX9CompatMode;
  339. opts.bFXCCompatMode = CGM.getLangOpts().EnableFXCCompatMode;
  340. m_pHLModule->SetHLOptions(opts);
  341. m_pHLModule->GetOP()->SetMinPrecision(opts.bUseMinPrecision);
  342. m_pHLModule->GetTypeSystem().SetMinPrecision(opts.bUseMinPrecision);
  343. m_pHLModule->SetAutoBindingSpace(CGM.getCodeGenOpts().HLSLDefaultSpace);
  344. m_pHLModule->SetValidatorVersion(CGM.getCodeGenOpts().HLSLValidatorMajorVer, CGM.getCodeGenOpts().HLSLValidatorMinorVer);
  345. m_bDebugInfo = CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::FullDebugInfo;
  346. // set profile
  347. m_pHLModule->SetShaderModel(SM);
  348. // set entry name
  349. if (!SM->IsLib())
  350. m_pHLModule->SetEntryFunctionName(CGM.getCodeGenOpts().HLSLEntryFunction);
  351. // set root signature version.
  352. if (CGM.getLangOpts().RootSigMinor == 0) {
  353. rootSigVer = hlsl::DxilRootSignatureVersion::Version_1_0;
  354. }
  355. else {
  356. DXASSERT(CGM.getLangOpts().RootSigMinor == 1,
  357. "else CGMSHLSLRuntime Constructor needs to be updated");
  358. rootSigVer = hlsl::DxilRootSignatureVersion::Version_1_1;
  359. }
  360. DXASSERT(CGM.getLangOpts().RootSigMajor == 1,
  361. "else CGMSHLSLRuntime Constructor needs to be updated");
  362. // add globalCB
  363. unique_ptr<HLCBuffer> CB = llvm::make_unique<HLCBuffer>(false, false);
  364. std::string globalCBName = "$Globals";
  365. CB->SetGlobalSymbol(nullptr);
  366. CB->SetGlobalName(globalCBName);
  367. globalCBIndex = m_pHLModule->GetCBuffers().size();
  368. CB->SetID(globalCBIndex);
  369. CB->SetRangeSize(1);
  370. CB->SetLowerBound(UINT_MAX);
  371. DXVERIFY_NOMSG(globalCBIndex == m_pHLModule->AddCBuffer(std::move(CB)));
  372. // set Float Denorm Mode
  373. m_pHLModule->SetFloat32DenormMode(CGM.getCodeGenOpts().HLSLFloat32DenormMode);
  374. // set DefaultLinkage
  375. m_pHLModule->SetDefaultLinkage(CGM.getCodeGenOpts().DefaultLinkage);
  376. // Fill in m_ExportMap, which maps from internal name to zero or more renames
  377. m_ExportMap.clear();
  378. std::string errors;
  379. llvm::raw_string_ostream os(errors);
  380. if (!m_ExportMap.ParseExports(CGM.getCodeGenOpts().HLSLLibraryExports, os)) {
  381. DiagnosticsEngine &Diags = CGM.getDiags();
  382. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "Error parsing -exports options: %0");
  383. Diags.Report(DiagID) << os.str();
  384. }
  385. }
  386. void CGMSHLSLRuntime::AddHLSLIntrinsicOpcodeToFunction(Function *F,
  387. unsigned opcode) {
  388. m_IntrinsicMap.emplace_back(F,opcode);
  389. }
  390. void CGMSHLSLRuntime::CheckParameterAnnotation(
  391. SourceLocation SLoc, const DxilParameterAnnotation &paramInfo,
  392. bool isPatchConstantFunction) {
  393. if (!paramInfo.HasSemanticString()) {
  394. return;
  395. }
  396. llvm::StringRef semFullName = paramInfo.GetSemanticStringRef();
  397. DxilParamInputQual paramQual = paramInfo.GetParamInputQual();
  398. if (paramQual == DxilParamInputQual::Inout) {
  399. CheckParameterAnnotation(SLoc, DxilParamInputQual::In, semFullName, isPatchConstantFunction);
  400. CheckParameterAnnotation(SLoc, DxilParamInputQual::Out, semFullName, isPatchConstantFunction);
  401. return;
  402. }
  403. CheckParameterAnnotation(SLoc, paramQual, semFullName, isPatchConstantFunction);
  404. }
  405. void CGMSHLSLRuntime::CheckParameterAnnotation(
  406. SourceLocation SLoc, DxilParamInputQual paramQual, llvm::StringRef semFullName,
  407. bool isPatchConstantFunction) {
  408. const ShaderModel *SM = m_pHLModule->GetShaderModel();
  409. DXIL::SigPointKind sigPoint = SigPointFromInputQual(
  410. paramQual, SM->GetKind(), isPatchConstantFunction);
  411. llvm::StringRef semName;
  412. unsigned semIndex;
  413. Semantic::DecomposeNameAndIndex(semFullName, &semName, &semIndex);
  414. const Semantic *pSemantic =
  415. Semantic::GetByName(semName, sigPoint, SM->GetMajor(), SM->GetMinor());
  416. if (pSemantic->IsInvalid()) {
  417. DiagnosticsEngine &Diags = CGM.getDiags();
  418. unsigned DiagID =
  419. Diags.getCustomDiagID(DiagnosticsEngine::Error, "invalid semantic '%0' for %1 %2.%3");
  420. Diags.Report(SLoc, DiagID) << semName << SM->GetKindName() << SM->GetMajor() << SM->GetMinor();
  421. }
  422. }
  423. SourceLocation
  424. CGMSHLSLRuntime::SetSemantic(const NamedDecl *decl,
  425. DxilParameterAnnotation &paramInfo) {
  426. for (const hlsl::UnusualAnnotation *it : decl->getUnusualAnnotations()) {
  427. if (it->getKind() == hlsl::UnusualAnnotation::UA_SemanticDecl) {
  428. const hlsl::SemanticDecl *sd = cast<hlsl::SemanticDecl>(it);
  429. paramInfo.SetSemanticString(sd->SemanticName);
  430. if (m_PreciseOutputSet.count(StringRef(sd->SemanticName).lower()))
  431. paramInfo.SetPrecise();
  432. return it->Loc;
  433. }
  434. }
  435. return SourceLocation();
  436. }
  437. static DXIL::TessellatorDomain StringToDomain(StringRef domain) {
  438. if (domain == "isoline")
  439. return DXIL::TessellatorDomain::IsoLine;
  440. if (domain == "tri")
  441. return DXIL::TessellatorDomain::Tri;
  442. if (domain == "quad")
  443. return DXIL::TessellatorDomain::Quad;
  444. return DXIL::TessellatorDomain::Undefined;
  445. }
  446. static DXIL::TessellatorPartitioning StringToPartitioning(StringRef partition) {
  447. if (partition == "integer")
  448. return DXIL::TessellatorPartitioning::Integer;
  449. if (partition == "pow2")
  450. return DXIL::TessellatorPartitioning::Pow2;
  451. if (partition == "fractional_even")
  452. return DXIL::TessellatorPartitioning::FractionalEven;
  453. if (partition == "fractional_odd")
  454. return DXIL::TessellatorPartitioning::FractionalOdd;
  455. return DXIL::TessellatorPartitioning::Undefined;
  456. }
  457. static DXIL::TessellatorOutputPrimitive
  458. StringToTessOutputPrimitive(StringRef primitive) {
  459. if (primitive == "point")
  460. return DXIL::TessellatorOutputPrimitive::Point;
  461. if (primitive == "line")
  462. return DXIL::TessellatorOutputPrimitive::Line;
  463. if (primitive == "triangle_cw")
  464. return DXIL::TessellatorOutputPrimitive::TriangleCW;
  465. if (primitive == "triangle_ccw")
  466. return DXIL::TessellatorOutputPrimitive::TriangleCCW;
  467. return DXIL::TessellatorOutputPrimitive::Undefined;
  468. }
  469. static DXIL::MeshOutputTopology
  470. StringToMeshOutputTopology(StringRef topology) {
  471. if (topology == "line")
  472. return DXIL::MeshOutputTopology::Line;
  473. if (topology == "triangle")
  474. return DXIL::MeshOutputTopology::Triangle;
  475. return DXIL::MeshOutputTopology::Undefined;
  476. }
  477. static unsigned GetMatrixSizeInCB(QualType Ty, bool defaultRowMajor,
  478. bool b64Bit) {
  479. bool bRowMajor;
  480. if (!hlsl::HasHLSLMatOrientation(Ty, &bRowMajor))
  481. bRowMajor = defaultRowMajor;
  482. unsigned row, col;
  483. hlsl::GetHLSLMatRowColCount(Ty, row, col);
  484. unsigned EltSize = b64Bit ? 8 : 4;
  485. // Align to 4 * 4bytes.
  486. unsigned alignment = 4 * 4;
  487. if (bRowMajor) {
  488. unsigned rowSize = EltSize * col;
  489. // 3x64bit or 4x64bit align to 32 bytes.
  490. if (rowSize > alignment)
  491. alignment <<= 1;
  492. return alignment * (row - 1) + col * EltSize;
  493. } else {
  494. unsigned rowSize = EltSize * row;
  495. // 3x64bit or 4x64bit align to 32 bytes.
  496. if (rowSize > alignment)
  497. alignment <<= 1;
  498. return alignment * (col - 1) + row * EltSize;
  499. }
  500. }
  501. static CompType::Kind BuiltinTyToCompTy(const BuiltinType *BTy, bool bSNorm,
  502. bool bUNorm) {
  503. CompType::Kind kind = CompType::Kind::Invalid;
  504. switch (BTy->getKind()) {
  505. // HLSL Changes begin
  506. case BuiltinType::Int8_4Packed:
  507. kind = CompType::Kind::PackedS8x32;
  508. break;
  509. case BuiltinType::UInt8_4Packed:
  510. kind = CompType::Kind::PackedU8x32;
  511. break;
  512. // HLSL Changes end
  513. case BuiltinType::UInt:
  514. kind = CompType::Kind::U32;
  515. break;
  516. case BuiltinType::Min16UInt: // HLSL Change
  517. case BuiltinType::UShort:
  518. kind = CompType::Kind::U16;
  519. break;
  520. case BuiltinType::ULongLong:
  521. kind = CompType::Kind::U64;
  522. break;
  523. case BuiltinType::Int:
  524. kind = CompType::Kind::I32;
  525. break;
  526. // HLSL Changes begin
  527. case BuiltinType::Min12Int:
  528. case BuiltinType::Min16Int:
  529. // HLSL Changes end
  530. case BuiltinType::Short:
  531. kind = CompType::Kind::I16;
  532. break;
  533. case BuiltinType::LongLong:
  534. kind = CompType::Kind::I64;
  535. break;
  536. // HLSL Changes begin
  537. case BuiltinType::Min10Float:
  538. case BuiltinType::Min16Float:
  539. // HLSL Changes end
  540. case BuiltinType::Half:
  541. if (bSNorm)
  542. kind = CompType::Kind::SNormF16;
  543. else if (bUNorm)
  544. kind = CompType::Kind::UNormF16;
  545. else
  546. kind = CompType::Kind::F16;
  547. break;
  548. case BuiltinType::HalfFloat: // HLSL Change
  549. case BuiltinType::Float:
  550. if (bSNorm)
  551. kind = CompType::Kind::SNormF32;
  552. else if (bUNorm)
  553. kind = CompType::Kind::UNormF32;
  554. else
  555. kind = CompType::Kind::F32;
  556. break;
  557. case BuiltinType::Double:
  558. if (bSNorm)
  559. kind = CompType::Kind::SNormF64;
  560. else if (bUNorm)
  561. kind = CompType::Kind::UNormF64;
  562. else
  563. kind = CompType::Kind::F64;
  564. break;
  565. case BuiltinType::Bool:
  566. kind = CompType::Kind::I1;
  567. break;
  568. default:
  569. // Other types not used by HLSL.
  570. break;
  571. }
  572. return kind;
  573. }
  574. static DxilSampler::SamplerKind KeywordToSamplerKind(llvm::StringRef keyword) {
  575. // TODO: refactor for faster search (switch by 1/2/3 first letters, then
  576. // compare)
  577. return llvm::StringSwitch<DxilSampler::SamplerKind>(keyword)
  578. .Case("SamplerState", DxilSampler::SamplerKind::Default)
  579. .Case("SamplerComparisonState", DxilSampler::SamplerKind::Comparison)
  580. .Default(DxilSampler::SamplerKind::Invalid);
  581. }
  582. MDNode *CGMSHLSLRuntime::GetOrAddResTypeMD(QualType resTy, bool bCreate) {
  583. const RecordType *RT = resTy->getAs<RecordType>();
  584. if (!RT)
  585. return nullptr;
  586. RecordDecl *RD = RT->getDecl();
  587. SourceLocation loc = RD->getLocation();
  588. hlsl::DxilResourceBase::Class resClass = TypeToClass(resTy);
  589. llvm::Type *Ty = CGM.getTypes().ConvertType(resTy);
  590. auto it = resMetadataMap.find(Ty);
  591. if (!bCreate && it != resMetadataMap.end())
  592. return it->second;
  593. // Save resource type metadata.
  594. switch (resClass) {
  595. case DXIL::ResourceClass::UAV: {
  596. DxilResource UAV;
  597. // TODO: save globalcoherent to variable in EmitHLSLBuiltinCallExpr.
  598. SetUAVSRV(loc, resClass, &UAV, resTy);
  599. // Set global symbol to save type.
  600. UAV.SetGlobalSymbol(UndefValue::get(Ty->getPointerTo()));
  601. MDNode *MD = m_pHLModule->DxilUAVToMDNode(UAV);
  602. resMetadataMap[Ty] = MD;
  603. return MD;
  604. } break;
  605. case DXIL::ResourceClass::SRV: {
  606. DxilResource SRV;
  607. SetUAVSRV(loc, resClass, &SRV, resTy);
  608. // Set global symbol to save type.
  609. SRV.SetGlobalSymbol(UndefValue::get(Ty->getPointerTo()));
  610. MDNode *MD = m_pHLModule->DxilSRVToMDNode(SRV);
  611. resMetadataMap[Ty] = MD;
  612. return MD;
  613. } break;
  614. case DXIL::ResourceClass::Sampler: {
  615. DxilSampler S;
  616. DxilSampler::SamplerKind kind = KeywordToSamplerKind(RD->getName());
  617. S.SetSamplerKind(kind);
  618. // Set global symbol to save type.
  619. S.SetGlobalSymbol(UndefValue::get(Ty->getPointerTo()));
  620. MDNode *MD = m_pHLModule->DxilSamplerToMDNode(S);
  621. resMetadataMap[Ty] = MD;
  622. return MD;
  623. }
  624. default:
  625. // Skip OutputStream for GS.
  626. return nullptr;
  627. }
  628. }
  629. namespace {
  630. MatrixOrientation GetMatrixMajor(QualType Ty, bool bDefaultRowMajor) {
  631. DXASSERT_NOMSG(hlsl::IsHLSLMatType(Ty));
  632. bool bIsRowMajor = bDefaultRowMajor;
  633. HasHLSLMatOrientation(Ty, &bIsRowMajor);
  634. return bIsRowMajor ? MatrixOrientation::RowMajor
  635. : MatrixOrientation::ColumnMajor;
  636. }
  637. QualType GetArrayEltType(ASTContext &Context, QualType Ty) {
  638. while (const clang::ArrayType *ArrayTy = Context.getAsArrayType(Ty))
  639. Ty = ArrayTy->getElementType();
  640. return Ty;
  641. }
  642. bool IsTextureBufferViewName(StringRef keyword) {
  643. return keyword == "TextureBuffer";
  644. }
  645. bool IsTextureBufferView(clang::QualType Ty, clang::ASTContext &context) {
  646. Ty = Ty.getCanonicalType();
  647. if (const clang::ArrayType *arrayType = context.getAsArrayType(Ty)) {
  648. return IsTextureBufferView(arrayType->getElementType(), context);
  649. } else if (const RecordType *RT = Ty->getAsStructureType()) {
  650. return IsTextureBufferViewName(RT->getDecl()->getName());
  651. } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
  652. if (const ClassTemplateSpecializationDecl *templateDecl =
  653. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl())) {
  654. return IsTextureBufferViewName(templateDecl->getName());
  655. }
  656. }
  657. return false;
  658. }
  659. } // namespace
  660. DxilResourceProperties CGMSHLSLRuntime::BuildResourceProperty(QualType resTy) {
  661. resTy = GetArrayEltType(CGM.getContext(), resTy);
  662. const RecordType *RT = resTy->getAs<RecordType>();
  663. DxilResourceProperties RP;
  664. if (!RT) {
  665. return RP;
  666. }
  667. RecordDecl *RD = RT->getDecl();
  668. SourceLocation loc = RD->getLocation();
  669. hlsl::DxilResourceBase::Class resClass = TypeToClass(resTy);
  670. if (resClass == DXIL::ResourceClass::Invalid)
  671. return RP;
  672. llvm::Type *Ty = CGM.getTypes().ConvertType(resTy);
  673. switch (resClass) {
  674. case DXIL::ResourceClass::UAV: {
  675. DxilResource UAV;
  676. // TODO: save globalcoherent to variable in EmitHLSLBuiltinCallExpr.
  677. SetUAVSRV(loc, resClass, &UAV, resTy);
  678. UAV.SetGlobalSymbol(UndefValue::get(Ty->getPointerTo()));
  679. RP = resource_helper::loadPropsFromResourceBase(&UAV);
  680. } break;
  681. case DXIL::ResourceClass::SRV: {
  682. DxilResource SRV;
  683. SetUAVSRV(loc, resClass, &SRV, resTy);
  684. SRV.SetGlobalSymbol(UndefValue::get(Ty->getPointerTo()));
  685. RP = resource_helper::loadPropsFromResourceBase(&SRV);
  686. } break;
  687. case DXIL::ResourceClass::Sampler: {
  688. DxilSampler::SamplerKind kind = KeywordToSamplerKind(RD->getName());
  689. DxilSampler Sampler;
  690. Sampler.SetSamplerKind(kind);
  691. RP = resource_helper::loadPropsFromResourceBase(&Sampler);
  692. } break;
  693. case DXIL::ResourceClass::CBuffer: {
  694. DxilCBuffer CB;
  695. CB.SetGlobalSymbol(UndefValue::get(Ty->getPointerTo()));
  696. if (IsTextureBufferView(resTy, CGM.getContext()))
  697. CB.SetKind(DXIL::ResourceKind::TBuffer);
  698. DxilTypeSystem &typeSys = m_pHLModule->GetTypeSystem();
  699. unsigned arrayEltSize = 0;
  700. QualType ResultTy = hlsl::GetHLSLResourceResultType(resTy);
  701. unsigned Size = AddTypeAnnotation(ResultTy, typeSys, arrayEltSize);
  702. CB.SetSize(Size);
  703. RP = resource_helper::loadPropsFromResourceBase(&CB);
  704. } break;
  705. default:
  706. break;
  707. }
  708. return RP;
  709. }
  710. bool CGMSHLSLRuntime::AddValToPropertyMap(Value *V, QualType Ty) {
  711. return objectProperties.AddResource(V, BuildResourceProperty(Ty));
  712. }
  713. void CGMSHLSLRuntime::ConstructFieldAttributedAnnotation(
  714. DxilFieldAnnotation &fieldAnnotation, QualType fieldTy,
  715. bool bDefaultRowMajor) {
  716. QualType Ty = fieldTy;
  717. if (Ty->isReferenceType())
  718. Ty = Ty.getNonReferenceType();
  719. // Get element type.
  720. Ty = GetArrayEltType(CGM.getContext(), Ty);
  721. QualType EltTy = Ty;
  722. if (hlsl::IsHLSLMatType(Ty)) {
  723. DxilMatrixAnnotation Matrix;
  724. Matrix.Orientation = GetMatrixMajor(Ty, bDefaultRowMajor);
  725. hlsl::GetHLSLMatRowColCount(Ty, Matrix.Rows, Matrix.Cols);
  726. fieldAnnotation.SetMatrixAnnotation(Matrix);
  727. EltTy = hlsl::GetHLSLMatElementType(Ty);
  728. }
  729. if (hlsl::IsHLSLVecType(Ty))
  730. EltTy = hlsl::GetHLSLVecElementType(Ty);
  731. if (IsHLSLResourceType(Ty)) {
  732. // Always create for llvm::Type could be same for different QualType.
  733. // TODO: change to DxilProperties.
  734. MDNode *MD = GetOrAddResTypeMD(Ty, /*bCreate*/ true);
  735. fieldAnnotation.SetResourceAttribute(MD);
  736. }
  737. bool bSNorm = false;
  738. bool bUNorm = false;
  739. if (HasHLSLUNormSNorm(Ty, &bSNorm) && !bSNorm)
  740. bUNorm = true;
  741. if (EltTy->isBuiltinType()) {
  742. const BuiltinType *BTy = EltTy->getAs<BuiltinType>();
  743. CompType::Kind kind = BuiltinTyToCompTy(BTy, bSNorm, bUNorm);
  744. fieldAnnotation.SetCompType(kind);
  745. } else if (EltTy->isEnumeralType()) {
  746. const EnumType *ETy = EltTy->getAs<EnumType>();
  747. QualType type = ETy->getDecl()->getIntegerType();
  748. if (const BuiltinType *BTy =
  749. dyn_cast<BuiltinType>(type->getCanonicalTypeInternal()))
  750. fieldAnnotation.SetCompType(BuiltinTyToCompTy(BTy, bSNorm, bUNorm));
  751. } else {
  752. DXASSERT(!bSNorm && !bUNorm,
  753. "snorm/unorm on invalid type, validate at handleHLSLTypeAttr");
  754. }
  755. }
  756. static void ConstructFieldInterpolation(DxilFieldAnnotation &fieldAnnotation,
  757. FieldDecl *fieldDecl) {
  758. // Keep undefined for interpMode here.
  759. InterpolationMode InterpMode = {fieldDecl->hasAttr<HLSLNoInterpolationAttr>(),
  760. fieldDecl->hasAttr<HLSLLinearAttr>(),
  761. fieldDecl->hasAttr<HLSLNoPerspectiveAttr>(),
  762. fieldDecl->hasAttr<HLSLCentroidAttr>(),
  763. fieldDecl->hasAttr<HLSLSampleAttr>()};
  764. if (InterpMode.GetKind() != InterpolationMode::Kind::Undefined)
  765. fieldAnnotation.SetInterpolationMode(InterpMode);
  766. }
  767. static unsigned AlignBaseOffset(unsigned baseOffset, unsigned size, QualType Ty,
  768. bool bDefaultRowMajor) {
  769. bool needNewAlign = Ty->isArrayType();
  770. if (IsHLSLMatType(Ty)) {
  771. bool bRowMajor = false;
  772. if (!hlsl::HasHLSLMatOrientation(Ty, &bRowMajor))
  773. bRowMajor = bDefaultRowMajor;
  774. unsigned row, col;
  775. hlsl::GetHLSLMatRowColCount(Ty, row, col);
  776. needNewAlign |= !bRowMajor && col > 1;
  777. needNewAlign |= bRowMajor && row > 1;
  778. } else if (Ty->isStructureOrClassType() && !hlsl::IsHLSLVecType(Ty)) {
  779. needNewAlign = true;
  780. }
  781. unsigned scalarSizeInBytes = 4;
  782. const clang::BuiltinType *BT = Ty->getAs<clang::BuiltinType>();
  783. if (hlsl::IsHLSLVecMatType(Ty)) {
  784. BT = hlsl::GetElementTypeOrType(Ty)->getAs<clang::BuiltinType>();
  785. }
  786. if (BT) {
  787. if (BT->getKind() == clang::BuiltinType::Kind::Double ||
  788. BT->getKind() == clang::BuiltinType::Kind::LongLong)
  789. scalarSizeInBytes = 8;
  790. else if (BT->getKind() == clang::BuiltinType::Kind::Half ||
  791. BT->getKind() == clang::BuiltinType::Kind::Short ||
  792. BT->getKind() == clang::BuiltinType::Kind::UShort)
  793. scalarSizeInBytes = 2;
  794. }
  795. return AlignBufferOffsetInLegacy(baseOffset, size, scalarSizeInBytes,
  796. needNewAlign);
  797. }
  798. static unsigned AlignBaseOffset(QualType Ty, unsigned baseOffset,
  799. bool bDefaultRowMajor,
  800. CodeGen::CodeGenModule &CGM,
  801. llvm::DataLayout &layout) {
  802. QualType paramTy = Ty.getCanonicalType();
  803. if (const ReferenceType *RefType = dyn_cast<ReferenceType>(paramTy))
  804. paramTy = RefType->getPointeeType();
  805. // Get size.
  806. llvm::Type *Type = CGM.getTypes().ConvertType(paramTy);
  807. unsigned size = layout.getTypeAllocSize(Type);
  808. return AlignBaseOffset(baseOffset, size, paramTy, bDefaultRowMajor);
  809. }
  810. unsigned CGMSHLSLRuntime::ConstructStructAnnotation(DxilStructAnnotation *annotation,
  811. DxilPayloadAnnotation* payloadAnnotation,
  812. const RecordDecl *RD,
  813. DxilTypeSystem &dxilTypeSys) {
  814. unsigned fieldIdx = 0;
  815. unsigned offset = 0;
  816. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  817. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  818. // If template, save template args
  819. if (const ClassTemplateSpecializationDecl *templateSpecializationDecl =
  820. dyn_cast<ClassTemplateSpecializationDecl>(CXXRD)) {
  821. const clang::TemplateArgumentList &args = templateSpecializationDecl->getTemplateInstantiationArgs();
  822. for (unsigned i = 0; i < args.size(); ++i) {
  823. DxilTemplateArgAnnotation &argAnnotation = annotation->GetTemplateArgAnnotation(i);
  824. const clang::TemplateArgument &arg = args[i];
  825. switch (arg.getKind()) {
  826. case clang::TemplateArgument::ArgKind::Type:
  827. argAnnotation.SetType(CGM.getTypes().ConvertType(arg.getAsType()));
  828. break;
  829. case clang::TemplateArgument::ArgKind::Integral:
  830. argAnnotation.SetIntegral(arg.getAsIntegral().getExtValue());
  831. break;
  832. default:
  833. break;
  834. }
  835. }
  836. }
  837. if (CXXRD->getNumBases()) {
  838. // Add base as field.
  839. for (const auto &I : CXXRD->bases()) {
  840. const CXXRecordDecl *BaseDecl =
  841. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  842. std::string fieldSemName = "";
  843. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  844. // Align offset.
  845. offset = AlignBaseOffset(parentTy, offset, bDefaultRowMajor, CGM,
  846. dataLayout);
  847. unsigned CBufferOffset = offset;
  848. unsigned arrayEltSize = 0;
  849. // Process field to make sure the size of field is ready.
  850. unsigned size =
  851. AddTypeAnnotation(parentTy, dxilTypeSys, arrayEltSize);
  852. // Update offset.
  853. offset += size;
  854. if (size > 0) {
  855. DxilFieldAnnotation &fieldAnnotation =
  856. annotation->GetFieldAnnotation(fieldIdx++);
  857. fieldAnnotation.SetCBufferOffset(CBufferOffset);
  858. fieldAnnotation.SetFieldName(BaseDecl->getNameAsString());
  859. }
  860. }
  861. }
  862. }
  863. for (auto fieldDecl : RD->fields()) {
  864. std::string fieldSemName = "";
  865. QualType fieldTy = fieldDecl->getType();
  866. DXASSERT(!fieldDecl->isBitField(), "We should have already ensured we have no bitfields.");
  867. // Align offset.
  868. offset = AlignBaseOffset(fieldTy, offset, bDefaultRowMajor, CGM, dataLayout);
  869. unsigned CBufferOffset = offset;
  870. DxilFieldAnnotation &fieldAnnotation = annotation->GetFieldAnnotation(fieldIdx++);
  871. ConstructFieldAttributedAnnotation(fieldAnnotation, fieldTy, bDefaultRowMajor);
  872. // Try to get info from fieldDecl.
  873. for (const hlsl::UnusualAnnotation *it :
  874. fieldDecl->getUnusualAnnotations()) {
  875. switch (it->getKind()) {
  876. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  877. const hlsl::SemanticDecl *sd = cast<hlsl::SemanticDecl>(it);
  878. fieldSemName = sd->SemanticName;
  879. } break;
  880. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  881. const hlsl::ConstantPacking *cp = cast<hlsl::ConstantPacking>(it);
  882. CBufferOffset = cp->Subcomponent << 2;
  883. CBufferOffset += cp->ComponentOffset;
  884. // Change to byte.
  885. CBufferOffset <<= 2;
  886. } break;
  887. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  888. // register assignment only works on global constant.
  889. DiagnosticsEngine &Diags = CGM.getDiags();
  890. unsigned DiagID = Diags.getCustomDiagID(
  891. DiagnosticsEngine::Error,
  892. "location semantics cannot be specified on members.");
  893. Diags.Report(it->Loc, DiagID);
  894. return 0;
  895. } break;
  896. case hlsl::UnusualAnnotation::UA_PayloadAccessQualifier: {
  897. // Forward payload access qualifiers to fieldAnnotation.
  898. if (payloadAnnotation) {
  899. const hlsl::PayloadAccessAnnotation *annotation =
  900. cast<hlsl::PayloadAccessAnnotation>(it);
  901. DxilPayloadFieldAnnotation &payloadFieldAnnotation =
  902. payloadAnnotation->GetFieldAnnotation(fieldIdx - 1);
  903. payloadFieldAnnotation.SetCompType(
  904. fieldAnnotation.GetCompType().GetKind());
  905. for (auto stage : annotation->ShaderStages) {
  906. payloadFieldAnnotation.AddPayloadFieldQualifier(
  907. stage, annotation->qualifier);
  908. }
  909. }
  910. } break;
  911. default:
  912. llvm_unreachable("only semantic for input/output");
  913. break;
  914. }
  915. }
  916. unsigned arrayEltSize = 0;
  917. // Process field to make sure the size of field is ready.
  918. unsigned size = AddTypeAnnotation(fieldDecl->getType(), dxilTypeSys, arrayEltSize);
  919. // Update offset.
  920. offset += size;
  921. ConstructFieldInterpolation(fieldAnnotation, fieldDecl);
  922. if (fieldDecl->hasAttr<HLSLPreciseAttr>())
  923. fieldAnnotation.SetPrecise();
  924. fieldAnnotation.SetCBufferOffset(CBufferOffset);
  925. fieldAnnotation.SetFieldName(fieldDecl->getName());
  926. if (!fieldSemName.empty()) {
  927. fieldAnnotation.SetSemanticString(fieldSemName);
  928. if (m_PreciseOutputSet.count(StringRef(fieldSemName).lower()))
  929. fieldAnnotation.SetPrecise();
  930. }
  931. }
  932. annotation->SetCBufferSize(offset);
  933. if (offset == 0) {
  934. annotation->MarkEmptyStruct();
  935. }
  936. return offset;
  937. }
  938. static bool IsElementInputOutputType(QualType Ty) {
  939. return Ty->isBuiltinType() || hlsl::IsHLSLVecMatType(Ty) || Ty->isEnumeralType();
  940. }
  941. static unsigned GetNumTemplateArgsForRecordDecl(const RecordDecl *RD) {
  942. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  943. if (const ClassTemplateSpecializationDecl *templateSpecializationDecl =
  944. dyn_cast<ClassTemplateSpecializationDecl>(CXXRD)) {
  945. const clang::TemplateArgumentList &args = templateSpecializationDecl->getTemplateInstantiationArgs();
  946. return args.size();
  947. }
  948. }
  949. return 0;
  950. }
  951. static bool ValidatePayloadDecl(const RecordDecl *Decl,
  952. const ShaderModel &Model,
  953. DiagnosticsEngine &Diag,
  954. const CodeGenOptions &Options) {
  955. // Already checked in Sema, this is not a payload.
  956. if (!Decl->hasAttr<HLSLRayPayloadAttr>())
  957. return false;
  958. // If we have a payload warn about them beeing dropped.
  959. if (!Options.HLSLEnablePayloadAccessQualifiers) {
  960. Diag.ReportOnce(Decl->getLocation(), diag::warn_hlsl_payload_qualifer_dropped);
  961. return false;
  962. }
  963. // Check if all fileds have a payload qualifier.
  964. bool allFieldsQualifed = true;
  965. for (FieldDecl *field : Decl->fields()) {
  966. bool fieldHasPayloadQualifier = false;
  967. bool isPayloadStruct = false;
  968. for (UnusualAnnotation *annotation : field->getUnusualAnnotations()) {
  969. fieldHasPayloadQualifier |= isa<hlsl::PayloadAccessAnnotation>(annotation);
  970. }
  971. // Check if this is a struct type.
  972. // If it is, check for the [payload] field, [payload] structs must carry
  973. // PayloadAccessQualifiers and these are taken from the struct directly.
  974. // If it is not a payload struct, check if it has qualifiers attached.
  975. if (RecordDecl *recordTy = field->getType()->getAsCXXRecordDecl()) {
  976. if (recordTy->hasAttr<HLSLRayPayloadAttr>())
  977. isPayloadStruct = true;
  978. }
  979. if (fieldHasPayloadQualifier && isPayloadStruct) {
  980. Diag.Report(field->getLocation(),
  981. diag::err_payload_fields_is_payload_and_overqualified)
  982. << field->getName();
  983. continue;
  984. }
  985. else
  986. {
  987. if (isPayloadStruct)
  988. fieldHasPayloadQualifier = true;
  989. }
  990. if (!fieldHasPayloadQualifier) {
  991. Diag.Report(field->getLocation(),
  992. diag::err_payload_fields_not_qualified)
  993. << field->getName();
  994. }
  995. allFieldsQualifed &= fieldHasPayloadQualifier;
  996. }
  997. if (!allFieldsQualifed) {
  998. Diag.Report(Decl->getLocation(), diag::err_not_all_payload_fields_qualified)
  999. << Decl->getName();
  1000. return false;
  1001. }
  1002. return true;
  1003. }
  1004. // Return the size for constant buffer of each decl.
  1005. unsigned CGMSHLSLRuntime::AddTypeAnnotation(QualType Ty,
  1006. DxilTypeSystem &dxilTypeSys,
  1007. unsigned &arrayEltSize) {
  1008. QualType paramTy = Ty.getCanonicalType();
  1009. if (const ReferenceType *RefType = dyn_cast<ReferenceType>(paramTy))
  1010. paramTy = RefType->getPointeeType();
  1011. // Get size.
  1012. llvm::Type *Type = CGM.getTypes().ConvertType(paramTy);
  1013. unsigned size = dataLayout.getTypeAllocSize(Type);
  1014. if (IsHLSLMatType(Ty)) {
  1015. llvm::Type *EltTy = HLMatrixType::cast(Type).getElementTypeForReg();
  1016. bool b64Bit = dataLayout.getTypeAllocSize(EltTy) == 8;
  1017. size = GetMatrixSizeInCB(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor,
  1018. b64Bit);
  1019. }
  1020. // Skip element types.
  1021. if (IsElementInputOutputType(paramTy))
  1022. return size;
  1023. else if (IsHLSLStreamOutputType(Ty)) {
  1024. return AddTypeAnnotation(GetHLSLOutputPatchElementType(Ty), dxilTypeSys,
  1025. arrayEltSize);
  1026. } else if (IsHLSLInputPatchType(Ty))
  1027. return AddTypeAnnotation(GetHLSLInputPatchElementType(Ty), dxilTypeSys,
  1028. arrayEltSize);
  1029. else if (IsHLSLOutputPatchType(Ty))
  1030. return AddTypeAnnotation(GetHLSLOutputPatchElementType(Ty), dxilTypeSys,
  1031. arrayEltSize);
  1032. else if (const RecordType *RT = paramTy->getAsStructureType()) {
  1033. RecordDecl *RD = RT->getDecl();
  1034. llvm::StructType *ST = CGM.getTypes().ConvertRecordDeclType(RD);
  1035. // Skip if already created.
  1036. if (DxilStructAnnotation *annotation = dxilTypeSys.GetStructAnnotation(ST)) {
  1037. unsigned structSize = annotation->GetCBufferSize();
  1038. return structSize;
  1039. }
  1040. DxilStructAnnotation *annotation = dxilTypeSys.AddStructAnnotation(ST,
  1041. GetNumTemplateArgsForRecordDecl(RT->getDecl()));
  1042. DxilPayloadAnnotation *payloadAnnotation = nullptr;
  1043. if (ValidatePayloadDecl(RT->getDecl(), *m_pHLModule->GetShaderModel(), CGM.getDiags(), CGM.getCodeGenOpts()))
  1044. payloadAnnotation = dxilTypeSys.AddPayloadAnnotation(ST);
  1045. return ConstructStructAnnotation(annotation, payloadAnnotation, RD, dxilTypeSys);
  1046. } else if (const RecordType *RT = dyn_cast<RecordType>(paramTy)) {
  1047. // For this pointer.
  1048. RecordDecl *RD = RT->getDecl();
  1049. llvm::StructType *ST = CGM.getTypes().ConvertRecordDeclType(RD);
  1050. // Skip if already created.
  1051. if (DxilStructAnnotation *annotation = dxilTypeSys.GetStructAnnotation(ST)) {
  1052. unsigned structSize = annotation->GetCBufferSize();
  1053. return structSize;
  1054. }
  1055. DxilStructAnnotation *annotation = dxilTypeSys.AddStructAnnotation(ST,
  1056. GetNumTemplateArgsForRecordDecl(RT->getDecl()));
  1057. DxilPayloadAnnotation* payloadAnnotation = nullptr;
  1058. if (ValidatePayloadDecl(RT->getDecl(), *m_pHLModule->GetShaderModel(), CGM.getDiags(), CGM.getCodeGenOpts()))
  1059. payloadAnnotation = dxilTypeSys.AddPayloadAnnotation(ST);
  1060. return ConstructStructAnnotation(annotation, payloadAnnotation, RD, dxilTypeSys);
  1061. } else if (IsHLSLResourceType(Ty)) {
  1062. // Save result type info.
  1063. AddTypeAnnotation(GetHLSLResourceResultType(Ty), dxilTypeSys, arrayEltSize);
  1064. // Resource don't count for cbuffer size.
  1065. return 0;
  1066. } else if (IsStringType(Ty)) {
  1067. // string won't be included in cbuffer
  1068. return 0;
  1069. } else {
  1070. unsigned arraySize = 0;
  1071. QualType arrayElementTy = Ty;
  1072. if (Ty->isConstantArrayType()) {
  1073. const ConstantArrayType *arrayTy =
  1074. CGM.getContext().getAsConstantArrayType(Ty);
  1075. DXASSERT(arrayTy != nullptr, "Must array type here");
  1076. arraySize = arrayTy->getSize().getLimitedValue();
  1077. arrayElementTy = arrayTy->getElementType();
  1078. }
  1079. else if (Ty->isIncompleteArrayType()) {
  1080. const IncompleteArrayType *arrayTy = CGM.getContext().getAsIncompleteArrayType(Ty);
  1081. arrayElementTy = arrayTy->getElementType();
  1082. } else {
  1083. DXASSERT(0, "Must array type here");
  1084. }
  1085. unsigned elementSize = AddTypeAnnotation(arrayElementTy, dxilTypeSys, arrayEltSize);
  1086. // Only set arrayEltSize once.
  1087. if (arrayEltSize == 0)
  1088. arrayEltSize = elementSize;
  1089. // Align to 4 * 4bytes.
  1090. unsigned alignedSize = (elementSize + 15) & 0xfffffff0;
  1091. return alignedSize * (arraySize - 1) + elementSize;
  1092. }
  1093. }
  1094. static DxilResource::Kind KeywordToKind(StringRef keyword) {
  1095. // TODO: refactor for faster search (switch by 1/2/3 first letters, then
  1096. // compare)
  1097. if (keyword == "Texture1D" || keyword == "RWTexture1D" || keyword == "RasterizerOrderedTexture1D")
  1098. return DxilResource::Kind::Texture1D;
  1099. if (keyword == "Texture2D" || keyword == "RWTexture2D" || keyword == "RasterizerOrderedTexture2D")
  1100. return DxilResource::Kind::Texture2D;
  1101. if (keyword == "Texture2DMS" || keyword == "RWTexture2DMS")
  1102. return DxilResource::Kind::Texture2DMS;
  1103. if (keyword == "FeedbackTexture2D")
  1104. return DxilResource::Kind::FeedbackTexture2D;
  1105. if (keyword == "Texture3D" || keyword == "RWTexture3D" || keyword == "RasterizerOrderedTexture3D")
  1106. return DxilResource::Kind::Texture3D;
  1107. if (keyword == "TextureCube" || keyword == "RWTextureCube")
  1108. return DxilResource::Kind::TextureCube;
  1109. if (keyword == "Texture1DArray" || keyword == "RWTexture1DArray" || keyword == "RasterizerOrderedTexture1DArray")
  1110. return DxilResource::Kind::Texture1DArray;
  1111. if (keyword == "Texture2DArray" || keyword == "RWTexture2DArray" || keyword == "RasterizerOrderedTexture2DArray")
  1112. return DxilResource::Kind::Texture2DArray;
  1113. if (keyword == "FeedbackTexture2DArray")
  1114. return DxilResource::Kind::FeedbackTexture2DArray;
  1115. if (keyword == "Texture2DMSArray" || keyword == "RWTexture2DMSArray")
  1116. return DxilResource::Kind::Texture2DMSArray;
  1117. if (keyword == "TextureCubeArray" || keyword == "RWTextureCubeArray")
  1118. return DxilResource::Kind::TextureCubeArray;
  1119. if (keyword == "ByteAddressBuffer" || keyword == "RWByteAddressBuffer" || keyword == "RasterizerOrderedByteAddressBuffer")
  1120. return DxilResource::Kind::RawBuffer;
  1121. if (keyword == "StructuredBuffer" || keyword == "RWStructuredBuffer" || keyword == "RasterizerOrderedStructuredBuffer")
  1122. return DxilResource::Kind::StructuredBuffer;
  1123. if (keyword == "AppendStructuredBuffer" || keyword == "ConsumeStructuredBuffer")
  1124. return DxilResource::Kind::StructuredBuffer;
  1125. // TODO: this is not efficient.
  1126. bool isBuffer = keyword == "Buffer";
  1127. isBuffer |= keyword == "RWBuffer";
  1128. isBuffer |= keyword == "RasterizerOrderedBuffer";
  1129. if (isBuffer)
  1130. return DxilResource::Kind::TypedBuffer;
  1131. if (keyword == "RaytracingAccelerationStructure")
  1132. return DxilResource::Kind::RTAccelerationStructure;
  1133. return DxilResource::Kind::Invalid;
  1134. }
  1135. void CGMSHLSLRuntime::AddHLSLFunctionInfo(Function *F, const FunctionDecl *FD) {
  1136. // Add hlsl intrinsic attr
  1137. unsigned intrinsicOpcode;
  1138. StringRef intrinsicGroup;
  1139. if (hlsl::GetIntrinsicOp(FD, intrinsicOpcode, intrinsicGroup)) {
  1140. AddHLSLIntrinsicOpcodeToFunction(F, intrinsicOpcode);
  1141. F->addFnAttr(hlsl::HLPrefix, intrinsicGroup);
  1142. StringRef lower;
  1143. if (hlsl::GetIntrinsicLowering(FD, lower))
  1144. hlsl::SetHLLowerStrategy(F, lower);
  1145. if (FD->hasAttr<HLSLWaveSensitiveAttr>())
  1146. hlsl::SetHLWaveSensitive(F);
  1147. // Don't need to add FunctionQual for intrinsic function.
  1148. return;
  1149. }
  1150. if (m_pHLModule->GetFloat32DenormMode() == DXIL::Float32DenormMode::FTZ) {
  1151. F->addFnAttr(DXIL::kFP32DenormKindString, DXIL::kFP32DenormValueFtzString);
  1152. }
  1153. else if (m_pHLModule->GetFloat32DenormMode() == DXIL::Float32DenormMode::Preserve) {
  1154. F->addFnAttr(DXIL::kFP32DenormKindString, DXIL::kFP32DenormValuePreserveString);
  1155. }
  1156. else if (m_pHLModule->GetFloat32DenormMode() == DXIL::Float32DenormMode::Any) {
  1157. F->addFnAttr(DXIL::kFP32DenormKindString, DXIL::kFP32DenormValueAnyString);
  1158. }
  1159. // Set entry function
  1160. const std::string &entryName = m_pHLModule->GetEntryFunctionName();
  1161. bool isEntry = FD->getNameAsString() == entryName;
  1162. if (isEntry) {
  1163. Entry.Func = F;
  1164. Entry.SL = FD->getLocation();
  1165. }
  1166. DiagnosticsEngine &Diags = CGM.getDiags();
  1167. std::unique_ptr<DxilFunctionProps> funcProps =
  1168. llvm::make_unique<DxilFunctionProps>();
  1169. funcProps->shaderKind = DXIL::ShaderKind::Invalid;
  1170. bool isCS = false;
  1171. bool isGS = false;
  1172. bool isHS = false;
  1173. bool isDS = false;
  1174. bool isVS = false;
  1175. bool isPS = false;
  1176. bool isRay = false;
  1177. bool isMS = false;
  1178. bool isAS = false;
  1179. if (const HLSLShaderAttr *Attr = FD->getAttr<HLSLShaderAttr>()) {
  1180. // Stage is already validate in HandleDeclAttributeForHLSL.
  1181. // Here just check first letter (or two).
  1182. switch (Attr->getStage()[0]) {
  1183. case 'c':
  1184. switch (Attr->getStage()[1]) {
  1185. case 'o':
  1186. isCS = true;
  1187. funcProps->shaderKind = DXIL::ShaderKind::Compute;
  1188. break;
  1189. case 'l':
  1190. isRay = true;
  1191. funcProps->shaderKind = DXIL::ShaderKind::ClosestHit;
  1192. break;
  1193. case 'a':
  1194. isRay = true;
  1195. funcProps->shaderKind = DXIL::ShaderKind::Callable;
  1196. break;
  1197. default:
  1198. break;
  1199. }
  1200. break;
  1201. case 'v':
  1202. isVS = true;
  1203. funcProps->shaderKind = DXIL::ShaderKind::Vertex;
  1204. break;
  1205. case 'h':
  1206. isHS = true;
  1207. funcProps->shaderKind = DXIL::ShaderKind::Hull;
  1208. break;
  1209. case 'd':
  1210. isDS = true;
  1211. funcProps->shaderKind = DXIL::ShaderKind::Domain;
  1212. break;
  1213. case 'g':
  1214. isGS = true;
  1215. funcProps->shaderKind = DXIL::ShaderKind::Geometry;
  1216. break;
  1217. case 'p':
  1218. isPS = true;
  1219. funcProps->shaderKind = DXIL::ShaderKind::Pixel;
  1220. break;
  1221. case 'r':
  1222. isRay = true;
  1223. funcProps->shaderKind = DXIL::ShaderKind::RayGeneration;
  1224. break;
  1225. case 'i':
  1226. isRay = true;
  1227. funcProps->shaderKind = DXIL::ShaderKind::Intersection;
  1228. break;
  1229. case 'a':
  1230. switch (Attr->getStage()[1]) {
  1231. case 'm':
  1232. isAS = true;
  1233. funcProps->shaderKind = DXIL::ShaderKind::Amplification;
  1234. break;
  1235. case 'n':
  1236. isRay = true;
  1237. funcProps->shaderKind = DXIL::ShaderKind::AnyHit;
  1238. break;
  1239. default:
  1240. break;
  1241. }
  1242. break;
  1243. case 'm':
  1244. switch (Attr->getStage()[1]) {
  1245. case 'e':
  1246. isMS = true;
  1247. funcProps->shaderKind = DXIL::ShaderKind::Mesh;
  1248. break;
  1249. case 'i':
  1250. isRay = true;
  1251. funcProps->shaderKind = DXIL::ShaderKind::Miss;
  1252. break;
  1253. default:
  1254. break;
  1255. }
  1256. break;
  1257. default:
  1258. break;
  1259. }
  1260. if (funcProps->shaderKind == DXIL::ShaderKind::Invalid) {
  1261. unsigned DiagID = Diags.getCustomDiagID(
  1262. DiagnosticsEngine::Error, "Invalid profile for shader attribute");
  1263. Diags.Report(Attr->getLocation(), DiagID);
  1264. }
  1265. if (isEntry && isRay) {
  1266. unsigned DiagID = Diags.getCustomDiagID(
  1267. DiagnosticsEngine::Error, "Ray function cannot be used as a global entry point");
  1268. Diags.Report(Attr->getLocation(), DiagID);
  1269. }
  1270. }
  1271. // Save patch constant function to patchConstantFunctionMap.
  1272. bool isPatchConstantFunction = false;
  1273. if (!isEntry && CGM.getContext().IsPatchConstantFunctionDecl(FD)) {
  1274. isPatchConstantFunction = true;
  1275. auto &PCI = patchConstantFunctionMap[FD->getName()];
  1276. PCI.SL = FD->getLocation();
  1277. PCI.Func = F;
  1278. ++PCI.NumOverloads;
  1279. for (ParmVarDecl *parmDecl : FD->parameters()) {
  1280. QualType Ty = parmDecl->getType();
  1281. if (IsHLSLOutputPatchType(Ty)) {
  1282. funcProps->ShaderProps.HS.outputControlPoints =
  1283. GetHLSLOutputPatchCount(parmDecl->getType());
  1284. } else if (IsHLSLInputPatchType(Ty)) {
  1285. funcProps->ShaderProps.HS.inputControlPoints =
  1286. GetHLSLInputPatchCount(parmDecl->getType());
  1287. }
  1288. }
  1289. // Mark patch constant functions that cannot be linked as exports
  1290. // InternalLinkage. Patch constant functions that are actually used
  1291. // will be set back to ExternalLinkage in FinishCodeGen.
  1292. if (funcProps->ShaderProps.HS.outputControlPoints ||
  1293. funcProps->ShaderProps.HS.inputControlPoints) {
  1294. PCI.Func->setLinkage(GlobalValue::InternalLinkage);
  1295. }
  1296. funcProps->shaderKind = DXIL::ShaderKind::Hull;
  1297. }
  1298. const ShaderModel *SM = m_pHLModule->GetShaderModel();
  1299. if (isEntry) {
  1300. funcProps->shaderKind = SM->GetKind();
  1301. if (funcProps->shaderKind == DXIL::ShaderKind::Mesh) {
  1302. isMS = true;
  1303. }
  1304. else if (funcProps->shaderKind == DXIL::ShaderKind::Amplification) {
  1305. isAS = true;
  1306. }
  1307. }
  1308. // Geometry shader.
  1309. if (const HLSLMaxVertexCountAttr *Attr =
  1310. FD->getAttr<HLSLMaxVertexCountAttr>()) {
  1311. isGS = true;
  1312. funcProps->shaderKind = DXIL::ShaderKind::Geometry;
  1313. funcProps->ShaderProps.GS.maxVertexCount = Attr->getCount();
  1314. funcProps->ShaderProps.GS.inputPrimitive = DXIL::InputPrimitive::Undefined;
  1315. if (isEntry && !SM->IsGS()) {
  1316. unsigned DiagID =
  1317. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1318. "attribute maxvertexcount only valid for GS.");
  1319. Diags.Report(Attr->getLocation(), DiagID);
  1320. return;
  1321. }
  1322. }
  1323. if (const HLSLInstanceAttr *Attr = FD->getAttr<HLSLInstanceAttr>()) {
  1324. unsigned instanceCount = Attr->getCount();
  1325. funcProps->ShaderProps.GS.instanceCount = instanceCount;
  1326. if (isEntry && !SM->IsGS()) {
  1327. unsigned DiagID =
  1328. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1329. "attribute maxvertexcount only valid for GS.");
  1330. Diags.Report(Attr->getLocation(), DiagID);
  1331. return;
  1332. }
  1333. } else {
  1334. // Set default instance count.
  1335. if (isGS)
  1336. funcProps->ShaderProps.GS.instanceCount = 1;
  1337. }
  1338. // Compute shader
  1339. if (const HLSLNumThreadsAttr *Attr = FD->getAttr<HLSLNumThreadsAttr>()) {
  1340. if (isMS) {
  1341. funcProps->ShaderProps.MS.numThreads[0] = Attr->getX();
  1342. funcProps->ShaderProps.MS.numThreads[1] = Attr->getY();
  1343. funcProps->ShaderProps.MS.numThreads[2] = Attr->getZ();
  1344. } else if (isAS) {
  1345. funcProps->ShaderProps.AS.numThreads[0] = Attr->getX();
  1346. funcProps->ShaderProps.AS.numThreads[1] = Attr->getY();
  1347. funcProps->ShaderProps.AS.numThreads[2] = Attr->getZ();
  1348. } else {
  1349. isCS = true;
  1350. funcProps->shaderKind = DXIL::ShaderKind::Compute;
  1351. funcProps->ShaderProps.CS.numThreads[0] = Attr->getX();
  1352. funcProps->ShaderProps.CS.numThreads[1] = Attr->getY();
  1353. funcProps->ShaderProps.CS.numThreads[2] = Attr->getZ();
  1354. }
  1355. if (isEntry && !SM->IsCS() && !SM->IsMS() && !SM->IsAS()) {
  1356. unsigned DiagID = Diags.getCustomDiagID(
  1357. DiagnosticsEngine::Error, "attribute numthreads only valid for CS/MS/AS.");
  1358. Diags.Report(Attr->getLocation(), DiagID);
  1359. return;
  1360. }
  1361. }
  1362. // Hull shader.
  1363. if (const HLSLPatchConstantFuncAttr *Attr =
  1364. FD->getAttr<HLSLPatchConstantFuncAttr>()) {
  1365. if (isEntry && !SM->IsHS()) {
  1366. unsigned DiagID = Diags.getCustomDiagID(
  1367. DiagnosticsEngine::Error,
  1368. "attribute patchconstantfunc only valid for HS.");
  1369. Diags.Report(Attr->getLocation(), DiagID);
  1370. return;
  1371. }
  1372. isHS = true;
  1373. funcProps->shaderKind = DXIL::ShaderKind::Hull;
  1374. HSEntryPatchConstantFuncAttr[F] = Attr;
  1375. } else {
  1376. // TODO: This is a duplicate check. We also have this check in
  1377. // hlsl::DiagnoseTranslationUnit(clang::Sema*).
  1378. if (isEntry && SM->IsHS()) {
  1379. unsigned DiagID = Diags.getCustomDiagID(
  1380. DiagnosticsEngine::Error,
  1381. "HS entry point must have the patchconstantfunc attribute");
  1382. Diags.Report(FD->getLocation(), DiagID);
  1383. return;
  1384. }
  1385. }
  1386. if (const HLSLOutputControlPointsAttr *Attr =
  1387. FD->getAttr<HLSLOutputControlPointsAttr>()) {
  1388. if (isHS) {
  1389. funcProps->ShaderProps.HS.outputControlPoints = Attr->getCount();
  1390. } else if (isEntry && !SM->IsHS()) {
  1391. unsigned DiagID = Diags.getCustomDiagID(
  1392. DiagnosticsEngine::Error,
  1393. "attribute outputcontrolpoints only valid for HS.");
  1394. Diags.Report(Attr->getLocation(), DiagID);
  1395. return;
  1396. }
  1397. }
  1398. if (const HLSLPartitioningAttr *Attr = FD->getAttr<HLSLPartitioningAttr>()) {
  1399. if (isHS) {
  1400. DXIL::TessellatorPartitioning partition =
  1401. StringToPartitioning(Attr->getScheme());
  1402. funcProps->ShaderProps.HS.partition = partition;
  1403. } else if (isEntry && !SM->IsHS()) {
  1404. unsigned DiagID =
  1405. Diags.getCustomDiagID(DiagnosticsEngine::Warning,
  1406. "attribute partitioning only valid for HS.");
  1407. Diags.Report(Attr->getLocation(), DiagID);
  1408. }
  1409. }
  1410. if (const HLSLOutputTopologyAttr *Attr =
  1411. FD->getAttr<HLSLOutputTopologyAttr>()) {
  1412. if (isHS) {
  1413. DXIL::TessellatorOutputPrimitive primitive =
  1414. StringToTessOutputPrimitive(Attr->getTopology());
  1415. funcProps->ShaderProps.HS.outputPrimitive = primitive;
  1416. }
  1417. else if (isMS) {
  1418. DXIL::MeshOutputTopology topology =
  1419. StringToMeshOutputTopology(Attr->getTopology());
  1420. funcProps->ShaderProps.MS.outputTopology = topology;
  1421. }
  1422. else if (isEntry && !SM->IsHS() && !SM->IsMS()) {
  1423. unsigned DiagID =
  1424. Diags.getCustomDiagID(DiagnosticsEngine::Warning,
  1425. "attribute outputtopology only valid for HS and MS.");
  1426. Diags.Report(Attr->getLocation(), DiagID);
  1427. }
  1428. }
  1429. if (isHS) {
  1430. funcProps->ShaderProps.HS.maxTessFactor = DXIL::kHSMaxTessFactorUpperBound;
  1431. funcProps->ShaderProps.HS.inputControlPoints = DXIL::kHSDefaultInputControlPointCount;
  1432. }
  1433. if (const HLSLMaxTessFactorAttr *Attr =
  1434. FD->getAttr<HLSLMaxTessFactorAttr>()) {
  1435. if (isHS) {
  1436. // TODO: change getFactor to return float.
  1437. llvm::APInt intV(32, Attr->getFactor());
  1438. funcProps->ShaderProps.HS.maxTessFactor = intV.bitsToFloat();
  1439. } else if (isEntry && !SM->IsHS()) {
  1440. unsigned DiagID =
  1441. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1442. "attribute maxtessfactor only valid for HS.");
  1443. Diags.Report(Attr->getLocation(), DiagID);
  1444. return;
  1445. }
  1446. }
  1447. // Hull or domain shader.
  1448. if (const HLSLDomainAttr *Attr = FD->getAttr<HLSLDomainAttr>()) {
  1449. if (isEntry && !SM->IsHS() && !SM->IsDS()) {
  1450. unsigned DiagID =
  1451. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1452. "attribute domain only valid for HS or DS.");
  1453. Diags.Report(Attr->getLocation(), DiagID);
  1454. return;
  1455. }
  1456. isDS = !isHS;
  1457. if (isDS)
  1458. funcProps->shaderKind = DXIL::ShaderKind::Domain;
  1459. DXIL::TessellatorDomain domain = StringToDomain(Attr->getDomainType());
  1460. if (isHS)
  1461. funcProps->ShaderProps.HS.domain = domain;
  1462. else
  1463. funcProps->ShaderProps.DS.domain = domain;
  1464. }
  1465. // Vertex shader.
  1466. if (const HLSLClipPlanesAttr *Attr = FD->getAttr<HLSLClipPlanesAttr>()) {
  1467. if (isEntry && !SM->IsVS()) {
  1468. unsigned DiagID = Diags.getCustomDiagID(
  1469. DiagnosticsEngine::Error, "attribute clipplane only valid for VS.");
  1470. Diags.Report(Attr->getLocation(), DiagID);
  1471. return;
  1472. }
  1473. isVS = true;
  1474. // The real job is done at EmitHLSLFunctionProlog where debug info is
  1475. // available. Only set shader kind here.
  1476. funcProps->shaderKind = DXIL::ShaderKind::Vertex;
  1477. }
  1478. // Pixel shader.
  1479. if (const HLSLEarlyDepthStencilAttr *Attr =
  1480. FD->getAttr<HLSLEarlyDepthStencilAttr>()) {
  1481. if (isEntry && !SM->IsPS()) {
  1482. unsigned DiagID = Diags.getCustomDiagID(
  1483. DiagnosticsEngine::Error,
  1484. "attribute earlydepthstencil only valid for PS.");
  1485. Diags.Report(Attr->getLocation(), DiagID);
  1486. return;
  1487. }
  1488. isPS = true;
  1489. funcProps->ShaderProps.PS.EarlyDepthStencil = true;
  1490. funcProps->shaderKind = DXIL::ShaderKind::Pixel;
  1491. }
  1492. if (const HLSLWaveSizeAttr *Attr = FD->getAttr<HLSLWaveSizeAttr>()) {
  1493. if (!m_pHLModule->GetShaderModel()->IsSM66Plus()) {
  1494. unsigned DiagID = Diags.getCustomDiagID(
  1495. DiagnosticsEngine::Error,
  1496. "attribute WaveSize only valid for shader model 6.6 and higher.");
  1497. Diags.Report(Attr->getLocation(), DiagID);
  1498. return;
  1499. }
  1500. if (!isCS) {
  1501. unsigned DiagID = Diags.getCustomDiagID(
  1502. DiagnosticsEngine::Error,
  1503. "attribute WaveSize only valid for CS.");
  1504. Diags.Report(Attr->getLocation(), DiagID);
  1505. return;
  1506. }
  1507. if (!isEntry) {
  1508. unsigned DiagID = Diags.getCustomDiagID(
  1509. DiagnosticsEngine::Error,
  1510. "attribute WaveSize only valid on entry point function.");
  1511. Diags.Report(Attr->getLocation(), DiagID);
  1512. return;
  1513. }
  1514. // validate that it is a power of 2 between 4 and 128
  1515. unsigned waveSize = Attr->getSize();
  1516. if (!DXIL::IsValidWaveSizeValue(waveSize)) {
  1517. unsigned DiagID = Diags.getCustomDiagID(
  1518. DiagnosticsEngine::Error,
  1519. "WaveSize value must be between %0 and %1 and a power of 2.");
  1520. Diags.Report(Attr->getLocation(), DiagID) << DXIL::kMinWaveSize << DXIL::kMaxWaveSize;
  1521. }
  1522. funcProps->waveSize = Attr->getSize();
  1523. }
  1524. const unsigned profileAttributes = isCS + isHS + isDS + isGS + isVS + isPS + isRay + isMS + isAS;
  1525. // TODO: check this in front-end and report error.
  1526. DXASSERT(profileAttributes < 2, "profile attributes are mutual exclusive");
  1527. if (isEntry) {
  1528. switch (funcProps->shaderKind) {
  1529. case ShaderModel::Kind::Compute:
  1530. case ShaderModel::Kind::Hull:
  1531. case ShaderModel::Kind::Domain:
  1532. case ShaderModel::Kind::Geometry:
  1533. case ShaderModel::Kind::Vertex:
  1534. case ShaderModel::Kind::Pixel:
  1535. case ShaderModel::Kind::Mesh:
  1536. case ShaderModel::Kind::Amplification:
  1537. DXASSERT(funcProps->shaderKind == SM->GetKind(),
  1538. "attribute profile not match entry function profile");
  1539. break;
  1540. case ShaderModel::Kind::Library:
  1541. case ShaderModel::Kind::Invalid:
  1542. // Non-shader stage shadermodels don't have entry points.
  1543. break;
  1544. }
  1545. }
  1546. DxilFunctionAnnotation *FuncAnnotation =
  1547. m_pHLModule->AddFunctionAnnotation(F);
  1548. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  1549. // Param Info
  1550. unsigned streamIndex = 0;
  1551. unsigned inputPatchCount = 0;
  1552. unsigned outputPatchCount = 0;
  1553. unsigned ArgNo = 0;
  1554. unsigned ParmIdx = 0;
  1555. auto ArgIt = F->arg_begin();
  1556. if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FD)) {
  1557. if (MethodDecl->isInstance()) {
  1558. QualType ThisTy = MethodDecl->getThisType(FD->getASTContext());
  1559. DxilParameterAnnotation &paramAnnotation =
  1560. FuncAnnotation->GetParameterAnnotation(ArgNo++);
  1561. ++ArgIt;
  1562. // Construct annoation for this pointer.
  1563. ConstructFieldAttributedAnnotation(paramAnnotation, ThisTy,
  1564. bDefaultRowMajor);
  1565. if (MethodDecl->isConst()) {
  1566. paramAnnotation.SetParamInputQual(DxilParamInputQual::In);
  1567. } else {
  1568. paramAnnotation.SetParamInputQual(DxilParamInputQual::Inout);
  1569. }
  1570. }
  1571. }
  1572. // Ret Info
  1573. QualType retTy = FD->getReturnType();
  1574. DxilParameterAnnotation *pRetTyAnnotation = nullptr;
  1575. if (F->getReturnType()->isVoidTy() && !retTy->isVoidType()) {
  1576. // SRet.
  1577. pRetTyAnnotation = &FuncAnnotation->GetParameterAnnotation(ArgNo++);
  1578. // Save resource properties for parameters.
  1579. AddValToPropertyMap(ArgIt, retTy);
  1580. ++ArgIt;
  1581. } else {
  1582. pRetTyAnnotation = &FuncAnnotation->GetRetTypeAnnotation();
  1583. }
  1584. DxilParameterAnnotation &retTyAnnotation = *pRetTyAnnotation;
  1585. // keep Undefined here, we cannot decide for struct
  1586. retTyAnnotation.SetInterpolationMode(
  1587. GetInterpMode(FD, CompType::Kind::Invalid, /*bKeepUndefined*/ true)
  1588. .GetKind());
  1589. SourceLocation retTySemanticLoc = SetSemantic(FD, retTyAnnotation);
  1590. retTyAnnotation.SetParamInputQual(DxilParamInputQual::Out);
  1591. if (isEntry) {
  1592. if (CGM.getLangOpts().EnableDX9CompatMode && retTyAnnotation.HasSemanticString()) {
  1593. RemapObsoleteSemantic(retTyAnnotation, /*isPatchConstantFunction*/ false);
  1594. }
  1595. CheckParameterAnnotation(retTySemanticLoc, retTyAnnotation,
  1596. /*isPatchConstantFunction*/ false);
  1597. }
  1598. if (isRay && !retTy->isVoidType()) {
  1599. Diags.Report(FD->getLocation(), Diags.getCustomDiagID(
  1600. DiagnosticsEngine::Error, "return type for ray tracing shaders must be void"));
  1601. }
  1602. ConstructFieldAttributedAnnotation(retTyAnnotation, retTy, bDefaultRowMajor);
  1603. if (FD->hasAttr<HLSLPreciseAttr>())
  1604. retTyAnnotation.SetPrecise();
  1605. if (isRay) {
  1606. funcProps->ShaderProps.Ray.payloadSizeInBytes = 0;
  1607. funcProps->ShaderProps.Ray.attributeSizeInBytes = 0;
  1608. }
  1609. bool hasOutIndices = false;
  1610. bool hasOutVertices = false;
  1611. bool hasOutPrimitives = false;
  1612. bool hasInPayload = false;
  1613. bool rayShaderHaveErrors = false;
  1614. for (; ArgNo < F->arg_size(); ++ArgNo, ++ParmIdx, ++ArgIt) {
  1615. DxilParameterAnnotation &paramAnnotation =
  1616. FuncAnnotation->GetParameterAnnotation(ArgNo);
  1617. const ParmVarDecl *parmDecl = FD->getParamDecl(ParmIdx);
  1618. QualType fieldTy = parmDecl->getType();
  1619. // Save object properties for parameters.
  1620. AddValToPropertyMap(ArgIt, fieldTy);
  1621. // if parameter type is a typedef, try to desugar it first.
  1622. if (isa<TypedefType>(fieldTy.getTypePtr()))
  1623. fieldTy = fieldTy.getDesugaredType(FD->getASTContext());
  1624. ConstructFieldAttributedAnnotation(paramAnnotation, fieldTy,
  1625. bDefaultRowMajor);
  1626. if (parmDecl->hasAttr<HLSLPreciseAttr>())
  1627. paramAnnotation.SetPrecise();
  1628. // keep Undefined here, we cannot decide for struct
  1629. InterpolationMode paramIM =
  1630. GetInterpMode(parmDecl, CompType::Kind::Invalid, KeepUndefinedTrue);
  1631. paramAnnotation.SetInterpolationMode(paramIM);
  1632. SourceLocation paramSemanticLoc = SetSemantic(parmDecl, paramAnnotation);
  1633. DxilParamInputQual dxilInputQ = DxilParamInputQual::In;
  1634. if (parmDecl->hasAttr<HLSLInOutAttr>())
  1635. dxilInputQ = DxilParamInputQual::Inout;
  1636. else if (parmDecl->hasAttr<HLSLOutAttr>())
  1637. dxilInputQ = DxilParamInputQual::Out;
  1638. if (parmDecl->hasAttr<HLSLOutAttr>() && parmDecl->hasAttr<HLSLInAttr>())
  1639. dxilInputQ = DxilParamInputQual::Inout;
  1640. if (parmDecl->hasAttr<HLSLOutAttr>() && parmDecl->hasAttr<HLSLIndicesAttr>()) {
  1641. if (hasOutIndices) {
  1642. unsigned DiagID = Diags.getCustomDiagID(
  1643. DiagnosticsEngine::Error,
  1644. "multiple out indices parameters not allowed");
  1645. Diags.Report(parmDecl->getLocation(), DiagID);
  1646. continue;
  1647. }
  1648. const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(fieldTy.getCanonicalType());
  1649. if (CAT == nullptr) {
  1650. unsigned DiagID = Diags.getCustomDiagID(
  1651. DiagnosticsEngine::Error,
  1652. "indices output is not an constant-length array");
  1653. Diags.Report(parmDecl->getLocation(), DiagID);
  1654. continue;
  1655. }
  1656. unsigned count = CAT->getSize().getZExtValue();
  1657. if (count > DXIL::kMaxMSOutputPrimitiveCount) {
  1658. unsigned DiagID = Diags.getCustomDiagID(
  1659. DiagnosticsEngine::Error,
  1660. "max primitive count should not exceed %0");
  1661. Diags.Report(parmDecl->getLocation(), DiagID) << DXIL::kMaxMSOutputPrimitiveCount;
  1662. continue;
  1663. }
  1664. if (funcProps->ShaderProps.MS.maxPrimitiveCount != 0 &&
  1665. funcProps->ShaderProps.MS.maxPrimitiveCount != count) {
  1666. unsigned DiagID = Diags.getCustomDiagID(
  1667. DiagnosticsEngine::Error,
  1668. "max primitive count mismatch");
  1669. Diags.Report(parmDecl->getLocation(), DiagID);
  1670. continue;
  1671. }
  1672. // Get element type.
  1673. QualType arrayEleTy = CAT->getElementType();
  1674. if (hlsl::IsHLSLVecType(arrayEleTy)) {
  1675. QualType vecEltTy = hlsl::GetHLSLVecElementType(arrayEleTy);
  1676. if (!vecEltTy->isUnsignedIntegerType() || CGM.getContext().getTypeSize(vecEltTy) != 32) {
  1677. unsigned DiagID = Diags.getCustomDiagID(
  1678. DiagnosticsEngine::Error,
  1679. "the element of out_indices array must be uint2 for line output or uint3 for triangle output");
  1680. Diags.Report(parmDecl->getLocation(), DiagID);
  1681. continue;
  1682. }
  1683. unsigned vecEltCount = hlsl::GetHLSLVecSize(arrayEleTy);
  1684. if (funcProps->ShaderProps.MS.outputTopology == DXIL::MeshOutputTopology::Line && vecEltCount != 2) {
  1685. unsigned DiagID = Diags.getCustomDiagID(
  1686. DiagnosticsEngine::Error,
  1687. "the element of out_indices array in a mesh shader whose output topology is line must be uint2");
  1688. Diags.Report(parmDecl->getLocation(), DiagID);
  1689. continue;
  1690. }
  1691. if (funcProps->ShaderProps.MS.outputTopology == DXIL::MeshOutputTopology::Triangle && vecEltCount != 3) {
  1692. unsigned DiagID = Diags.getCustomDiagID(
  1693. DiagnosticsEngine::Error,
  1694. "the element of out_indices array in a mesh shader whose output topology is triangle must be uint3");
  1695. Diags.Report(parmDecl->getLocation(), DiagID);
  1696. continue;
  1697. }
  1698. } else {
  1699. unsigned DiagID = Diags.getCustomDiagID(
  1700. DiagnosticsEngine::Error,
  1701. "the element of out_indices array must be uint2 for line output or uint3 for triangle output");
  1702. Diags.Report(parmDecl->getLocation(), DiagID);
  1703. continue;
  1704. }
  1705. dxilInputQ = DxilParamInputQual::OutIndices;
  1706. funcProps->ShaderProps.MS.maxPrimitiveCount = count;
  1707. hasOutIndices = true;
  1708. }
  1709. if (parmDecl->hasAttr<HLSLOutAttr>() && parmDecl->hasAttr<HLSLVerticesAttr>()) {
  1710. if (hasOutVertices) {
  1711. unsigned DiagID = Diags.getCustomDiagID(
  1712. DiagnosticsEngine::Error,
  1713. "multiple out vertices parameters not allowed");
  1714. Diags.Report(parmDecl->getLocation(), DiagID);
  1715. continue;
  1716. }
  1717. const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(fieldTy.getCanonicalType());
  1718. if (CAT == nullptr) {
  1719. unsigned DiagID = Diags.getCustomDiagID(
  1720. DiagnosticsEngine::Error,
  1721. "vertices output is not an constant-length array");
  1722. Diags.Report(parmDecl->getLocation(), DiagID);
  1723. continue;
  1724. }
  1725. unsigned count = CAT->getSize().getZExtValue();
  1726. if (count > DXIL::kMaxMSOutputVertexCount) {
  1727. unsigned DiagID = Diags.getCustomDiagID(
  1728. DiagnosticsEngine::Error,
  1729. "max vertex count should not exceed %0");
  1730. Diags.Report(parmDecl->getLocation(), DiagID) << DXIL::kMaxMSOutputVertexCount;
  1731. continue;
  1732. }
  1733. dxilInputQ = DxilParamInputQual::OutVertices;
  1734. funcProps->ShaderProps.MS.maxVertexCount = count;
  1735. hasOutVertices = true;
  1736. }
  1737. if (parmDecl->hasAttr<HLSLOutAttr>() && parmDecl->hasAttr<HLSLPrimitivesAttr>()) {
  1738. if (hasOutPrimitives) {
  1739. unsigned DiagID = Diags.getCustomDiagID(
  1740. DiagnosticsEngine::Error,
  1741. "multiple out primitives parameters not allowed");
  1742. Diags.Report(parmDecl->getLocation(), DiagID);
  1743. continue;
  1744. }
  1745. const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(fieldTy.getCanonicalType());
  1746. if (CAT == nullptr) {
  1747. unsigned DiagID = Diags.getCustomDiagID(
  1748. DiagnosticsEngine::Error,
  1749. "primitives output is not an constant-length array");
  1750. Diags.Report(parmDecl->getLocation(), DiagID);
  1751. continue;
  1752. }
  1753. unsigned count = CAT->getSize().getZExtValue();
  1754. if (count > DXIL::kMaxMSOutputPrimitiveCount) {
  1755. unsigned DiagID = Diags.getCustomDiagID(
  1756. DiagnosticsEngine::Error,
  1757. "max primitive count should not exceed %0");
  1758. Diags.Report(parmDecl->getLocation(), DiagID) << DXIL::kMaxMSOutputPrimitiveCount;
  1759. continue;
  1760. }
  1761. if (funcProps->ShaderProps.MS.maxPrimitiveCount != 0 &&
  1762. funcProps->ShaderProps.MS.maxPrimitiveCount != count) {
  1763. unsigned DiagID = Diags.getCustomDiagID(
  1764. DiagnosticsEngine::Error,
  1765. "max primitive count mismatch");
  1766. Diags.Report(parmDecl->getLocation(), DiagID);
  1767. continue;
  1768. }
  1769. dxilInputQ = DxilParamInputQual::OutPrimitives;
  1770. funcProps->ShaderProps.MS.maxPrimitiveCount = count;
  1771. hasOutPrimitives = true;
  1772. }
  1773. if (parmDecl->hasAttr<HLSLInAttr>() && parmDecl->hasAttr<HLSLPayloadAttr>()) {
  1774. if (hasInPayload) {
  1775. unsigned DiagID = Diags.getCustomDiagID(
  1776. DiagnosticsEngine::Error,
  1777. "multiple in payload parameters not allowed");
  1778. Diags.Report(parmDecl->getLocation(), DiagID);
  1779. continue;
  1780. }
  1781. dxilInputQ = DxilParamInputQual::InPayload;
  1782. DataLayout DL(&this->TheModule);
  1783. funcProps->ShaderProps.MS.payloadSizeInBytes = DL.getTypeAllocSize(
  1784. F->getFunctionType()->getFunctionParamType(ArgNo)->getPointerElementType());
  1785. hasInPayload = true;
  1786. }
  1787. DXIL::InputPrimitive inputPrimitive = DXIL::InputPrimitive::Undefined;
  1788. if (IsHLSLOutputPatchType(parmDecl->getType())) {
  1789. outputPatchCount++;
  1790. if (dxilInputQ != DxilParamInputQual::In) {
  1791. unsigned DiagID = Diags.getCustomDiagID(
  1792. DiagnosticsEngine::Error,
  1793. "OutputPatch should not be out/inout parameter");
  1794. Diags.Report(parmDecl->getLocation(), DiagID);
  1795. continue;
  1796. }
  1797. dxilInputQ = DxilParamInputQual::OutputPatch;
  1798. if (isDS)
  1799. funcProps->ShaderProps.DS.inputControlPoints =
  1800. GetHLSLOutputPatchCount(parmDecl->getType());
  1801. } else if (IsHLSLInputPatchType(parmDecl->getType())) {
  1802. inputPatchCount++;
  1803. if (dxilInputQ != DxilParamInputQual::In) {
  1804. unsigned DiagID = Diags.getCustomDiagID(
  1805. DiagnosticsEngine::Error,
  1806. "InputPatch should not be out/inout parameter");
  1807. Diags.Report(parmDecl->getLocation(), DiagID);
  1808. continue;
  1809. }
  1810. dxilInputQ = DxilParamInputQual::InputPatch;
  1811. if (isHS) {
  1812. funcProps->ShaderProps.HS.inputControlPoints =
  1813. GetHLSLInputPatchCount(parmDecl->getType());
  1814. } else if (isGS) {
  1815. inputPrimitive = (DXIL::InputPrimitive)(
  1816. (unsigned)DXIL::InputPrimitive::ControlPointPatch1 +
  1817. GetHLSLInputPatchCount(parmDecl->getType()) - 1);
  1818. }
  1819. } else if (IsHLSLStreamOutputType(parmDecl->getType())) {
  1820. // TODO: validation this at ASTContext::getFunctionType in
  1821. // AST/ASTContext.cpp
  1822. DXASSERT(dxilInputQ == DxilParamInputQual::Inout,
  1823. "stream output parameter must be inout");
  1824. switch (streamIndex) {
  1825. case 0:
  1826. dxilInputQ = DxilParamInputQual::OutStream0;
  1827. break;
  1828. case 1:
  1829. dxilInputQ = DxilParamInputQual::OutStream1;
  1830. break;
  1831. case 2:
  1832. dxilInputQ = DxilParamInputQual::OutStream2;
  1833. break;
  1834. case 3:
  1835. default:
  1836. // TODO: validation this at ASTContext::getFunctionType in
  1837. // AST/ASTContext.cpp
  1838. DXASSERT(streamIndex == 3, "stream number out of bound");
  1839. dxilInputQ = DxilParamInputQual::OutStream3;
  1840. break;
  1841. }
  1842. DXIL::PrimitiveTopology &streamTopology =
  1843. funcProps->ShaderProps.GS.streamPrimitiveTopologies[streamIndex];
  1844. if (IsHLSLPointStreamType(parmDecl->getType()))
  1845. streamTopology = DXIL::PrimitiveTopology::PointList;
  1846. else if (IsHLSLLineStreamType(parmDecl->getType()))
  1847. streamTopology = DXIL::PrimitiveTopology::LineStrip;
  1848. else {
  1849. DXASSERT(IsHLSLTriangleStreamType(parmDecl->getType()),
  1850. "invalid StreamType");
  1851. streamTopology = DXIL::PrimitiveTopology::TriangleStrip;
  1852. }
  1853. if (streamIndex > 0) {
  1854. bool bAllPoint =
  1855. streamTopology == DXIL::PrimitiveTopology::PointList &&
  1856. funcProps->ShaderProps.GS.streamPrimitiveTopologies[0] ==
  1857. DXIL::PrimitiveTopology::PointList;
  1858. if (!bAllPoint) {
  1859. unsigned DiagID = Diags.getCustomDiagID(
  1860. DiagnosticsEngine::Error, "when multiple GS output streams are "
  1861. "used they must be pointlists.");
  1862. Diags.Report(FD->getLocation(), DiagID);
  1863. }
  1864. }
  1865. streamIndex++;
  1866. }
  1867. unsigned GsInputArrayDim = 0;
  1868. if (parmDecl->hasAttr<HLSLTriangleAttr>()) {
  1869. inputPrimitive = DXIL::InputPrimitive::Triangle;
  1870. GsInputArrayDim = 3;
  1871. } else if (parmDecl->hasAttr<HLSLTriangleAdjAttr>()) {
  1872. inputPrimitive = DXIL::InputPrimitive::TriangleWithAdjacency;
  1873. GsInputArrayDim = 6;
  1874. } else if (parmDecl->hasAttr<HLSLPointAttr>()) {
  1875. inputPrimitive = DXIL::InputPrimitive::Point;
  1876. GsInputArrayDim = 1;
  1877. } else if (parmDecl->hasAttr<HLSLLineAdjAttr>()) {
  1878. inputPrimitive = DXIL::InputPrimitive::LineWithAdjacency;
  1879. GsInputArrayDim = 4;
  1880. } else if (parmDecl->hasAttr<HLSLLineAttr>()) {
  1881. inputPrimitive = DXIL::InputPrimitive::Line;
  1882. GsInputArrayDim = 2;
  1883. }
  1884. if (inputPrimitive != DXIL::InputPrimitive::Undefined) {
  1885. // Set to InputPrimitive for GS.
  1886. dxilInputQ = DxilParamInputQual::InputPrimitive;
  1887. if (funcProps->ShaderProps.GS.inputPrimitive ==
  1888. DXIL::InputPrimitive::Undefined) {
  1889. funcProps->ShaderProps.GS.inputPrimitive = inputPrimitive;
  1890. } else if (funcProps->ShaderProps.GS.inputPrimitive != inputPrimitive) {
  1891. unsigned DiagID = Diags.getCustomDiagID(
  1892. DiagnosticsEngine::Error, "input parameter conflicts with geometry "
  1893. "specifier of previous input parameters");
  1894. Diags.Report(parmDecl->getLocation(), DiagID);
  1895. }
  1896. }
  1897. if (GsInputArrayDim != 0) {
  1898. QualType Ty = parmDecl->getType();
  1899. if (!Ty->isConstantArrayType()) {
  1900. unsigned DiagID = Diags.getCustomDiagID(
  1901. DiagnosticsEngine::Error,
  1902. "input types for geometry shader must be constant size arrays");
  1903. Diags.Report(parmDecl->getLocation(), DiagID);
  1904. } else {
  1905. const ConstantArrayType *CAT = cast<ConstantArrayType>(Ty);
  1906. if (CAT->getSize().getLimitedValue() != GsInputArrayDim) {
  1907. StringRef primtiveNames[] = {
  1908. "invalid", // 0
  1909. "point", // 1
  1910. "line", // 2
  1911. "triangle", // 3
  1912. "lineadj", // 4
  1913. "invalid", // 5
  1914. "triangleadj", // 6
  1915. };
  1916. DXASSERT(GsInputArrayDim < llvm::array_lengthof(primtiveNames),
  1917. "Invalid array dim");
  1918. unsigned DiagID = Diags.getCustomDiagID(
  1919. DiagnosticsEngine::Error, "array dimension for %0 must be %1");
  1920. Diags.Report(parmDecl->getLocation(), DiagID)
  1921. << primtiveNames[GsInputArrayDim] << GsInputArrayDim;
  1922. }
  1923. }
  1924. }
  1925. // Validate Ray Tracing function parameter (some validation may be pushed into front end)
  1926. if (isRay) {
  1927. switch (funcProps->shaderKind) {
  1928. case DXIL::ShaderKind::RayGeneration:
  1929. case DXIL::ShaderKind::Intersection:
  1930. // RayGeneration and Intersection shaders are not allowed to have any input parameters
  1931. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1932. DiagnosticsEngine::Error, "parameters are not allowed for %0 shader"))
  1933. << (funcProps->shaderKind == DXIL::ShaderKind::RayGeneration ?
  1934. "raygeneration" : "intersection");
  1935. rayShaderHaveErrors = true;
  1936. case DXIL::ShaderKind::AnyHit:
  1937. case DXIL::ShaderKind::ClosestHit:
  1938. if (0 == ArgNo && dxilInputQ != DxilParamInputQual::Inout) {
  1939. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1940. DiagnosticsEngine::Error,
  1941. "ray payload parameter must be inout"));
  1942. rayShaderHaveErrors = true;
  1943. } else if (1 == ArgNo && dxilInputQ != DxilParamInputQual::In) {
  1944. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1945. DiagnosticsEngine::Error,
  1946. "intersection attributes parameter must be in"));
  1947. rayShaderHaveErrors = true;
  1948. } else if (ArgNo > 1) {
  1949. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1950. DiagnosticsEngine::Error,
  1951. "too many parameters, expected payload and attributes parameters only."));
  1952. rayShaderHaveErrors = true;
  1953. }
  1954. if (ArgNo < 2) {
  1955. if (!IsHLSLNumericUserDefinedType(parmDecl->getType())) {
  1956. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1957. DiagnosticsEngine::Error,
  1958. "payload and attribute structures must be user defined types with only numeric contents."));
  1959. rayShaderHaveErrors = true;
  1960. } else {
  1961. DataLayout DL(&this->TheModule);
  1962. unsigned size = DL.getTypeAllocSize(F->getFunctionType()->getFunctionParamType(ArgNo)->getPointerElementType());
  1963. if (0 == ArgNo)
  1964. funcProps->ShaderProps.Ray.payloadSizeInBytes = size;
  1965. else
  1966. funcProps->ShaderProps.Ray.attributeSizeInBytes = size;
  1967. }
  1968. }
  1969. break;
  1970. case DXIL::ShaderKind::Miss:
  1971. if (ArgNo > 0) {
  1972. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1973. DiagnosticsEngine::Error,
  1974. "only one parameter (ray payload) allowed for miss shader"));
  1975. rayShaderHaveErrors = true;
  1976. } else if (dxilInputQ != DxilParamInputQual::Inout) {
  1977. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1978. DiagnosticsEngine::Error,
  1979. "ray payload parameter must be declared inout"));
  1980. rayShaderHaveErrors = true;
  1981. }
  1982. if (ArgNo < 1) {
  1983. if (!IsHLSLNumericUserDefinedType(parmDecl->getType())) {
  1984. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1985. DiagnosticsEngine::Error,
  1986. "ray payload parameter must be a user defined type with only numeric contents."));
  1987. rayShaderHaveErrors = true;
  1988. } else {
  1989. DataLayout DL(&this->TheModule);
  1990. unsigned size = DL.getTypeAllocSize(F->getFunctionType()->getFunctionParamType(ArgNo)->getPointerElementType());
  1991. funcProps->ShaderProps.Ray.payloadSizeInBytes = size;
  1992. }
  1993. }
  1994. break;
  1995. case DXIL::ShaderKind::Callable:
  1996. if (ArgNo > 0) {
  1997. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1998. DiagnosticsEngine::Error,
  1999. "only one parameter allowed for callable shader"));
  2000. rayShaderHaveErrors = true;
  2001. } else if (dxilInputQ != DxilParamInputQual::Inout) {
  2002. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  2003. DiagnosticsEngine::Error,
  2004. "callable parameter must be declared inout"));
  2005. rayShaderHaveErrors = true;
  2006. }
  2007. if (ArgNo < 1) {
  2008. if (!IsHLSLNumericUserDefinedType(parmDecl->getType())) {
  2009. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  2010. DiagnosticsEngine::Error,
  2011. "callable parameter must be a user defined type with only numeric contents."));
  2012. rayShaderHaveErrors = true;
  2013. } else {
  2014. DataLayout DL(&this->TheModule);
  2015. unsigned size = DL.getTypeAllocSize(F->getFunctionType()->getFunctionParamType(ArgNo)->getPointerElementType());
  2016. funcProps->ShaderProps.Ray.paramSizeInBytes = size;
  2017. }
  2018. }
  2019. break;
  2020. }
  2021. }
  2022. paramAnnotation.SetParamInputQual(dxilInputQ);
  2023. if (isEntry) {
  2024. if (CGM.getLangOpts().EnableDX9CompatMode && paramAnnotation.HasSemanticString()) {
  2025. RemapObsoleteSemantic(paramAnnotation, /*isPatchConstantFunction*/ false);
  2026. }
  2027. CheckParameterAnnotation(paramSemanticLoc, paramAnnotation,
  2028. /*isPatchConstantFunction*/ false);
  2029. }
  2030. }
  2031. if (inputPatchCount > 1) {
  2032. unsigned DiagID = Diags.getCustomDiagID(
  2033. DiagnosticsEngine::Error, "may only have one InputPatch parameter");
  2034. Diags.Report(FD->getLocation(), DiagID);
  2035. }
  2036. if (outputPatchCount > 1) {
  2037. unsigned DiagID = Diags.getCustomDiagID(
  2038. DiagnosticsEngine::Error, "may only have one OutputPatch parameter");
  2039. Diags.Report(FD->getLocation(), DiagID);
  2040. }
  2041. // If Shader is a ray shader that requires parameters, make sure size is non-zero
  2042. if (isRay) {
  2043. bool bNeedsAttributes = false;
  2044. bool bNeedsPayload = false;
  2045. switch (funcProps->shaderKind) {
  2046. case DXIL::ShaderKind::AnyHit:
  2047. case DXIL::ShaderKind::ClosestHit:
  2048. bNeedsAttributes = true;
  2049. case DXIL::ShaderKind::Miss:
  2050. bNeedsPayload = true;
  2051. case DXIL::ShaderKind::Callable:
  2052. if (0 == funcProps->ShaderProps.Ray.payloadSizeInBytes) {
  2053. unsigned DiagID = bNeedsPayload ?
  2054. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2055. "shader must include inout payload structure parameter.") :
  2056. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2057. "shader must include inout parameter structure.");
  2058. Diags.Report(FD->getLocation(), DiagID);
  2059. rayShaderHaveErrors = true;
  2060. }
  2061. }
  2062. if (bNeedsAttributes &&
  2063. 0 == funcProps->ShaderProps.Ray.attributeSizeInBytes) {
  2064. Diags.Report(FD->getLocation(), Diags.getCustomDiagID(
  2065. DiagnosticsEngine::Error,
  2066. "shader must include attributes structure parameter."));
  2067. rayShaderHaveErrors = true;
  2068. }
  2069. }
  2070. // If we encountered an error during verification of RayTracing
  2071. // shader signatures, stop here. Otherwise we risk to trigger
  2072. // unhandled behaviour, i.e., DXC crashes when the payload is
  2073. // declared as matrix<float...> type.
  2074. if(rayShaderHaveErrors)
  2075. return;
  2076. // Type annotation for parameters and return type.
  2077. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  2078. unsigned arrayEltSize = 0;
  2079. AddTypeAnnotation(FD->getReturnType(), dxilTypeSys, arrayEltSize);
  2080. // Type annotation for this pointer.
  2081. if (const CXXMethodDecl *MFD = dyn_cast<CXXMethodDecl>(FD)) {
  2082. const CXXRecordDecl *RD = MFD->getParent();
  2083. QualType Ty = CGM.getContext().getTypeDeclType(RD);
  2084. AddTypeAnnotation(Ty, dxilTypeSys, arrayEltSize);
  2085. }
  2086. for (const ValueDecl *param : FD->params()) {
  2087. QualType Ty = param->getType();
  2088. AddTypeAnnotation(Ty, dxilTypeSys, arrayEltSize);
  2089. }
  2090. // clear isExportedEntry if not exporting entry
  2091. bool isExportedEntry = profileAttributes != 0;
  2092. if (isExportedEntry) {
  2093. // use unmangled or mangled name depending on which is used for final entry function
  2094. StringRef name = isRay ? F->getName() : FD->getName();
  2095. if (!m_ExportMap.IsExported(name)) {
  2096. isExportedEntry = false;
  2097. }
  2098. }
  2099. // Only add functionProps when exist.
  2100. if (isExportedEntry || isEntry)
  2101. m_pHLModule->AddDxilFunctionProps(F, funcProps);
  2102. if (isPatchConstantFunction)
  2103. patchConstantFunctionPropsMap[F] = std::move(funcProps);
  2104. // Save F to entry map.
  2105. if (isExportedEntry) {
  2106. if (entryFunctionMap.count(FD->getName())) {
  2107. DiagnosticsEngine &Diags = CGM.getDiags();
  2108. unsigned DiagID = Diags.getCustomDiagID(
  2109. DiagnosticsEngine::Error,
  2110. "redefinition of %0");
  2111. Diags.Report(FD->getLocStart(), DiagID) << FD->getName();
  2112. }
  2113. auto &Entry = entryFunctionMap[FD->getNameAsString()];
  2114. Entry.SL = FD->getLocation();
  2115. Entry.Func= F;
  2116. }
  2117. // Add target-dependent experimental function attributes
  2118. for (const auto &Attr : FD->specific_attrs<HLSLExperimentalAttr>()) {
  2119. F->addFnAttr(Twine("exp-", Attr->getName()).str(), Attr->getValue());
  2120. }
  2121. m_ScopeMap[F] = ScopeInfo(F);
  2122. }
  2123. void CGMSHLSLRuntime::RemapObsoleteSemantic(DxilParameterAnnotation &paramInfo, bool isPatchConstantFunction) {
  2124. DXASSERT(CGM.getLangOpts().EnableDX9CompatMode, "should be used only in back-compat mode");
  2125. const ShaderModel *SM = m_pHLModule->GetShaderModel();
  2126. DXIL::SigPointKind sigPointKind = SigPointFromInputQual(paramInfo.GetParamInputQual(), SM->GetKind(), isPatchConstantFunction);
  2127. hlsl::RemapObsoleteSemantic(paramInfo, sigPointKind, CGM.getLLVMContext());
  2128. }
  2129. void CGMSHLSLRuntime::EmitHLSLFunctionProlog(Function *F, const FunctionDecl *FD) {
  2130. // Support clip plane need debug info which not available when create function attribute.
  2131. if (const HLSLClipPlanesAttr *Attr = FD->getAttr<HLSLClipPlanesAttr>()) {
  2132. DxilFunctionProps &funcProps = m_pHLModule->GetDxilFunctionProps(F);
  2133. // Initialize to null.
  2134. memset(funcProps.ShaderProps.VS.clipPlanes, 0, sizeof(funcProps.ShaderProps.VS.clipPlanes));
  2135. // Create global for each clip plane, and use the clip plane val as init val.
  2136. auto AddClipPlane = [&](Expr *clipPlane, unsigned idx) {
  2137. if (DeclRefExpr *decl = dyn_cast<DeclRefExpr>(clipPlane)) {
  2138. const VarDecl *VD = cast<VarDecl>(decl->getDecl());
  2139. Constant *clipPlaneVal = CGM.GetAddrOfGlobalVar(VD);
  2140. funcProps.ShaderProps.VS.clipPlanes[idx] = clipPlaneVal;
  2141. if (m_bDebugInfo) {
  2142. CodeGenFunction CGF(CGM);
  2143. ApplyDebugLocation applyDebugLoc(CGF, clipPlane);
  2144. debugInfoMap[clipPlaneVal] = CGF.Builder.getCurrentDebugLocation();
  2145. }
  2146. } else {
  2147. // Must be a MemberExpr.
  2148. const MemberExpr *ME = cast<MemberExpr>(clipPlane);
  2149. CodeGenFunction CGF(CGM);
  2150. CodeGen::LValue LV = CGF.EmitMemberExpr(ME);
  2151. Value *addr = LV.getAddress();
  2152. funcProps.ShaderProps.VS.clipPlanes[idx] = cast<Constant>(addr);
  2153. if (m_bDebugInfo) {
  2154. CodeGenFunction CGF(CGM);
  2155. ApplyDebugLocation applyDebugLoc(CGF, clipPlane);
  2156. debugInfoMap[addr] = CGF.Builder.getCurrentDebugLocation();
  2157. }
  2158. }
  2159. };
  2160. if (Expr *clipPlane = Attr->getClipPlane1())
  2161. AddClipPlane(clipPlane, 0);
  2162. if (Expr *clipPlane = Attr->getClipPlane2())
  2163. AddClipPlane(clipPlane, 1);
  2164. if (Expr *clipPlane = Attr->getClipPlane3())
  2165. AddClipPlane(clipPlane, 2);
  2166. if (Expr *clipPlane = Attr->getClipPlane4())
  2167. AddClipPlane(clipPlane, 3);
  2168. if (Expr *clipPlane = Attr->getClipPlane5())
  2169. AddClipPlane(clipPlane, 4);
  2170. if (Expr *clipPlane = Attr->getClipPlane6())
  2171. AddClipPlane(clipPlane, 5);
  2172. clipPlaneFuncList.emplace_back(F);
  2173. }
  2174. // Update function linkage based on DefaultLinkage
  2175. // We will take care of patch constant functions later, once identified for certain.
  2176. if (!m_pHLModule->HasDxilFunctionProps(F)) {
  2177. if (F->getLinkage() == GlobalValue::LinkageTypes::ExternalLinkage) {
  2178. if (!FD->hasAttr<HLSLExportAttr>()) {
  2179. switch (CGM.getCodeGenOpts().DefaultLinkage) {
  2180. case DXIL::DefaultLinkage::Default:
  2181. if (m_pHLModule->GetShaderModel()->GetMinor() != ShaderModel::kOfflineMinor)
  2182. F->setLinkage(GlobalValue::LinkageTypes::InternalLinkage);
  2183. break;
  2184. case DXIL::DefaultLinkage::Internal:
  2185. F->setLinkage(GlobalValue::LinkageTypes::InternalLinkage);
  2186. break;
  2187. }
  2188. }
  2189. }
  2190. }
  2191. }
  2192. void CGMSHLSLRuntime::AddControlFlowHint(CodeGenFunction &CGF, const Stmt &S,
  2193. llvm::TerminatorInst *TI,
  2194. ArrayRef<const Attr *> Attrs) {
  2195. // Build hints.
  2196. bool bNoBranchFlatten = true;
  2197. bool bBranch = false;
  2198. bool bFlatten = false;
  2199. std::vector<DXIL::ControlFlowHint> hints;
  2200. for (const auto *Attr : Attrs) {
  2201. if (isa<HLSLBranchAttr>(Attr)) {
  2202. hints.emplace_back(DXIL::ControlFlowHint::Branch);
  2203. bNoBranchFlatten = false;
  2204. bBranch = true;
  2205. }
  2206. else if (isa<HLSLFlattenAttr>(Attr)) {
  2207. hints.emplace_back(DXIL::ControlFlowHint::Flatten);
  2208. bNoBranchFlatten = false;
  2209. bFlatten = true;
  2210. } else if (isa<HLSLForceCaseAttr>(Attr)) {
  2211. if (isa<SwitchStmt>(&S)) {
  2212. hints.emplace_back(DXIL::ControlFlowHint::ForceCase);
  2213. }
  2214. }
  2215. // Ignore fastopt, allow_uav_condition and call for now.
  2216. }
  2217. if (bNoBranchFlatten) {
  2218. // CHECK control flow option.
  2219. if (CGF.CGM.getCodeGenOpts().HLSLPreferControlFlow)
  2220. hints.emplace_back(DXIL::ControlFlowHint::Branch);
  2221. else if (CGF.CGM.getCodeGenOpts().HLSLAvoidControlFlow)
  2222. hints.emplace_back(DXIL::ControlFlowHint::Flatten);
  2223. }
  2224. if (bFlatten && bBranch) {
  2225. DiagnosticsEngine &Diags = CGM.getDiags();
  2226. unsigned DiagID = Diags.getCustomDiagID(
  2227. DiagnosticsEngine::Error,
  2228. "can't use branch and flatten attributes together");
  2229. Diags.Report(S.getLocStart(), DiagID);
  2230. }
  2231. if (hints.size()) {
  2232. // Add meta data to the instruction.
  2233. MDNode *hintsNode = DxilMDHelper::EmitControlFlowHints(Context, hints);
  2234. TI->setMetadata(DxilMDHelper::kDxilControlFlowHintMDName, hintsNode);
  2235. }
  2236. }
  2237. void CGMSHLSLRuntime::MarkRetTemp(CodeGenFunction &CGF, Value *V,
  2238. QualType QualTy) {
  2239. // Save object properties for ret temp.
  2240. AddValToPropertyMap(V, QualTy);
  2241. }
  2242. void CGMSHLSLRuntime::MarkCallArgumentTemp(CodeGenFunction &CGF, llvm::Value *V,
  2243. clang::QualType QualTy) {
  2244. // Save object properties for call arg temp.
  2245. // Ignore V already in property map.
  2246. if (objectProperties.GetResource(V).isValid())
  2247. return;
  2248. AddValToPropertyMap(V, QualTy);
  2249. }
  2250. void CGMSHLSLRuntime::FinishAutoVar(CodeGenFunction &CGF, const VarDecl &D,
  2251. llvm::Value *V) {
  2252. if (D.hasAttr<HLSLPreciseAttr>()) {
  2253. AllocaInst *AI = cast<AllocaInst>(V);
  2254. HLModule::MarkPreciseAttributeWithMetadata(AI);
  2255. }
  2256. // Add type annotation for local variable.
  2257. DxilTypeSystem &typeSys = m_pHLModule->GetTypeSystem();
  2258. unsigned arrayEltSize = 0;
  2259. AddTypeAnnotation(D.getType(), typeSys, arrayEltSize);
  2260. // Save object properties for local variables.
  2261. AddValToPropertyMap(V, D.getType());
  2262. }
  2263. hlsl::InterpolationMode CGMSHLSLRuntime::GetInterpMode(const Decl *decl,
  2264. CompType compType,
  2265. bool bKeepUndefined) {
  2266. InterpolationMode Interp(
  2267. decl->hasAttr<HLSLNoInterpolationAttr>(), decl->hasAttr<HLSLLinearAttr>(),
  2268. decl->hasAttr<HLSLNoPerspectiveAttr>(), decl->hasAttr<HLSLCentroidAttr>(),
  2269. decl->hasAttr<HLSLSampleAttr>());
  2270. DXASSERT(Interp.IsValid(), "otherwise front-end missing validation");
  2271. if (Interp.IsUndefined() && !bKeepUndefined) {
  2272. // Type-based default: linear for floats, constant for others.
  2273. if (compType.IsFloatTy())
  2274. Interp = InterpolationMode::Kind::Linear;
  2275. else
  2276. Interp = InterpolationMode::Kind::Constant;
  2277. }
  2278. return Interp;
  2279. }
  2280. hlsl::CompType CGMSHLSLRuntime::GetCompType(const BuiltinType *BT) {
  2281. hlsl::CompType ElementType = hlsl::CompType::getInvalid();
  2282. switch (BT->getKind()) {
  2283. case BuiltinType::Bool:
  2284. ElementType = hlsl::CompType::getI1();
  2285. break;
  2286. case BuiltinType::Double:
  2287. ElementType = hlsl::CompType::getF64();
  2288. break;
  2289. case BuiltinType::HalfFloat: // HLSL Change
  2290. case BuiltinType::Float:
  2291. ElementType = hlsl::CompType::getF32();
  2292. break;
  2293. // HLSL Changes begin
  2294. case BuiltinType::Min10Float:
  2295. case BuiltinType::Min16Float:
  2296. // HLSL Changes end
  2297. case BuiltinType::Half:
  2298. ElementType = hlsl::CompType::getF16();
  2299. break;
  2300. case BuiltinType::Int:
  2301. ElementType = hlsl::CompType::getI32();
  2302. break;
  2303. case BuiltinType::LongLong:
  2304. ElementType = hlsl::CompType::getI64();
  2305. break;
  2306. // HLSL Changes begin
  2307. case BuiltinType::Min12Int:
  2308. case BuiltinType::Min16Int:
  2309. // HLSL Changes end
  2310. case BuiltinType::Short:
  2311. ElementType = hlsl::CompType::getI16();
  2312. break;
  2313. // HLSL Changes begin
  2314. case BuiltinType::Int8_4Packed:
  2315. case BuiltinType::UInt8_4Packed:
  2316. // HLSL Changes end
  2317. case BuiltinType::UInt:
  2318. ElementType = hlsl::CompType::getU32();
  2319. break;
  2320. case BuiltinType::ULongLong:
  2321. ElementType = hlsl::CompType::getU64();
  2322. break;
  2323. case BuiltinType::Min16UInt: // HLSL Change
  2324. case BuiltinType::UShort:
  2325. ElementType = hlsl::CompType::getU16();
  2326. break;
  2327. default:
  2328. llvm_unreachable("unsupported type");
  2329. break;
  2330. }
  2331. return ElementType;
  2332. }
  2333. /// Add resource to the program
  2334. void CGMSHLSLRuntime::addResource(Decl *D) {
  2335. if (HLSLBufferDecl *BD = dyn_cast<HLSLBufferDecl>(D))
  2336. GetOrCreateCBuffer(BD);
  2337. else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  2338. hlsl::DxilResourceBase::Class resClass = TypeToClass(VD->getType());
  2339. // Save resource properties for global variables.
  2340. if (resClass != DXIL::ResourceClass::Invalid) {
  2341. GlobalVariable *GV = cast<GlobalVariable>(CGM.GetAddrOfGlobalVar(VD));
  2342. AddValToPropertyMap(GV, VD->getType());
  2343. }
  2344. // skip decl has init which is resource.
  2345. if (VD->hasInit() && resClass != DXIL::ResourceClass::Invalid)
  2346. return;
  2347. // skip static global.
  2348. if (!VD->hasExternalFormalLinkage()) {
  2349. if (VD->hasInit() && VD->getType().isConstQualified()) {
  2350. Expr* InitExp = VD->getInit();
  2351. GlobalVariable *GV = cast<GlobalVariable>(CGM.GetAddrOfGlobalVar(VD));
  2352. // Only save const static global of struct type.
  2353. if (GV->getType()->getElementType()->isStructTy()) {
  2354. staticConstGlobalInitMap[InitExp] = GV;
  2355. }
  2356. }
  2357. // Add type annotation for static global variable.
  2358. DxilTypeSystem &typeSys = m_pHLModule->GetTypeSystem();
  2359. unsigned arrayEltSize = 0;
  2360. AddTypeAnnotation(VD->getType(), typeSys, arrayEltSize);
  2361. return;
  2362. }
  2363. if (D->hasAttr<HLSLGroupSharedAttr>()) {
  2364. GlobalVariable *GV = cast<GlobalVariable>(CGM.GetAddrOfGlobalVar(VD));
  2365. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  2366. unsigned arraySize = 0;
  2367. AddTypeAnnotation(VD->getType(), dxilTypeSys, arraySize);
  2368. m_pHLModule->AddGroupSharedVariable(GV);
  2369. return;
  2370. }
  2371. switch (resClass) {
  2372. case hlsl::DxilResourceBase::Class::Sampler:
  2373. AddSampler(VD);
  2374. break;
  2375. case hlsl::DxilResourceBase::Class::UAV:
  2376. case hlsl::DxilResourceBase::Class::SRV:
  2377. AddUAVSRV(VD, resClass);
  2378. break;
  2379. case hlsl::DxilResourceBase::Class::Invalid: {
  2380. // normal global constant, add to global CB
  2381. HLCBuffer &globalCB = GetGlobalCBuffer();
  2382. AddConstant(VD, globalCB);
  2383. break;
  2384. }
  2385. case DXIL::ResourceClass::CBuffer:
  2386. AddConstantBufferView(VD);
  2387. break;
  2388. }
  2389. }
  2390. }
  2391. /// Add subobject to the module
  2392. void CGMSHLSLRuntime::addSubobject(Decl *D) {
  2393. VarDecl *VD = dyn_cast<VarDecl>(D);
  2394. DXASSERT(VD != nullptr, "must be a global variable");
  2395. DXIL::SubobjectKind subobjKind;
  2396. DXIL::HitGroupType hgType;
  2397. if (!hlsl::GetHLSLSubobjectKind(VD->getType(), subobjKind, hgType)) {
  2398. DXASSERT(false, "not a valid subobject declaration");
  2399. return;
  2400. }
  2401. Expr *initExpr = const_cast<Expr*>(VD->getAnyInitializer());
  2402. if (!initExpr) {
  2403. DiagnosticsEngine &Diags = CGM.getDiags();
  2404. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "subobject needs to be initialized");
  2405. Diags.Report(D->getLocStart(), DiagID);
  2406. return;
  2407. }
  2408. if (InitListExpr *initListExpr = dyn_cast<InitListExpr>(initExpr)) {
  2409. try {
  2410. CreateSubobject(subobjKind, VD->getName(), initListExpr->getInits(), initListExpr->getNumInits(), hgType);
  2411. } catch (hlsl::Exception&) {
  2412. DiagnosticsEngine &Diags = CGM.getDiags();
  2413. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "internal error creating subobject");
  2414. Diags.Report(initExpr->getLocStart(), DiagID);
  2415. return;
  2416. }
  2417. }
  2418. else {
  2419. DiagnosticsEngine &Diags = CGM.getDiags();
  2420. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "expected initialization list");
  2421. Diags.Report(initExpr->getLocStart(), DiagID);
  2422. return;
  2423. }
  2424. }
  2425. // TODO: collect such helper utility functions in one place.
  2426. static DxilResourceBase::Class KeywordToClass(const std::string &keyword) {
  2427. // TODO: refactor for faster search (switch by 1/2/3 first letters, then
  2428. // compare)
  2429. if (keyword == "SamplerState")
  2430. return DxilResourceBase::Class::Sampler;
  2431. if (keyword == "SamplerComparisonState")
  2432. return DxilResourceBase::Class::Sampler;
  2433. if (keyword == "ConstantBuffer")
  2434. return DxilResourceBase::Class::CBuffer;
  2435. if (keyword == "TextureBuffer")
  2436. return DxilResourceBase::Class::CBuffer;
  2437. bool isSRV = keyword == "Buffer";
  2438. isSRV |= keyword == "ByteAddressBuffer";
  2439. isSRV |= keyword == "RaytracingAccelerationStructure";
  2440. isSRV |= keyword == "StructuredBuffer";
  2441. isSRV |= keyword == "Texture1D";
  2442. isSRV |= keyword == "Texture1DArray";
  2443. isSRV |= keyword == "Texture2D";
  2444. isSRV |= keyword == "Texture2DArray";
  2445. isSRV |= keyword == "Texture3D";
  2446. isSRV |= keyword == "TextureCube";
  2447. isSRV |= keyword == "TextureCubeArray";
  2448. isSRV |= keyword == "Texture2DMS";
  2449. isSRV |= keyword == "Texture2DMSArray";
  2450. if (isSRV)
  2451. return DxilResourceBase::Class::SRV;
  2452. bool isUAV = keyword == "RWBuffer";
  2453. isUAV |= keyword == "RWByteAddressBuffer";
  2454. isUAV |= keyword == "RWStructuredBuffer";
  2455. isUAV |= keyword == "RWTexture1D";
  2456. isUAV |= keyword == "RWTexture1DArray";
  2457. isUAV |= keyword == "RWTexture2D";
  2458. isUAV |= keyword == "RWTexture2DArray";
  2459. isUAV |= keyword == "RWTexture3D";
  2460. isUAV |= keyword == "RWTextureCube";
  2461. isUAV |= keyword == "RWTextureCubeArray";
  2462. isUAV |= keyword == "RWTexture2DMS";
  2463. isUAV |= keyword == "RWTexture2DMSArray";
  2464. isUAV |= keyword == "AppendStructuredBuffer";
  2465. isUAV |= keyword == "ConsumeStructuredBuffer";
  2466. isUAV |= keyword == "RasterizerOrderedBuffer";
  2467. isUAV |= keyword == "RasterizerOrderedByteAddressBuffer";
  2468. isUAV |= keyword == "RasterizerOrderedStructuredBuffer";
  2469. isUAV |= keyword == "RasterizerOrderedTexture1D";
  2470. isUAV |= keyword == "RasterizerOrderedTexture1DArray";
  2471. isUAV |= keyword == "RasterizerOrderedTexture2D";
  2472. isUAV |= keyword == "RasterizerOrderedTexture2DArray";
  2473. isUAV |= keyword == "RasterizerOrderedTexture3D";
  2474. isUAV |= keyword == "FeedbackTexture2D";
  2475. isUAV |= keyword == "FeedbackTexture2DArray";
  2476. if (isUAV)
  2477. return DxilResourceBase::Class::UAV;
  2478. return DxilResourceBase::Class::Invalid;
  2479. }
  2480. // This should probably be refactored to ASTContextHLSL, and follow types
  2481. // rather than do string comparisons.
  2482. DXIL::ResourceClass
  2483. hlsl::GetResourceClassForType(const clang::ASTContext &context,
  2484. clang::QualType Ty) {
  2485. Ty = Ty.getCanonicalType();
  2486. if (const clang::ArrayType *arrayType = context.getAsArrayType(Ty)) {
  2487. return GetResourceClassForType(context, arrayType->getElementType());
  2488. } else if (const RecordType *RT = Ty->getAsStructureType()) {
  2489. return KeywordToClass(RT->getDecl()->getName());
  2490. } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
  2491. if (const ClassTemplateSpecializationDecl *templateDecl =
  2492. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl())) {
  2493. return KeywordToClass(templateDecl->getName());
  2494. }
  2495. }
  2496. return hlsl::DxilResourceBase::Class::Invalid;
  2497. }
  2498. hlsl::DxilResourceBase::Class CGMSHLSLRuntime::TypeToClass(clang::QualType Ty) {
  2499. return hlsl::GetResourceClassForType(CGM.getContext(), Ty);
  2500. }
  2501. namespace {
  2502. void GetResourceDeclElemTypeAndRangeSize(CodeGenModule &CGM, HLModule &HL, VarDecl &VD,
  2503. QualType &ElemType, unsigned& rangeSize) {
  2504. // We can't canonicalize nor desugar the type without losing the 'snorm' in Buffer<snorm float>
  2505. ElemType = VD.getType();
  2506. rangeSize = 1;
  2507. while (const clang::ArrayType *arrayType = CGM.getContext().getAsArrayType(ElemType)) {
  2508. if (rangeSize != UINT_MAX) {
  2509. if (arrayType->isConstantArrayType()) {
  2510. rangeSize *= cast<ConstantArrayType>(arrayType)->getSize().getLimitedValue();
  2511. }
  2512. else {
  2513. if (HL.GetHLOptions().bLegacyResourceReservation) {
  2514. DiagnosticsEngine &Diags = CGM.getDiags();
  2515. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2516. "unbounded resources are not supported with -flegacy-resource-reservation");
  2517. Diags.Report(VD.getLocation(), DiagID);
  2518. }
  2519. rangeSize = UINT_MAX;
  2520. }
  2521. }
  2522. ElemType = arrayType->getElementType();
  2523. }
  2524. }
  2525. }
  2526. static void InitFromUnusualAnnotations(DxilResourceBase &Resource, NamedDecl &Decl) {
  2527. for (hlsl::UnusualAnnotation* It : Decl.getUnusualAnnotations()) {
  2528. switch (It->getKind()) {
  2529. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  2530. hlsl::RegisterAssignment* RegAssign = cast<hlsl::RegisterAssignment>(It);
  2531. if (RegAssign->RegisterType) {
  2532. Resource.SetLowerBound(RegAssign->RegisterNumber);
  2533. // For backcompat, don't auto-assign the register space if there's an
  2534. // explicit register type.
  2535. Resource.SetSpaceID(RegAssign->RegisterSpace.getValueOr(0));
  2536. }
  2537. else {
  2538. Resource.SetSpaceID(RegAssign->RegisterSpace.getValueOr(UINT_MAX));
  2539. }
  2540. break;
  2541. }
  2542. case hlsl::UnusualAnnotation::UA_SemanticDecl:
  2543. // Ignore Semantics
  2544. break;
  2545. case hlsl::UnusualAnnotation::UA_ConstantPacking:
  2546. // Should be handled by front-end
  2547. llvm_unreachable("packoffset on resource");
  2548. break;
  2549. case hlsl::UnusualAnnotation::UA_PayloadAccessQualifier:
  2550. // Should be handled by front-end
  2551. llvm_unreachable("payload qualifier on resource");
  2552. break;
  2553. default:
  2554. llvm_unreachable("unknown UnusualAnnotation on resource");
  2555. break;
  2556. }
  2557. }
  2558. }
  2559. uint32_t CGMSHLSLRuntime::AddSampler(VarDecl *samplerDecl) {
  2560. llvm::GlobalVariable *val =
  2561. cast<llvm::GlobalVariable>(CGM.GetAddrOfGlobalVar(samplerDecl));
  2562. unique_ptr<DxilSampler> hlslRes(new DxilSampler);
  2563. hlslRes->SetLowerBound(UINT_MAX);
  2564. hlslRes->SetSpaceID(UINT_MAX);
  2565. hlslRes->SetGlobalSymbol(val);
  2566. hlslRes->SetGlobalName(samplerDecl->getName());
  2567. QualType VarTy;
  2568. unsigned rangeSize;
  2569. GetResourceDeclElemTypeAndRangeSize(CGM, *m_pHLModule, *samplerDecl,
  2570. VarTy, rangeSize);
  2571. hlslRes->SetRangeSize(rangeSize);
  2572. const RecordType *RT = VarTy->getAs<RecordType>();
  2573. DxilSampler::SamplerKind kind = KeywordToSamplerKind(RT->getDecl()->getName());
  2574. hlslRes->SetSamplerKind(kind);
  2575. InitFromUnusualAnnotations(*hlslRes, *samplerDecl);
  2576. hlslRes->SetID(m_pHLModule->GetSamplers().size());
  2577. return m_pHLModule->AddSampler(std::move(hlslRes));
  2578. }
  2579. bool CGMSHLSLRuntime::GetAsConstantUInt32(clang::Expr *expr, uint32_t *value) {
  2580. APSInt result;
  2581. if (!expr->EvaluateAsInt(result, CGM.getContext())) {
  2582. DiagnosticsEngine &Diags = CGM.getDiags();
  2583. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2584. "cannot convert to constant unsigned int");
  2585. Diags.Report(expr->getLocStart(), DiagID);
  2586. return false;
  2587. }
  2588. *value = result.getLimitedValue(UINT32_MAX);
  2589. return true;
  2590. }
  2591. bool CGMSHLSLRuntime::GetAsConstantString(clang::Expr *expr, StringRef *value, bool failWhenEmpty /*=false*/) {
  2592. Expr::EvalResult result;
  2593. DiagnosticsEngine &Diags = CGM.getDiags();
  2594. unsigned DiagID = 0;
  2595. if (expr->EvaluateAsRValue(result, CGM.getContext())) {
  2596. if (result.Val.isLValue()) {
  2597. DXASSERT_NOMSG(result.Val.getLValueOffset().isZero());
  2598. DXASSERT_NOMSG(result.Val.getLValueCallIndex() == 0);
  2599. const Expr *evExpr = result.Val.getLValueBase().get<const Expr *>();
  2600. if (const StringLiteral *strLit = dyn_cast<const StringLiteral>(evExpr)) {
  2601. *value = strLit->getBytes();
  2602. if (!failWhenEmpty || !(*value).empty()) {
  2603. return true;
  2604. }
  2605. DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "empty string not expected here");
  2606. }
  2607. }
  2608. }
  2609. if (!DiagID)
  2610. DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "cannot convert to constant string");
  2611. Diags.Report(expr->getLocStart(), DiagID);
  2612. return false;
  2613. }
  2614. std::vector<StringRef> CGMSHLSLRuntime::ParseSubobjectExportsAssociations(StringRef exports) {
  2615. std::vector<StringRef> parsedExports;
  2616. const char *pData = exports.data();
  2617. const char *pEnd = pData + exports.size();
  2618. const char *pLast = pData;
  2619. while (pData < pEnd) {
  2620. if (*pData == ';') {
  2621. if (pLast < pData) {
  2622. parsedExports.emplace_back(StringRef(pLast, pData - pLast));
  2623. }
  2624. pLast = pData + 1;
  2625. }
  2626. pData++;
  2627. }
  2628. if (pLast < pData) {
  2629. parsedExports.emplace_back(StringRef(pLast, pData - pLast));
  2630. }
  2631. return parsedExports;
  2632. }
  2633. void CGMSHLSLRuntime::CreateSubobject(DXIL::SubobjectKind kind, const StringRef name,
  2634. clang::Expr **args, unsigned int argCount,
  2635. DXIL::HitGroupType hgType /*= (DXIL::HitGroupType)(-1)*/) {
  2636. DxilSubobjects *subobjects = m_pHLModule->GetSubobjects();
  2637. if (!subobjects) {
  2638. subobjects = new DxilSubobjects();
  2639. m_pHLModule->ResetSubobjects(subobjects);
  2640. }
  2641. DxilRootSignatureCompilationFlags flags = DxilRootSignatureCompilationFlags::GlobalRootSignature;
  2642. switch (kind) {
  2643. case DXIL::SubobjectKind::StateObjectConfig: {
  2644. uint32_t flags;
  2645. DXASSERT_NOMSG(argCount == 1);
  2646. if (GetAsConstantUInt32(args[0], &flags)) {
  2647. subobjects->CreateStateObjectConfig(name, flags);
  2648. }
  2649. break;
  2650. }
  2651. case DXIL::SubobjectKind::LocalRootSignature:
  2652. flags = DxilRootSignatureCompilationFlags::LocalRootSignature;
  2653. __fallthrough;
  2654. case DXIL::SubobjectKind::GlobalRootSignature: {
  2655. DXASSERT_NOMSG(argCount == 1);
  2656. StringRef signature;
  2657. if (!GetAsConstantString(args[0], &signature, true))
  2658. return;
  2659. RootSignatureHandle RootSigHandle;
  2660. CompileRootSignature(signature, CGM.getDiags(), args[0]->getLocStart(), rootSigVer, flags, &RootSigHandle);
  2661. if (!RootSigHandle.IsEmpty()) {
  2662. RootSigHandle.EnsureSerializedAvailable();
  2663. subobjects->CreateRootSignature(name, kind == DXIL::SubobjectKind::LocalRootSignature,
  2664. RootSigHandle.GetSerializedBytes(), RootSigHandle.GetSerializedSize(), &signature);
  2665. }
  2666. break;
  2667. }
  2668. case DXIL::SubobjectKind::SubobjectToExportsAssociation: {
  2669. DXASSERT_NOMSG(argCount == 2);
  2670. StringRef subObjName, exports;
  2671. if (!GetAsConstantString(args[0], &subObjName, true) ||
  2672. !GetAsConstantString(args[1], &exports, false))
  2673. return;
  2674. std::vector<StringRef> exportList = ParseSubobjectExportsAssociations(exports);
  2675. subobjects->CreateSubobjectToExportsAssociation(name, subObjName, exportList.data(), exportList.size());
  2676. break;
  2677. }
  2678. case DXIL::SubobjectKind::RaytracingShaderConfig: {
  2679. DXASSERT_NOMSG(argCount == 2);
  2680. uint32_t maxPayloadSize;
  2681. uint32_t MaxAttributeSize;
  2682. if (!GetAsConstantUInt32(args[0], &maxPayloadSize) ||
  2683. !GetAsConstantUInt32(args[1], &MaxAttributeSize))
  2684. return;
  2685. subobjects->CreateRaytracingShaderConfig(name, maxPayloadSize, MaxAttributeSize);
  2686. break;
  2687. }
  2688. case DXIL::SubobjectKind::RaytracingPipelineConfig: {
  2689. DXASSERT_NOMSG(argCount == 1);
  2690. uint32_t maxTraceRecursionDepth;
  2691. if (!GetAsConstantUInt32(args[0], &maxTraceRecursionDepth))
  2692. return;
  2693. subobjects->CreateRaytracingPipelineConfig(name, maxTraceRecursionDepth);
  2694. break;
  2695. }
  2696. case DXIL::SubobjectKind::HitGroup: {
  2697. switch (hgType) {
  2698. case DXIL::HitGroupType::Triangle: {
  2699. DXASSERT_NOMSG(argCount == 2);
  2700. StringRef anyhit, closesthit;
  2701. if (!GetAsConstantString(args[0], &anyhit) ||
  2702. !GetAsConstantString(args[1], &closesthit))
  2703. return;
  2704. subobjects->CreateHitGroup(name, DXIL::HitGroupType::Triangle, anyhit, closesthit, llvm::StringRef(""));
  2705. break;
  2706. }
  2707. case DXIL::HitGroupType::ProceduralPrimitive: {
  2708. DXASSERT_NOMSG(argCount == 3);
  2709. StringRef anyhit, closesthit, intersection;
  2710. if (!GetAsConstantString(args[0], &anyhit) ||
  2711. !GetAsConstantString(args[1], &closesthit) ||
  2712. !GetAsConstantString(args[2], &intersection, true))
  2713. return;
  2714. subobjects->CreateHitGroup(name, DXIL::HitGroupType::ProceduralPrimitive, anyhit, closesthit, intersection);
  2715. break;
  2716. }
  2717. default:
  2718. llvm_unreachable("unknown HitGroupType");
  2719. }
  2720. break;
  2721. }
  2722. case DXIL::SubobjectKind::RaytracingPipelineConfig1: {
  2723. DXASSERT_NOMSG(argCount == 2);
  2724. uint32_t maxTraceRecursionDepth;
  2725. uint32_t raytracingPipelineFlags;
  2726. if (!GetAsConstantUInt32(args[0], &maxTraceRecursionDepth))
  2727. return;
  2728. if (!GetAsConstantUInt32(args[1], &raytracingPipelineFlags))
  2729. return;
  2730. subobjects->CreateRaytracingPipelineConfig1(name, maxTraceRecursionDepth, raytracingPipelineFlags);
  2731. break;
  2732. }
  2733. default:
  2734. llvm_unreachable("unknown SubobjectKind");
  2735. break;
  2736. }
  2737. }
  2738. static void CollectScalarTypes(std::vector<QualType> &ScalarTys, QualType Ty) {
  2739. if (Ty->isRecordType()) {
  2740. if (hlsl::IsHLSLMatType(Ty)) {
  2741. QualType EltTy = hlsl::GetHLSLMatElementType(Ty);
  2742. unsigned row = 0;
  2743. unsigned col = 0;
  2744. hlsl::GetRowsAndCols(Ty, row, col);
  2745. unsigned size = col*row;
  2746. for (unsigned i = 0; i < size; i++) {
  2747. CollectScalarTypes(ScalarTys, EltTy);
  2748. }
  2749. } else if (hlsl::IsHLSLVecType(Ty)) {
  2750. QualType EltTy = hlsl::GetHLSLVecElementType(Ty);
  2751. unsigned row = 0;
  2752. unsigned col = 0;
  2753. hlsl::GetRowsAndColsForAny(Ty, row, col);
  2754. unsigned size = col;
  2755. for (unsigned i = 0; i < size; i++) {
  2756. CollectScalarTypes(ScalarTys, EltTy);
  2757. }
  2758. } else {
  2759. const RecordType *RT = Ty->getAsStructureType();
  2760. // For CXXRecord.
  2761. if (!RT)
  2762. RT = Ty->getAs<RecordType>();
  2763. RecordDecl *RD = RT->getDecl();
  2764. for (FieldDecl *field : RD->fields())
  2765. CollectScalarTypes(ScalarTys, field->getType());
  2766. }
  2767. } else if (Ty->isArrayType()) {
  2768. const clang::ArrayType *AT = Ty->getAsArrayTypeUnsafe();
  2769. QualType EltTy = AT->getElementType();
  2770. // Set it to 5 for unsized array.
  2771. unsigned size = 5;
  2772. if (AT->isConstantArrayType()) {
  2773. size = cast<ConstantArrayType>(AT)->getSize().getLimitedValue();
  2774. }
  2775. for (unsigned i=0;i<size;i++) {
  2776. CollectScalarTypes(ScalarTys, EltTy);
  2777. }
  2778. } else {
  2779. ScalarTys.emplace_back(Ty);
  2780. }
  2781. }
  2782. bool CGMSHLSLRuntime::SetUAVSRV(SourceLocation loc,
  2783. hlsl::DxilResourceBase::Class resClass,
  2784. DxilResource *hlslRes, QualType QualTy) {
  2785. RecordDecl *RD = QualTy->getAs<RecordType>()->getDecl();
  2786. hlsl::DxilResource::Kind kind = KeywordToKind(RD->getName());
  2787. DXASSERT_NOMSG(kind != hlsl::DxilResource::Kind::Invalid);
  2788. hlslRes->SetKind(kind);
  2789. // Type annotation for result type of resource.
  2790. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  2791. unsigned arrayEltSize = 0;
  2792. AddTypeAnnotation(QualType(RD->getTypeForDecl(),0), dxilTypeSys, arrayEltSize);
  2793. if (kind == hlsl::DxilResource::Kind::Texture2DMS ||
  2794. kind == hlsl::DxilResource::Kind::Texture2DMSArray) {
  2795. const ClassTemplateSpecializationDecl *templateDecl =
  2796. cast<ClassTemplateSpecializationDecl>(RD);
  2797. const clang::TemplateArgument &sampleCountArg =
  2798. templateDecl->getTemplateArgs()[1];
  2799. uint32_t sampleCount = sampleCountArg.getAsIntegral().getLimitedValue();
  2800. hlslRes->SetSampleCount(sampleCount);
  2801. }
  2802. if (hlsl::DxilResource::IsAnyTexture(kind)) {
  2803. const ClassTemplateSpecializationDecl *templateDecl = cast<ClassTemplateSpecializationDecl>(RD);
  2804. const clang::TemplateArgument &texelTyArg = templateDecl->getTemplateArgs()[0];
  2805. llvm::Type *texelTy = CGM.getTypes().ConvertType(texelTyArg.getAsType());
  2806. if (!texelTy->isFloatingPointTy() && !texelTy->isIntegerTy()
  2807. && !hlsl::IsHLSLVecType(texelTyArg.getAsType())) {
  2808. DiagnosticsEngine &Diags = CGM.getDiags();
  2809. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2810. "texture resource texel type must be scalar or vector");
  2811. Diags.Report(loc, DiagID);
  2812. return false;
  2813. }
  2814. }
  2815. QualType resultTy = hlsl::GetHLSLResourceResultType(QualTy);
  2816. if (kind != hlsl::DxilResource::Kind::StructuredBuffer && !resultTy.isNull()) {
  2817. QualType Ty = resultTy;
  2818. QualType EltTy = Ty;
  2819. if (hlsl::IsHLSLVecType(Ty)) {
  2820. EltTy = hlsl::GetHLSLVecElementType(Ty);
  2821. } else if (hlsl::IsHLSLMatType(Ty)) {
  2822. EltTy = hlsl::GetHLSLMatElementType(Ty);
  2823. } else if (hlsl::IsHLSLAggregateType(resultTy)) {
  2824. // Struct or array in a none-struct resource.
  2825. std::vector<QualType> ScalarTys;
  2826. CollectScalarTypes(ScalarTys, resultTy);
  2827. unsigned size = ScalarTys.size();
  2828. if (size == 0) {
  2829. DiagnosticsEngine &Diags = CGM.getDiags();
  2830. unsigned DiagID = Diags.getCustomDiagID(
  2831. DiagnosticsEngine::Error,
  2832. "object's templated type must have at least one element");
  2833. Diags.Report(loc, DiagID);
  2834. return false;
  2835. }
  2836. if (size > 4) {
  2837. DiagnosticsEngine &Diags = CGM.getDiags();
  2838. unsigned DiagID = Diags.getCustomDiagID(
  2839. DiagnosticsEngine::Error, "elements of typed buffers and textures "
  2840. "must fit in four 32-bit quantities");
  2841. Diags.Report(loc, DiagID);
  2842. return false;
  2843. }
  2844. EltTy = ScalarTys[0];
  2845. for (QualType ScalarTy : ScalarTys) {
  2846. if (ScalarTy != EltTy) {
  2847. DiagnosticsEngine &Diags = CGM.getDiags();
  2848. unsigned DiagID = Diags.getCustomDiagID(
  2849. DiagnosticsEngine::Error,
  2850. "all template type components must have the same type");
  2851. Diags.Report(loc, DiagID);
  2852. return false;
  2853. }
  2854. }
  2855. }
  2856. bool bSNorm = false;
  2857. bool bHasNormAttribute = hlsl::HasHLSLUNormSNorm(Ty, &bSNorm);
  2858. if (const BuiltinType *BTy = EltTy->getAs<BuiltinType>()) {
  2859. CompType::Kind kind = BuiltinTyToCompTy(BTy, bHasNormAttribute && bSNorm, bHasNormAttribute && !bSNorm);
  2860. // 64bits types are implemented with u32.
  2861. if (kind == CompType::Kind::U64 || kind == CompType::Kind::I64 ||
  2862. kind == CompType::Kind::SNormF64 ||
  2863. kind == CompType::Kind::UNormF64 || kind == CompType::Kind::F64) {
  2864. kind = CompType::Kind::U32;
  2865. }
  2866. hlslRes->SetCompType(kind);
  2867. } else {
  2868. DXASSERT(!bHasNormAttribute, "snorm/unorm on invalid type");
  2869. }
  2870. }
  2871. if (hlslRes->IsFeedbackTexture()) {
  2872. hlslRes->SetSamplerFeedbackType(
  2873. static_cast<DXIL::SamplerFeedbackType>(hlsl::GetHLSLResourceTemplateUInt(QualTy)));
  2874. }
  2875. hlslRes->SetROV(RD->getName().startswith("RasterizerOrdered"));
  2876. if (kind == hlsl::DxilResource::Kind::TypedBuffer ||
  2877. kind == hlsl::DxilResource::Kind::StructuredBuffer) {
  2878. const ClassTemplateSpecializationDecl *templateDecl =
  2879. cast<ClassTemplateSpecializationDecl>(RD);
  2880. const clang::TemplateArgument &retTyArg =
  2881. templateDecl->getTemplateArgs()[0];
  2882. llvm::Type *retTy = CGM.getTypes().ConvertType(retTyArg.getAsType());
  2883. uint32_t strideInBytes = dataLayout.getTypeAllocSize(retTy);
  2884. hlslRes->SetElementStride(strideInBytes);
  2885. }
  2886. if (HasHLSLGloballyCoherent(QualTy)) {
  2887. hlslRes->SetGloballyCoherent(true);
  2888. }
  2889. if (resClass == hlsl::DxilResourceBase::Class::SRV) {
  2890. if (hlslRes->IsGloballyCoherent()) {
  2891. DiagnosticsEngine &Diags = CGM.getDiags();
  2892. unsigned DiagID = Diags.getCustomDiagID(
  2893. DiagnosticsEngine::Error, "globallycoherent can only be used with "
  2894. "Unordered Access View buffers.");
  2895. Diags.Report(loc, DiagID);
  2896. return false;
  2897. }
  2898. hlslRes->SetRW(false);
  2899. hlslRes->SetID(m_pHLModule->GetSRVs().size());
  2900. } else {
  2901. hlslRes->SetRW(true);
  2902. hlslRes->SetID(m_pHLModule->GetUAVs().size());
  2903. }
  2904. return true;
  2905. }
  2906. uint32_t CGMSHLSLRuntime::AddUAVSRV(VarDecl *decl,
  2907. hlsl::DxilResourceBase::Class resClass) {
  2908. llvm::GlobalVariable *val =
  2909. cast<llvm::GlobalVariable>(CGM.GetAddrOfGlobalVar(decl));
  2910. unique_ptr<HLResource> hlslRes(new HLResource);
  2911. hlslRes->SetLowerBound(UINT_MAX);
  2912. hlslRes->SetSpaceID(UINT_MAX);
  2913. hlslRes->SetGlobalSymbol(val);
  2914. hlslRes->SetGlobalName(decl->getName());
  2915. QualType VarTy;
  2916. unsigned rangeSize;
  2917. GetResourceDeclElemTypeAndRangeSize(CGM, *m_pHLModule, *decl,
  2918. VarTy, rangeSize);
  2919. hlslRes->SetRangeSize(rangeSize);
  2920. InitFromUnusualAnnotations(*hlslRes, *decl);
  2921. if (decl->hasAttr<HLSLGloballyCoherentAttr>()) {
  2922. hlslRes->SetGloballyCoherent(true);
  2923. }
  2924. if (!SetUAVSRV(decl->getLocation(), resClass, hlslRes.get(), VarTy))
  2925. return 0;
  2926. if (resClass == hlsl::DxilResourceBase::Class::SRV) {
  2927. return m_pHLModule->AddSRV(std::move(hlslRes));
  2928. } else {
  2929. return m_pHLModule->AddUAV(std::move(hlslRes));
  2930. }
  2931. }
  2932. static bool IsResourceInType(const clang::ASTContext &context,
  2933. clang::QualType Ty) {
  2934. Ty = Ty.getCanonicalType();
  2935. if (const clang::ArrayType *arrayType = context.getAsArrayType(Ty)) {
  2936. return IsResourceInType(context, arrayType->getElementType());
  2937. } else if (const RecordType *RT = Ty->getAsStructureType()) {
  2938. if (KeywordToClass(RT->getDecl()->getName()) != DxilResourceBase::Class::Invalid)
  2939. return true;
  2940. const CXXRecordDecl* typeRecordDecl = RT->getAsCXXRecordDecl();
  2941. if (typeRecordDecl && !typeRecordDecl->isImplicit()) {
  2942. for (auto field : typeRecordDecl->fields()) {
  2943. if (IsResourceInType(context, field->getType()))
  2944. return true;
  2945. }
  2946. }
  2947. } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
  2948. if (const ClassTemplateSpecializationDecl *templateDecl =
  2949. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl())) {
  2950. if (KeywordToClass(templateDecl->getName()) != DxilResourceBase::Class::Invalid)
  2951. return true;
  2952. }
  2953. }
  2954. return false; // no resources found
  2955. }
  2956. void CGMSHLSLRuntime::AddConstantToCB(GlobalVariable *CV, StringRef Name,
  2957. QualType Ty, unsigned LowerBound,
  2958. HLCBuffer &CB) {
  2959. std::unique_ptr<DxilResourceBase> pHlslConst =
  2960. llvm::make_unique<DxilResourceBase>(DXIL::ResourceClass::Invalid);
  2961. pHlslConst->SetLowerBound(LowerBound);
  2962. pHlslConst->SetSpaceID(0);
  2963. pHlslConst->SetGlobalSymbol(CV);
  2964. pHlslConst->SetGlobalName(Name);
  2965. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  2966. unsigned arrayEltSize = 0;
  2967. unsigned size = AddTypeAnnotation(Ty, dxilTypeSys, arrayEltSize);
  2968. pHlslConst->SetRangeSize(size);
  2969. CB.AddConst(pHlslConst);
  2970. }
  2971. void CGMSHLSLRuntime::AddConstant(VarDecl *constDecl, HLCBuffer &CB) {
  2972. if (constDecl->getStorageClass() == SC_Static) {
  2973. // For static inside cbuffer, take as global static.
  2974. // Don't add to cbuffer.
  2975. CGM.EmitGlobal(constDecl);
  2976. // Add type annotation for static global types.
  2977. // May need it when cast from cbuf.
  2978. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  2979. unsigned arraySize = 0;
  2980. AddTypeAnnotation(constDecl->getType(), dxilTypeSys, arraySize);
  2981. return;
  2982. }
  2983. llvm::Constant *constVal = CGM.GetAddrOfGlobalVar(constDecl);
  2984. // Add debug info for constVal.
  2985. if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
  2986. if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
  2987. DI->EmitGlobalVariable(cast<GlobalVariable>(constVal), constDecl);
  2988. }
  2989. auto &regBindings = constantRegBindingMap[constVal];
  2990. // Save resource properties for cbuffer variables.
  2991. AddValToPropertyMap(constVal, constDecl->getType());
  2992. bool isGlobalCB = CB.GetID() == globalCBIndex;
  2993. uint32_t offset = 0;
  2994. bool userOffset = false;
  2995. for (hlsl::UnusualAnnotation *it : constDecl->getUnusualAnnotations()) {
  2996. switch (it->getKind()) {
  2997. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  2998. if (!isGlobalCB) {
  2999. // TODO: check cannot mix packoffset elements with nonpackoffset
  3000. // elements in a cbuffer.
  3001. hlsl::ConstantPacking *cp = cast<hlsl::ConstantPacking>(it);
  3002. offset = cp->Subcomponent << 2;
  3003. offset += cp->ComponentOffset;
  3004. // Change to byte.
  3005. offset <<= 2;
  3006. userOffset = true;
  3007. } else {
  3008. DiagnosticsEngine &Diags = CGM.getDiags();
  3009. unsigned DiagID = Diags.getCustomDiagID(
  3010. DiagnosticsEngine::Error,
  3011. "packoffset is only allowed in a constant buffer.");
  3012. Diags.Report(it->Loc, DiagID);
  3013. }
  3014. break;
  3015. }
  3016. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  3017. RegisterAssignment *ra = cast<RegisterAssignment>(it);
  3018. if (isGlobalCB) {
  3019. if (ra->RegisterSpace.hasValue()) {
  3020. DiagnosticsEngine& Diags = CGM.getDiags();
  3021. unsigned DiagID = Diags.getCustomDiagID(
  3022. DiagnosticsEngine::Error,
  3023. "register space cannot be specified on global constants.");
  3024. Diags.Report(it->Loc, DiagID);
  3025. }
  3026. offset = ra->RegisterNumber << 2;
  3027. // Change to byte.
  3028. offset <<= 2;
  3029. userOffset = true;
  3030. }
  3031. switch (ra->RegisterType) {
  3032. default:
  3033. break;
  3034. case 't':
  3035. regBindings.emplace_back(
  3036. std::make_pair(DXIL::ResourceClass::SRV, ra->RegisterNumber));
  3037. break;
  3038. case 'u':
  3039. regBindings.emplace_back(
  3040. std::make_pair(DXIL::ResourceClass::UAV, ra->RegisterNumber));
  3041. break;
  3042. case 's':
  3043. regBindings.emplace_back(
  3044. std::make_pair(DXIL::ResourceClass::Sampler, ra->RegisterNumber));
  3045. break;
  3046. }
  3047. break;
  3048. }
  3049. case hlsl::UnusualAnnotation::UA_SemanticDecl:
  3050. // skip semantic on constant
  3051. break;
  3052. case hlsl::UnusualAnnotation::UA_PayloadAccessQualifier:
  3053. // skip payload qualifers on constant
  3054. break;
  3055. }
  3056. }
  3057. unsigned LowerBound = userOffset ? offset : UINT_MAX;
  3058. AddConstantToCB(cast<llvm::GlobalVariable>(constVal), constDecl->getName(),
  3059. constDecl->getType(), LowerBound, CB);
  3060. // Save fieldAnnotation for the const var.
  3061. DxilFieldAnnotation fieldAnnotation;
  3062. if (userOffset)
  3063. fieldAnnotation.SetCBufferOffset(offset);
  3064. QualType Ty = constDecl->getType();
  3065. // Get the nested element type.
  3066. if (Ty->isArrayType()) {
  3067. while (const ConstantArrayType *arrayTy =
  3068. CGM.getContext().getAsConstantArrayType(Ty)) {
  3069. Ty = arrayTy->getElementType();
  3070. }
  3071. }
  3072. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  3073. ConstructFieldAttributedAnnotation(fieldAnnotation, Ty, bDefaultRowMajor);
  3074. m_ConstVarAnnotationMap[constVal] = fieldAnnotation;
  3075. }
  3076. namespace {
  3077. unique_ptr<HLCBuffer> CreateHLCBuf(NamedDecl *D, bool bIsView, bool bIsTBuf) {
  3078. unique_ptr<HLCBuffer> CB = llvm::make_unique<HLCBuffer>(bIsView, bIsTBuf);
  3079. // setup the CB
  3080. CB->SetGlobalSymbol(nullptr);
  3081. CB->SetGlobalName(D->getNameAsString());
  3082. CB->SetSpaceID(UINT_MAX);
  3083. CB->SetLowerBound(UINT_MAX);
  3084. if (bIsTBuf)
  3085. CB->SetKind(DXIL::ResourceKind::TBuffer);
  3086. InitFromUnusualAnnotations(*CB, *D);
  3087. return CB;
  3088. }
  3089. } // namespace
  3090. uint32_t CGMSHLSLRuntime::AddCBuffer(HLSLBufferDecl *D) {
  3091. unique_ptr<HLCBuffer> CB = CreateHLCBuf(D, false, !D->isCBuffer());
  3092. // Add constant
  3093. auto declsEnds = D->decls_end();
  3094. CB->SetRangeSize(1);
  3095. for (auto it = D->decls_begin(); it != declsEnds; it++) {
  3096. if (VarDecl *constDecl = dyn_cast<VarDecl>(*it)) {
  3097. AddConstant(constDecl, *CB.get());
  3098. } else if (isa<EmptyDecl>(*it)) {
  3099. // Nothing to do for this declaration.
  3100. } else if (isa<CXXRecordDecl>(*it)) {
  3101. // Nothing to do for this declaration.
  3102. } else if (isa<FunctionDecl>(*it)) {
  3103. // A function within an cbuffer is effectively a top-level function,
  3104. // as it only refers to globally scoped declarations.
  3105. this->CGM.EmitTopLevelDecl(*it);
  3106. } else {
  3107. HLSLBufferDecl *inner = cast<HLSLBufferDecl>(*it);
  3108. GetOrCreateCBuffer(inner);
  3109. }
  3110. }
  3111. CB->SetID(m_pHLModule->GetCBuffers().size());
  3112. return m_pHLModule->AddCBuffer(std::move(CB));
  3113. }
  3114. uint32_t CGMSHLSLRuntime::AddConstantBufferView(VarDecl *D) {
  3115. QualType Ty = D->getType();
  3116. unique_ptr<HLCBuffer> CB = CreateHLCBuf(D, true, IsTextureBufferView(Ty, CGM.getContext()));
  3117. CB->SetRangeSize(1);
  3118. if (Ty->isArrayType()) {
  3119. if (!Ty->isIncompleteArrayType()) {
  3120. unsigned arraySize = 1;
  3121. while (Ty->isArrayType()) {
  3122. Ty = Ty->getCanonicalTypeUnqualified();
  3123. const ConstantArrayType *AT = cast<ConstantArrayType>(Ty);
  3124. arraySize *= AT->getSize().getLimitedValue();
  3125. Ty = AT->getElementType();
  3126. }
  3127. CB->SetRangeSize(arraySize);
  3128. } else {
  3129. Ty = QualType(Ty->getArrayElementTypeNoTypeQual(),0);
  3130. CB->SetRangeSize(UINT_MAX);
  3131. }
  3132. CB->SetIsArray();
  3133. }
  3134. QualType ResultTy = hlsl::GetHLSLResourceResultType(Ty);
  3135. // Search defined structure for resource objects and fail
  3136. if (CB->GetRangeSize() > 1 && IsResourceInType(CGM.getContext(), ResultTy)) {
  3137. DiagnosticsEngine &Diags = CGM.getDiags();
  3138. unsigned DiagID = Diags.getCustomDiagID(
  3139. DiagnosticsEngine::Error,
  3140. "object types not supported in cbuffer/tbuffer view arrays.");
  3141. Diags.Report(D->getLocation(), DiagID);
  3142. return UINT_MAX;
  3143. }
  3144. // Not allow offset for CBV.
  3145. unsigned LowerBound = 0;
  3146. GlobalVariable *GV = cast<GlobalVariable>(CGM.GetAddrOfGlobalVar(D));
  3147. AddConstantToCB(GV, D->getName(), ResultTy, LowerBound, *CB.get());
  3148. CB->SetResultType(CGM.getTypes().ConvertType(ResultTy));
  3149. CB->SetID(m_pHLModule->GetCBuffers().size());
  3150. return m_pHLModule->AddCBuffer(std::move(CB));
  3151. }
  3152. HLCBuffer &CGMSHLSLRuntime::GetOrCreateCBuffer(HLSLBufferDecl *D) {
  3153. if (constantBufMap.count(D) != 0) {
  3154. uint32_t cbIndex = constantBufMap[D];
  3155. return *static_cast<HLCBuffer*>(&(m_pHLModule->GetCBuffer(cbIndex)));
  3156. }
  3157. uint32_t cbID = AddCBuffer(D);
  3158. constantBufMap[D] = cbID;
  3159. return *static_cast<HLCBuffer*>(&(m_pHLModule->GetCBuffer(cbID)));
  3160. }
  3161. void CGMSHLSLRuntime::FinishCodeGen() {
  3162. HLModule &HLM = *m_pHLModule;
  3163. llvm::Module &M = TheModule;
  3164. // Do this before CloneShaderEntry and TranslateRayQueryConstructor to avoid
  3165. // update valToResPropertiesMap for cloned inst.
  3166. FinishIntrinsics(HLM, m_IntrinsicMap, objectProperties);
  3167. bool bWaveEnabledStage = m_pHLModule->GetShaderModel()->IsPS() ||
  3168. m_pHLModule->GetShaderModel()->IsCS() ||
  3169. m_pHLModule->GetShaderModel()->IsLib();
  3170. // Handle lang extensions if provided.
  3171. if (CGM.getCodeGenOpts().HLSLExtensionsCodegen) {
  3172. ExtensionCodeGen(HLM, CGM);
  3173. }
  3174. StructurizeMultiRet(M, CGM, m_ScopeMap, bWaveEnabledStage, m_DxBreaks);
  3175. FinishEntries(HLM, Entry, CGM, entryFunctionMap, HSEntryPatchConstantFuncAttr,
  3176. patchConstantFunctionMap, patchConstantFunctionPropsMap);
  3177. ReplaceConstStaticGlobals(staticConstGlobalInitListMap,
  3178. staticConstGlobalCtorMap);
  3179. // Create copy for clip plane.
  3180. if (!clipPlaneFuncList.empty()) {
  3181. FinishClipPlane(HLM, clipPlaneFuncList, debugInfoMap, CGM);
  3182. }
  3183. // Add Reg bindings for resource in cb.
  3184. AddRegBindingsForResourceInConstantBuffer(HLM, constantRegBindingMap);
  3185. // Allocate constant buffers.
  3186. // Create Global variable and type annotation for each CBuffer.
  3187. FinishCBuffer(HLM, CBufferType, m_ConstVarAnnotationMap);
  3188. // Translate calls to RayQuery constructor into hl Allocate calls
  3189. TranslateRayQueryConstructor(HLM);
  3190. bool bIsLib = HLM.GetShaderModel()->IsLib();
  3191. StringRef GlobalCtorName = "llvm.global_ctors";
  3192. llvm::SmallVector<llvm::Function *, 2> Ctors;
  3193. CollectCtorFunctions(M, GlobalCtorName, Ctors, CGM);
  3194. if (!Ctors.empty()) {
  3195. if (!bIsLib) {
  3196. // need this for "llvm.global_dtors"?
  3197. Function *patchConstantFn = nullptr;
  3198. if (HLM.GetShaderModel()->IsHS()) {
  3199. patchConstantFn = HLM.GetPatchConstantFunction();
  3200. }
  3201. ProcessCtorFunctions(M, Ctors, Entry.Func, patchConstantFn);
  3202. // remove the GV
  3203. if (GlobalVariable *GV = M.getGlobalVariable(GlobalCtorName))
  3204. GV->eraseFromParent();
  3205. } else {
  3206. // Call ctors for each entry.
  3207. DenseSet<Function *> processedPatchConstantFnSet;
  3208. for (auto &Entry : entryFunctionMap) {
  3209. Function *F = Entry.second.Func;
  3210. Function *patchConstFunc = nullptr;
  3211. auto AttrIter = HSEntryPatchConstantFuncAttr.find(F);
  3212. if (AttrIter != HSEntryPatchConstantFuncAttr.end()) {
  3213. StringRef funcName = AttrIter->second->getFunctionName();
  3214. auto PatchEntry = patchConstantFunctionMap.find(funcName);
  3215. if (PatchEntry != patchConstantFunctionMap.end() &&
  3216. PatchEntry->second.NumOverloads == 1) {
  3217. patchConstFunc = PatchEntry->second.Func;
  3218. // Each patchConstFunc should only be processed once.
  3219. if (patchConstFunc &&
  3220. processedPatchConstantFnSet.count(patchConstFunc) == 0)
  3221. processedPatchConstantFnSet.insert(patchConstFunc);
  3222. else
  3223. patchConstFunc = nullptr;
  3224. }
  3225. }
  3226. ProcessCtorFunctions(M, Ctors, F, patchConstFunc);
  3227. }
  3228. }
  3229. }
  3230. UpdateLinkage(HLM, CGM, m_ExportMap, entryFunctionMap,
  3231. patchConstantFunctionMap);
  3232. // Do simple transform to make later lower pass easier.
  3233. SimpleTransformForHLDXIR(&M);
  3234. // Add dx.break function and make appropriate breaks conditional on it.
  3235. AddDxBreak(M, m_DxBreaks);
  3236. // At this point, we have a high-level DXIL module - record this.
  3237. SetPauseResumePasses(*m_pHLModule->GetModule(), "hlsl-hlemit",
  3238. "hlsl-hlensure");
  3239. }
  3240. RValue CGMSHLSLRuntime::EmitHLSLBuiltinCallExpr(CodeGenFunction &CGF,
  3241. const FunctionDecl *FD,
  3242. const CallExpr *E,
  3243. ReturnValueSlot ReturnValue) {
  3244. const Decl *TargetDecl = E->getCalleeDecl();
  3245. llvm::Value *Callee = CGF.EmitScalarExpr(E->getCallee());
  3246. RValue RV = CGF.EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue,
  3247. TargetDecl);
  3248. if (RV.isScalar() && RV.getScalarVal() != nullptr) {
  3249. if (CallInst *CI = dyn_cast<CallInst>(RV.getScalarVal())) {
  3250. Function *F = CI->getCalledFunction();
  3251. HLOpcodeGroup group = hlsl::GetHLOpcodeGroup(F);
  3252. if (group == HLOpcodeGroup::HLIntrinsic) {
  3253. bool allOperandImm = true;
  3254. for (auto &operand : CI->arg_operands()) {
  3255. bool isImm = isa<ConstantInt>(operand) || isa<ConstantFP>(operand) ||
  3256. isa<ConstantAggregateZero>(operand) || isa<ConstantDataVector>(operand);
  3257. if (!isImm) {
  3258. allOperandImm = false;
  3259. break;
  3260. } else if (operand->getType()->isHalfTy()) {
  3261. // Not support half Eval yet.
  3262. allOperandImm = false;
  3263. break;
  3264. }
  3265. }
  3266. if (allOperandImm) {
  3267. unsigned intrinsicOpcode;
  3268. StringRef intrinsicGroup;
  3269. hlsl::GetIntrinsicOp(FD, intrinsicOpcode, intrinsicGroup);
  3270. IntrinsicOp opcode = static_cast<IntrinsicOp>(intrinsicOpcode);
  3271. if (Value *Result = TryEvalIntrinsic(CI, opcode, CGM.getLangOpts().HLSLVersion)) {
  3272. RV = RValue::get(Result);
  3273. }
  3274. }
  3275. }
  3276. }
  3277. }
  3278. return RV;
  3279. }
  3280. static HLOpcodeGroup GetHLOpcodeGroup(const clang::Stmt::StmtClass stmtClass) {
  3281. switch (stmtClass) {
  3282. case Stmt::CStyleCastExprClass:
  3283. case Stmt::ImplicitCastExprClass:
  3284. case Stmt::CXXFunctionalCastExprClass:
  3285. return HLOpcodeGroup::HLCast;
  3286. case Stmt::InitListExprClass:
  3287. return HLOpcodeGroup::HLInit;
  3288. case Stmt::BinaryOperatorClass:
  3289. case Stmt::CompoundAssignOperatorClass:
  3290. return HLOpcodeGroup::HLBinOp;
  3291. case Stmt::UnaryOperatorClass:
  3292. return HLOpcodeGroup::HLUnOp;
  3293. case Stmt::ExtMatrixElementExprClass:
  3294. return HLOpcodeGroup::HLSubscript;
  3295. case Stmt::CallExprClass:
  3296. return HLOpcodeGroup::HLIntrinsic;
  3297. case Stmt::ConditionalOperatorClass:
  3298. return HLOpcodeGroup::HLSelect;
  3299. default:
  3300. llvm_unreachable("not support operation");
  3301. }
  3302. }
  3303. // NOTE: This table must match BinaryOperator::Opcode
  3304. static const HLBinaryOpcode BinaryOperatorKindMap[] = {
  3305. HLBinaryOpcode::Invalid, // PtrMemD
  3306. HLBinaryOpcode::Invalid, // PtrMemI
  3307. HLBinaryOpcode::Mul, HLBinaryOpcode::Div, HLBinaryOpcode::Rem,
  3308. HLBinaryOpcode::Add, HLBinaryOpcode::Sub, HLBinaryOpcode::Shl,
  3309. HLBinaryOpcode::Shr, HLBinaryOpcode::LT, HLBinaryOpcode::GT,
  3310. HLBinaryOpcode::LE, HLBinaryOpcode::GE, HLBinaryOpcode::EQ,
  3311. HLBinaryOpcode::NE, HLBinaryOpcode::And, HLBinaryOpcode::Xor,
  3312. HLBinaryOpcode::Or, HLBinaryOpcode::LAnd, HLBinaryOpcode::LOr,
  3313. HLBinaryOpcode::Invalid, // Assign,
  3314. // The assign part is done by matrix store
  3315. HLBinaryOpcode::Mul, // MulAssign
  3316. HLBinaryOpcode::Div, // DivAssign
  3317. HLBinaryOpcode::Rem, // RemAssign
  3318. HLBinaryOpcode::Add, // AddAssign
  3319. HLBinaryOpcode::Sub, // SubAssign
  3320. HLBinaryOpcode::Shl, // ShlAssign
  3321. HLBinaryOpcode::Shr, // ShrAssign
  3322. HLBinaryOpcode::And, // AndAssign
  3323. HLBinaryOpcode::Xor, // XorAssign
  3324. HLBinaryOpcode::Or, // OrAssign
  3325. HLBinaryOpcode::Invalid, // Comma
  3326. };
  3327. // NOTE: This table must match UnaryOperator::Opcode
  3328. static const HLUnaryOpcode UnaryOperatorKindMap[] = {
  3329. HLUnaryOpcode::PostInc, HLUnaryOpcode::PostDec,
  3330. HLUnaryOpcode::PreInc, HLUnaryOpcode::PreDec,
  3331. HLUnaryOpcode::Invalid, // AddrOf,
  3332. HLUnaryOpcode::Invalid, // Deref,
  3333. HLUnaryOpcode::Plus, HLUnaryOpcode::Minus,
  3334. HLUnaryOpcode::Not, HLUnaryOpcode::LNot,
  3335. HLUnaryOpcode::Invalid, // Real,
  3336. HLUnaryOpcode::Invalid, // Imag,
  3337. HLUnaryOpcode::Invalid, // Extension
  3338. };
  3339. static unsigned GetHLOpcode(const Expr *E) {
  3340. switch (E->getStmtClass()) {
  3341. case Stmt::CompoundAssignOperatorClass:
  3342. case Stmt::BinaryOperatorClass: {
  3343. const clang::BinaryOperator *binOp = cast<clang::BinaryOperator>(E);
  3344. HLBinaryOpcode binOpcode = BinaryOperatorKindMap[binOp->getOpcode()];
  3345. if (HasUnsignedOpcode(binOpcode)) {
  3346. if (hlsl::IsHLSLUnsigned(binOp->getLHS()->getType())) {
  3347. binOpcode = GetUnsignedOpcode(binOpcode);
  3348. }
  3349. }
  3350. return static_cast<unsigned>(binOpcode);
  3351. }
  3352. case Stmt::UnaryOperatorClass: {
  3353. const UnaryOperator *unOp = cast<clang::UnaryOperator>(E);
  3354. HLUnaryOpcode unOpcode = UnaryOperatorKindMap[unOp->getOpcode()];
  3355. return static_cast<unsigned>(unOpcode);
  3356. }
  3357. case Stmt::ImplicitCastExprClass:
  3358. case Stmt::CStyleCastExprClass: {
  3359. const CastExpr *CE = cast<CastExpr>(E);
  3360. bool toUnsigned = hlsl::IsHLSLUnsigned(E->getType());
  3361. bool fromUnsigned = hlsl::IsHLSLUnsigned(CE->getSubExpr()->getType());
  3362. if (toUnsigned && fromUnsigned)
  3363. return static_cast<unsigned>(HLCastOpcode::UnsignedUnsignedCast);
  3364. else if (toUnsigned)
  3365. return static_cast<unsigned>(HLCastOpcode::ToUnsignedCast);
  3366. else if (fromUnsigned)
  3367. return static_cast<unsigned>(HLCastOpcode::FromUnsignedCast);
  3368. else
  3369. return static_cast<unsigned>(HLCastOpcode::DefaultCast);
  3370. }
  3371. default:
  3372. return 0;
  3373. }
  3374. }
  3375. static Value *
  3376. EmitHLSLMatrixOperationCallImp(CGBuilderTy &Builder, HLOpcodeGroup group,
  3377. unsigned opcode, llvm::Type *RetType,
  3378. ArrayRef<Value *> paramList, llvm::Module &M) {
  3379. SmallVector<llvm::Type *, 4> paramTyList;
  3380. // Add the opcode param
  3381. llvm::Type *opcodeTy = llvm::Type::getInt32Ty(M.getContext());
  3382. paramTyList.emplace_back(opcodeTy);
  3383. for (Value *param : paramList) {
  3384. paramTyList.emplace_back(param->getType());
  3385. }
  3386. llvm::FunctionType *funcTy =
  3387. llvm::FunctionType::get(RetType, paramTyList, false);
  3388. Function *opFunc = GetOrCreateHLFunction(M, funcTy, group, opcode);
  3389. SmallVector<Value *, 4> opcodeParamList;
  3390. Value *opcodeConst = Constant::getIntegerValue(opcodeTy, APInt(32, opcode));
  3391. opcodeParamList.emplace_back(opcodeConst);
  3392. opcodeParamList.append(paramList.begin(), paramList.end());
  3393. return Builder.CreateCall(opFunc, opcodeParamList);
  3394. }
  3395. static Value *EmitHLSLArrayInit(CGBuilderTy &Builder, HLOpcodeGroup group,
  3396. unsigned opcode, llvm::Type *RetType,
  3397. ArrayRef<Value *> paramList, llvm::Module &M) {
  3398. // It's a matrix init.
  3399. if (!RetType->isVoidTy())
  3400. return EmitHLSLMatrixOperationCallImp(Builder, group, opcode, RetType,
  3401. paramList, M);
  3402. Value *arrayPtr = paramList[0];
  3403. llvm::ArrayType *AT =
  3404. cast<llvm::ArrayType>(arrayPtr->getType()->getPointerElementType());
  3405. // Avoid the arrayPtr.
  3406. unsigned paramSize = paramList.size() - 1;
  3407. // Support simple case here.
  3408. if (paramSize == AT->getArrayNumElements()) {
  3409. bool typeMatch = true;
  3410. llvm::Type *EltTy = AT->getArrayElementType();
  3411. if (EltTy->isAggregateType()) {
  3412. // Aggregate Type use pointer in initList.
  3413. EltTy = llvm::PointerType::get(EltTy, 0);
  3414. }
  3415. for (unsigned i = 1; i < paramList.size(); i++) {
  3416. if (paramList[i]->getType() != EltTy) {
  3417. typeMatch = false;
  3418. break;
  3419. }
  3420. }
  3421. // Both size and type match.
  3422. if (typeMatch) {
  3423. bool isPtr = EltTy->isPointerTy();
  3424. llvm::Type *i32Ty = llvm::Type::getInt32Ty(EltTy->getContext());
  3425. Constant *zero = ConstantInt::get(i32Ty, 0);
  3426. for (unsigned i = 1; i < paramList.size(); i++) {
  3427. Constant *idx = ConstantInt::get(i32Ty, i - 1);
  3428. Value *GEP = Builder.CreateInBoundsGEP(arrayPtr, {zero, idx});
  3429. Value *Elt = paramList[i];
  3430. if (isPtr) {
  3431. Elt = Builder.CreateLoad(Elt);
  3432. }
  3433. Builder.CreateStore(Elt, GEP);
  3434. }
  3435. // The return value will not be used.
  3436. return nullptr;
  3437. }
  3438. }
  3439. // Other case will be lowered in later pass.
  3440. return EmitHLSLMatrixOperationCallImp(Builder, group, opcode, RetType,
  3441. paramList, M);
  3442. }
  3443. void CGMSHLSLRuntime::FlattenValToInitList(CodeGenFunction &CGF, SmallVector<Value *, 4> &elts,
  3444. SmallVector<QualType, 4> &eltTys,
  3445. QualType Ty, Value *val) {
  3446. CGBuilderTy &Builder = CGF.Builder;
  3447. llvm::Type *valTy = val->getType();
  3448. if (valTy->isPointerTy()) {
  3449. llvm::Type *valEltTy = valTy->getPointerElementType();
  3450. if (valEltTy->isVectorTy() ||
  3451. valEltTy->isSingleValueType()) {
  3452. Value *ldVal = Builder.CreateLoad(val);
  3453. FlattenValToInitList(CGF, elts, eltTys, Ty, ldVal);
  3454. } else if (HLMatrixType::isa(valEltTy)) {
  3455. Value *ldVal = EmitHLSLMatrixLoad(Builder, val, Ty);
  3456. FlattenValToInitList(CGF, elts, eltTys, Ty, ldVal);
  3457. } else {
  3458. llvm::Type *i32Ty = llvm::Type::getInt32Ty(valTy->getContext());
  3459. Value *zero = ConstantInt::get(i32Ty, 0);
  3460. if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(valEltTy)) {
  3461. QualType EltTy = Ty->getAsArrayTypeUnsafe()->getElementType();
  3462. for (unsigned i = 0; i < AT->getArrayNumElements(); i++) {
  3463. Value *gepIdx = ConstantInt::get(i32Ty, i);
  3464. Value *EltPtr = Builder.CreateInBoundsGEP(val, {zero, gepIdx});
  3465. FlattenValToInitList(CGF, elts, eltTys, EltTy,EltPtr);
  3466. }
  3467. } else {
  3468. // Struct.
  3469. StructType *ST = cast<StructType>(valEltTy);
  3470. if (dxilutil::IsHLSLObjectType(ST)) {
  3471. // Save object directly like basic type.
  3472. elts.emplace_back(Builder.CreateLoad(val));
  3473. eltTys.emplace_back(Ty);
  3474. } else {
  3475. RecordDecl *RD = Ty->getAsStructureType()->getDecl();
  3476. const CGRecordLayout& RL = CGF.getTypes().getCGRecordLayout(RD);
  3477. // Take care base.
  3478. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  3479. if (CXXRD->getNumBases()) {
  3480. for (const auto &I : CXXRD->bases()) {
  3481. const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(
  3482. I.getType()->castAs<RecordType>()->getDecl());
  3483. if (BaseDecl->field_empty())
  3484. continue;
  3485. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  3486. unsigned i = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  3487. Value *gepIdx = ConstantInt::get(i32Ty, i);
  3488. Value *EltPtr = Builder.CreateInBoundsGEP(val, {zero, gepIdx});
  3489. FlattenValToInitList(CGF, elts, eltTys, parentTy, EltPtr);
  3490. }
  3491. }
  3492. }
  3493. for (auto fieldIter = RD->field_begin(), fieldEnd = RD->field_end();
  3494. fieldIter != fieldEnd; ++fieldIter) {
  3495. unsigned i = RL.getLLVMFieldNo(*fieldIter);
  3496. Value *gepIdx = ConstantInt::get(i32Ty, i);
  3497. Value *EltPtr = Builder.CreateInBoundsGEP(val, {zero, gepIdx});
  3498. FlattenValToInitList(CGF, elts, eltTys, fieldIter->getType(), EltPtr);
  3499. }
  3500. }
  3501. }
  3502. }
  3503. } else {
  3504. if (HLMatrixType MatTy = HLMatrixType::dyn_cast(valTy)) {
  3505. llvm::Type *EltTy = MatTy.getElementTypeForReg();
  3506. // All matrix Value should be row major.
  3507. // Init list is row major in scalar.
  3508. // So the order is match here, just cast to vector.
  3509. unsigned matSize = MatTy.getNumElements();
  3510. bool isRowMajor = hlsl::IsHLSLMatRowMajor(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  3511. HLCastOpcode opcode = isRowMajor ? HLCastOpcode::RowMatrixToVecCast
  3512. : HLCastOpcode::ColMatrixToVecCast;
  3513. // Cast to vector.
  3514. val = EmitHLSLMatrixOperationCallImp(
  3515. Builder, HLOpcodeGroup::HLCast,
  3516. static_cast<unsigned>(opcode),
  3517. llvm::VectorType::get(EltTy, matSize), {val}, TheModule);
  3518. valTy = val->getType();
  3519. }
  3520. if (valTy->isVectorTy()) {
  3521. QualType EltTy = hlsl::GetElementTypeOrType(Ty);
  3522. unsigned vecSize = valTy->getVectorNumElements();
  3523. for (unsigned i = 0; i < vecSize; i++) {
  3524. Value *Elt = Builder.CreateExtractElement(val, i);
  3525. elts.emplace_back(Elt);
  3526. eltTys.emplace_back(EltTy);
  3527. }
  3528. } else {
  3529. DXASSERT(valTy->isSingleValueType(), "must be single value type here");
  3530. elts.emplace_back(val);
  3531. eltTys.emplace_back(Ty);
  3532. }
  3533. }
  3534. }
  3535. static Value* ConvertScalarOrVector(CGBuilderTy& Builder, CodeGenTypes &Types,
  3536. Value *Val, QualType SrcQualTy, QualType DstQualTy) {
  3537. llvm::Type *SrcTy = Val->getType();
  3538. llvm::Type *DstTy = Types.ConvertType(DstQualTy);
  3539. DXASSERT(Val->getType() == Types.ConvertType(SrcQualTy), "QualType/Value mismatch!");
  3540. DXASSERT((SrcTy->isIntOrIntVectorTy() || SrcTy->isFPOrFPVectorTy())
  3541. && (DstTy->isIntOrIntVectorTy() || DstTy->isFPOrFPVectorTy()),
  3542. "EmitNumericConversion can only be used with int/float scalars/vectors.");
  3543. if (SrcTy == DstTy) return Val; // Valid no-op, including uint to int / int to uint
  3544. DXASSERT(SrcTy->isVectorTy()
  3545. ? (DstTy->isVectorTy() && SrcTy->getVectorNumElements() == DstTy->getVectorNumElements())
  3546. : !DstTy->isVectorTy(),
  3547. "EmitNumericConversion can only cast between scalars or vectors of matching sizes");
  3548. // Conversions to bools are comparisons
  3549. if (DstTy->getScalarSizeInBits() == 1) {
  3550. // fcmp une is what regular clang uses in C++ for (bool)f;
  3551. return SrcTy->isIntOrIntVectorTy()
  3552. ? Builder.CreateICmpNE(Val, llvm::Constant::getNullValue(SrcTy), "tobool")
  3553. : Builder.CreateFCmpUNE(Val, llvm::Constant::getNullValue(SrcTy), "tobool");
  3554. }
  3555. // Cast necessary
  3556. auto CastOp = static_cast<Instruction::CastOps>(HLModule::GetNumericCastOp(
  3557. SrcTy, hlsl::IsHLSLUnsigned(SrcQualTy), DstTy, hlsl::IsHLSLUnsigned(DstQualTy)));
  3558. return Builder.CreateCast(CastOp, Val, DstTy);
  3559. }
  3560. static Value* ConvertScalarOrVector(CodeGenFunction &CGF,
  3561. Value *Val, QualType SrcQualTy, QualType DstQualTy) {
  3562. return ConvertScalarOrVector(CGF.Builder, CGF.getTypes(), Val, SrcQualTy, DstQualTy);
  3563. }
  3564. // Cast elements in initlist if not match the target type.
  3565. // idx is current element index in initlist, Ty is target type.
  3566. // TODO: Stop handling missing cast here. Handle the casting of non-scalar values
  3567. // to their destination type in init list expressions at AST level.
  3568. static void AddMissingCastOpsInInitList(SmallVector<Value *, 4> &elts, SmallVector<QualType, 4> &eltTys, unsigned &idx, QualType Ty, CodeGenFunction &CGF) {
  3569. if (Ty->isArrayType()) {
  3570. const clang::ArrayType *AT = Ty->getAsArrayTypeUnsafe();
  3571. // Must be ConstantArrayType here.
  3572. unsigned arraySize = cast<ConstantArrayType>(AT)->getSize().getLimitedValue();
  3573. QualType EltTy = AT->getElementType();
  3574. for (unsigned i = 0; i < arraySize; i++)
  3575. AddMissingCastOpsInInitList(elts, eltTys, idx, EltTy, CGF);
  3576. } else if (IsHLSLVecType(Ty)) {
  3577. QualType EltTy = GetHLSLVecElementType(Ty);
  3578. unsigned vecSize = GetHLSLVecSize(Ty);
  3579. for (unsigned i=0;i< vecSize;i++)
  3580. AddMissingCastOpsInInitList(elts, eltTys, idx, EltTy, CGF);
  3581. } else if (IsHLSLMatType(Ty)) {
  3582. QualType EltTy = GetHLSLMatElementType(Ty);
  3583. unsigned row, col;
  3584. GetHLSLMatRowColCount(Ty, row, col);
  3585. unsigned matSize = row*col;
  3586. for (unsigned i = 0; i < matSize; i++)
  3587. AddMissingCastOpsInInitList(elts, eltTys, idx, EltTy, CGF);
  3588. } else if (Ty->isRecordType()) {
  3589. if (dxilutil::IsHLSLObjectType(CGF.ConvertType(Ty))) {
  3590. // Skip hlsl object.
  3591. idx++;
  3592. } else {
  3593. const RecordType *RT = Ty->getAsStructureType();
  3594. // For CXXRecord.
  3595. if (!RT)
  3596. RT = Ty->getAs<RecordType>();
  3597. RecordDecl *RD = RT->getDecl();
  3598. // Take care base.
  3599. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  3600. if (CXXRD->getNumBases()) {
  3601. for (const auto &I : CXXRD->bases()) {
  3602. const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(
  3603. I.getType()->castAs<RecordType>()->getDecl());
  3604. if (BaseDecl->field_empty())
  3605. continue;
  3606. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  3607. AddMissingCastOpsInInitList(elts, eltTys, idx, parentTy, CGF);
  3608. }
  3609. }
  3610. }
  3611. for (FieldDecl *field : RD->fields())
  3612. AddMissingCastOpsInInitList(elts, eltTys, idx, field->getType(), CGF);
  3613. }
  3614. }
  3615. else {
  3616. // Basic type.
  3617. elts[idx] = ConvertScalarOrVector(CGF, elts[idx], eltTys[idx], Ty);
  3618. idx++;
  3619. }
  3620. }
  3621. static void StoreInitListToDestPtr(Value *DestPtr,
  3622. SmallVector<Value *, 4> &elts, unsigned &idx,
  3623. QualType Type, bool bDefaultRowMajor,
  3624. CodeGenFunction &CGF, llvm::Module &M) {
  3625. CodeGenTypes &Types = CGF.getTypes();
  3626. CGBuilderTy &Builder = CGF.Builder;
  3627. llvm::Type *Ty = DestPtr->getType()->getPointerElementType();
  3628. if (Ty->isVectorTy()) {
  3629. llvm::Type *RegTy = CGF.ConvertType(Type);
  3630. Value *Result = UndefValue::get(RegTy);
  3631. for (unsigned i = 0; i < RegTy->getVectorNumElements(); i++)
  3632. Result = Builder.CreateInsertElement(Result, elts[idx + i], i);
  3633. Result = CGF.EmitToMemory(Result, Type);
  3634. Builder.CreateStore(Result, DestPtr);
  3635. idx += Ty->getVectorNumElements();
  3636. } else if (HLMatrixType MatTy = HLMatrixType::dyn_cast(Ty)) {
  3637. bool isRowMajor = hlsl::IsHLSLMatRowMajor(Type, bDefaultRowMajor);
  3638. std::vector<Value *> matInitList(MatTy.getNumElements());
  3639. for (unsigned c = 0; c < MatTy.getNumColumns(); c++) {
  3640. for (unsigned r = 0; r < MatTy.getNumRows(); r++) {
  3641. unsigned matIdx = c * MatTy.getNumRows() + r;
  3642. matInitList[matIdx] = elts[idx + matIdx];
  3643. }
  3644. }
  3645. idx += MatTy.getNumElements();
  3646. Value *matVal =
  3647. EmitHLSLMatrixOperationCallImp(Builder, HLOpcodeGroup::HLInit,
  3648. /*opcode*/ 0, Ty, matInitList, M);
  3649. // matVal return from HLInit is row major.
  3650. // If DestPtr is row major, just store it directly.
  3651. if (!isRowMajor) {
  3652. // ColMatStore need a col major value.
  3653. // Cast row major matrix into col major.
  3654. // Then store it.
  3655. Value *colMatVal = EmitHLSLMatrixOperationCallImp(
  3656. Builder, HLOpcodeGroup::HLCast,
  3657. static_cast<unsigned>(HLCastOpcode::RowMatrixToColMatrix), Ty,
  3658. {matVal}, M);
  3659. EmitHLSLMatrixOperationCallImp(
  3660. Builder, HLOpcodeGroup::HLMatLoadStore,
  3661. static_cast<unsigned>(HLMatLoadStoreOpcode::ColMatStore), Ty,
  3662. {DestPtr, colMatVal}, M);
  3663. } else {
  3664. EmitHLSLMatrixOperationCallImp(
  3665. Builder, HLOpcodeGroup::HLMatLoadStore,
  3666. static_cast<unsigned>(HLMatLoadStoreOpcode::RowMatStore), Ty,
  3667. {DestPtr, matVal}, M);
  3668. }
  3669. } else if (Ty->isStructTy()) {
  3670. if (dxilutil::IsHLSLObjectType(Ty)) {
  3671. Builder.CreateStore(elts[idx], DestPtr);
  3672. idx++;
  3673. } else {
  3674. Constant *zero = Builder.getInt32(0);
  3675. const RecordType *RT = Type->getAsStructureType();
  3676. // For CXXRecord.
  3677. if (!RT)
  3678. RT = Type->getAs<RecordType>();
  3679. RecordDecl *RD = RT->getDecl();
  3680. const CGRecordLayout &RL = Types.getCGRecordLayout(RD);
  3681. // Take care base.
  3682. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  3683. if (CXXRD->getNumBases()) {
  3684. for (const auto &I : CXXRD->bases()) {
  3685. const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(
  3686. I.getType()->castAs<RecordType>()->getDecl());
  3687. if (BaseDecl->field_empty())
  3688. continue;
  3689. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  3690. unsigned i = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  3691. Constant *gepIdx = Builder.getInt32(i);
  3692. Value *GEP = Builder.CreateInBoundsGEP(DestPtr, {zero, gepIdx});
  3693. StoreInitListToDestPtr(GEP, elts, idx, parentTy,
  3694. bDefaultRowMajor, CGF, M);
  3695. }
  3696. }
  3697. }
  3698. for (FieldDecl *field : RD->fields()) {
  3699. unsigned i = RL.getLLVMFieldNo(field);
  3700. Constant *gepIdx = Builder.getInt32(i);
  3701. Value *GEP = Builder.CreateInBoundsGEP(DestPtr, {zero, gepIdx});
  3702. StoreInitListToDestPtr(GEP, elts, idx, field->getType(),
  3703. bDefaultRowMajor, CGF, M);
  3704. }
  3705. }
  3706. } else if (Ty->isArrayTy()) {
  3707. Constant *zero = Builder.getInt32(0);
  3708. QualType EltType = Type->getAsArrayTypeUnsafe()->getElementType();
  3709. for (unsigned i = 0; i < Ty->getArrayNumElements(); i++) {
  3710. Constant *gepIdx = Builder.getInt32(i);
  3711. Value *GEP = Builder.CreateInBoundsGEP(DestPtr, {zero, gepIdx});
  3712. StoreInitListToDestPtr(GEP, elts, idx, EltType, bDefaultRowMajor,
  3713. CGF, M);
  3714. }
  3715. } else {
  3716. DXASSERT(Ty->isSingleValueType(), "invalid type");
  3717. llvm::Type *i1Ty = Builder.getInt1Ty();
  3718. Value *V = elts[idx];
  3719. if (V->getType() == i1Ty &&
  3720. DestPtr->getType()->getPointerElementType() != i1Ty) {
  3721. V = Builder.CreateZExt(V, DestPtr->getType()->getPointerElementType());
  3722. }
  3723. Builder.CreateStore(V, DestPtr);
  3724. idx++;
  3725. }
  3726. }
  3727. void CGMSHLSLRuntime::ScanInitList(CodeGenFunction &CGF, InitListExpr *E,
  3728. SmallVector<Value *, 4> &EltValList,
  3729. SmallVector<QualType, 4> &EltTyList) {
  3730. unsigned NumInitElements = E->getNumInits();
  3731. for (unsigned i = 0; i != NumInitElements; ++i) {
  3732. Expr *init = E->getInit(i);
  3733. QualType iType = init->getType();
  3734. if (InitListExpr *initList = dyn_cast<InitListExpr>(init)) {
  3735. ScanInitList(CGF, initList, EltValList, EltTyList);
  3736. } else if (CodeGenFunction::hasScalarEvaluationKind(iType)) {
  3737. llvm::Value *initVal = CGF.EmitScalarExpr(init);
  3738. FlattenValToInitList(CGF, EltValList, EltTyList, iType, initVal);
  3739. } else {
  3740. AggValueSlot Slot =
  3741. CGF.CreateAggTemp(init->getType(), "Agg.InitList.tmp");
  3742. CGF.EmitAggExpr(init, Slot);
  3743. llvm::Value *aggPtr = Slot.getAddr();
  3744. FlattenValToInitList(CGF, EltValList, EltTyList, iType, aggPtr);
  3745. }
  3746. }
  3747. }
  3748. // Is Type of E match Ty.
  3749. static bool ExpTypeMatch(Expr *E, QualType Ty, ASTContext &Ctx, CodeGenTypes &Types) {
  3750. if (InitListExpr *initList = dyn_cast<InitListExpr>(E)) {
  3751. unsigned NumInitElements = initList->getNumInits();
  3752. // Skip vector and matrix type.
  3753. if (Ty->isVectorType())
  3754. return false;
  3755. if (hlsl::IsHLSLVecMatType(Ty))
  3756. return false;
  3757. if (Ty->isStructureOrClassType()) {
  3758. RecordDecl *record = Ty->castAs<RecordType>()->getDecl();
  3759. bool bMatch = true;
  3760. unsigned i = 0;
  3761. for (auto it = record->field_begin(), end = record->field_end();
  3762. it != end; it++) {
  3763. if (i == NumInitElements) {
  3764. bMatch = false;
  3765. break;
  3766. }
  3767. Expr *init = initList->getInit(i++);
  3768. QualType EltTy = it->getType();
  3769. bMatch &= ExpTypeMatch(init, EltTy, Ctx, Types);
  3770. if (!bMatch)
  3771. break;
  3772. }
  3773. bMatch &= i == NumInitElements;
  3774. if (bMatch && initList->getType()->isVoidType()) {
  3775. initList->setType(Ty);
  3776. }
  3777. return bMatch;
  3778. } else if (Ty->isArrayType() && !Ty->isIncompleteArrayType()) {
  3779. const ConstantArrayType *AT = Ctx.getAsConstantArrayType(Ty);
  3780. QualType EltTy = AT->getElementType();
  3781. unsigned size = AT->getSize().getZExtValue();
  3782. if (size != NumInitElements)
  3783. return false;
  3784. bool bMatch = true;
  3785. for (unsigned i = 0; i != NumInitElements; ++i) {
  3786. Expr *init = initList->getInit(i);
  3787. bMatch &= ExpTypeMatch(init, EltTy, Ctx, Types);
  3788. if (!bMatch)
  3789. break;
  3790. }
  3791. if (bMatch && initList->getType()->isVoidType()) {
  3792. initList->setType(Ty);
  3793. }
  3794. return bMatch;
  3795. } else {
  3796. return false;
  3797. }
  3798. } else {
  3799. llvm::Type *ExpTy = Types.ConvertType(E->getType());
  3800. llvm::Type *TargetTy = Types.ConvertType(Ty);
  3801. return ExpTy == TargetTy;
  3802. }
  3803. }
  3804. bool CGMSHLSLRuntime::IsTrivalInitListExpr(CodeGenFunction &CGF,
  3805. InitListExpr *E) {
  3806. QualType Ty = E->getType();
  3807. bool result = ExpTypeMatch(E, Ty, CGF.getContext(), CGF.getTypes());
  3808. if (result) {
  3809. auto iter = staticConstGlobalInitMap.find(E);
  3810. if (iter != staticConstGlobalInitMap.end()) {
  3811. GlobalVariable * GV = iter->second;
  3812. auto &InitConstants = staticConstGlobalInitListMap[GV];
  3813. // Add Constant to InitList.
  3814. for (unsigned i=0;i<E->getNumInits();i++) {
  3815. Expr *Expr = E->getInit(i);
  3816. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Expr)) {
  3817. if (Cast->getCastKind() == CK_LValueToRValue) {
  3818. Expr = Cast->getSubExpr();
  3819. }
  3820. }
  3821. // Only do this on lvalue, if not lvalue, it will not be constant
  3822. // anyway.
  3823. if (Expr->isLValue()) {
  3824. LValue LV = CGF.EmitLValue(Expr);
  3825. if (LV.isSimple()) {
  3826. Constant *SrcPtr = dyn_cast<Constant>(LV.getAddress());
  3827. if (SrcPtr && !isa<UndefValue>(SrcPtr)) {
  3828. InitConstants.emplace_back(SrcPtr);
  3829. continue;
  3830. }
  3831. }
  3832. }
  3833. // Only support simple LV and Constant Ptr case.
  3834. // Other case just go normal path.
  3835. InitConstants.clear();
  3836. break;
  3837. }
  3838. if (InitConstants.empty())
  3839. staticConstGlobalInitListMap.erase(GV);
  3840. else
  3841. staticConstGlobalCtorMap[GV] = CGF.CurFn;
  3842. }
  3843. }
  3844. return result;
  3845. }
  3846. Value *CGMSHLSLRuntime::EmitHLSLInitListExpr(CodeGenFunction &CGF, InitListExpr *E,
  3847. // The destPtr when emiting aggregate init, for normal case, it will be null.
  3848. Value *DestPtr) {
  3849. if (DestPtr && E->getNumInits() == 1) {
  3850. llvm::Type *ExpTy = CGF.ConvertType(E->getType());
  3851. llvm::Type *TargetTy = CGF.ConvertType(E->getInit(0)->getType());
  3852. if (ExpTy == TargetTy) {
  3853. Expr *Expr = E->getInit(0);
  3854. LValue LV = CGF.EmitLValue(Expr);
  3855. if (LV.isSimple()) {
  3856. Value *SrcPtr = LV.getAddress();
  3857. SmallVector<Value *, 4> idxList;
  3858. EmitHLSLAggregateCopy(CGF, SrcPtr, DestPtr, idxList, Expr->getType(),
  3859. E->getType(), SrcPtr->getType());
  3860. return nullptr;
  3861. }
  3862. }
  3863. }
  3864. SmallVector<Value *, 4> EltValList;
  3865. SmallVector<QualType, 4> EltTyList;
  3866. ScanInitList(CGF, E, EltValList, EltTyList);
  3867. QualType ResultTy = E->getType();
  3868. unsigned idx = 0;
  3869. // Create cast if need.
  3870. AddMissingCastOpsInInitList(EltValList, EltTyList, idx, ResultTy, CGF);
  3871. DXASSERT(idx == EltValList.size(), "size must match");
  3872. llvm::Type *RetTy = CGF.ConvertType(ResultTy);
  3873. if (DestPtr) {
  3874. SmallVector<Value *, 4> ParamList;
  3875. DXASSERT_NOMSG(RetTy->isAggregateType());
  3876. ParamList.emplace_back(DestPtr);
  3877. ParamList.append(EltValList.begin(), EltValList.end());
  3878. idx = 0;
  3879. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  3880. StoreInitListToDestPtr(DestPtr, EltValList, idx, ResultTy,
  3881. bDefaultRowMajor, CGF, TheModule);
  3882. return nullptr;
  3883. }
  3884. if (IsHLSLVecType(ResultTy)) {
  3885. Value *Result = UndefValue::get(RetTy);
  3886. for (unsigned i = 0; i < RetTy->getVectorNumElements(); i++)
  3887. Result = CGF.Builder.CreateInsertElement(Result, EltValList[i], i);
  3888. return Result;
  3889. } else {
  3890. // Must be matrix here.
  3891. DXASSERT(IsHLSLMatType(ResultTy), "must be matrix type here.");
  3892. return EmitHLSLMatrixOperationCallImp(CGF.Builder, HLOpcodeGroup::HLInit,
  3893. /*opcode*/ 0, RetTy, EltValList,
  3894. TheModule);
  3895. }
  3896. }
  3897. static void FlatConstToList(CodeGenTypes &Types, bool bDefaultRowMajor,
  3898. Constant *C, QualType QualTy,
  3899. SmallVectorImpl<Constant *> &EltVals, SmallVectorImpl<QualType> &EltQualTys) {
  3900. llvm::Type *Ty = C->getType();
  3901. DXASSERT(Types.ConvertTypeForMem(QualTy) == Ty, "QualType/Type mismatch!");
  3902. if (llvm::VectorType *VecTy = dyn_cast<llvm::VectorType>(Ty)) {
  3903. DXASSERT(hlsl::IsHLSLVecType(QualTy), "QualType/Type mismatch!");
  3904. QualType VecElemQualTy = hlsl::GetHLSLVecElementType(QualTy);
  3905. for (unsigned i = 0; i < VecTy->getNumElements(); i++) {
  3906. EltVals.emplace_back(C->getAggregateElement(i));
  3907. EltQualTys.emplace_back(VecElemQualTy);
  3908. }
  3909. } else if (HLMatrixType::isa(Ty)) {
  3910. DXASSERT(hlsl::IsHLSLMatType(QualTy), "QualType/Type mismatch!");
  3911. // matrix type is struct { [rowcount x <colcount x T>] };
  3912. // Strip the struct level here.
  3913. Constant *RowArrayVal = C->getAggregateElement((unsigned)0);
  3914. QualType MatEltQualTy = hlsl::GetHLSLMatElementType(QualTy);
  3915. unsigned RowCount, ColCount;
  3916. hlsl::GetHLSLMatRowColCount(QualTy, RowCount, ColCount);
  3917. // Get all the elements from the array of row vectors.
  3918. // Matrices are never in memory representation so convert as needed.
  3919. SmallVector<Constant *, 16> MatElts;
  3920. for (unsigned r = 0; r < RowCount; ++r) {
  3921. Constant *RowVec = RowArrayVal->getAggregateElement(r);
  3922. for (unsigned c = 0; c < ColCount; ++c) {
  3923. Constant *MatElt = RowVec->getAggregateElement(c);
  3924. if (MatEltQualTy->isBooleanType()) {
  3925. DXASSERT(MatElt->getType()->isIntegerTy(1),
  3926. "Matrix elements should be in their register representation.");
  3927. MatElt = llvm::ConstantExpr::getZExt(MatElt, Types.ConvertTypeForMem(MatEltQualTy));
  3928. }
  3929. MatElts.emplace_back(MatElt);
  3930. }
  3931. }
  3932. // Return the elements in the order respecting the orientation.
  3933. // Constant initializers are used as the initial value for static variables,
  3934. // which live in memory. This is why they have to respect memory packing order.
  3935. bool IsRowMajor = hlsl::IsHLSLMatRowMajor(QualTy, bDefaultRowMajor);
  3936. for (unsigned r = 0; r < RowCount; ++r) {
  3937. for (unsigned c = 0; c < ColCount; ++c) {
  3938. unsigned Idx = IsRowMajor ? (r * ColCount + c) : (c * RowCount + r);
  3939. EltVals.emplace_back(MatElts[Idx]);
  3940. EltQualTys.emplace_back(MatEltQualTy);
  3941. }
  3942. }
  3943. }
  3944. else if (const clang::ConstantArrayType *ClangArrayTy = Types.getContext().getAsConstantArrayType(QualTy)) {
  3945. QualType ArrayEltQualTy = ClangArrayTy->getElementType();
  3946. uint64_t ArraySize = ClangArrayTy->getSize().getLimitedValue();
  3947. DXASSERT(cast<llvm::ArrayType>(Ty)->getArrayNumElements() == ArraySize, "QualType/Type mismatch!");
  3948. for (unsigned i = 0; i < ArraySize; i++) {
  3949. FlatConstToList(Types, bDefaultRowMajor, C->getAggregateElement(i), ArrayEltQualTy,
  3950. EltVals, EltQualTys);
  3951. }
  3952. }
  3953. else if (const clang::RecordType* RecordTy = QualTy->getAs<clang::RecordType>()) {
  3954. DXASSERT(dyn_cast<llvm::StructType>(Ty) != nullptr, "QualType/Type mismatch!");
  3955. RecordDecl *RecordDecl = RecordTy->getDecl();
  3956. const CGRecordLayout &RL = Types.getCGRecordLayout(RecordDecl);
  3957. // Take care base.
  3958. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RecordDecl)) {
  3959. if (CXXRD->getNumBases()) {
  3960. for (const auto &I : CXXRD->bases()) {
  3961. const CXXRecordDecl *BaseDecl =
  3962. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  3963. if (BaseDecl->field_empty())
  3964. continue;
  3965. QualType BaseQualTy = QualType(BaseDecl->getTypeForDecl(), 0);
  3966. unsigned BaseFieldIdx = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  3967. FlatConstToList(Types, bDefaultRowMajor,
  3968. C->getAggregateElement(BaseFieldIdx), BaseQualTy, EltVals, EltQualTys);
  3969. }
  3970. }
  3971. }
  3972. for (auto FieldIt = RecordDecl->field_begin(), fieldEnd = RecordDecl->field_end();
  3973. FieldIt != fieldEnd; ++FieldIt) {
  3974. unsigned FieldIndex = RL.getLLVMFieldNo(*FieldIt);
  3975. FlatConstToList(Types, bDefaultRowMajor,
  3976. C->getAggregateElement(FieldIndex), FieldIt->getType(), EltVals, EltQualTys);
  3977. }
  3978. }
  3979. else {
  3980. // At this point, we should have scalars in their memory representation
  3981. DXASSERT_NOMSG(QualTy->isBuiltinType());
  3982. EltVals.emplace_back(C);
  3983. EltQualTys.emplace_back(QualTy);
  3984. }
  3985. }
  3986. static bool ScanConstInitList(CodeGenModule &CGM, bool bDefaultRowMajor,
  3987. InitListExpr *InitList,
  3988. SmallVectorImpl<Constant *> &EltVals,
  3989. SmallVectorImpl<QualType> &EltQualTys) {
  3990. unsigned NumInitElements = InitList->getNumInits();
  3991. for (unsigned i = 0; i != NumInitElements; ++i) {
  3992. Expr *InitExpr = InitList->getInit(i);
  3993. QualType InitQualTy = InitExpr->getType();
  3994. if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(InitExpr)) {
  3995. if (!ScanConstInitList(CGM, bDefaultRowMajor, SubInitList, EltVals, EltQualTys))
  3996. return false;
  3997. } else if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(InitExpr)) {
  3998. if (VarDecl *Var = dyn_cast<VarDecl>(DeclRef->getDecl())) {
  3999. if (!Var->hasInit())
  4000. return false;
  4001. if (Constant *InitVal = CGM.EmitConstantInit(*Var)) {
  4002. FlatConstToList(CGM.getTypes(), bDefaultRowMajor,
  4003. InitVal, InitQualTy, EltVals, EltQualTys);
  4004. } else {
  4005. return false;
  4006. }
  4007. } else {
  4008. return false;
  4009. }
  4010. } else if (hlsl::IsHLSLMatType(InitQualTy)) {
  4011. return false;
  4012. } else if (CodeGenFunction::hasScalarEvaluationKind(InitQualTy)) {
  4013. if (Constant *InitVal = CGM.EmitConstantExpr(InitExpr, InitQualTy)) {
  4014. FlatConstToList(CGM.getTypes(), bDefaultRowMajor, InitVal, InitQualTy, EltVals, EltQualTys);
  4015. } else {
  4016. return false;
  4017. }
  4018. } else {
  4019. return false;
  4020. }
  4021. }
  4022. return true;
  4023. }
  4024. static Constant *BuildConstInitializer(CodeGenTypes &Types, bool bDefaultRowMajor,
  4025. QualType QualTy, bool MemRepr,
  4026. SmallVectorImpl<Constant *> &EltVals, SmallVectorImpl<QualType> &EltQualTys, unsigned &EltIdx);
  4027. static Constant *BuildConstMatrix(CodeGenTypes &Types, bool bDefaultRowMajor, QualType QualTy,
  4028. SmallVectorImpl<Constant *> &EltVals, SmallVectorImpl<QualType> &EltQualTys, unsigned &EltIdx) {
  4029. QualType MatEltTy = hlsl::GetHLSLMatElementType(QualTy);
  4030. unsigned RowCount, ColCount;
  4031. hlsl::GetHLSLMatRowColCount(QualTy, RowCount, ColCount);
  4032. bool IsRowMajor = hlsl::IsHLSLMatRowMajor(QualTy, bDefaultRowMajor);
  4033. // Save initializer elements first.
  4034. // Matrix initializer is row major.
  4035. SmallVector<Constant *, 16> RowMajorMatElts;
  4036. for (unsigned i = 0; i < RowCount * ColCount; i++) {
  4037. // Matrix elements are never in their memory representation,
  4038. // to preserve type information for later lowering.
  4039. bool MemRepr = false;
  4040. RowMajorMatElts.emplace_back(BuildConstInitializer(
  4041. Types, bDefaultRowMajor, MatEltTy, MemRepr,
  4042. EltVals, EltQualTys, EltIdx));
  4043. }
  4044. SmallVector<Constant *, 16> FinalMatElts;
  4045. if (IsRowMajor) {
  4046. FinalMatElts = RowMajorMatElts;
  4047. }
  4048. else {
  4049. // Cast row major to col major.
  4050. for (unsigned c = 0; c < ColCount; c++) {
  4051. for (unsigned r = 0; r < RowCount; r++) {
  4052. FinalMatElts.emplace_back(RowMajorMatElts[r * ColCount + c]);
  4053. }
  4054. }
  4055. }
  4056. // The type is vector<element, col>[row].
  4057. SmallVector<Constant *, 4> Rows;
  4058. unsigned idx = 0;
  4059. for (unsigned r = 0; r < RowCount; r++) {
  4060. SmallVector<Constant *, 4> RowElts;
  4061. for (unsigned c = 0; c < ColCount; c++) {
  4062. RowElts.emplace_back(FinalMatElts[idx++]);
  4063. }
  4064. Rows.emplace_back(llvm::ConstantVector::get(RowElts));
  4065. }
  4066. Constant *RowArray = llvm::ConstantArray::get(
  4067. llvm::ArrayType::get(Rows[0]->getType(), Rows.size()), Rows);
  4068. return llvm::ConstantStruct::get(cast<llvm::StructType>(Types.ConvertType(QualTy)), RowArray);
  4069. }
  4070. static Constant *BuildConstStruct(CodeGenTypes &Types, bool bDefaultRowMajor, QualType QualTy,
  4071. SmallVectorImpl<Constant *> &EltVals, SmallVectorImpl<QualType> &EltQualTys, unsigned &EltIdx) {
  4072. const RecordDecl *Record = QualTy->castAs<RecordType>()->getDecl();
  4073. bool MemRepr = true; // Structs are always in their memory representation
  4074. SmallVector<Constant *, 4> FieldVals;
  4075. if (const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
  4076. if (CXXRecord->getNumBases()) {
  4077. // Add base as field.
  4078. for (const auto &BaseSpec : CXXRecord->bases()) {
  4079. const CXXRecordDecl *BaseDecl =
  4080. cast<CXXRecordDecl>(BaseSpec.getType()->castAs<RecordType>()->getDecl());
  4081. // Skip empty struct.
  4082. if (BaseDecl->field_empty())
  4083. continue;
  4084. // Add base as a whole constant. Not as element.
  4085. FieldVals.emplace_back(BuildConstInitializer(Types, bDefaultRowMajor,
  4086. BaseSpec.getType(), MemRepr, EltVals, EltQualTys, EltIdx));
  4087. }
  4088. }
  4089. }
  4090. for (auto FieldIt = Record->field_begin(), FieldEnd = Record->field_end();
  4091. FieldIt != FieldEnd; ++FieldIt) {
  4092. FieldVals.emplace_back(BuildConstInitializer(Types, bDefaultRowMajor,
  4093. FieldIt->getType(), MemRepr, EltVals, EltQualTys, EltIdx));
  4094. }
  4095. return llvm::ConstantStruct::get(cast<llvm::StructType>(Types.ConvertTypeForMem(QualTy)), FieldVals);
  4096. }
  4097. static Constant *BuildConstInitializer(CodeGenTypes &Types, bool bDefaultRowMajor,
  4098. QualType QualTy, bool MemRepr,
  4099. SmallVectorImpl<Constant *> &EltVals, SmallVectorImpl<QualType> &EltQualTys, unsigned &EltIdx) {
  4100. if (hlsl::IsHLSLVecType(QualTy)) {
  4101. QualType VecEltQualTy = hlsl::GetHLSLVecElementType(QualTy);
  4102. unsigned VecSize = hlsl::GetHLSLVecSize(QualTy);
  4103. SmallVector<Constant *, 4> VecElts;
  4104. for (unsigned i = 0; i < VecSize; i++) {
  4105. VecElts.emplace_back(BuildConstInitializer(Types, bDefaultRowMajor,
  4106. VecEltQualTy, MemRepr,
  4107. EltVals, EltQualTys, EltIdx));
  4108. }
  4109. return llvm::ConstantVector::get(VecElts);
  4110. }
  4111. else if (const clang::ConstantArrayType *ArrayTy = Types.getContext().getAsConstantArrayType(QualTy)) {
  4112. QualType ArrayEltQualTy = QualType(ArrayTy->getArrayElementTypeNoTypeQual(), 0);
  4113. uint64_t ArraySize = ArrayTy->getSize().getLimitedValue();
  4114. SmallVector<Constant *, 4> ArrayElts;
  4115. for (unsigned i = 0; i < ArraySize; i++) {
  4116. ArrayElts.emplace_back(BuildConstInitializer(Types, bDefaultRowMajor,
  4117. ArrayEltQualTy, true, // Array elements must be in their memory representation
  4118. EltVals, EltQualTys, EltIdx));
  4119. }
  4120. return llvm::ConstantArray::get(
  4121. cast<llvm::ArrayType>(Types.ConvertTypeForMem(QualTy)), ArrayElts);
  4122. }
  4123. else if (hlsl::IsHLSLMatType(QualTy)) {
  4124. return BuildConstMatrix(Types, bDefaultRowMajor, QualTy,
  4125. EltVals, EltQualTys, EltIdx);
  4126. }
  4127. else if (QualTy->getAs<clang::RecordType>() != nullptr) {
  4128. return BuildConstStruct(Types, bDefaultRowMajor, QualTy,
  4129. EltVals, EltQualTys, EltIdx);
  4130. } else {
  4131. DXASSERT_NOMSG(QualTy->isBuiltinType());
  4132. Constant *EltVal = EltVals[EltIdx];
  4133. QualType EltQualTy = EltQualTys[EltIdx];
  4134. EltIdx++;
  4135. // Initializer constants are in their memory representation.
  4136. if (EltQualTy == QualTy && MemRepr) return EltVal;
  4137. CGBuilderTy Builder(EltVal->getContext());
  4138. if (EltQualTy->isBooleanType()) {
  4139. // Convert to register representation
  4140. // We don't have access to CodeGenFunction::EmitFromMemory here
  4141. DXASSERT_NOMSG(!EltVal->getType()->isIntegerTy(1));
  4142. EltVal = cast<Constant>(Builder.CreateICmpNE(EltVal, Constant::getNullValue(EltVal->getType())));
  4143. }
  4144. Constant *Result = cast<Constant>(ConvertScalarOrVector(Builder, Types, EltVal, EltQualTy, QualTy));
  4145. if (QualTy->isBooleanType() && MemRepr) {
  4146. // Convert back to the memory representation
  4147. // We don't have access to CodeGenFunction::EmitToMemory here
  4148. DXASSERT_NOMSG(Result->getType()->isIntegerTy(1));
  4149. Result = cast<Constant>(Builder.CreateZExt(Result, Types.ConvertTypeForMem(QualTy)));
  4150. }
  4151. return Result;
  4152. }
  4153. }
  4154. Constant *CGMSHLSLRuntime::EmitHLSLConstInitListExpr(CodeGenModule &CGM,
  4155. InitListExpr *E) {
  4156. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  4157. SmallVector<Constant *, 4> EltVals;
  4158. SmallVector<QualType, 4> EltQualTys;
  4159. if (!ScanConstInitList(CGM, bDefaultRowMajor, E, EltVals, EltQualTys))
  4160. return nullptr;
  4161. QualType QualTy = E->getType();
  4162. unsigned EltIdx = 0;
  4163. bool MemRepr = true;
  4164. return BuildConstInitializer(CGM.getTypes(), bDefaultRowMajor,
  4165. QualTy, MemRepr, EltVals, EltQualTys, EltIdx);
  4166. }
  4167. Value *CGMSHLSLRuntime::EmitHLSLMatrixOperationCall(
  4168. CodeGenFunction &CGF, const clang::Expr *E, llvm::Type *RetType,
  4169. ArrayRef<Value *> paramList) {
  4170. HLOpcodeGroup group = GetHLOpcodeGroup(E->getStmtClass());
  4171. unsigned opcode = GetHLOpcode(E);
  4172. if (group == HLOpcodeGroup::HLInit)
  4173. return EmitHLSLArrayInit(CGF.Builder, group, opcode, RetType, paramList,
  4174. TheModule);
  4175. else
  4176. return EmitHLSLMatrixOperationCallImp(CGF.Builder, group, opcode, RetType,
  4177. paramList, TheModule);
  4178. }
  4179. void CGMSHLSLRuntime::EmitHLSLDiscard(CodeGenFunction &CGF) {
  4180. EmitHLSLMatrixOperationCallImp(
  4181. CGF.Builder, HLOpcodeGroup::HLIntrinsic,
  4182. static_cast<unsigned>(IntrinsicOp::IOP_clip),
  4183. llvm::Type::getVoidTy(CGF.getLLVMContext()),
  4184. {ConstantFP::get(llvm::Type::getFloatTy(CGF.getLLVMContext()), -1.0f)},
  4185. TheModule);
  4186. }
  4187. // Emit an artificially conditionalized branch for a break operation when in a potentially wave-enabled stage
  4188. // This allows the block containing what would have been an unconditional break to be included in the loop
  4189. // If the block uses values that are wave-sensitive, it needs to stay in the loop to prevent optimizations
  4190. // that might produce incorrect results by ignoring the volatile aspect of wave operation results.
  4191. BranchInst *CGMSHLSLRuntime::EmitHLSLCondBreak(CodeGenFunction &CGF, Function *F, BasicBlock *DestBB, BasicBlock *AltBB) {
  4192. // If not a wave-enabled stage, we can keep everything unconditional as before
  4193. if (!m_pHLModule->GetShaderModel()->IsPS() && !m_pHLModule->GetShaderModel()->IsCS() &&
  4194. !m_pHLModule->GetShaderModel()->IsLib()) {
  4195. return CGF.Builder.CreateBr(DestBB);
  4196. }
  4197. // Create a branch that is temporarily conditional on a constant
  4198. // FinalizeCodeGen will turn this into a function, DxilFinalize will turn it into a global var
  4199. llvm::Type *boolTy = llvm::Type::getInt1Ty(Context);
  4200. BranchInst *BI = CGF.Builder.CreateCondBr(llvm::ConstantInt::get(boolTy,1), DestBB, AltBB);
  4201. m_DxBreaks.emplace_back(BI);
  4202. return BI;
  4203. }
  4204. static llvm::Type *MergeIntType(llvm::IntegerType *T0, llvm::IntegerType *T1) {
  4205. if (T0->getBitWidth() > T1->getBitWidth())
  4206. return T0;
  4207. else
  4208. return T1;
  4209. }
  4210. static Value *CreateExt(CGBuilderTy &Builder, Value *Src, llvm::Type *DstTy,
  4211. bool bSigned) {
  4212. if (bSigned)
  4213. return Builder.CreateSExt(Src, DstTy);
  4214. else
  4215. return Builder.CreateZExt(Src, DstTy);
  4216. }
  4217. // For integer literal, try to get lowest precision.
  4218. static Value *CalcHLSLLiteralToLowestPrecision(CGBuilderTy &Builder, Value *Src,
  4219. bool bSigned) {
  4220. if (ConstantInt *CI = dyn_cast<ConstantInt>(Src)) {
  4221. APInt v = CI->getValue();
  4222. switch (v.getActiveWords()) {
  4223. case 4:
  4224. return Builder.getInt32(v.getLimitedValue());
  4225. case 8:
  4226. return Builder.getInt64(v.getLimitedValue());
  4227. case 2:
  4228. // TODO: use low precision type when support it in dxil.
  4229. // return Builder.getInt16(v.getLimitedValue());
  4230. return Builder.getInt32(v.getLimitedValue());
  4231. case 1:
  4232. // TODO: use precision type when support it in dxil.
  4233. // return Builder.getInt8(v.getLimitedValue());
  4234. return Builder.getInt32(v.getLimitedValue());
  4235. default:
  4236. return nullptr;
  4237. }
  4238. } else if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
  4239. if (SI->getType()->isIntegerTy()) {
  4240. Value *T = SI->getTrueValue();
  4241. Value *F = SI->getFalseValue();
  4242. Value *lowT = CalcHLSLLiteralToLowestPrecision(Builder, T, bSigned);
  4243. Value *lowF = CalcHLSLLiteralToLowestPrecision(Builder, F, bSigned);
  4244. if (lowT && lowF && lowT != T && lowF != F) {
  4245. llvm::IntegerType *TTy = cast<llvm::IntegerType>(lowT->getType());
  4246. llvm::IntegerType *FTy = cast<llvm::IntegerType>(lowF->getType());
  4247. llvm::Type *Ty = MergeIntType(TTy, FTy);
  4248. if (TTy != Ty) {
  4249. lowT = CreateExt(Builder, lowT, Ty, bSigned);
  4250. }
  4251. if (FTy != Ty) {
  4252. lowF = CreateExt(Builder, lowF, Ty, bSigned);
  4253. }
  4254. Value *Cond = SI->getCondition();
  4255. return Builder.CreateSelect(Cond, lowT, lowF);
  4256. }
  4257. }
  4258. } else if (llvm::BinaryOperator *BO = dyn_cast<llvm::BinaryOperator>(Src)) {
  4259. Value *Src0 = BO->getOperand(0);
  4260. Value *Src1 = BO->getOperand(1);
  4261. Value *CastSrc0 = CalcHLSLLiteralToLowestPrecision(Builder, Src0, bSigned);
  4262. Value *CastSrc1 = CalcHLSLLiteralToLowestPrecision(Builder, Src1, bSigned);
  4263. if (Src0 != CastSrc0 && Src1 != CastSrc1 && CastSrc0 && CastSrc1 &&
  4264. CastSrc0->getType() == CastSrc1->getType()) {
  4265. llvm::IntegerType *Ty0 = cast<llvm::IntegerType>(CastSrc0->getType());
  4266. llvm::IntegerType *Ty1 = cast<llvm::IntegerType>(CastSrc0->getType());
  4267. llvm::Type *Ty = MergeIntType(Ty0, Ty1);
  4268. if (Ty0 != Ty) {
  4269. CastSrc0 = CreateExt(Builder, CastSrc0, Ty, bSigned);
  4270. }
  4271. if (Ty1 != Ty) {
  4272. CastSrc1 = CreateExt(Builder, CastSrc1, Ty, bSigned);
  4273. }
  4274. return Builder.CreateBinOp(BO->getOpcode(), CastSrc0, CastSrc1);
  4275. }
  4276. }
  4277. return nullptr;
  4278. }
  4279. Value *CGMSHLSLRuntime::EmitHLSLLiteralCast(CodeGenFunction &CGF, Value *Src,
  4280. QualType SrcType,
  4281. QualType DstType) {
  4282. auto &Builder = CGF.Builder;
  4283. llvm::Type *DstTy = CGF.ConvertType(DstType);
  4284. bool bSrcSigned = SrcType->isSignedIntegerType();
  4285. if (ConstantInt *CI = dyn_cast<ConstantInt>(Src)) {
  4286. APInt v = CI->getValue();
  4287. if (llvm::IntegerType *IT = dyn_cast<llvm::IntegerType>(DstTy)) {
  4288. v = v.trunc(IT->getBitWidth());
  4289. switch (IT->getBitWidth()) {
  4290. case 32:
  4291. return Builder.getInt32(v.getLimitedValue());
  4292. case 64:
  4293. return Builder.getInt64(v.getLimitedValue());
  4294. case 16:
  4295. return Builder.getInt16(v.getLimitedValue());
  4296. case 8:
  4297. return Builder.getInt8(v.getLimitedValue());
  4298. default:
  4299. return nullptr;
  4300. }
  4301. } else {
  4302. DXASSERT_NOMSG(DstTy->isFloatingPointTy());
  4303. int64_t val = v.getLimitedValue();
  4304. if (v.isNegative())
  4305. val = 0-v.abs().getLimitedValue();
  4306. if (DstTy->isDoubleTy())
  4307. return ConstantFP::get(DstTy, (double)val);
  4308. else if (DstTy->isFloatTy())
  4309. return ConstantFP::get(DstTy, (float)val);
  4310. else {
  4311. if (bSrcSigned)
  4312. return Builder.CreateSIToFP(Src, DstTy);
  4313. else
  4314. return Builder.CreateUIToFP(Src, DstTy);
  4315. }
  4316. }
  4317. } else if (ConstantFP *CF = dyn_cast<ConstantFP>(Src)) {
  4318. APFloat v = CF->getValueAPF();
  4319. double dv = v.convertToDouble();
  4320. if (llvm::IntegerType *IT = dyn_cast<llvm::IntegerType>(DstTy)) {
  4321. switch (IT->getBitWidth()) {
  4322. case 32:
  4323. return Builder.getInt32(dv);
  4324. case 64:
  4325. return Builder.getInt64(dv);
  4326. case 16:
  4327. return Builder.getInt16(dv);
  4328. case 8:
  4329. return Builder.getInt8(dv);
  4330. default:
  4331. return nullptr;
  4332. }
  4333. } else {
  4334. if (DstTy->isFloatTy()) {
  4335. float fv = dv;
  4336. return ConstantFP::get(DstTy->getContext(), APFloat(fv));
  4337. } else {
  4338. return Builder.CreateFPTrunc(Src, DstTy);
  4339. }
  4340. }
  4341. } else if (dyn_cast<UndefValue>(Src)) {
  4342. return UndefValue::get(DstTy);
  4343. } else {
  4344. Instruction *I = cast<Instruction>(Src);
  4345. if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
  4346. Value *T = SI->getTrueValue();
  4347. Value *F = SI->getFalseValue();
  4348. Value *Cond = SI->getCondition();
  4349. if (isa<llvm::ConstantInt>(T) && isa<llvm::ConstantInt>(F)) {
  4350. llvm::APInt lhs = cast<llvm::ConstantInt>(T)->getValue();
  4351. llvm::APInt rhs = cast<llvm::ConstantInt>(F)->getValue();
  4352. if (DstTy == Builder.getInt32Ty()) {
  4353. T = Builder.getInt32(lhs.getLimitedValue());
  4354. F = Builder.getInt32(rhs.getLimitedValue());
  4355. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  4356. return Sel;
  4357. } else if (DstTy->isFloatingPointTy()) {
  4358. T = ConstantFP::get(DstTy, int64_t(lhs.getLimitedValue()));
  4359. F = ConstantFP::get(DstTy, int64_t(rhs.getLimitedValue()));
  4360. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  4361. return Sel;
  4362. }
  4363. } else if (isa<llvm::ConstantFP>(T) && isa<llvm::ConstantFP>(F)) {
  4364. llvm::APFloat lhs = cast<llvm::ConstantFP>(T)->getValueAPF();
  4365. llvm::APFloat rhs = cast<llvm::ConstantFP>(F)->getValueAPF();
  4366. double ld = lhs.convertToDouble();
  4367. double rd = rhs.convertToDouble();
  4368. if (DstTy->isFloatTy()) {
  4369. float lf = ld;
  4370. float rf = rd;
  4371. T = ConstantFP::get(DstTy->getContext(), APFloat(lf));
  4372. F = ConstantFP::get(DstTy->getContext(), APFloat(rf));
  4373. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  4374. return Sel;
  4375. } else if (DstTy == Builder.getInt32Ty()) {
  4376. T = Builder.getInt32(ld);
  4377. F = Builder.getInt32(rd);
  4378. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  4379. return Sel;
  4380. } else if (DstTy == Builder.getInt64Ty()) {
  4381. T = Builder.getInt64(ld);
  4382. F = Builder.getInt64(rd);
  4383. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  4384. return Sel;
  4385. }
  4386. }
  4387. } else if (llvm::BinaryOperator *BO = dyn_cast<llvm::BinaryOperator>(I)) {
  4388. // For integer binary operator, do the calc on lowest precision, then cast
  4389. // to dstTy.
  4390. if (I->getType()->isIntegerTy()) {
  4391. bool bSigned = DstType->isSignedIntegerType();
  4392. Value *CastResult =
  4393. CalcHLSLLiteralToLowestPrecision(Builder, BO, bSigned);
  4394. if (!CastResult)
  4395. return nullptr;
  4396. if (dyn_cast<llvm::IntegerType>(DstTy)) {
  4397. if (DstTy == CastResult->getType()) {
  4398. return CastResult;
  4399. } else {
  4400. if (bSigned)
  4401. return Builder.CreateSExtOrTrunc(CastResult, DstTy);
  4402. else
  4403. return Builder.CreateZExtOrTrunc(CastResult, DstTy);
  4404. }
  4405. } else {
  4406. if (bSrcSigned)
  4407. return Builder.CreateSIToFP(CastResult, DstTy);
  4408. else
  4409. return Builder.CreateUIToFP(CastResult, DstTy);
  4410. }
  4411. }
  4412. }
  4413. // TODO: support other opcode if need.
  4414. return nullptr;
  4415. }
  4416. }
  4417. // For case like ((float3xfloat3)mat4x4).m21 or ((float3xfloat3)mat4x4)[1], just
  4418. // treat it like mat4x4.m21 or mat4x4[1].
  4419. static Value *GetOriginMatrixOperandAndUpdateMatSize(Value *Ptr, unsigned &row,
  4420. unsigned &col) {
  4421. if (CallInst *Mat = dyn_cast<CallInst>(Ptr)) {
  4422. HLOpcodeGroup OpcodeGroup =
  4423. GetHLOpcodeGroupByName(Mat->getCalledFunction());
  4424. if (OpcodeGroup == HLOpcodeGroup::HLCast) {
  4425. HLCastOpcode castOpcode = static_cast<HLCastOpcode>(GetHLOpcode(Mat));
  4426. if (castOpcode == HLCastOpcode::DefaultCast) {
  4427. Ptr = Mat->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  4428. // Remove the cast which is useless now.
  4429. Mat->eraseFromParent();
  4430. // Update row and col.
  4431. HLMatrixType matTy =
  4432. HLMatrixType::cast(Ptr->getType()->getPointerElementType());
  4433. row = matTy.getNumRows();
  4434. col = matTy.getNumColumns();
  4435. // Don't update RetTy and DxilGeneration pass will do the right thing.
  4436. return Ptr;
  4437. }
  4438. }
  4439. }
  4440. return nullptr;
  4441. }
  4442. Value *CGMSHLSLRuntime::EmitHLSLMatrixSubscript(CodeGenFunction &CGF,
  4443. llvm::Type *RetType,
  4444. llvm::Value *Ptr,
  4445. llvm::Value *Idx,
  4446. clang::QualType Ty) {
  4447. bool isRowMajor =
  4448. hlsl::IsHLSLMatRowMajor(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  4449. unsigned opcode =
  4450. isRowMajor ? static_cast<unsigned>(HLSubscriptOpcode::RowMatSubscript)
  4451. : static_cast<unsigned>(HLSubscriptOpcode::ColMatSubscript);
  4452. Value *matBase = Ptr;
  4453. DXASSERT(matBase->getType()->isPointerTy(),
  4454. "matrix subscript should return pointer");
  4455. RetType =
  4456. llvm::PointerType::get(RetType->getPointerElementType(),
  4457. matBase->getType()->getPointerAddressSpace());
  4458. unsigned row, col;
  4459. hlsl::GetHLSLMatRowColCount(Ty, row, col);
  4460. unsigned resultCol = col;
  4461. if (Value *OriginPtr = GetOriginMatrixOperandAndUpdateMatSize(Ptr, row, col)) {
  4462. Ptr = OriginPtr;
  4463. // Update col to result col to get correct result size.
  4464. col = resultCol;
  4465. }
  4466. // Lower mat[Idx] into real idx.
  4467. SmallVector<Value *, 8> args;
  4468. args.emplace_back(Ptr);
  4469. if (isRowMajor) {
  4470. Value *cCol = ConstantInt::get(Idx->getType(), col);
  4471. Value *Base = CGF.Builder.CreateMul(cCol, Idx);
  4472. for (unsigned i = 0; i < col; i++) {
  4473. Value *c = ConstantInt::get(Idx->getType(), i);
  4474. // r * col + c
  4475. Value *matIdx = CGF.Builder.CreateAdd(Base, c);
  4476. args.emplace_back(matIdx);
  4477. }
  4478. } else {
  4479. for (unsigned i = 0; i < col; i++) {
  4480. Value *cMulRow = ConstantInt::get(Idx->getType(), i * row);
  4481. // c * row + r
  4482. Value *matIdx = CGF.Builder.CreateAdd(cMulRow, Idx);
  4483. args.emplace_back(matIdx);
  4484. }
  4485. }
  4486. Value *matSub =
  4487. EmitHLSLMatrixOperationCallImp(CGF.Builder, HLOpcodeGroup::HLSubscript,
  4488. opcode, RetType, args, TheModule);
  4489. return matSub;
  4490. }
  4491. Value *CGMSHLSLRuntime::EmitHLSLMatrixElement(CodeGenFunction &CGF,
  4492. llvm::Type *RetType,
  4493. ArrayRef<Value *> paramList,
  4494. QualType Ty) {
  4495. bool isRowMajor =
  4496. hlsl::IsHLSLMatRowMajor(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  4497. unsigned opcode =
  4498. isRowMajor ? static_cast<unsigned>(HLSubscriptOpcode::RowMatElement)
  4499. : static_cast<unsigned>(HLSubscriptOpcode::ColMatElement);
  4500. Value *matBase = paramList[0];
  4501. DXASSERT(matBase->getType()->isPointerTy(),
  4502. "matrix element should return pointer");
  4503. RetType =
  4504. llvm::PointerType::get(RetType->getPointerElementType(),
  4505. matBase->getType()->getPointerAddressSpace());
  4506. Value *idx = paramList[HLOperandIndex::kMatSubscriptSubOpIdx-1];
  4507. // Lower _m00 into real idx.
  4508. // -1 to avoid opcode param which is added in EmitHLSLMatrixOperationCallImp.
  4509. Value *args[] = {paramList[HLOperandIndex::kMatSubscriptMatOpIdx - 1],
  4510. paramList[HLOperandIndex::kMatSubscriptSubOpIdx - 1]};
  4511. unsigned row, col;
  4512. hlsl::GetHLSLMatRowColCount(Ty, row, col);
  4513. Value *Ptr = paramList[0];
  4514. if (Value *OriginPtr = GetOriginMatrixOperandAndUpdateMatSize(Ptr, row, col)) {
  4515. args[0] = OriginPtr;
  4516. }
  4517. // For all zero idx. Still all zero idx.
  4518. if (ConstantAggregateZero *zeros = dyn_cast<ConstantAggregateZero>(idx)) {
  4519. Constant *zero = zeros->getAggregateElement((unsigned)0);
  4520. std::vector<Constant *> elts(zeros->getNumElements() >> 1, zero);
  4521. args[HLOperandIndex::kMatSubscriptSubOpIdx - 1] = ConstantVector::get(elts);
  4522. } else {
  4523. ConstantDataSequential *elts = cast<ConstantDataSequential>(idx);
  4524. unsigned count = elts->getNumElements();
  4525. std::vector<Constant *> idxs(count >> 1);
  4526. for (unsigned i = 0; i < count; i += 2) {
  4527. unsigned rowIdx = elts->getElementAsInteger(i);
  4528. unsigned colIdx = elts->getElementAsInteger(i + 1);
  4529. unsigned matIdx = 0;
  4530. if (isRowMajor) {
  4531. matIdx = rowIdx * col + colIdx;
  4532. } else {
  4533. matIdx = colIdx * row + rowIdx;
  4534. }
  4535. idxs[i >> 1] = CGF.Builder.getInt32(matIdx);
  4536. }
  4537. args[HLOperandIndex::kMatSubscriptSubOpIdx - 1] = ConstantVector::get(idxs);
  4538. }
  4539. return EmitHLSLMatrixOperationCallImp(CGF.Builder, HLOpcodeGroup::HLSubscript,
  4540. opcode, RetType, args, TheModule);
  4541. }
  4542. Value *CGMSHLSLRuntime::EmitHLSLMatrixLoad(CGBuilderTy &Builder, Value *Ptr,
  4543. QualType Ty) {
  4544. bool isRowMajor =
  4545. hlsl::IsHLSLMatRowMajor(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  4546. unsigned opcode =
  4547. isRowMajor
  4548. ? static_cast<unsigned>(HLMatLoadStoreOpcode::RowMatLoad)
  4549. : static_cast<unsigned>(HLMatLoadStoreOpcode::ColMatLoad);
  4550. Value *matVal = EmitHLSLMatrixOperationCallImp(
  4551. Builder, HLOpcodeGroup::HLMatLoadStore, opcode,
  4552. Ptr->getType()->getPointerElementType(), {Ptr}, TheModule);
  4553. if (!isRowMajor) {
  4554. // ColMatLoad will return a col major matrix.
  4555. // All matrix Value should be row major.
  4556. // Cast it to row major.
  4557. matVal = EmitHLSLMatrixOperationCallImp(
  4558. Builder, HLOpcodeGroup::HLCast,
  4559. static_cast<unsigned>(HLCastOpcode::ColMatrixToRowMatrix),
  4560. matVal->getType(), {matVal}, TheModule);
  4561. }
  4562. return matVal;
  4563. }
  4564. void CGMSHLSLRuntime::EmitHLSLMatrixStore(CGBuilderTy &Builder, Value *Val,
  4565. Value *DestPtr, QualType Ty) {
  4566. bool isRowMajor =
  4567. hlsl::IsHLSLMatRowMajor(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  4568. unsigned opcode =
  4569. isRowMajor
  4570. ? static_cast<unsigned>(HLMatLoadStoreOpcode::RowMatStore)
  4571. : static_cast<unsigned>(HLMatLoadStoreOpcode::ColMatStore);
  4572. if (!isRowMajor) {
  4573. Value *ColVal = nullptr;
  4574. // If Val is casted from col major. Just use the original col major val.
  4575. if (CallInst *CI = dyn_cast<CallInst>(Val)) {
  4576. hlsl::HLOpcodeGroup group =
  4577. hlsl::GetHLOpcodeGroupByName(CI->getCalledFunction());
  4578. if (group == HLOpcodeGroup::HLCast) {
  4579. HLCastOpcode castOp = static_cast<HLCastOpcode>(hlsl::GetHLOpcode(CI));
  4580. if (castOp == HLCastOpcode::ColMatrixToRowMatrix) {
  4581. ColVal = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  4582. }
  4583. }
  4584. }
  4585. if (ColVal) {
  4586. Val = ColVal;
  4587. } else {
  4588. // All matrix Value should be row major.
  4589. // ColMatStore need a col major value.
  4590. // Cast it to row major.
  4591. Val = EmitHLSLMatrixOperationCallImp(
  4592. Builder, HLOpcodeGroup::HLCast,
  4593. static_cast<unsigned>(HLCastOpcode::RowMatrixToColMatrix),
  4594. Val->getType(), {Val}, TheModule);
  4595. }
  4596. }
  4597. EmitHLSLMatrixOperationCallImp(Builder, HLOpcodeGroup::HLMatLoadStore, opcode,
  4598. Val->getType(), {DestPtr, Val}, TheModule);
  4599. }
  4600. bool CGMSHLSLRuntime::NeedHLSLMartrixCastForStoreOp(const clang::Decl* TD,
  4601. llvm::SmallVector<llvm::Value*, 16>& IRCallArgs) {
  4602. const clang::FunctionDecl* FD = dyn_cast<clang::FunctionDecl>(TD);
  4603. unsigned opcode = 0;
  4604. StringRef group;
  4605. if (!hlsl::GetIntrinsicOp(FD, opcode, group))
  4606. return false;
  4607. if (opcode != (unsigned)hlsl::IntrinsicOp::MOP_Store)
  4608. return false;
  4609. // Note that the store op is not yet an HL op. It's just a call
  4610. // to mangled rwbab store function. So adjust the store val position.
  4611. const unsigned storeValOpIdx = HLOperandIndex::kStoreValOpIdx - 1;
  4612. if (storeValOpIdx >= IRCallArgs.size()) {
  4613. return false;
  4614. }
  4615. return HLMatrixType::isa(IRCallArgs[storeValOpIdx]->getType());
  4616. }
  4617. void CGMSHLSLRuntime::EmitHLSLMartrixCastForStoreOp(CodeGenFunction& CGF,
  4618. SmallVector<llvm::Value*, 16>& IRCallArgs,
  4619. llvm::SmallVector<clang::QualType, 16>& ArgTys) {
  4620. // Note that the store op is not yet an HL op. It's just a call
  4621. // to mangled rwbab store function. So adjust the store val position.
  4622. const unsigned storeValOpIdx = HLOperandIndex::kStoreValOpIdx - 1;
  4623. if (storeValOpIdx >= IRCallArgs.size() ||
  4624. storeValOpIdx >= ArgTys.size()) {
  4625. return;
  4626. }
  4627. if (!hlsl::IsHLSLMatType(ArgTys[storeValOpIdx]))
  4628. return;
  4629. bool isRowMajor =
  4630. hlsl::IsHLSLMatRowMajor(ArgTys[storeValOpIdx], m_pHLModule->GetHLOptions().bDefaultRowMajor);
  4631. if (!isRowMajor) {
  4632. IRCallArgs[storeValOpIdx] = EmitHLSLMatrixOperationCallImp(
  4633. CGF.Builder, HLOpcodeGroup::HLCast,
  4634. static_cast<unsigned>(HLCastOpcode::RowMatrixToColMatrix),
  4635. IRCallArgs[storeValOpIdx]->getType(), { IRCallArgs[storeValOpIdx] }, TheModule);
  4636. }
  4637. }
  4638. Value *CGMSHLSLRuntime::EmitHLSLMatrixLoad(CodeGenFunction &CGF, Value *Ptr,
  4639. QualType Ty) {
  4640. return EmitHLSLMatrixLoad(CGF.Builder, Ptr, Ty);
  4641. }
  4642. void CGMSHLSLRuntime::EmitHLSLMatrixStore(CodeGenFunction &CGF, Value *Val,
  4643. Value *DestPtr, QualType Ty) {
  4644. EmitHLSLMatrixStore(CGF.Builder, Val, DestPtr, Ty);
  4645. }
  4646. // Copy data from srcPtr to destPtr.
  4647. static void SimplePtrCopy(Value *DestPtr, Value *SrcPtr,
  4648. ArrayRef<Value *> idxList, CGBuilderTy &Builder) {
  4649. if (idxList.size() > 1) {
  4650. DestPtr = Builder.CreateInBoundsGEP(DestPtr, idxList);
  4651. SrcPtr = Builder.CreateInBoundsGEP(SrcPtr, idxList);
  4652. }
  4653. llvm::LoadInst *ld = Builder.CreateLoad(SrcPtr);
  4654. Builder.CreateStore(ld, DestPtr);
  4655. }
  4656. // Get Element val from SrvVal with extract value.
  4657. static Value *GetEltVal(Value *SrcVal, ArrayRef<Value*> idxList,
  4658. CGBuilderTy &Builder) {
  4659. Value *Val = SrcVal;
  4660. // Skip beginning pointer type.
  4661. for (unsigned i = 1; i < idxList.size(); i++) {
  4662. ConstantInt *idx = cast<ConstantInt>(idxList[i]);
  4663. llvm::Type *Ty = Val->getType();
  4664. if (Ty->isAggregateType()) {
  4665. Val = Builder.CreateExtractValue(Val, idx->getLimitedValue());
  4666. }
  4667. }
  4668. return Val;
  4669. }
  4670. // Copy srcVal to destPtr.
  4671. static void SimpleValCopy(Value *DestPtr, Value *SrcVal,
  4672. ArrayRef<Value*> idxList,
  4673. CGBuilderTy &Builder) {
  4674. Value *DestGEP = Builder.CreateInBoundsGEP(DestPtr, idxList);
  4675. Value *Val = GetEltVal(SrcVal, idxList, Builder);
  4676. Builder.CreateStore(Val, DestGEP);
  4677. }
  4678. static void SimpleCopy(Value *Dest, Value *Src,
  4679. ArrayRef<Value *> idxList,
  4680. CGBuilderTy &Builder) {
  4681. if (Src->getType()->isPointerTy())
  4682. SimplePtrCopy(Dest, Src, idxList, Builder);
  4683. else
  4684. SimpleValCopy(Dest, Src, idxList, Builder);
  4685. }
  4686. void CGMSHLSLRuntime::FlattenAggregatePtrToGepList(
  4687. CodeGenFunction &CGF, Value *Ptr, SmallVector<Value *, 4> &idxList,
  4688. clang::QualType Type, llvm::Type *Ty, SmallVector<Value *, 4> &GepList,
  4689. SmallVector<QualType, 4> &EltTyList) {
  4690. if (llvm::PointerType *PT = dyn_cast<llvm::PointerType>(Ty)) {
  4691. Constant *idx = Constant::getIntegerValue(
  4692. IntegerType::get(Ty->getContext(), 32), APInt(32, 0));
  4693. idxList.emplace_back(idx);
  4694. FlattenAggregatePtrToGepList(CGF, Ptr, idxList, Type, PT->getElementType(),
  4695. GepList, EltTyList);
  4696. idxList.pop_back();
  4697. } else if (HLMatrixType MatTy = HLMatrixType::dyn_cast(Ty)) {
  4698. // Use matLd/St for matrix.
  4699. llvm::Type *EltTy = MatTy.getElementTypeForReg();
  4700. llvm::PointerType *EltPtrTy =
  4701. llvm::PointerType::get(EltTy, Ptr->getType()->getPointerAddressSpace());
  4702. QualType EltQualTy = hlsl::GetHLSLMatElementType(Type);
  4703. Value *matPtr = CGF.Builder.CreateInBoundsGEP(Ptr, idxList);
  4704. // Flatten matrix to elements.
  4705. for (unsigned r = 0; r < MatTy.getNumRows(); r++) {
  4706. for (unsigned c = 0; c < MatTy.getNumColumns(); c++) {
  4707. ConstantInt *cRow = CGF.Builder.getInt32(r);
  4708. ConstantInt *cCol = CGF.Builder.getInt32(c);
  4709. Constant *CV = llvm::ConstantVector::get({cRow, cCol});
  4710. GepList.push_back(
  4711. EmitHLSLMatrixElement(CGF, EltPtrTy, {matPtr, CV}, Type));
  4712. EltTyList.push_back(EltQualTy);
  4713. }
  4714. }
  4715. } else if (StructType *ST = dyn_cast<StructType>(Ty)) {
  4716. if (dxilutil::IsHLSLObjectType(ST)) {
  4717. // Avoid split HLSL object.
  4718. Value *GEP = CGF.Builder.CreateInBoundsGEP(Ptr, idxList);
  4719. GepList.push_back(GEP);
  4720. EltTyList.push_back(Type);
  4721. return;
  4722. }
  4723. const clang::RecordType *RT = Type->getAsStructureType();
  4724. RecordDecl *RD = RT->getDecl();
  4725. const CGRecordLayout &RL = CGF.getTypes().getCGRecordLayout(RD);
  4726. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  4727. if (CXXRD->getNumBases()) {
  4728. // Add base as field.
  4729. for (const auto &I : CXXRD->bases()) {
  4730. const CXXRecordDecl *BaseDecl =
  4731. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  4732. // Skip empty struct.
  4733. if (BaseDecl->field_empty())
  4734. continue;
  4735. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  4736. llvm::Type *parentType = CGF.ConvertType(parentTy);
  4737. unsigned i = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  4738. Constant *idx = llvm::Constant::getIntegerValue(
  4739. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  4740. idxList.emplace_back(idx);
  4741. FlattenAggregatePtrToGepList(CGF, Ptr, idxList, parentTy, parentType,
  4742. GepList, EltTyList);
  4743. idxList.pop_back();
  4744. }
  4745. }
  4746. }
  4747. for (auto fieldIter = RD->field_begin(), fieldEnd = RD->field_end();
  4748. fieldIter != fieldEnd; ++fieldIter) {
  4749. unsigned i = RL.getLLVMFieldNo(*fieldIter);
  4750. llvm::Type *ET = ST->getElementType(i);
  4751. Constant *idx = llvm::Constant::getIntegerValue(
  4752. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  4753. idxList.emplace_back(idx);
  4754. FlattenAggregatePtrToGepList(CGF, Ptr, idxList, fieldIter->getType(), ET,
  4755. GepList, EltTyList);
  4756. idxList.pop_back();
  4757. }
  4758. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty)) {
  4759. llvm::Type *ET = AT->getElementType();
  4760. QualType EltType = CGF.getContext().getBaseElementType(Type);
  4761. for (uint32_t i = 0; i < AT->getNumElements(); i++) {
  4762. Constant *idx = Constant::getIntegerValue(
  4763. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  4764. idxList.emplace_back(idx);
  4765. FlattenAggregatePtrToGepList(CGF, Ptr, idxList, EltType, ET, GepList,
  4766. EltTyList);
  4767. idxList.pop_back();
  4768. }
  4769. } else if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(Ty)) {
  4770. // Flatten vector too.
  4771. QualType EltTy = hlsl::GetHLSLVecElementType(Type);
  4772. for (uint32_t i = 0; i < VT->getNumElements(); i++) {
  4773. Constant *idx = CGF.Builder.getInt32(i);
  4774. idxList.emplace_back(idx);
  4775. Value *GEP = CGF.Builder.CreateInBoundsGEP(Ptr, idxList);
  4776. GepList.push_back(GEP);
  4777. EltTyList.push_back(EltTy);
  4778. idxList.pop_back();
  4779. }
  4780. } else {
  4781. Value *GEP = CGF.Builder.CreateInBoundsGEP(Ptr, idxList);
  4782. GepList.push_back(GEP);
  4783. EltTyList.push_back(Type);
  4784. }
  4785. }
  4786. void CGMSHLSLRuntime::LoadElements(CodeGenFunction &CGF,
  4787. ArrayRef<Value *> Ptrs, ArrayRef<QualType> QualTys,
  4788. SmallVector<Value *, 4> &Vals) {
  4789. for (size_t i = 0, e = Ptrs.size(); i < e; i++) {
  4790. Value *Ptr = Ptrs[i];
  4791. llvm::Type *Ty = Ptr->getType()->getPointerElementType();
  4792. DXASSERT_LOCALVAR(Ty, Ty->isIntegerTy() || Ty->isFloatingPointTy(), "Expected only element types.");
  4793. Value *Val = CGF.Builder.CreateLoad(Ptr);
  4794. Val = CGF.EmitFromMemory(Val, QualTys[i]);
  4795. Vals.push_back(Val);
  4796. }
  4797. }
  4798. void CGMSHLSLRuntime::ConvertAndStoreElements(CodeGenFunction &CGF,
  4799. ArrayRef<Value *> SrcVals, ArrayRef<QualType> SrcQualTys,
  4800. ArrayRef<Value *> DstPtrs, ArrayRef<QualType> DstQualTys) {
  4801. for (size_t i = 0, e = DstPtrs.size(); i < e; i++) {
  4802. Value *DstPtr = DstPtrs[i];
  4803. QualType DstQualTy = DstQualTys[i];
  4804. Value *SrcVal = SrcVals[i];
  4805. QualType SrcQualTy = SrcQualTys[i];
  4806. DXASSERT(SrcVal->getType()->isIntegerTy() || SrcVal->getType()->isFloatingPointTy(),
  4807. "Expected only element types.");
  4808. llvm::Value *Result = ConvertScalarOrVector(CGF, SrcVal, SrcQualTy, DstQualTy);
  4809. Result = CGF.EmitToMemory(Result, DstQualTy);
  4810. CGF.Builder.CreateStore(Result, DstPtr);
  4811. }
  4812. }
  4813. static bool AreMatrixArrayOrientationMatching(ASTContext& Context,
  4814. HLModule &Module, QualType LhsTy, QualType RhsTy) {
  4815. while (const clang::ArrayType *LhsArrayTy = Context.getAsArrayType(LhsTy)) {
  4816. LhsTy = LhsArrayTy->getElementType();
  4817. RhsTy = Context.getAsArrayType(RhsTy)->getElementType();
  4818. }
  4819. bool LhsRowMajor, RhsRowMajor;
  4820. LhsRowMajor = RhsRowMajor = Module.GetHLOptions().bDefaultRowMajor;
  4821. HasHLSLMatOrientation(LhsTy, &LhsRowMajor);
  4822. HasHLSLMatOrientation(RhsTy, &RhsRowMajor);
  4823. return LhsRowMajor == RhsRowMajor;
  4824. }
  4825. static llvm::Value *CreateInBoundsGEPIfNeeded(llvm::Value *Ptr, ArrayRef<Value*> IdxList, CGBuilderTy &Builder) {
  4826. DXASSERT(IdxList.size() > 0, "Invalid empty GEP index list");
  4827. // If the GEP list is a single zero, it's a no-op, so save us the trouble.
  4828. if (IdxList.size() == 1) {
  4829. if (ConstantInt *FirstIdx = dyn_cast<ConstantInt>(IdxList[0])) {
  4830. if (FirstIdx->isZero()) return Ptr;
  4831. }
  4832. }
  4833. return Builder.CreateInBoundsGEP(Ptr, IdxList);
  4834. }
  4835. // Copy data from SrcPtr to DestPtr.
  4836. // For matrix, use MatLoad/MatStore.
  4837. // For matrix array, EmitHLSLAggregateCopy on each element.
  4838. // For struct or array, use memcpy.
  4839. // Other just load/store.
  4840. void CGMSHLSLRuntime::EmitHLSLAggregateCopy(
  4841. CodeGenFunction &CGF, llvm::Value *SrcPtr, llvm::Value *DestPtr,
  4842. SmallVector<Value *, 4> &idxList, clang::QualType SrcType,
  4843. clang::QualType DestType, llvm::Type *Ty) {
  4844. if (llvm::PointerType *PT = dyn_cast<llvm::PointerType>(Ty)) {
  4845. Constant *idx = Constant::getIntegerValue(
  4846. IntegerType::get(Ty->getContext(), 32), APInt(32, 0));
  4847. idxList.emplace_back(idx);
  4848. EmitHLSLAggregateCopy(CGF, SrcPtr, DestPtr, idxList, SrcType, DestType,
  4849. PT->getElementType());
  4850. idxList.pop_back();
  4851. } else if (HLMatrixType::isa(Ty)) {
  4852. // Use matLd/St for matrix.
  4853. Value *SrcMatPtr = CreateInBoundsGEPIfNeeded(SrcPtr, idxList, CGF.Builder);
  4854. Value *DestMatPtr = CreateInBoundsGEPIfNeeded(DestPtr, idxList, CGF.Builder);
  4855. Value *ldMat = EmitHLSLMatrixLoad(CGF, SrcMatPtr, SrcType);
  4856. EmitHLSLMatrixStore(CGF, ldMat, DestMatPtr, DestType);
  4857. } else if (StructType *ST = dyn_cast<StructType>(Ty)) {
  4858. if (dxilutil::IsHLSLObjectType(ST)) {
  4859. // Avoid split HLSL object.
  4860. SimpleCopy(DestPtr, SrcPtr, idxList, CGF.Builder);
  4861. return;
  4862. }
  4863. Value *SrcStructPtr = CreateInBoundsGEPIfNeeded(SrcPtr, idxList, CGF.Builder);
  4864. Value *DestStructPtr = CreateInBoundsGEPIfNeeded(DestPtr, idxList, CGF.Builder);
  4865. unsigned size = this->TheModule.getDataLayout().getTypeAllocSize(ST);
  4866. // Memcpy struct.
  4867. CGF.Builder.CreateMemCpy(DestStructPtr, SrcStructPtr, size, 1);
  4868. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty)) {
  4869. if (!HLMatrixType::isMatrixArray(Ty)
  4870. || AreMatrixArrayOrientationMatching(CGF.getContext(), *m_pHLModule, SrcType, DestType)) {
  4871. Value *SrcArrayPtr = CreateInBoundsGEPIfNeeded(SrcPtr, idxList, CGF.Builder);
  4872. Value *DestArrayPtr = CreateInBoundsGEPIfNeeded(DestPtr, idxList, CGF.Builder);
  4873. unsigned size = this->TheModule.getDataLayout().getTypeAllocSize(AT);
  4874. // Memcpy non-matrix array.
  4875. CGF.Builder.CreateMemCpy(DestArrayPtr, SrcArrayPtr, size, 1);
  4876. } else {
  4877. // Copy matrix arrays elementwise if orientation changes are needed.
  4878. llvm::Type *ET = AT->getElementType();
  4879. QualType EltDestType = CGF.getContext().getBaseElementType(DestType);
  4880. QualType EltSrcType = CGF.getContext().getBaseElementType(SrcType);
  4881. for (uint32_t i = 0; i < AT->getNumElements(); i++) {
  4882. Constant *idx = Constant::getIntegerValue(
  4883. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  4884. idxList.emplace_back(idx);
  4885. EmitHLSLAggregateCopy(CGF, SrcPtr, DestPtr, idxList, EltSrcType,
  4886. EltDestType, ET);
  4887. idxList.pop_back();
  4888. }
  4889. }
  4890. } else {
  4891. SimpleCopy(DestPtr, SrcPtr, idxList, CGF.Builder);
  4892. }
  4893. }
  4894. void CGMSHLSLRuntime::EmitHLSLAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  4895. llvm::Value *DestPtr,
  4896. clang::QualType Ty) {
  4897. SmallVector<Value *, 4> idxList;
  4898. EmitHLSLAggregateCopy(CGF, SrcPtr, DestPtr, idxList, Ty, Ty, SrcPtr->getType());
  4899. }
  4900. // Make sure all element type of struct is same type.
  4901. static bool IsStructWithSameElementType(llvm::StructType *ST, llvm::Type *Ty) {
  4902. for (llvm::Type *EltTy : ST->elements()) {
  4903. if (StructType *EltSt = dyn_cast<StructType>(EltTy)) {
  4904. if (!IsStructWithSameElementType(EltSt, Ty))
  4905. return false;
  4906. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(EltTy)) {
  4907. llvm::Type *ArrayEltTy = dxilutil::GetArrayEltTy(AT);
  4908. if (ArrayEltTy == Ty) {
  4909. continue;
  4910. } else if (StructType *EltSt = dyn_cast<StructType>(EltTy)) {
  4911. if (!IsStructWithSameElementType(EltSt, Ty))
  4912. return false;
  4913. } else {
  4914. return false;
  4915. }
  4916. } else if (EltTy != Ty)
  4917. return false;
  4918. }
  4919. return true;
  4920. }
  4921. // To memcpy, need element type match.
  4922. // For struct type, the layout should match in cbuffer layout.
  4923. // struct { float2 x; float3 y; } will not match struct { float3 x; float2 y; }.
  4924. // struct { float2 x; float3 y; } will not match array of float.
  4925. static bool IsTypeMatchForMemcpy(llvm::Type *SrcTy, llvm::Type *DestTy) {
  4926. llvm::Type *SrcEltTy = dxilutil::GetArrayEltTy(SrcTy);
  4927. llvm::Type *DestEltTy = dxilutil::GetArrayEltTy(DestTy);
  4928. if (SrcEltTy == DestEltTy)
  4929. return true;
  4930. llvm::StructType *SrcST = dyn_cast<llvm::StructType>(SrcEltTy);
  4931. llvm::StructType *DestST = dyn_cast<llvm::StructType>(DestEltTy);
  4932. if (SrcST && DestST) {
  4933. // Only allow identical struct.
  4934. return SrcST->isLayoutIdentical(DestST);
  4935. } else if (!SrcST && !DestST) {
  4936. // For basic type, if one is array, one is not array, layout is different.
  4937. // If both array, type mismatch. If both basic, copy should be fine.
  4938. // So all return false.
  4939. return false;
  4940. } else {
  4941. // One struct, one basic type.
  4942. // Make sure all struct element match the basic type and basic type is
  4943. // vector4.
  4944. llvm::StructType *ST = SrcST ? SrcST : DestST;
  4945. llvm::Type *Ty = SrcST ? DestEltTy : SrcEltTy;
  4946. if (!Ty->isVectorTy())
  4947. return false;
  4948. if (Ty->getVectorNumElements() != 4)
  4949. return false;
  4950. return IsStructWithSameElementType(ST, Ty);
  4951. }
  4952. }
  4953. static bool IsVec4ArrayToScalarArrayForMemcpy(llvm::Type *SrcTy, llvm::Type *DestTy, const DataLayout &DL) {
  4954. if (!SrcTy->isArrayTy())
  4955. return false;
  4956. llvm::Type *SrcEltTy = dxilutil::GetArrayEltTy(SrcTy);
  4957. llvm::Type *DestEltTy = dxilutil::GetArrayEltTy(DestTy);
  4958. if (SrcEltTy == DestEltTy)
  4959. return true;
  4960. llvm::VectorType *VT = dyn_cast<llvm::VectorType>(SrcEltTy);
  4961. if (!VT)
  4962. return false;
  4963. if (DL.getTypeSizeInBits(VT) != 128)
  4964. return false;
  4965. if (DL.getTypeSizeInBits(DestEltTy) < 32)
  4966. return false;
  4967. return VT->getElementType() == DestEltTy;
  4968. }
  4969. void CGMSHLSLRuntime::EmitHLSLFlatConversionAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  4970. clang::QualType SrcTy,
  4971. llvm::Value *DestPtr,
  4972. clang::QualType DestTy) {
  4973. llvm::Type *SrcPtrTy = SrcPtr->getType()->getPointerElementType();
  4974. llvm::Type *DestPtrTy = DestPtr->getType()->getPointerElementType();
  4975. const DataLayout &DL = TheModule.getDataLayout();
  4976. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  4977. if (SrcPtrTy == DestPtrTy) {
  4978. bool bMatArrayRotate = false;
  4979. if (HLMatrixType::isMatrixArrayPtr(SrcPtr->getType())) {
  4980. QualType SrcEltTy = GetArrayEltType(CGM.getContext(), SrcTy);
  4981. QualType DestEltTy = GetArrayEltType(CGM.getContext(), DestTy);
  4982. if (GetMatrixMajor(SrcEltTy, bDefaultRowMajor) !=
  4983. GetMatrixMajor(DestEltTy, bDefaultRowMajor)) {
  4984. bMatArrayRotate = true;
  4985. }
  4986. }
  4987. if (!bMatArrayRotate) {
  4988. // Memcpy if type is match.
  4989. unsigned size = DL.getTypeAllocSize(SrcPtrTy);
  4990. CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, size, 1);
  4991. return;
  4992. }
  4993. } else if (dxilutil::IsHLSLResourceDescType(SrcPtrTy) &&
  4994. (dxilutil::IsHLSLResourceType(DestPtrTy) ||
  4995. GetResourceClassForType(CGM.getContext(), DestTy) ==
  4996. DXIL::ResourceClass::CBuffer)) {
  4997. // Cast resource desc to resource.// Make sure to generate Inst to help lowering.
  4998. bool originAllowFolding = CGF.Builder.AllowFolding;
  4999. CGF.Builder.AllowFolding = false;
  5000. Value *CastPtr = CGF.Builder.CreatePointerCast(SrcPtr, DestPtr->getType());
  5001. CGF.Builder.AllowFolding = originAllowFolding;
  5002. // Load resource.
  5003. Value *V = CGF.Builder.CreateLoad(CastPtr);
  5004. // Store to resource ptr.
  5005. CGF.Builder.CreateStore(V, DestPtr);
  5006. return;
  5007. } else if (GetResourceClassForType(CGM.getContext(), SrcTy) ==
  5008. DXIL::ResourceClass::CBuffer) {
  5009. llvm::Type *ResultTy =
  5010. CGM.getTypes().ConvertType(hlsl::GetHLSLResourceResultType(SrcTy));
  5011. if (ResultTy == DestPtrTy) {
  5012. // Cast ConstantBuffer to result type then copy.
  5013. Value *Cast = CGF.Builder.CreateBitCast(
  5014. SrcPtr,
  5015. ResultTy->getPointerTo(DestPtr->getType()->getPointerAddressSpace()));
  5016. unsigned size = DL.getTypeAllocSize(
  5017. DestPtrTy);
  5018. CGF.Builder.CreateMemCpy(DestPtr, Cast, size, 1);
  5019. return;
  5020. }
  5021. } else if (dxilutil::IsHLSLObjectType(dxilutil::GetArrayEltTy(SrcPtrTy)) &&
  5022. dxilutil::IsHLSLObjectType(dxilutil::GetArrayEltTy(DestPtrTy))) {
  5023. unsigned sizeSrc = DL.getTypeAllocSize(SrcPtrTy);
  5024. unsigned sizeDest = DL.getTypeAllocSize(DestPtrTy);
  5025. CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, std::max(sizeSrc, sizeDest), 1);
  5026. return;
  5027. } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(DestPtr)) {
  5028. if (GV->isInternalLinkage(GV->getLinkage()) &&
  5029. IsTypeMatchForMemcpy(SrcPtrTy, DestPtrTy)) {
  5030. unsigned sizeSrc = DL.getTypeAllocSize(SrcPtrTy);
  5031. unsigned sizeDest = DL.getTypeAllocSize(DestPtrTy);
  5032. CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, std::min(sizeSrc, sizeDest), 1);
  5033. return;
  5034. } else if (GlobalVariable *SrcGV = dyn_cast<GlobalVariable>(SrcPtr)) {
  5035. if (GV->isInternalLinkage(GV->getLinkage()) &&
  5036. m_ConstVarAnnotationMap.count(SrcGV) &&
  5037. IsVec4ArrayToScalarArrayForMemcpy(SrcPtrTy, DestPtrTy, DL)) {
  5038. unsigned sizeSrc = DL.getTypeAllocSize(SrcPtrTy);
  5039. unsigned sizeDest = DL.getTypeAllocSize(DestPtrTy);
  5040. if (sizeSrc == sizeDest) {
  5041. CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, sizeSrc, 1);
  5042. return;
  5043. }
  5044. }
  5045. }
  5046. }
  5047. // It is possible to implement EmitHLSLAggregateCopy, EmitHLSLAggregateStore
  5048. // the same way. But split value to scalar will generate many instruction when
  5049. // src type is same as dest type.
  5050. SmallVector<Value *, 4> GEPIdxStack;
  5051. SmallVector<Value *, 4> SrcPtrs;
  5052. SmallVector<QualType, 4> SrcQualTys;
  5053. FlattenAggregatePtrToGepList(CGF, SrcPtr, GEPIdxStack, SrcTy, SrcPtr->getType(),
  5054. SrcPtrs, SrcQualTys);
  5055. SmallVector<Value *, 4> SrcVals;
  5056. LoadElements(CGF, SrcPtrs, SrcQualTys, SrcVals);
  5057. GEPIdxStack.clear();
  5058. SmallVector<Value *, 4> DstPtrs;
  5059. SmallVector<QualType, 4> DstQualTys;
  5060. FlattenAggregatePtrToGepList(CGF, DestPtr, GEPIdxStack, DestTy,
  5061. DestPtr->getType(), DstPtrs, DstQualTys);
  5062. ConvertAndStoreElements(CGF, SrcVals, SrcQualTys, DstPtrs, DstQualTys);
  5063. }
  5064. void CGMSHLSLRuntime::EmitHLSLAggregateStore(CodeGenFunction &CGF, llvm::Value *SrcVal,
  5065. llvm::Value *DestPtr,
  5066. clang::QualType Ty) {
  5067. DXASSERT(0, "aggregate return type will use SRet, no aggregate store should exist");
  5068. }
  5069. // Either copies a scalar to a scalar, a scalar to a vector, or splats a scalar to a vector
  5070. static void SimpleFlatValCopy(CodeGenFunction &CGF,
  5071. Value *SrcVal, QualType SrcQualTy, Value *DstPtr, QualType DstQualTy) {
  5072. DXASSERT(SrcVal->getType() == CGF.ConvertType(SrcQualTy), "QualType/Type mismatch!");
  5073. llvm::Type *DstTy = DstPtr->getType()->getPointerElementType();
  5074. DXASSERT(DstTy == CGF.ConvertTypeForMem(DstQualTy), "QualType/Type mismatch!");
  5075. llvm::VectorType *DstVecTy = dyn_cast<llvm::VectorType>(DstTy);
  5076. QualType DstScalarQualTy = DstQualTy;
  5077. if (DstVecTy) {
  5078. DstScalarQualTy = hlsl::GetHLSLVecElementType(DstQualTy);
  5079. }
  5080. Value *ResultScalar = ConvertScalarOrVector(CGF, SrcVal, SrcQualTy, DstScalarQualTy);
  5081. ResultScalar = CGF.EmitToMemory(ResultScalar, DstScalarQualTy);
  5082. if (DstVecTy) {
  5083. llvm::VectorType *DstScalarVecTy = llvm::VectorType::get(ResultScalar->getType(), 1);
  5084. Value *ResultScalarVec = CGF.Builder.CreateInsertElement(
  5085. UndefValue::get(DstScalarVecTy), ResultScalar, (uint64_t)0);
  5086. std::vector<int> ShufIdx(DstVecTy->getNumElements(), 0);
  5087. Value *ResultVec = CGF.Builder.CreateShuffleVector(ResultScalarVec, ResultScalarVec, ShufIdx);
  5088. CGF.Builder.CreateStore(ResultVec, DstPtr);
  5089. } else
  5090. CGF.Builder.CreateStore(ResultScalar, DstPtr);
  5091. }
  5092. void CGMSHLSLRuntime::EmitHLSLSplat(
  5093. CodeGenFunction &CGF, Value *SrcVal, llvm::Value *DestPtr,
  5094. SmallVector<Value *, 4> &idxList, QualType Type, QualType SrcType,
  5095. llvm::Type *Ty) {
  5096. if (llvm::PointerType *PT = dyn_cast<llvm::PointerType>(Ty)) {
  5097. idxList.emplace_back(CGF.Builder.getInt32(0));
  5098. EmitHLSLSplat(CGF, SrcVal, DestPtr, idxList, Type,
  5099. SrcType, PT->getElementType());
  5100. idxList.pop_back();
  5101. } else if (HLMatrixType MatTy = HLMatrixType::dyn_cast(Ty)) {
  5102. // Use matLd/St for matrix.
  5103. Value *dstGEP = CGF.Builder.CreateInBoundsGEP(DestPtr, idxList);
  5104. llvm::Type *EltTy = MatTy.getElementTypeForReg();
  5105. llvm::VectorType *VT1 = llvm::VectorType::get(EltTy, 1);
  5106. SrcVal = ConvertScalarOrVector(CGF, SrcVal, SrcType, hlsl::GetHLSLMatElementType(Type));
  5107. // Splat the value
  5108. Value *V1 = CGF.Builder.CreateInsertElement(UndefValue::get(VT1), SrcVal,
  5109. (uint64_t)0);
  5110. std::vector<int> shufIdx(MatTy.getNumElements(), 0);
  5111. Value *VecMat = CGF.Builder.CreateShuffleVector(V1, V1, shufIdx);
  5112. Value *MatInit = EmitHLSLMatrixOperationCallImp(
  5113. CGF.Builder, HLOpcodeGroup::HLInit, 0, Ty, {VecMat}, TheModule);
  5114. EmitHLSLMatrixStore(CGF, MatInit, dstGEP, Type);
  5115. } else if (StructType *ST = dyn_cast<StructType>(Ty)) {
  5116. DXASSERT(!dxilutil::IsHLSLObjectType(ST), "cannot cast to hlsl object, Sema should reject");
  5117. const clang::RecordType *RT = Type->getAsStructureType();
  5118. RecordDecl *RD = RT->getDecl();
  5119. const CGRecordLayout &RL = CGF.getTypes().getCGRecordLayout(RD);
  5120. // Take care base.
  5121. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  5122. if (CXXRD->getNumBases()) {
  5123. for (const auto &I : CXXRD->bases()) {
  5124. const CXXRecordDecl *BaseDecl =
  5125. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  5126. if (BaseDecl->field_empty())
  5127. continue;
  5128. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  5129. unsigned i = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  5130. llvm::Type *ET = ST->getElementType(i);
  5131. Constant *idx = llvm::Constant::getIntegerValue(
  5132. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  5133. idxList.emplace_back(idx);
  5134. EmitHLSLSplat(CGF, SrcVal, DestPtr, idxList, parentTy, SrcType, ET);
  5135. idxList.pop_back();
  5136. }
  5137. }
  5138. }
  5139. for (auto fieldIter = RD->field_begin(), fieldEnd = RD->field_end();
  5140. fieldIter != fieldEnd; ++fieldIter) {
  5141. unsigned i = RL.getLLVMFieldNo(*fieldIter);
  5142. llvm::Type *ET = ST->getElementType(i);
  5143. Constant *idx = llvm::Constant::getIntegerValue(
  5144. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  5145. idxList.emplace_back(idx);
  5146. EmitHLSLSplat(CGF, SrcVal, DestPtr, idxList, fieldIter->getType(), SrcType, ET);
  5147. idxList.pop_back();
  5148. }
  5149. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty)) {
  5150. llvm::Type *ET = AT->getElementType();
  5151. QualType EltType = CGF.getContext().getBaseElementType(Type);
  5152. for (uint32_t i = 0; i < AT->getNumElements(); i++) {
  5153. Constant *idx = Constant::getIntegerValue(
  5154. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  5155. idxList.emplace_back(idx);
  5156. EmitHLSLSplat(CGF, SrcVal, DestPtr, idxList, EltType, SrcType, ET);
  5157. idxList.pop_back();
  5158. }
  5159. } else {
  5160. DestPtr = CGF.Builder.CreateInBoundsGEP(DestPtr, idxList);
  5161. SimpleFlatValCopy(CGF, SrcVal, SrcType, DestPtr, Type);
  5162. }
  5163. }
  5164. void CGMSHLSLRuntime::EmitHLSLFlatConversion(CodeGenFunction &CGF,
  5165. Value *Val,
  5166. Value *DestPtr,
  5167. QualType Ty,
  5168. QualType SrcTy) {
  5169. SmallVector<Value *, 4> SrcVals;
  5170. SmallVector<QualType, 4> SrcQualTys;
  5171. FlattenValToInitList(CGF, SrcVals, SrcQualTys, SrcTy, Val);
  5172. if (SrcVals.size() == 1) {
  5173. // Perform a splat
  5174. SmallVector<Value *, 4> GEPIdxStack;
  5175. GEPIdxStack.emplace_back(CGF.Builder.getInt32(0)); // Add first 0 for DestPtr.
  5176. EmitHLSLSplat(
  5177. CGF, SrcVals[0], DestPtr, GEPIdxStack, Ty, SrcQualTys[0],
  5178. DestPtr->getType()->getPointerElementType());
  5179. }
  5180. else {
  5181. SmallVector<Value *, 4> GEPIdxStack;
  5182. SmallVector<Value *, 4> DstPtrs;
  5183. SmallVector<QualType, 4> DstQualTys;
  5184. FlattenAggregatePtrToGepList(CGF, DestPtr, GEPIdxStack, Ty, DestPtr->getType(), DstPtrs, DstQualTys);
  5185. ConvertAndStoreElements(CGF, SrcVals, SrcQualTys, DstPtrs, DstQualTys);
  5186. }
  5187. }
  5188. void CGMSHLSLRuntime::EmitHLSLRootSignature(CodeGenFunction &CGF,
  5189. HLSLRootSignatureAttr *RSA,
  5190. Function *Fn) {
  5191. // Only parse root signature for entry function.
  5192. if (Fn != Entry.Func)
  5193. return;
  5194. StringRef StrRef = RSA->getSignatureName();
  5195. DiagnosticsEngine &Diags = CGF.getContext().getDiagnostics();
  5196. SourceLocation SLoc = RSA->getLocation();
  5197. RootSignatureHandle RootSigHandle;
  5198. clang::CompileRootSignature(StrRef, Diags, SLoc, rootSigVer, DxilRootSignatureCompilationFlags::GlobalRootSignature, &RootSigHandle);
  5199. if (!RootSigHandle.IsEmpty()) {
  5200. RootSigHandle.EnsureSerializedAvailable();
  5201. m_pHLModule->SetSerializedRootSignature(RootSigHandle.GetSerializedBytes(),
  5202. RootSigHandle.GetSerializedSize());
  5203. }
  5204. }
  5205. void CGMSHLSLRuntime::EmitHLSLOutParamConversionInit(
  5206. CodeGenFunction &CGF, const FunctionDecl *FD, const CallExpr *E,
  5207. llvm::SmallVector<LValue, 8> &castArgList,
  5208. llvm::SmallVector<const Stmt *, 8> &argList,
  5209. llvm::SmallVector<LValue, 8> &lifetimeCleanupList,
  5210. const std::function<void(const VarDecl *, llvm::Value *)> &TmpArgMap) {
  5211. // Special case: skip first argument of CXXOperatorCall (it is "this").
  5212. unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(E) ? 1 : 0;
  5213. for (uint32_t i = 0; i < FD->getNumParams(); i++) {
  5214. const ParmVarDecl *Param = FD->getParamDecl(i);
  5215. const Expr *Arg = E->getArg(i+ArgsToSkip);
  5216. QualType ParamTy = Param->getType().getNonReferenceType();
  5217. bool isObject = dxilutil::IsHLSLObjectType(CGF.ConvertTypeForMem(ParamTy));
  5218. bool isVector = hlsl::IsHLSLVecType(ParamTy);
  5219. bool isArray = ParamTy->isArrayType();
  5220. // Check for array of matrix
  5221. QualType ParamElTy = ParamTy;
  5222. while (ParamElTy->isArrayType())
  5223. ParamElTy = ParamElTy->getAsArrayTypeUnsafe()->getElementType();
  5224. bool isMatrix = hlsl::IsHLSLMatType(ParamElTy);
  5225. bool isAggregateType = !isObject &&
  5226. (isArray || (ParamTy->isRecordType() && !(isMatrix || isVector)));
  5227. bool EmitRValueAgg = false;
  5228. bool RValOnRef = false;
  5229. if (!Param->isModifierOut()) {
  5230. if (!isAggregateType && !isObject) {
  5231. if (Arg->isRValue() && Param->getType()->isReferenceType()) {
  5232. // RValue on a reference type.
  5233. if (const CStyleCastExpr *cCast = dyn_cast<CStyleCastExpr>(Arg)) {
  5234. // TODO: Evolving this to warn then fail in future language versions.
  5235. // Allow special case like cast uint to uint for back-compat.
  5236. if (cCast->getCastKind() == CastKind::CK_NoOp) {
  5237. if (const ImplicitCastExpr *cast =
  5238. dyn_cast<ImplicitCastExpr>(cCast->getSubExpr())) {
  5239. if (cast->getCastKind() == CastKind::CK_LValueToRValue) {
  5240. // update the arg
  5241. argList[i] = cast->getSubExpr();
  5242. continue;
  5243. }
  5244. }
  5245. }
  5246. }
  5247. // EmitLValue will report error.
  5248. // Mark RValOnRef to create tmpArg for it.
  5249. RValOnRef = true;
  5250. } else {
  5251. continue;
  5252. }
  5253. } else if (isAggregateType) {
  5254. // aggregate in-only - emit RValue, unless LValueToRValue cast
  5255. EmitRValueAgg = true;
  5256. if (const ImplicitCastExpr *cast =
  5257. dyn_cast<ImplicitCastExpr>(Arg)) {
  5258. if (cast->getCastKind() == CastKind::CK_LValueToRValue) {
  5259. EmitRValueAgg = false;
  5260. }
  5261. }
  5262. } else {
  5263. // Must be object
  5264. DXASSERT(isObject, "otherwise, flow condition changed, breaking assumption");
  5265. // in-only objects should be skipped to preserve previous behavior.
  5266. continue;
  5267. }
  5268. }
  5269. // Skip unbounded array, since we cannot preserve copy-in copy-out
  5270. // semantics for these.
  5271. if (ParamTy->isIncompleteArrayType()) {
  5272. continue;
  5273. }
  5274. if (!Param->isModifierOut() && !RValOnRef) {
  5275. // No need to copy arg to in-only param for hlsl intrinsic.
  5276. if (const FunctionDecl *Callee = E->getDirectCallee()) {
  5277. if (Callee->hasAttr<HLSLIntrinsicAttr>())
  5278. continue;
  5279. }
  5280. }
  5281. // get original arg
  5282. // FIXME: This will not emit in correct argument order with the other
  5283. // arguments. This should be integrated into
  5284. // CodeGenFunction::EmitCallArg if possible.
  5285. RValue argRV; // emit this if aggregate arg on in-only param
  5286. LValue argLV; // otherwise, we may emit this
  5287. llvm::Value *argAddr = nullptr;
  5288. QualType argType = Arg->getType();
  5289. CharUnits argAlignment;
  5290. if (EmitRValueAgg) {
  5291. argRV = CGF.EmitAnyExprToTemp(Arg);
  5292. argAddr = argRV.getAggregateAddr(); // must be alloca
  5293. argAlignment = CharUnits::fromQuantity(cast<AllocaInst>(argAddr)->getAlignment());
  5294. argLV = LValue::MakeAddr(argAddr, ParamTy, argAlignment, CGF.getContext());
  5295. } else {
  5296. argLV = CGF.EmitLValue(Arg);
  5297. if (argLV.isSimple())
  5298. argAddr = argLV.getAddress();
  5299. bool mustCopy = false;
  5300. // If matrix orientation changes, we must copy here
  5301. // TODO: A high level intrinsic for matrix array copy with orientation
  5302. // change would be much easier to optimize/eliminate at high level
  5303. // after inline.
  5304. if (!mustCopy && isMatrix) {
  5305. mustCopy = !AreMatrixArrayOrientationMatching(
  5306. CGF.getContext(), *m_pHLModule, argType, ParamTy);
  5307. }
  5308. if (!mustCopy) {
  5309. // When there's argument need to lower like buffer/cbuffer load, need to
  5310. // copy to let the lower not happen on argument when calle is noinline
  5311. // or extern functions. Will do it in HLLegalizeParameter after known
  5312. // which functions are extern but before inline.
  5313. bool bConstGlobal = false;
  5314. Value *Ptr = argAddr;
  5315. while (GEPOperator *GEP = dyn_cast_or_null<GEPOperator>(Ptr)) {
  5316. Ptr = GEP->getPointerOperand();
  5317. }
  5318. if (GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(Ptr)) {
  5319. bConstGlobal = m_ConstVarAnnotationMap.count(GV) | GV->isConstant();
  5320. }
  5321. // Skip copy-in copy-out when safe.
  5322. // The unsafe case will be global variable alias with parameter.
  5323. // Then global variable is updated in the function, the parameter will
  5324. // be updated silently. For non global variable or constant global
  5325. // variable, it should be safe.
  5326. if (argAddr &&
  5327. (isa<AllocaInst>(Ptr) || isa<Argument>(Ptr) || bConstGlobal)) {
  5328. llvm::Type *ToTy = CGF.ConvertType(ParamTy.getNonReferenceType());
  5329. if (argAddr->getType()->getPointerElementType() == ToTy &&
  5330. // Check clang Type for case like int cast to unsigned.
  5331. ParamTy.getNonReferenceType().getCanonicalType().getTypePtr() ==
  5332. Arg->getType().getCanonicalType().getTypePtr())
  5333. continue;
  5334. }
  5335. }
  5336. argType = argLV.getType(); // TBD: Can this be different than Arg->getType()?
  5337. argAlignment = argLV.getAlignment();
  5338. }
  5339. // After emit Arg, we must update the argList[i],
  5340. // otherwise we get double emit of the expression.
  5341. // create temp Var
  5342. VarDecl *tmpArg =
  5343. VarDecl::Create(CGF.getContext(), const_cast<FunctionDecl *>(FD),
  5344. SourceLocation(), SourceLocation(),
  5345. /*IdentifierInfo*/ nullptr, ParamTy,
  5346. CGF.getContext().getTrivialTypeSourceInfo(ParamTy),
  5347. StorageClass::SC_Auto);
  5348. // Aggregate type will be indirect param convert to pointer type.
  5349. // So don't update to ReferenceType, use RValue for it.
  5350. const DeclRefExpr *tmpRef = DeclRefExpr::Create(
  5351. CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), tmpArg,
  5352. /*enclosing*/ false, tmpArg->getLocation(), ParamTy,
  5353. (isAggregateType || isObject) ? VK_RValue : VK_LValue);
  5354. // must update the arg, since we did emit Arg, else we get double emit.
  5355. argList[i] = tmpRef;
  5356. // create alloc for the tmp arg
  5357. Value *tmpArgAddr = nullptr;
  5358. BasicBlock *InsertBlock = CGF.Builder.GetInsertBlock();
  5359. Function *F = InsertBlock->getParent();
  5360. // Make sure the alloca is in entry block to stop inline create stacksave.
  5361. IRBuilder<> AllocaBuilder(dxilutil::FindAllocaInsertionPt(F));
  5362. tmpArgAddr = AllocaBuilder.CreateAlloca(CGF.ConvertTypeForMem(ParamTy));
  5363. if (CGM.getCodeGenOpts().HLSLEnableLifetimeMarkers) {
  5364. const uint64_t AllocaSize = CGM.getDataLayout().getTypeAllocSize(CGF.ConvertTypeForMem(ParamTy));
  5365. CGF.EmitLifetimeStart(AllocaSize, tmpArgAddr);
  5366. }
  5367. // add it to local decl map
  5368. TmpArgMap(tmpArg, tmpArgAddr);
  5369. LValue tmpLV = LValue::MakeAddr(tmpArgAddr, ParamTy, argAlignment,
  5370. CGF.getContext());
  5371. // save for cast after call
  5372. if (Param->isModifierOut()) {
  5373. castArgList.emplace_back(tmpLV);
  5374. castArgList.emplace_back(argLV);
  5375. if (isVector && !hlsl::IsHLSLVecType(argType)) {
  5376. // This assumes only implicit casts because explicit casts can only produce RValues
  5377. // currently and out parameters are LValues.
  5378. DiagnosticsEngine &Diags = CGM.getDiags();
  5379. Diags.Report(Param->getLocation(), diag::warn_hlsl_implicit_vector_truncation);
  5380. }
  5381. }
  5382. // save to generate lifetime end after call
  5383. if (CGM.getCodeGenOpts().HLSLEnableLifetimeMarkers)
  5384. lifetimeCleanupList.emplace_back(tmpLV);
  5385. // cast before the call
  5386. if (Param->isModifierIn() &&
  5387. // Don't copy object
  5388. !isObject) {
  5389. QualType ArgTy = Arg->getType();
  5390. Value *outVal = nullptr;
  5391. if (!isAggregateType) {
  5392. if (!IsHLSLMatType(ParamTy)) {
  5393. RValue outRVal = CGF.EmitLoadOfLValue(argLV, SourceLocation());
  5394. outVal = outRVal.getScalarVal();
  5395. } else {
  5396. DXASSERT(argAddr, "should be RV or simple LV");
  5397. outVal = EmitHLSLMatrixLoad(CGF, argAddr, ArgTy);
  5398. }
  5399. llvm::Type *ToTy = tmpArgAddr->getType()->getPointerElementType();
  5400. if (HLMatrixType::isa(ToTy)) {
  5401. Value *castVal = CGF.Builder.CreateBitCast(outVal, ToTy);
  5402. EmitHLSLMatrixStore(CGF, castVal, tmpArgAddr, ParamTy);
  5403. }
  5404. else {
  5405. if (outVal->getType()->isVectorTy()) {
  5406. Value *castVal = ConvertScalarOrVector(CGF, outVal, argType, ParamTy);
  5407. castVal = CGF.EmitToMemory(castVal, ParamTy);
  5408. CGF.Builder.CreateStore(castVal, tmpArgAddr);
  5409. } else {
  5410. // This allows for splatting, unlike the above.
  5411. SimpleFlatValCopy(CGF, outVal, argType, tmpArgAddr, ParamTy);
  5412. }
  5413. }
  5414. } else {
  5415. DXASSERT(argAddr, "should be RV or simple LV");
  5416. SmallVector<Value *, 4> idxList;
  5417. EmitHLSLAggregateCopy(CGF, argAddr, tmpArgAddr,
  5418. idxList, ArgTy, ParamTy,
  5419. argAddr->getType());
  5420. }
  5421. }
  5422. }
  5423. }
  5424. void CGMSHLSLRuntime::EmitHLSLOutParamConversionCopyBack(
  5425. CodeGenFunction &CGF, llvm::SmallVector<LValue, 8> &castArgList,
  5426. llvm::SmallVector<LValue, 8> &lifetimeCleanupList) {
  5427. for (uint32_t i = 0; i < castArgList.size(); i += 2) {
  5428. // cast after the call
  5429. LValue tmpLV = castArgList[i];
  5430. LValue argLV = castArgList[i + 1];
  5431. QualType ArgTy = argLV.getType().getNonReferenceType();
  5432. QualType ParamTy = tmpLV.getType().getNonReferenceType();
  5433. Value *tmpArgAddr = tmpLV.getAddress();
  5434. Value *outVal = nullptr;
  5435. bool isAggregateTy = hlsl::IsHLSLAggregateType(ArgTy);
  5436. bool isObject = dxilutil::IsHLSLObjectType(
  5437. tmpArgAddr->getType()->getPointerElementType());
  5438. if (!isObject) {
  5439. if (!isAggregateTy) {
  5440. if (!IsHLSLMatType(ParamTy))
  5441. outVal = CGF.Builder.CreateLoad(tmpArgAddr);
  5442. else
  5443. outVal = EmitHLSLMatrixLoad(CGF, tmpArgAddr, ParamTy);
  5444. outVal = CGF.EmitFromMemory(outVal, ParamTy);
  5445. llvm::Type *ToTy = CGF.ConvertType(ArgTy);
  5446. llvm::Type *FromTy = outVal->getType();
  5447. Value *castVal = outVal;
  5448. if (ToTy == FromTy) {
  5449. // Don't need cast.
  5450. } else if (ToTy->getScalarType() == FromTy->getScalarType()) {
  5451. if (ToTy->getScalarType() == ToTy) {
  5452. DXASSERT(FromTy->isVectorTy(), "must be vector");
  5453. castVal = CGF.Builder.CreateExtractElement(outVal, (uint64_t)0);
  5454. } else {
  5455. DXASSERT(!FromTy->isVectorTy(), "must be scalar type");
  5456. DXASSERT(ToTy->isVectorTy() && ToTy->getVectorNumElements() == 1,
  5457. "must be vector of 1 element");
  5458. castVal = UndefValue::get(ToTy);
  5459. castVal =
  5460. CGF.Builder.CreateInsertElement(castVal, outVal, (uint64_t)0);
  5461. }
  5462. } else {
  5463. castVal = ConvertScalarOrVector(CGF,
  5464. outVal, tmpLV.getType(), argLV.getType());
  5465. }
  5466. if (!HLMatrixType::isa(ToTy))
  5467. CGF.EmitStoreThroughLValue(RValue::get(castVal), argLV);
  5468. else {
  5469. Value *destPtr = argLV.getAddress();
  5470. EmitHLSLMatrixStore(CGF, castVal, destPtr, ArgTy);
  5471. }
  5472. } else {
  5473. SmallVector<Value *, 4> idxList;
  5474. EmitHLSLAggregateCopy(CGF, tmpLV.getAddress(), argLV.getAddress(),
  5475. idxList, ParamTy, ArgTy,
  5476. argLV.getAddress()->getType());
  5477. }
  5478. } else
  5479. tmpArgAddr->replaceAllUsesWith(argLV.getAddress());
  5480. }
  5481. for (LValue &tmpLV : lifetimeCleanupList) {
  5482. QualType ParamTy = tmpLV.getType().getNonReferenceType();
  5483. Value *tmpArgAddr = tmpLV.getAddress();
  5484. const uint64_t AllocaSize = CGM.getDataLayout().getTypeAllocSize(CGF.ConvertTypeForMem(ParamTy));
  5485. CGF.EmitLifetimeEnd(CGF.Builder.getInt64(AllocaSize), tmpArgAddr);
  5486. }
  5487. }
  5488. ScopeInfo *CGMSHLSLRuntime::GetScopeInfo(Function *F) {
  5489. auto it = m_ScopeMap.find(F);
  5490. if (it == m_ScopeMap.end())
  5491. return nullptr;
  5492. return &it->second;
  5493. }
  5494. void CGMSHLSLRuntime::MarkIfStmt(CodeGenFunction &CGF, BasicBlock *endIfBB) {
  5495. if (ScopeInfo *Scope = GetScopeInfo(CGF.CurFn))
  5496. Scope->AddIf(endIfBB);
  5497. }
  5498. void CGMSHLSLRuntime::MarkSwitchStmt(CodeGenFunction &CGF,
  5499. SwitchInst *switchInst,
  5500. BasicBlock *endSwitch) {
  5501. if (ScopeInfo *Scope = GetScopeInfo(CGF.CurFn))
  5502. Scope->AddSwitch(endSwitch);
  5503. }
  5504. void CGMSHLSLRuntime::MarkReturnStmt(CodeGenFunction &CGF,
  5505. BasicBlock *bbWithRet) {
  5506. if (ScopeInfo *Scope = GetScopeInfo(CGF.CurFn))
  5507. Scope->AddRet(bbWithRet);
  5508. }
  5509. void CGMSHLSLRuntime::MarkLoopStmt(CodeGenFunction &CGF,
  5510. BasicBlock *loopContinue,
  5511. BasicBlock *loopExit) {
  5512. if (ScopeInfo *Scope = GetScopeInfo(CGF.CurFn))
  5513. Scope->AddLoop(loopContinue, loopExit);
  5514. }
  5515. void CGMSHLSLRuntime::MarkScopeEnd(CodeGenFunction &CGF) {
  5516. if (ScopeInfo *Scope = GetScopeInfo(CGF.CurFn)) {
  5517. llvm::BasicBlock *CurBB = CGF.Builder.GetInsertBlock();
  5518. bool bScopeFinishedWithRet = !CurBB || CurBB->getTerminator();
  5519. Scope->EndScope(bScopeFinishedWithRet);
  5520. }
  5521. }
  5522. CGHLSLRuntime *CodeGen::CreateMSHLSLRuntime(CodeGenModule &CGM) {
  5523. return new CGMSHLSLRuntime(CGM);
  5524. }