CGHLSLMS.cpp 222 KB

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