CGHLSLMS.cpp 225 KB

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