CGHLSLMS.cpp 222 KB

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