ScalarReplAggregatesHLSL.cpp 261 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103
  1. //===- ScalarReplAggregatesHLSL.cpp - Scalar Replacement of Aggregates ----===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //===----------------------------------------------------------------------===//
  10. //
  11. // Based on ScalarReplAggregates.cpp. The difference is HLSL version will keep
  12. // array so it can break up all structure.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/ADT/SetVector.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/ADT/Statistic.h"
  18. #include "llvm/Analysis/AssumptionCache.h"
  19. #include "llvm/Analysis/Loads.h"
  20. #include "llvm/Analysis/ValueTracking.h"
  21. #include "llvm/Analysis/PostDominators.h"
  22. #include "llvm/IR/CallSite.h"
  23. #include "llvm/IR/Constants.h"
  24. #include "llvm/IR/DIBuilder.h"
  25. #include "llvm/IR/DataLayout.h"
  26. #include "llvm/IR/DebugInfo.h"
  27. #include "llvm/IR/DerivedTypes.h"
  28. #include "llvm/IR/Dominators.h"
  29. #include "llvm/IR/Function.h"
  30. #include "llvm/IR/GetElementPtrTypeIterator.h"
  31. #include "llvm/IR/GlobalVariable.h"
  32. #include "llvm/IR/IRBuilder.h"
  33. #include "llvm/IR/Instructions.h"
  34. #include "llvm/IR/IntrinsicInst.h"
  35. #include "llvm/IR/LLVMContext.h"
  36. #include "llvm/IR/Module.h"
  37. #include "llvm/IR/Operator.h"
  38. #include "llvm/Pass.h"
  39. #include "llvm/Support/Debug.h"
  40. #include "llvm/Support/ErrorHandling.h"
  41. #include "llvm/Support/MathExtras.h"
  42. #include "llvm/Support/raw_ostream.h"
  43. #include "llvm/Transforms/Scalar.h"
  44. #include "llvm/Transforms/Utils/Local.h"
  45. #include "llvm/Transforms/Utils/PromoteMemToReg.h"
  46. #include "llvm/Transforms/Utils/SSAUpdater.h"
  47. #include "llvm/Transforms/Utils/Local.h"
  48. #include "dxc/HLSL/HLOperations.h"
  49. #include "dxc/HLSL/DxilConstants.h"
  50. #include "dxc/HLSL/HLModule.h"
  51. #include "dxc/HLSL/DxilUtil.h"
  52. #include "dxc/HLSL/DxilModule.h"
  53. #include "dxc/HlslIntrinsicOp.h"
  54. #include "dxc/HLSL/DxilTypeSystem.h"
  55. #include "dxc/HLSL/HLMatrixLowerHelper.h"
  56. #include "dxc/HLSL/DxilOperations.h"
  57. #include <deque>
  58. #include <unordered_map>
  59. #include <unordered_set>
  60. #include <queue>
  61. using namespace llvm;
  62. using namespace hlsl;
  63. #define DEBUG_TYPE "scalarreplhlsl"
  64. STATISTIC(NumReplaced, "Number of allocas broken up");
  65. STATISTIC(NumPromoted, "Number of allocas promoted");
  66. STATISTIC(NumAdjusted, "Number of scalar allocas adjusted to allow promotion");
  67. namespace {
  68. class SROA_Helper {
  69. public:
  70. // Split V into AllocaInsts with Builder and save the new AllocaInsts into Elts.
  71. // Then do SROA on V.
  72. static bool DoScalarReplacement(Value *V, std::vector<Value *> &Elts,
  73. IRBuilder<> &Builder, bool bFlatVector,
  74. bool hasPrecise, DxilTypeSystem &typeSys,
  75. const DataLayout &DL,
  76. SmallVector<Value *, 32> &DeadInsts);
  77. static bool DoScalarReplacement(GlobalVariable *GV, std::vector<Value *> &Elts,
  78. IRBuilder<> &Builder, bool bFlatVector,
  79. bool hasPrecise, DxilTypeSystem &typeSys,
  80. const DataLayout &DL,
  81. SmallVector<Value *, 32> &DeadInsts);
  82. // Lower memcpy related to V.
  83. static bool LowerMemcpy(Value *V, DxilFieldAnnotation *annotation,
  84. DxilTypeSystem &typeSys, const DataLayout &DL,
  85. bool bAllowReplace);
  86. static void MarkEmptyStructUsers(Value *V,
  87. SmallVector<Value *, 32> &DeadInsts);
  88. static bool IsEmptyStructType(Type *Ty, DxilTypeSystem &typeSys);
  89. private:
  90. SROA_Helper(Value *V, ArrayRef<Value *> Elts,
  91. SmallVector<Value *, 32> &DeadInsts, DxilTypeSystem &ts,
  92. const DataLayout &dl)
  93. : OldVal(V), NewElts(Elts), DeadInsts(DeadInsts), typeSys(ts), DL(dl) {}
  94. void RewriteForScalarRepl(Value *V, IRBuilder<> &Builder);
  95. private:
  96. // Must be a pointer type val.
  97. Value * OldVal;
  98. // Flattened elements for OldVal.
  99. ArrayRef<Value*> NewElts;
  100. SmallVector<Value *, 32> &DeadInsts;
  101. DxilTypeSystem &typeSys;
  102. const DataLayout &DL;
  103. void RewriteForConstExpr(ConstantExpr *user, IRBuilder<> &Builder);
  104. void RewriteForGEP(GEPOperator *GEP, IRBuilder<> &Builder);
  105. void RewriteForAddrSpaceCast(ConstantExpr *user, IRBuilder<> &Builder);
  106. void RewriteForLoad(LoadInst *loadInst);
  107. void RewriteForStore(StoreInst *storeInst);
  108. void RewriteMemIntrin(MemIntrinsic *MI, Value *OldV);
  109. void RewriteCall(CallInst *CI);
  110. void RewriteBitCast(BitCastInst *BCI);
  111. void RewriteCallArg(CallInst *CI, unsigned ArgIdx, bool bIn, bool bOut);
  112. };
  113. struct SROA_HLSL : public FunctionPass {
  114. SROA_HLSL(bool Promote, int T, bool hasDT, char &ID, int ST, int AT, int SLT)
  115. : FunctionPass(ID), HasDomTree(hasDT), RunPromotion(Promote) {
  116. if (AT == -1)
  117. ArrayElementThreshold = 8;
  118. else
  119. ArrayElementThreshold = AT;
  120. if (SLT == -1)
  121. // Do not limit the scalar integer load size if no threshold is given.
  122. ScalarLoadThreshold = -1;
  123. else
  124. ScalarLoadThreshold = SLT;
  125. }
  126. bool runOnFunction(Function &F) override;
  127. bool performScalarRepl(Function &F, DxilTypeSystem &typeSys);
  128. bool performPromotion(Function &F);
  129. bool markPrecise(Function &F);
  130. private:
  131. bool HasDomTree;
  132. bool RunPromotion;
  133. /// DeadInsts - Keep track of instructions we have made dead, so that
  134. /// we can remove them after we are done working.
  135. SmallVector<Value *, 32> DeadInsts;
  136. /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
  137. /// information about the uses. All these fields are initialized to false
  138. /// and set to true when something is learned.
  139. struct AllocaInfo {
  140. /// The alloca to promote.
  141. AllocaInst *AI;
  142. /// CheckedPHIs - This is a set of verified PHI nodes, to prevent infinite
  143. /// looping and avoid redundant work.
  144. SmallPtrSet<PHINode *, 8> CheckedPHIs;
  145. /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
  146. bool isUnsafe : 1;
  147. /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
  148. bool isMemCpySrc : 1;
  149. /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
  150. bool isMemCpyDst : 1;
  151. /// hasSubelementAccess - This is true if a subelement of the alloca is
  152. /// ever accessed, or false if the alloca is only accessed with mem
  153. /// intrinsics or load/store that only access the entire alloca at once.
  154. bool hasSubelementAccess : 1;
  155. /// hasALoadOrStore - This is true if there are any loads or stores to it.
  156. /// The alloca may just be accessed with memcpy, for example, which would
  157. /// not set this.
  158. bool hasALoadOrStore : 1;
  159. /// hasArrayIndexing - This is true if there are any dynamic array
  160. /// indexing to it.
  161. bool hasArrayIndexing : 1;
  162. /// hasVectorIndexing - This is true if there are any dynamic vector
  163. /// indexing to it.
  164. bool hasVectorIndexing : 1;
  165. explicit AllocaInfo(AllocaInst *ai)
  166. : AI(ai), isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
  167. hasSubelementAccess(false), hasALoadOrStore(false),
  168. hasArrayIndexing(false), hasVectorIndexing(false) {}
  169. };
  170. /// ArrayElementThreshold - The maximum number of elements an array can
  171. /// have to be considered for SROA.
  172. unsigned ArrayElementThreshold;
  173. /// ScalarLoadThreshold - The maximum size in bits of scalars to load when
  174. /// converting to scalar
  175. unsigned ScalarLoadThreshold;
  176. void MarkUnsafe(AllocaInfo &I, Instruction *User) {
  177. I.isUnsafe = true;
  178. DEBUG(dbgs() << " Transformation preventing inst: " << *User << '\n');
  179. }
  180. bool isSafeAllocaToScalarRepl(AllocaInst *AI);
  181. void isSafeForScalarRepl(Instruction *I, uint64_t Offset, AllocaInfo &Info);
  182. void isSafePHISelectUseForScalarRepl(Instruction *User, uint64_t Offset,
  183. AllocaInfo &Info);
  184. void isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset, AllocaInfo &Info);
  185. void isSafeMemAccess(uint64_t Offset, uint64_t MemSize, Type *MemOpType,
  186. bool isStore, AllocaInfo &Info, Instruction *TheAccess,
  187. bool AllowWholeAccess);
  188. bool TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size,
  189. const DataLayout &DL);
  190. void DeleteDeadInstructions();
  191. bool ShouldAttemptScalarRepl(AllocaInst *AI);
  192. };
  193. // SROA_DT - SROA that uses DominatorTree.
  194. struct SROA_DT_HLSL : public SROA_HLSL {
  195. static char ID;
  196. public:
  197. SROA_DT_HLSL(bool Promote = false, int T = -1, int ST = -1, int AT = -1, int SLT = -1)
  198. : SROA_HLSL(Promote, T, true, ID, ST, AT, SLT) {
  199. initializeSROA_DTPass(*PassRegistry::getPassRegistry());
  200. }
  201. // getAnalysisUsage - This pass does not require any passes, but we know it
  202. // will not alter the CFG, so say so.
  203. void getAnalysisUsage(AnalysisUsage &AU) const override {
  204. AU.addRequired<AssumptionCacheTracker>();
  205. AU.addRequired<DominatorTreeWrapperPass>();
  206. AU.setPreservesCFG();
  207. }
  208. };
  209. // SROA_SSAUp - SROA that uses SSAUpdater.
  210. struct SROA_SSAUp_HLSL : public SROA_HLSL {
  211. static char ID;
  212. public:
  213. SROA_SSAUp_HLSL(bool Promote = false, int T = -1, int ST = -1, int AT = -1, int SLT = -1)
  214. : SROA_HLSL(Promote, T, false, ID, ST, AT, SLT) {
  215. initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
  216. }
  217. // getAnalysisUsage - This pass does not require any passes, but we know it
  218. // will not alter the CFG, so say so.
  219. void getAnalysisUsage(AnalysisUsage &AU) const override {
  220. AU.addRequired<AssumptionCacheTracker>();
  221. AU.setPreservesCFG();
  222. }
  223. };
  224. // Simple struct to split memcpy into ld/st
  225. struct MemcpySplitter {
  226. llvm::LLVMContext &m_context;
  227. DxilTypeSystem &m_typeSys;
  228. public:
  229. MemcpySplitter(llvm::LLVMContext &context, DxilTypeSystem &typeSys)
  230. : m_context(context), m_typeSys(typeSys) {}
  231. void Split(llvm::Function &F);
  232. static void PatchMemCpyWithZeroIdxGEP(Module &M);
  233. static void PatchMemCpyWithZeroIdxGEP(MemCpyInst *MI, const DataLayout &DL);
  234. static void SplitMemCpy(MemCpyInst *MI, const DataLayout &DL,
  235. DxilFieldAnnotation *fieldAnnotation,
  236. DxilTypeSystem &typeSys,
  237. const bool bEltMemCpy = true);
  238. };
  239. }
  240. char SROA_DT_HLSL::ID = 0;
  241. char SROA_SSAUp_HLSL::ID = 0;
  242. INITIALIZE_PASS_BEGIN(SROA_DT_HLSL, "scalarreplhlsl",
  243. "Scalar Replacement of Aggregates HLSL (DT)", false,
  244. false)
  245. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  246. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  247. INITIALIZE_PASS_END(SROA_DT_HLSL, "scalarreplhlsl",
  248. "Scalar Replacement of Aggregates HLSL (DT)", false, false)
  249. INITIALIZE_PASS_BEGIN(SROA_SSAUp_HLSL, "scalarreplhlsl-ssa",
  250. "Scalar Replacement of Aggregates HLSL (SSAUp)", false,
  251. false)
  252. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  253. INITIALIZE_PASS_END(SROA_SSAUp_HLSL, "scalarreplhlsl-ssa",
  254. "Scalar Replacement of Aggregates HLSL (SSAUp)", false,
  255. false)
  256. // Public interface to the ScalarReplAggregates pass
  257. FunctionPass *llvm::createScalarReplAggregatesHLSLPass(bool UseDomTree, bool Promote) {
  258. if (UseDomTree)
  259. return new SROA_DT_HLSL(Promote);
  260. return new SROA_SSAUp_HLSL(Promote);
  261. }
  262. //===----------------------------------------------------------------------===//
  263. // Convert To Scalar Optimization.
  264. //===----------------------------------------------------------------------===//
  265. namespace {
  266. /// ConvertToScalarInfo - This class implements the "Convert To Scalar"
  267. /// optimization, which scans the uses of an alloca and determines if it can
  268. /// rewrite it in terms of a single new alloca that can be mem2reg'd.
  269. class ConvertToScalarInfo {
  270. /// AllocaSize - The size of the alloca being considered in bytes.
  271. unsigned AllocaSize;
  272. const DataLayout &DL;
  273. unsigned ScalarLoadThreshold;
  274. /// IsNotTrivial - This is set to true if there is some access to the object
  275. /// which means that mem2reg can't promote it.
  276. bool IsNotTrivial;
  277. /// ScalarKind - Tracks the kind of alloca being considered for promotion,
  278. /// computed based on the uses of the alloca rather than the LLVM type system.
  279. enum {
  280. Unknown,
  281. // Accesses via GEPs that are consistent with element access of a vector
  282. // type. This will not be converted into a vector unless there is a later
  283. // access using an actual vector type.
  284. ImplicitVector,
  285. // Accesses via vector operations and GEPs that are consistent with the
  286. // layout of a vector type.
  287. Vector,
  288. // An integer bag-of-bits with bitwise operations for insertion and
  289. // extraction. Any combination of types can be converted into this kind
  290. // of scalar.
  291. Integer
  292. } ScalarKind;
  293. /// VectorTy - This tracks the type that we should promote the vector to if
  294. /// it is possible to turn it into a vector. This starts out null, and if it
  295. /// isn't possible to turn into a vector type, it gets set to VoidTy.
  296. VectorType *VectorTy;
  297. /// HadNonMemTransferAccess - True if there is at least one access to the
  298. /// alloca that is not a MemTransferInst. We don't want to turn structs into
  299. /// large integers unless there is some potential for optimization.
  300. bool HadNonMemTransferAccess;
  301. /// HadDynamicAccess - True if some element of this alloca was dynamic.
  302. /// We don't yet have support for turning a dynamic access into a large
  303. /// integer.
  304. bool HadDynamicAccess;
  305. public:
  306. explicit ConvertToScalarInfo(unsigned Size, const DataLayout &DL,
  307. unsigned SLT)
  308. : AllocaSize(Size), DL(DL), ScalarLoadThreshold(SLT), IsNotTrivial(false),
  309. ScalarKind(Unknown), VectorTy(nullptr), HadNonMemTransferAccess(false),
  310. HadDynamicAccess(false) {}
  311. AllocaInst *TryConvert(AllocaInst *AI);
  312. private:
  313. bool CanConvertToScalar(Value *V, uint64_t Offset, Value *NonConstantIdx);
  314. void MergeInTypeForLoadOrStore(Type *In, uint64_t Offset);
  315. bool MergeInVectorType(VectorType *VInTy, uint64_t Offset);
  316. void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset,
  317. Value *NonConstantIdx);
  318. Value *ConvertScalar_ExtractValue(Value *NV, Type *ToType, uint64_t Offset,
  319. Value *NonConstantIdx,
  320. IRBuilder<> &Builder);
  321. Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
  322. uint64_t Offset, Value *NonConstantIdx,
  323. IRBuilder<> &Builder);
  324. };
  325. } // end anonymous namespace.
  326. /// TryConvert - Analyze the specified alloca, and if it is safe to do so,
  327. /// rewrite it to be a new alloca which is mem2reg'able. This returns the new
  328. /// alloca if possible or null if not.
  329. AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
  330. // If we can't convert this scalar, or if mem2reg can trivially do it, bail
  331. // out.
  332. if (!CanConvertToScalar(AI, 0, nullptr) || !IsNotTrivial)
  333. return nullptr;
  334. // If an alloca has only memset / memcpy uses, it may still have an Unknown
  335. // ScalarKind. Treat it as an Integer below.
  336. if (ScalarKind == Unknown)
  337. ScalarKind = Integer;
  338. if (ScalarKind == Vector && VectorTy->getBitWidth() != AllocaSize * 8)
  339. ScalarKind = Integer;
  340. // If we were able to find a vector type that can handle this with
  341. // insert/extract elements, and if there was at least one use that had
  342. // a vector type, promote this to a vector. We don't want to promote
  343. // random stuff that doesn't use vectors (e.g. <9 x double>) because then
  344. // we just get a lot of insert/extracts. If at least one vector is
  345. // involved, then we probably really do have a union of vector/array.
  346. Type *NewTy;
  347. if (ScalarKind == Vector) {
  348. assert(VectorTy && "Missing type for vector scalar.");
  349. DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = " << *VectorTy
  350. << '\n');
  351. NewTy = VectorTy; // Use the vector type.
  352. } else {
  353. unsigned BitWidth = AllocaSize * 8;
  354. // Do not convert to scalar integer if the alloca size exceeds the
  355. // scalar load threshold.
  356. if (BitWidth > ScalarLoadThreshold)
  357. return nullptr;
  358. if ((ScalarKind == ImplicitVector || ScalarKind == Integer) &&
  359. !HadNonMemTransferAccess && !DL.fitsInLegalInteger(BitWidth))
  360. return nullptr;
  361. // Dynamic accesses on integers aren't yet supported. They need us to shift
  362. // by a dynamic amount which could be difficult to work out as we might not
  363. // know whether to use a left or right shift.
  364. if (ScalarKind == Integer && HadDynamicAccess)
  365. return nullptr;
  366. DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
  367. // Create and insert the integer alloca.
  368. NewTy = IntegerType::get(AI->getContext(), BitWidth);
  369. }
  370. AllocaInst *NewAI =
  371. new AllocaInst(NewTy, nullptr, "", AI->getParent()->begin());
  372. ConvertUsesToScalar(AI, NewAI, 0, nullptr);
  373. return NewAI;
  374. }
  375. /// MergeInTypeForLoadOrStore - Add the 'In' type to the accumulated vector type
  376. /// (VectorTy) so far at the offset specified by Offset (which is specified in
  377. /// bytes).
  378. ///
  379. /// There are two cases we handle here:
  380. /// 1) A union of vector types of the same size and potentially its elements.
  381. /// Here we turn element accesses into insert/extract element operations.
  382. /// This promotes a <4 x float> with a store of float to the third element
  383. /// into a <4 x float> that uses insert element.
  384. /// 2) A fully general blob of memory, which we turn into some (potentially
  385. /// large) integer type with extract and insert operations where the loads
  386. /// and stores would mutate the memory. We mark this by setting VectorTy
  387. /// to VoidTy.
  388. void ConvertToScalarInfo::MergeInTypeForLoadOrStore(Type *In, uint64_t Offset) {
  389. // If we already decided to turn this into a blob of integer memory, there is
  390. // nothing to be done.
  391. if (ScalarKind == Integer)
  392. return;
  393. // If this could be contributing to a vector, analyze it.
  394. // If the In type is a vector that is the same size as the alloca, see if it
  395. // matches the existing VecTy.
  396. if (VectorType *VInTy = dyn_cast<VectorType>(In)) {
  397. if (MergeInVectorType(VInTy, Offset))
  398. return;
  399. } else if (In->isFloatTy() || In->isDoubleTy() ||
  400. (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
  401. isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
  402. // Full width accesses can be ignored, because they can always be turned
  403. // into bitcasts.
  404. unsigned EltSize = In->getPrimitiveSizeInBits() / 8;
  405. if (EltSize == AllocaSize)
  406. return;
  407. // If we're accessing something that could be an element of a vector, see
  408. // if the implied vector agrees with what we already have and if Offset is
  409. // compatible with it.
  410. if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
  411. (!VectorTy ||
  412. EltSize == VectorTy->getElementType()->getPrimitiveSizeInBits() / 8)) {
  413. if (!VectorTy) {
  414. ScalarKind = ImplicitVector;
  415. VectorTy = VectorType::get(In, AllocaSize / EltSize);
  416. }
  417. return;
  418. }
  419. }
  420. // Otherwise, we have a case that we can't handle with an optimized vector
  421. // form. We can still turn this into a large integer.
  422. ScalarKind = Integer;
  423. }
  424. /// MergeInVectorType - Handles the vector case of MergeInTypeForLoadOrStore,
  425. /// returning true if the type was successfully merged and false otherwise.
  426. bool ConvertToScalarInfo::MergeInVectorType(VectorType *VInTy,
  427. uint64_t Offset) {
  428. if (VInTy->getBitWidth() / 8 == AllocaSize && Offset == 0) {
  429. // If we're storing/loading a vector of the right size, allow it as a
  430. // vector. If this the first vector we see, remember the type so that
  431. // we know the element size. If this is a subsequent access, ignore it
  432. // even if it is a differing type but the same size. Worst case we can
  433. // bitcast the resultant vectors.
  434. if (!VectorTy)
  435. VectorTy = VInTy;
  436. ScalarKind = Vector;
  437. return true;
  438. }
  439. return false;
  440. }
  441. /// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
  442. /// its accesses to a single vector type, return true and set VecTy to
  443. /// the new type. If we could convert the alloca into a single promotable
  444. /// integer, return true but set VecTy to VoidTy. Further, if the use is not a
  445. /// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
  446. /// is the current offset from the base of the alloca being analyzed.
  447. ///
  448. /// If we see at least one access to the value that is as a vector type, set the
  449. /// SawVec flag.
  450. bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset,
  451. Value *NonConstantIdx) {
  452. for (User *U : V->users()) {
  453. Instruction *UI = cast<Instruction>(U);
  454. if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
  455. // Don't break volatile loads.
  456. if (!LI->isSimple())
  457. return false;
  458. HadNonMemTransferAccess = true;
  459. MergeInTypeForLoadOrStore(LI->getType(), Offset);
  460. continue;
  461. }
  462. if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
  463. // Storing the pointer, not into the value?
  464. if (SI->getOperand(0) == V || !SI->isSimple())
  465. return false;
  466. HadNonMemTransferAccess = true;
  467. MergeInTypeForLoadOrStore(SI->getOperand(0)->getType(), Offset);
  468. continue;
  469. }
  470. if (BitCastInst *BCI = dyn_cast<BitCastInst>(UI)) {
  471. if (!onlyUsedByLifetimeMarkers(BCI))
  472. IsNotTrivial = true; // Can't be mem2reg'd.
  473. if (!CanConvertToScalar(BCI, Offset, NonConstantIdx))
  474. return false;
  475. continue;
  476. }
  477. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UI)) {
  478. // If this is a GEP with a variable indices, we can't handle it.
  479. PointerType *PtrTy = dyn_cast<PointerType>(GEP->getPointerOperandType());
  480. if (!PtrTy)
  481. return false;
  482. // Compute the offset that this GEP adds to the pointer.
  483. SmallVector<Value *, 8> Indices(GEP->op_begin() + 1, GEP->op_end());
  484. Value *GEPNonConstantIdx = nullptr;
  485. if (!GEP->hasAllConstantIndices()) {
  486. if (!isa<VectorType>(PtrTy->getElementType()))
  487. return false;
  488. if (NonConstantIdx)
  489. return false;
  490. GEPNonConstantIdx = Indices.pop_back_val();
  491. if (!GEPNonConstantIdx->getType()->isIntegerTy(32))
  492. return false;
  493. HadDynamicAccess = true;
  494. } else
  495. GEPNonConstantIdx = NonConstantIdx;
  496. uint64_t GEPOffset = DL.getIndexedOffset(PtrTy, Indices);
  497. // See if all uses can be converted.
  498. if (!CanConvertToScalar(GEP, Offset + GEPOffset, GEPNonConstantIdx))
  499. return false;
  500. IsNotTrivial = true; // Can't be mem2reg'd.
  501. HadNonMemTransferAccess = true;
  502. continue;
  503. }
  504. // If this is a constant sized memset of a constant value (e.g. 0) we can
  505. // handle it.
  506. if (MemSetInst *MSI = dyn_cast<MemSetInst>(UI)) {
  507. // Store to dynamic index.
  508. if (NonConstantIdx)
  509. return false;
  510. // Store of constant value.
  511. if (!isa<ConstantInt>(MSI->getValue()))
  512. return false;
  513. // Store of constant size.
  514. ConstantInt *Len = dyn_cast<ConstantInt>(MSI->getLength());
  515. if (!Len)
  516. return false;
  517. // If the size differs from the alloca, we can only convert the alloca to
  518. // an integer bag-of-bits.
  519. // FIXME: This should handle all of the cases that are currently accepted
  520. // as vector element insertions.
  521. if (Len->getZExtValue() != AllocaSize || Offset != 0)
  522. ScalarKind = Integer;
  523. IsNotTrivial = true; // Can't be mem2reg'd.
  524. HadNonMemTransferAccess = true;
  525. continue;
  526. }
  527. // If this is a memcpy or memmove into or out of the whole allocation, we
  528. // can handle it like a load or store of the scalar type.
  529. if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(UI)) {
  530. // Store to dynamic index.
  531. if (NonConstantIdx)
  532. return false;
  533. ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
  534. if (!Len || Len->getZExtValue() != AllocaSize || Offset != 0)
  535. return false;
  536. IsNotTrivial = true; // Can't be mem2reg'd.
  537. continue;
  538. }
  539. // If this is a lifetime intrinsic, we can handle it.
  540. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(UI)) {
  541. if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
  542. II->getIntrinsicID() == Intrinsic::lifetime_end) {
  543. continue;
  544. }
  545. }
  546. // Otherwise, we cannot handle this!
  547. return false;
  548. }
  549. return true;
  550. }
  551. /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
  552. /// directly. This happens when we are converting an "integer union" to a
  553. /// single integer scalar, or when we are converting a "vector union" to a
  554. /// vector with insert/extractelement instructions.
  555. ///
  556. /// Offset is an offset from the original alloca, in bits that need to be
  557. /// shifted to the right. By the end of this, there should be no uses of Ptr.
  558. void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
  559. uint64_t Offset,
  560. Value *NonConstantIdx) {
  561. while (!Ptr->use_empty()) {
  562. Instruction *User = cast<Instruction>(Ptr->user_back());
  563. if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
  564. ConvertUsesToScalar(CI, NewAI, Offset, NonConstantIdx);
  565. CI->eraseFromParent();
  566. continue;
  567. }
  568. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
  569. // Compute the offset that this GEP adds to the pointer.
  570. SmallVector<Value *, 8> Indices(GEP->op_begin() + 1, GEP->op_end());
  571. Value *GEPNonConstantIdx = nullptr;
  572. if (!GEP->hasAllConstantIndices()) {
  573. assert(!NonConstantIdx &&
  574. "Dynamic GEP reading from dynamic GEP unsupported");
  575. GEPNonConstantIdx = Indices.pop_back_val();
  576. } else
  577. GEPNonConstantIdx = NonConstantIdx;
  578. uint64_t GEPOffset =
  579. DL.getIndexedOffset(GEP->getPointerOperandType(), Indices);
  580. ConvertUsesToScalar(GEP, NewAI, Offset + GEPOffset * 8,
  581. GEPNonConstantIdx);
  582. GEP->eraseFromParent();
  583. continue;
  584. }
  585. IRBuilder<> Builder(User);
  586. if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
  587. // The load is a bit extract from NewAI shifted right by Offset bits.
  588. Value *LoadedVal = Builder.CreateLoad(NewAI);
  589. Value *NewLoadVal = ConvertScalar_ExtractValue(
  590. LoadedVal, LI->getType(), Offset, NonConstantIdx, Builder);
  591. LI->replaceAllUsesWith(NewLoadVal);
  592. LI->eraseFromParent();
  593. continue;
  594. }
  595. if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
  596. assert(SI->getOperand(0) != Ptr && "Consistency error!");
  597. Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName() + ".in");
  598. Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
  599. NonConstantIdx, Builder);
  600. Builder.CreateStore(New, NewAI);
  601. SI->eraseFromParent();
  602. // If the load we just inserted is now dead, then the inserted store
  603. // overwrote the entire thing.
  604. if (Old->use_empty())
  605. Old->eraseFromParent();
  606. continue;
  607. }
  608. // If this is a constant sized memset of a constant value (e.g. 0) we can
  609. // transform it into a store of the expanded constant value.
  610. if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
  611. assert(MSI->getRawDest() == Ptr && "Consistency error!");
  612. assert(!NonConstantIdx && "Cannot replace dynamic memset with insert");
  613. int64_t SNumBytes = cast<ConstantInt>(MSI->getLength())->getSExtValue();
  614. if (SNumBytes > 0 && (SNumBytes >> 32) == 0) {
  615. unsigned NumBytes = static_cast<unsigned>(SNumBytes);
  616. unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
  617. // Compute the value replicated the right number of times.
  618. APInt APVal(NumBytes * 8, Val);
  619. // Splat the value if non-zero.
  620. if (Val)
  621. for (unsigned i = 1; i != NumBytes; ++i)
  622. APVal |= APVal << 8;
  623. Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName() + ".in");
  624. Value *New = ConvertScalar_InsertValue(
  625. ConstantInt::get(User->getContext(), APVal), Old, Offset, nullptr,
  626. Builder);
  627. Builder.CreateStore(New, NewAI);
  628. // If the load we just inserted is now dead, then the memset overwrote
  629. // the entire thing.
  630. if (Old->use_empty())
  631. Old->eraseFromParent();
  632. }
  633. MSI->eraseFromParent();
  634. continue;
  635. }
  636. // If this is a memcpy or memmove into or out of the whole allocation, we
  637. // can handle it like a load or store of the scalar type.
  638. if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
  639. assert(Offset == 0 && "must be store to start of alloca");
  640. assert(!NonConstantIdx && "Cannot replace dynamic transfer with insert");
  641. // If the source and destination are both to the same alloca, then this is
  642. // a noop copy-to-self, just delete it. Otherwise, emit a load and store
  643. // as appropriate.
  644. AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, DL, 0));
  645. if (GetUnderlyingObject(MTI->getSource(), DL, 0) != OrigAI) {
  646. // Dest must be OrigAI, change this to be a load from the original
  647. // pointer (bitcasted), then a store to our new alloca.
  648. assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
  649. Value *SrcPtr = MTI->getSource();
  650. PointerType *SPTy = cast<PointerType>(SrcPtr->getType());
  651. PointerType *AIPTy = cast<PointerType>(NewAI->getType());
  652. if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
  653. AIPTy = PointerType::get(AIPTy->getElementType(),
  654. SPTy->getAddressSpace());
  655. }
  656. SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
  657. LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
  658. SrcVal->setAlignment(MTI->getAlignment());
  659. Builder.CreateStore(SrcVal, NewAI);
  660. } else if (GetUnderlyingObject(MTI->getDest(), DL, 0) != OrigAI) {
  661. // Src must be OrigAI, change this to be a load from NewAI then a store
  662. // through the original dest pointer (bitcasted).
  663. assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
  664. LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
  665. PointerType *DPTy = cast<PointerType>(MTI->getDest()->getType());
  666. PointerType *AIPTy = cast<PointerType>(NewAI->getType());
  667. if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
  668. AIPTy = PointerType::get(AIPTy->getElementType(),
  669. DPTy->getAddressSpace());
  670. }
  671. Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
  672. StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
  673. NewStore->setAlignment(MTI->getAlignment());
  674. } else {
  675. // Noop transfer. Src == Dst
  676. }
  677. MTI->eraseFromParent();
  678. continue;
  679. }
  680. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
  681. if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
  682. II->getIntrinsicID() == Intrinsic::lifetime_end) {
  683. // There's no need to preserve these, as the resulting alloca will be
  684. // converted to a register anyways.
  685. II->eraseFromParent();
  686. continue;
  687. }
  688. }
  689. llvm_unreachable("Unsupported operation!");
  690. }
  691. }
  692. /// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
  693. /// or vector value FromVal, extracting the bits from the offset specified by
  694. /// Offset. This returns the value, which is of type ToType.
  695. ///
  696. /// This happens when we are converting an "integer union" to a single
  697. /// integer scalar, or when we are converting a "vector union" to a vector with
  698. /// insert/extractelement instructions.
  699. ///
  700. /// Offset is an offset from the original alloca, in bits that need to be
  701. /// shifted to the right.
  702. Value *ConvertToScalarInfo::ConvertScalar_ExtractValue(Value *FromVal,
  703. Type *ToType,
  704. uint64_t Offset,
  705. Value *NonConstantIdx,
  706. IRBuilder<> &Builder) {
  707. // If the load is of the whole new alloca, no conversion is needed.
  708. Type *FromType = FromVal->getType();
  709. if (FromType == ToType && Offset == 0)
  710. return FromVal;
  711. // If the result alloca is a vector type, this is either an element
  712. // access or a bitcast to another vector type of the same size.
  713. if (VectorType *VTy = dyn_cast<VectorType>(FromType)) {
  714. unsigned FromTypeSize = DL.getTypeAllocSize(FromType);
  715. unsigned ToTypeSize = DL.getTypeAllocSize(ToType);
  716. if (FromTypeSize == ToTypeSize)
  717. return Builder.CreateBitCast(FromVal, ToType);
  718. // Otherwise it must be an element access.
  719. unsigned Elt = 0;
  720. if (Offset) {
  721. unsigned EltSize = DL.getTypeAllocSizeInBits(VTy->getElementType());
  722. Elt = Offset / EltSize;
  723. assert(EltSize * Elt == Offset && "Invalid modulus in validity checking");
  724. }
  725. // Return the element extracted out of it.
  726. Value *Idx;
  727. if (NonConstantIdx) {
  728. if (Elt)
  729. Idx = Builder.CreateAdd(NonConstantIdx, Builder.getInt32(Elt),
  730. "dyn.offset");
  731. else
  732. Idx = NonConstantIdx;
  733. } else
  734. Idx = Builder.getInt32(Elt);
  735. Value *V = Builder.CreateExtractElement(FromVal, Idx);
  736. if (V->getType() != ToType)
  737. V = Builder.CreateBitCast(V, ToType);
  738. return V;
  739. }
  740. // If ToType is a first class aggregate, extract out each of the pieces and
  741. // use insertvalue's to form the FCA.
  742. if (StructType *ST = dyn_cast<StructType>(ToType)) {
  743. assert(!NonConstantIdx &&
  744. "Dynamic indexing into struct types not supported");
  745. const StructLayout &Layout = *DL.getStructLayout(ST);
  746. Value *Res = UndefValue::get(ST);
  747. for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
  748. Value *Elt = ConvertScalar_ExtractValue(
  749. FromVal, ST->getElementType(i),
  750. Offset + Layout.getElementOffsetInBits(i), nullptr, Builder);
  751. Res = Builder.CreateInsertValue(Res, Elt, i);
  752. }
  753. return Res;
  754. }
  755. if (ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
  756. assert(!NonConstantIdx &&
  757. "Dynamic indexing into array types not supported");
  758. uint64_t EltSize = DL.getTypeAllocSizeInBits(AT->getElementType());
  759. Value *Res = UndefValue::get(AT);
  760. for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
  761. Value *Elt =
  762. ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
  763. Offset + i * EltSize, nullptr, Builder);
  764. Res = Builder.CreateInsertValue(Res, Elt, i);
  765. }
  766. return Res;
  767. }
  768. // Otherwise, this must be a union that was converted to an integer value.
  769. IntegerType *NTy = cast<IntegerType>(FromVal->getType());
  770. // If this is a big-endian system and the load is narrower than the
  771. // full alloca type, we need to do a shift to get the right bits.
  772. int ShAmt = 0;
  773. if (DL.isBigEndian()) {
  774. // On big-endian machines, the lowest bit is stored at the bit offset
  775. // from the pointer given by getTypeStoreSizeInBits. This matters for
  776. // integers with a bitwidth that is not a multiple of 8.
  777. ShAmt = DL.getTypeStoreSizeInBits(NTy) - DL.getTypeStoreSizeInBits(ToType) -
  778. Offset;
  779. } else {
  780. ShAmt = Offset;
  781. }
  782. // Note: we support negative bitwidths (with shl) which are not defined.
  783. // We do this to support (f.e.) loads off the end of a structure where
  784. // only some bits are used.
  785. if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
  786. FromVal = Builder.CreateLShr(FromVal,
  787. ConstantInt::get(FromVal->getType(), ShAmt));
  788. else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
  789. FromVal = Builder.CreateShl(FromVal,
  790. ConstantInt::get(FromVal->getType(), -ShAmt));
  791. // Finally, unconditionally truncate the integer to the right width.
  792. unsigned LIBitWidth = DL.getTypeSizeInBits(ToType);
  793. if (LIBitWidth < NTy->getBitWidth())
  794. FromVal = Builder.CreateTrunc(
  795. FromVal, IntegerType::get(FromVal->getContext(), LIBitWidth));
  796. else if (LIBitWidth > NTy->getBitWidth())
  797. FromVal = Builder.CreateZExt(
  798. FromVal, IntegerType::get(FromVal->getContext(), LIBitWidth));
  799. // If the result is an integer, this is a trunc or bitcast.
  800. if (ToType->isIntegerTy()) {
  801. // Should be done.
  802. } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
  803. // Just do a bitcast, we know the sizes match up.
  804. FromVal = Builder.CreateBitCast(FromVal, ToType);
  805. } else {
  806. // Otherwise must be a pointer.
  807. FromVal = Builder.CreateIntToPtr(FromVal, ToType);
  808. }
  809. assert(FromVal->getType() == ToType && "Didn't convert right?");
  810. return FromVal;
  811. }
  812. /// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
  813. /// or vector value "Old" at the offset specified by Offset.
  814. ///
  815. /// This happens when we are converting an "integer union" to a
  816. /// single integer scalar, or when we are converting a "vector union" to a
  817. /// vector with insert/extractelement instructions.
  818. ///
  819. /// Offset is an offset from the original alloca, in bits that need to be
  820. /// shifted to the right.
  821. ///
  822. /// NonConstantIdx is an index value if there was a GEP with a non-constant
  823. /// index value. If this is 0 then all GEPs used to find this insert address
  824. /// are constant.
  825. Value *ConvertToScalarInfo::ConvertScalar_InsertValue(Value *SV, Value *Old,
  826. uint64_t Offset,
  827. Value *NonConstantIdx,
  828. IRBuilder<> &Builder) {
  829. // Convert the stored type to the actual type, shift it left to insert
  830. // then 'or' into place.
  831. Type *AllocaType = Old->getType();
  832. LLVMContext &Context = Old->getContext();
  833. if (VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
  834. uint64_t VecSize = DL.getTypeAllocSizeInBits(VTy);
  835. uint64_t ValSize = DL.getTypeAllocSizeInBits(SV->getType());
  836. // Changing the whole vector with memset or with an access of a different
  837. // vector type?
  838. if (ValSize == VecSize)
  839. return Builder.CreateBitCast(SV, AllocaType);
  840. // Must be an element insertion.
  841. Type *EltTy = VTy->getElementType();
  842. if (SV->getType() != EltTy)
  843. SV = Builder.CreateBitCast(SV, EltTy);
  844. uint64_t EltSize = DL.getTypeAllocSizeInBits(EltTy);
  845. unsigned Elt = Offset / EltSize;
  846. Value *Idx;
  847. if (NonConstantIdx) {
  848. if (Elt)
  849. Idx = Builder.CreateAdd(NonConstantIdx, Builder.getInt32(Elt),
  850. "dyn.offset");
  851. else
  852. Idx = NonConstantIdx;
  853. } else
  854. Idx = Builder.getInt32(Elt);
  855. return Builder.CreateInsertElement(Old, SV, Idx);
  856. }
  857. // If SV is a first-class aggregate value, insert each value recursively.
  858. if (StructType *ST = dyn_cast<StructType>(SV->getType())) {
  859. assert(!NonConstantIdx &&
  860. "Dynamic indexing into struct types not supported");
  861. const StructLayout &Layout = *DL.getStructLayout(ST);
  862. for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
  863. Value *Elt = Builder.CreateExtractValue(SV, i);
  864. Old = ConvertScalar_InsertValue(Elt, Old,
  865. Offset + Layout.getElementOffsetInBits(i),
  866. nullptr, Builder);
  867. }
  868. return Old;
  869. }
  870. if (ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
  871. assert(!NonConstantIdx &&
  872. "Dynamic indexing into array types not supported");
  873. uint64_t EltSize = DL.getTypeAllocSizeInBits(AT->getElementType());
  874. for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
  875. Value *Elt = Builder.CreateExtractValue(SV, i);
  876. Old = ConvertScalar_InsertValue(Elt, Old, Offset + i * EltSize, nullptr,
  877. Builder);
  878. }
  879. return Old;
  880. }
  881. // If SV is a float, convert it to the appropriate integer type.
  882. // If it is a pointer, do the same.
  883. unsigned SrcWidth = DL.getTypeSizeInBits(SV->getType());
  884. unsigned DestWidth = DL.getTypeSizeInBits(AllocaType);
  885. unsigned SrcStoreWidth = DL.getTypeStoreSizeInBits(SV->getType());
  886. unsigned DestStoreWidth = DL.getTypeStoreSizeInBits(AllocaType);
  887. if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
  888. SV =
  889. Builder.CreateBitCast(SV, IntegerType::get(SV->getContext(), SrcWidth));
  890. else if (SV->getType()->isPointerTy())
  891. SV = Builder.CreatePtrToInt(SV, DL.getIntPtrType(SV->getType()));
  892. // Zero extend or truncate the value if needed.
  893. if (SV->getType() != AllocaType) {
  894. if (SV->getType()->getPrimitiveSizeInBits() <
  895. AllocaType->getPrimitiveSizeInBits())
  896. SV = Builder.CreateZExt(SV, AllocaType);
  897. else {
  898. // Truncation may be needed if storing more than the alloca can hold
  899. // (undefined behavior).
  900. SV = Builder.CreateTrunc(SV, AllocaType);
  901. SrcWidth = DestWidth;
  902. SrcStoreWidth = DestStoreWidth;
  903. }
  904. }
  905. // If this is a big-endian system and the store is narrower than the
  906. // full alloca type, we need to do a shift to get the right bits.
  907. int ShAmt = 0;
  908. if (DL.isBigEndian()) {
  909. // On big-endian machines, the lowest bit is stored at the bit offset
  910. // from the pointer given by getTypeStoreSizeInBits. This matters for
  911. // integers with a bitwidth that is not a multiple of 8.
  912. ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
  913. } else {
  914. ShAmt = Offset;
  915. }
  916. // Note: we support negative bitwidths (with shr) which are not defined.
  917. // We do this to support (f.e.) stores off the end of a structure where
  918. // only some bits in the structure are set.
  919. APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
  920. if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
  921. SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(), ShAmt));
  922. Mask <<= ShAmt;
  923. } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
  924. SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(), -ShAmt));
  925. Mask = Mask.lshr(-ShAmt);
  926. }
  927. // Mask out the bits we are about to insert from the old value, and or
  928. // in the new bits.
  929. if (SrcWidth != DestWidth) {
  930. assert(DestWidth > SrcWidth);
  931. Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
  932. SV = Builder.CreateOr(Old, SV, "ins");
  933. }
  934. return SV;
  935. }
  936. //===----------------------------------------------------------------------===//
  937. // SRoA Driver
  938. //===----------------------------------------------------------------------===//
  939. bool SROA_HLSL::runOnFunction(Function &F) {
  940. Module *M = F.getParent();
  941. HLModule &HLM = M->GetOrCreateHLModule();
  942. DxilTypeSystem &typeSys = HLM.GetTypeSystem();
  943. bool Changed = performScalarRepl(F, typeSys);
  944. // change rest memcpy into ld/st.
  945. MemcpySplitter splitter(F.getContext(), typeSys);
  946. splitter.Split(F);
  947. Changed |= markPrecise(F);
  948. return Changed;
  949. }
  950. namespace {
  951. class AllocaPromoter : public LoadAndStorePromoter {
  952. AllocaInst *AI;
  953. DIBuilder *DIB;
  954. SmallVector<DbgDeclareInst *, 4> DDIs;
  955. SmallVector<DbgValueInst *, 4> DVIs;
  956. public:
  957. AllocaPromoter(ArrayRef<Instruction *> Insts, SSAUpdater &S, DIBuilder *DB)
  958. : LoadAndStorePromoter(Insts, S), AI(nullptr), DIB(DB) {}
  959. void run(AllocaInst *AI, const SmallVectorImpl<Instruction *> &Insts) {
  960. // Remember which alloca we're promoting (for isInstInList).
  961. this->AI = AI;
  962. if (auto *L = LocalAsMetadata::getIfExists(AI)) {
  963. if (auto *DINode = MetadataAsValue::getIfExists(AI->getContext(), L)) {
  964. for (User *U : DINode->users())
  965. if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
  966. DDIs.push_back(DDI);
  967. else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
  968. DVIs.push_back(DVI);
  969. }
  970. }
  971. LoadAndStorePromoter::run(Insts);
  972. AI->eraseFromParent();
  973. for (SmallVectorImpl<DbgDeclareInst *>::iterator I = DDIs.begin(),
  974. E = DDIs.end();
  975. I != E; ++I) {
  976. DbgDeclareInst *DDI = *I;
  977. DDI->eraseFromParent();
  978. }
  979. for (SmallVectorImpl<DbgValueInst *>::iterator I = DVIs.begin(),
  980. E = DVIs.end();
  981. I != E; ++I) {
  982. DbgValueInst *DVI = *I;
  983. DVI->eraseFromParent();
  984. }
  985. }
  986. bool
  987. isInstInList(Instruction *I,
  988. const SmallVectorImpl<Instruction *> &Insts) const override {
  989. if (LoadInst *LI = dyn_cast<LoadInst>(I))
  990. return LI->getOperand(0) == AI;
  991. return cast<StoreInst>(I)->getPointerOperand() == AI;
  992. }
  993. void updateDebugInfo(Instruction *Inst) const override {
  994. for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
  995. E = DDIs.end();
  996. I != E; ++I) {
  997. DbgDeclareInst *DDI = *I;
  998. if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
  999. ConvertDebugDeclareToDebugValue(DDI, SI, *DIB);
  1000. else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
  1001. ConvertDebugDeclareToDebugValue(DDI, LI, *DIB);
  1002. }
  1003. for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
  1004. E = DVIs.end();
  1005. I != E; ++I) {
  1006. DbgValueInst *DVI = *I;
  1007. Value *Arg = nullptr;
  1008. if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
  1009. // If an argument is zero extended then use argument directly. The ZExt
  1010. // may be zapped by an optimization pass in future.
  1011. if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
  1012. Arg = dyn_cast<Argument>(ZExt->getOperand(0));
  1013. if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
  1014. Arg = dyn_cast<Argument>(SExt->getOperand(0));
  1015. if (!Arg)
  1016. Arg = SI->getOperand(0);
  1017. } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
  1018. Arg = LI->getOperand(0);
  1019. } else {
  1020. continue;
  1021. }
  1022. DIB->insertDbgValueIntrinsic(Arg, 0, DVI->getVariable(),
  1023. DVI->getExpression(), DVI->getDebugLoc(),
  1024. Inst);
  1025. }
  1026. }
  1027. };
  1028. } // end anon namespace
  1029. /// isSafeSelectToSpeculate - Select instructions that use an alloca and are
  1030. /// subsequently loaded can be rewritten to load both input pointers and then
  1031. /// select between the result, allowing the load of the alloca to be promoted.
  1032. /// From this:
  1033. /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
  1034. /// %V = load i32* %P2
  1035. /// to:
  1036. /// %V1 = load i32* %Alloca -> will be mem2reg'd
  1037. /// %V2 = load i32* %Other
  1038. /// %V = select i1 %cond, i32 %V1, i32 %V2
  1039. ///
  1040. /// We can do this to a select if its only uses are loads and if the operand to
  1041. /// the select can be loaded unconditionally.
  1042. static bool isSafeSelectToSpeculate(SelectInst *SI) {
  1043. const DataLayout &DL = SI->getModule()->getDataLayout();
  1044. bool TDerefable = isDereferenceablePointer(SI->getTrueValue(), DL);
  1045. bool FDerefable = isDereferenceablePointer(SI->getFalseValue(), DL);
  1046. for (User *U : SI->users()) {
  1047. LoadInst *LI = dyn_cast<LoadInst>(U);
  1048. if (!LI || !LI->isSimple())
  1049. return false;
  1050. // Both operands to the select need to be dereferencable, either absolutely
  1051. // (e.g. allocas) or at this point because we can see other accesses to it.
  1052. if (!TDerefable &&
  1053. !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
  1054. LI->getAlignment()))
  1055. return false;
  1056. if (!FDerefable &&
  1057. !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
  1058. LI->getAlignment()))
  1059. return false;
  1060. }
  1061. return true;
  1062. }
  1063. /// isSafePHIToSpeculate - PHI instructions that use an alloca and are
  1064. /// subsequently loaded can be rewritten to load both input pointers in the pred
  1065. /// blocks and then PHI the results, allowing the load of the alloca to be
  1066. /// promoted.
  1067. /// From this:
  1068. /// %P2 = phi [i32* %Alloca, i32* %Other]
  1069. /// %V = load i32* %P2
  1070. /// to:
  1071. /// %V1 = load i32* %Alloca -> will be mem2reg'd
  1072. /// ...
  1073. /// %V2 = load i32* %Other
  1074. /// ...
  1075. /// %V = phi [i32 %V1, i32 %V2]
  1076. ///
  1077. /// We can do this to a select if its only uses are loads and if the operand to
  1078. /// the select can be loaded unconditionally.
  1079. static bool isSafePHIToSpeculate(PHINode *PN) {
  1080. // For now, we can only do this promotion if the load is in the same block as
  1081. // the PHI, and if there are no stores between the phi and load.
  1082. // TODO: Allow recursive phi users.
  1083. // TODO: Allow stores.
  1084. BasicBlock *BB = PN->getParent();
  1085. unsigned MaxAlign = 0;
  1086. for (User *U : PN->users()) {
  1087. LoadInst *LI = dyn_cast<LoadInst>(U);
  1088. if (!LI || !LI->isSimple())
  1089. return false;
  1090. // For now we only allow loads in the same block as the PHI. This is a
  1091. // common case that happens when instcombine merges two loads through a PHI.
  1092. if (LI->getParent() != BB)
  1093. return false;
  1094. // Ensure that there are no instructions between the PHI and the load that
  1095. // could store.
  1096. for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
  1097. if (BBI->mayWriteToMemory())
  1098. return false;
  1099. MaxAlign = std::max(MaxAlign, LI->getAlignment());
  1100. }
  1101. const DataLayout &DL = PN->getModule()->getDataLayout();
  1102. // Okay, we know that we have one or more loads in the same block as the PHI.
  1103. // We can transform this if it is safe to push the loads into the predecessor
  1104. // blocks. The only thing to watch out for is that we can't put a possibly
  1105. // trapping load in the predecessor if it is a critical edge.
  1106. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  1107. BasicBlock *Pred = PN->getIncomingBlock(i);
  1108. Value *InVal = PN->getIncomingValue(i);
  1109. // If the terminator of the predecessor has side-effects (an invoke),
  1110. // there is no safe place to put a load in the predecessor.
  1111. if (Pred->getTerminator()->mayHaveSideEffects())
  1112. return false;
  1113. // If the value is produced by the terminator of the predecessor
  1114. // (an invoke), there is no valid place to put a load in the predecessor.
  1115. if (Pred->getTerminator() == InVal)
  1116. return false;
  1117. // If the predecessor has a single successor, then the edge isn't critical.
  1118. if (Pred->getTerminator()->getNumSuccessors() == 1)
  1119. continue;
  1120. // If this pointer is always safe to load, or if we can prove that there is
  1121. // already a load in the block, then we can move the load to the pred block.
  1122. if (isDereferenceablePointer(InVal, DL) ||
  1123. isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign))
  1124. continue;
  1125. return false;
  1126. }
  1127. return true;
  1128. }
  1129. /// tryToMakeAllocaBePromotable - This returns true if the alloca only has
  1130. /// direct (non-volatile) loads and stores to it. If the alloca is close but
  1131. /// not quite there, this will transform the code to allow promotion. As such,
  1132. /// it is a non-pure predicate.
  1133. static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const DataLayout &DL) {
  1134. SetVector<Instruction *, SmallVector<Instruction *, 4>,
  1135. SmallPtrSet<Instruction *, 4>>
  1136. InstsToRewrite;
  1137. for (User *U : AI->users()) {
  1138. if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
  1139. if (!LI->isSimple())
  1140. return false;
  1141. continue;
  1142. }
  1143. if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  1144. if (SI->getOperand(0) == AI || !SI->isSimple())
  1145. return false; // Don't allow a store OF the AI, only INTO the AI.
  1146. continue;
  1147. }
  1148. if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
  1149. // If the condition being selected on is a constant, fold the select, yes
  1150. // this does (rarely) happen early on.
  1151. if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
  1152. Value *Result = SI->getOperand(1 + CI->isZero());
  1153. SI->replaceAllUsesWith(Result);
  1154. SI->eraseFromParent();
  1155. // This is very rare and we just scrambled the use list of AI, start
  1156. // over completely.
  1157. return tryToMakeAllocaBePromotable(AI, DL);
  1158. }
  1159. // If it is safe to turn "load (select c, AI, ptr)" into a select of two
  1160. // loads, then we can transform this by rewriting the select.
  1161. if (!isSafeSelectToSpeculate(SI))
  1162. return false;
  1163. InstsToRewrite.insert(SI);
  1164. continue;
  1165. }
  1166. if (PHINode *PN = dyn_cast<PHINode>(U)) {
  1167. if (PN->use_empty()) { // Dead PHIs can be stripped.
  1168. InstsToRewrite.insert(PN);
  1169. continue;
  1170. }
  1171. // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
  1172. // in the pred blocks, then we can transform this by rewriting the PHI.
  1173. if (!isSafePHIToSpeculate(PN))
  1174. return false;
  1175. InstsToRewrite.insert(PN);
  1176. continue;
  1177. }
  1178. if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
  1179. if (onlyUsedByLifetimeMarkers(BCI)) {
  1180. InstsToRewrite.insert(BCI);
  1181. continue;
  1182. }
  1183. }
  1184. return false;
  1185. }
  1186. // If there are no instructions to rewrite, then all uses are load/stores and
  1187. // we're done!
  1188. if (InstsToRewrite.empty())
  1189. return true;
  1190. // If we have instructions that need to be rewritten for this to be promotable
  1191. // take care of it now.
  1192. for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
  1193. if (BitCastInst *BCI = dyn_cast<BitCastInst>(InstsToRewrite[i])) {
  1194. // This could only be a bitcast used by nothing but lifetime intrinsics.
  1195. for (BitCastInst::user_iterator I = BCI->user_begin(),
  1196. E = BCI->user_end();
  1197. I != E;)
  1198. cast<Instruction>(*I++)->eraseFromParent();
  1199. BCI->eraseFromParent();
  1200. continue;
  1201. }
  1202. if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
  1203. // Selects in InstsToRewrite only have load uses. Rewrite each as two
  1204. // loads with a new select.
  1205. while (!SI->use_empty()) {
  1206. LoadInst *LI = cast<LoadInst>(SI->user_back());
  1207. IRBuilder<> Builder(LI);
  1208. LoadInst *TrueLoad =
  1209. Builder.CreateLoad(SI->getTrueValue(), LI->getName() + ".t");
  1210. LoadInst *FalseLoad =
  1211. Builder.CreateLoad(SI->getFalseValue(), LI->getName() + ".f");
  1212. // Transfer alignment and AA info if present.
  1213. TrueLoad->setAlignment(LI->getAlignment());
  1214. FalseLoad->setAlignment(LI->getAlignment());
  1215. AAMDNodes Tags;
  1216. LI->getAAMetadata(Tags);
  1217. if (Tags) {
  1218. TrueLoad->setAAMetadata(Tags);
  1219. FalseLoad->setAAMetadata(Tags);
  1220. }
  1221. Value *V =
  1222. Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
  1223. V->takeName(LI);
  1224. LI->replaceAllUsesWith(V);
  1225. LI->eraseFromParent();
  1226. }
  1227. // Now that all the loads are gone, the select is gone too.
  1228. SI->eraseFromParent();
  1229. continue;
  1230. }
  1231. // Otherwise, we have a PHI node which allows us to push the loads into the
  1232. // predecessors.
  1233. PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
  1234. if (PN->use_empty()) {
  1235. PN->eraseFromParent();
  1236. continue;
  1237. }
  1238. Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
  1239. PHINode *NewPN = PHINode::Create(LoadTy, PN->getNumIncomingValues(),
  1240. PN->getName() + ".ld", PN);
  1241. // Get the AA tags and alignment to use from one of the loads. It doesn't
  1242. // matter which one we get and if any differ, it doesn't matter.
  1243. LoadInst *SomeLoad = cast<LoadInst>(PN->user_back());
  1244. AAMDNodes AATags;
  1245. SomeLoad->getAAMetadata(AATags);
  1246. unsigned Align = SomeLoad->getAlignment();
  1247. // Rewrite all loads of the PN to use the new PHI.
  1248. while (!PN->use_empty()) {
  1249. LoadInst *LI = cast<LoadInst>(PN->user_back());
  1250. LI->replaceAllUsesWith(NewPN);
  1251. LI->eraseFromParent();
  1252. }
  1253. // Inject loads into all of the pred blocks. Keep track of which blocks we
  1254. // insert them into in case we have multiple edges from the same block.
  1255. DenseMap<BasicBlock *, LoadInst *> InsertedLoads;
  1256. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  1257. BasicBlock *Pred = PN->getIncomingBlock(i);
  1258. LoadInst *&Load = InsertedLoads[Pred];
  1259. if (!Load) {
  1260. Load = new LoadInst(PN->getIncomingValue(i),
  1261. PN->getName() + "." + Pred->getName(),
  1262. Pred->getTerminator());
  1263. Load->setAlignment(Align);
  1264. if (AATags)
  1265. Load->setAAMetadata(AATags);
  1266. }
  1267. NewPN->addIncoming(Load, Pred);
  1268. }
  1269. PN->eraseFromParent();
  1270. }
  1271. ++NumAdjusted;
  1272. return true;
  1273. }
  1274. bool SROA_HLSL::performPromotion(Function &F) {
  1275. std::vector<AllocaInst *> Allocas;
  1276. const DataLayout &DL = F.getParent()->getDataLayout();
  1277. DominatorTree *DT = nullptr;
  1278. if (HasDomTree)
  1279. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  1280. AssumptionCache &AC =
  1281. getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  1282. BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
  1283. DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
  1284. bool Changed = false;
  1285. SmallVector<Instruction *, 64> Insts;
  1286. while (1) {
  1287. Allocas.clear();
  1288. // Find allocas that are safe to promote, by looking at all instructions in
  1289. // the entry node
  1290. for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
  1291. if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) { // Is it an alloca?
  1292. DbgDeclareInst *DDI = llvm::FindAllocaDbgDeclare(AI);
  1293. // Skip alloca has debug info when not promote.
  1294. if (DDI && !RunPromotion) {
  1295. continue;
  1296. }
  1297. if (tryToMakeAllocaBePromotable(AI, DL))
  1298. Allocas.push_back(AI);
  1299. }
  1300. if (Allocas.empty())
  1301. break;
  1302. if (HasDomTree)
  1303. PromoteMemToReg(Allocas, *DT, nullptr, &AC);
  1304. else {
  1305. SSAUpdater SSA;
  1306. for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
  1307. AllocaInst *AI = Allocas[i];
  1308. // Build list of instructions to promote.
  1309. for (User *U : AI->users())
  1310. Insts.push_back(cast<Instruction>(U));
  1311. AllocaPromoter(Insts, SSA, &DIB).run(AI, Insts);
  1312. Insts.clear();
  1313. }
  1314. }
  1315. NumPromoted += Allocas.size();
  1316. Changed = true;
  1317. }
  1318. return Changed;
  1319. }
  1320. /// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
  1321. /// SROA. It must be a struct or array type with a small number of elements.
  1322. bool SROA_HLSL::ShouldAttemptScalarRepl(AllocaInst *AI) {
  1323. Type *T = AI->getAllocatedType();
  1324. // promote every struct.
  1325. if (dyn_cast<StructType>(T))
  1326. return true;
  1327. // promote every array.
  1328. if (dyn_cast<ArrayType>(T))
  1329. return true;
  1330. return false;
  1331. }
  1332. // performScalarRepl - This algorithm is a simple worklist driven algorithm,
  1333. // which runs on all of the alloca instructions in the entry block, removing
  1334. // them if they are only used by getelementptr instructions.
  1335. //
  1336. bool SROA_HLSL::performScalarRepl(Function &F, DxilTypeSystem &typeSys) {
  1337. std::vector<AllocaInst *> AllocaList;
  1338. const DataLayout &DL = F.getParent()->getDataLayout();
  1339. // Make sure big alloca split first.
  1340. // This will simplify memcpy check between part of big alloca and small
  1341. // alloca. Big alloca will be split to smaller piece first, when process the
  1342. // alloca, it will be alloca flattened from big alloca instead of a GEP of big
  1343. // alloca.
  1344. auto size_cmp = [&DL](const AllocaInst *a0, const AllocaInst *a1) -> bool {
  1345. return DL.getTypeAllocSize(a0->getAllocatedType()) <
  1346. DL.getTypeAllocSize(a1->getAllocatedType());
  1347. };
  1348. std::priority_queue<AllocaInst *, std::vector<AllocaInst *>,
  1349. std::function<bool(AllocaInst *, AllocaInst *)>>
  1350. WorkList(size_cmp);
  1351. std::unordered_map<AllocaInst*, DbgDeclareInst*> DDIMap;
  1352. // Scan the entry basic block, adding allocas to the worklist.
  1353. BasicBlock &BB = F.getEntryBlock();
  1354. for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
  1355. if (AllocaInst *A = dyn_cast<AllocaInst>(I)) {
  1356. if (!A->user_empty()) {
  1357. WorkList.push(A);
  1358. // merge GEP use for the allocs
  1359. HLModule::MergeGepUse(A);
  1360. if (DbgDeclareInst *DDI = llvm::FindAllocaDbgDeclare(A)) {
  1361. DDIMap[A] = DDI;
  1362. }
  1363. }
  1364. }
  1365. DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
  1366. // Process the worklist
  1367. bool Changed = false;
  1368. while (!WorkList.empty()) {
  1369. AllocaInst *AI = WorkList.top();
  1370. WorkList.pop();
  1371. // Handle dead allocas trivially. These can be formed by SROA'ing arrays
  1372. // with unused elements.
  1373. if (AI->use_empty()) {
  1374. AI->eraseFromParent();
  1375. Changed = true;
  1376. continue;
  1377. }
  1378. const bool bAllowReplace = true;
  1379. if (SROA_Helper::LowerMemcpy(AI, /*annotation*/ nullptr, typeSys, DL,
  1380. bAllowReplace)) {
  1381. Changed = true;
  1382. continue;
  1383. }
  1384. // If this alloca is impossible for us to promote, reject it early.
  1385. if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
  1386. continue;
  1387. // Check to see if we can perform the core SROA transformation. We cannot
  1388. // transform the allocation instruction if it is an array allocation
  1389. // (allocations OF arrays are ok though), and an allocation of a scalar
  1390. // value cannot be decomposed at all.
  1391. uint64_t AllocaSize = DL.getTypeAllocSize(AI->getAllocatedType());
  1392. // Do not promote [0 x %struct].
  1393. if (AllocaSize == 0)
  1394. continue;
  1395. Type *Ty = AI->getAllocatedType();
  1396. // Skip empty struct type.
  1397. if (SROA_Helper::IsEmptyStructType(Ty, typeSys)) {
  1398. SROA_Helper::MarkEmptyStructUsers(AI, DeadInsts);
  1399. DeleteDeadInstructions();
  1400. continue;
  1401. }
  1402. // If the alloca looks like a good candidate for scalar replacement, and
  1403. // if
  1404. // all its users can be transformed, then split up the aggregate into its
  1405. // separate elements.
  1406. if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
  1407. std::vector<Value *> Elts;
  1408. IRBuilder<> Builder(dxilutil::FirstNonAllocaInsertionPt(AI));
  1409. bool hasPrecise = HLModule::HasPreciseAttributeWithMetadata(AI);
  1410. bool SROAed = SROA_Helper::DoScalarReplacement(
  1411. AI, Elts, Builder, /*bFlatVector*/ true, hasPrecise, typeSys, DL,
  1412. DeadInsts);
  1413. if (SROAed) {
  1414. Type *Ty = AI->getAllocatedType();
  1415. // Skip empty struct parameters.
  1416. if (StructType *ST = dyn_cast<StructType>(Ty)) {
  1417. if (!HLMatrixLower::IsMatrixType(Ty)) {
  1418. DxilStructAnnotation *SA = typeSys.GetStructAnnotation(ST);
  1419. if (SA && SA->IsEmptyStruct()) {
  1420. for (User *U : AI->users()) {
  1421. if (StoreInst *SI = dyn_cast<StoreInst>(U))
  1422. DeadInsts.emplace_back(SI);
  1423. }
  1424. DeleteDeadInstructions();
  1425. AI->replaceAllUsesWith(UndefValue::get(AI->getType()));
  1426. AI->eraseFromParent();
  1427. continue;
  1428. }
  1429. }
  1430. }
  1431. DbgDeclareInst *DDI = nullptr;
  1432. unsigned debugOffset = 0;
  1433. auto iter = DDIMap.find(AI);
  1434. if (iter != DDIMap.end()) {
  1435. DDI = iter->second;
  1436. }
  1437. // Push Elts into workList.
  1438. for (auto iter = Elts.begin(); iter != Elts.end(); iter++) {
  1439. AllocaInst *Elt = cast<AllocaInst>(*iter);
  1440. WorkList.push(Elt);
  1441. if (DDI) {
  1442. Type *Ty = Elt->getAllocatedType();
  1443. unsigned size = DL.getTypeAllocSize(Ty);
  1444. DIExpression *DDIExp =
  1445. DIB.createBitPieceExpression(debugOffset, size);
  1446. debugOffset += size;
  1447. DbgDeclareInst *EltDDI = cast<DbgDeclareInst>(DIB.insertDeclare(
  1448. Elt, DDI->getVariable(), DDIExp, DDI->getDebugLoc(), DDI));
  1449. DDIMap[Elt] = EltDDI;
  1450. }
  1451. }
  1452. // Now erase any instructions that were made dead while rewriting the
  1453. // alloca.
  1454. DeleteDeadInstructions();
  1455. ++NumReplaced;
  1456. AI->eraseFromParent();
  1457. Changed = true;
  1458. continue;
  1459. }
  1460. }
  1461. }
  1462. return Changed;
  1463. }
  1464. // markPrecise - To save the precise attribute on alloca inst which might be removed by promote,
  1465. // mark precise attribute with function call on alloca inst stores.
  1466. bool SROA_HLSL::markPrecise(Function &F) {
  1467. bool Changed = false;
  1468. BasicBlock &BB = F.getEntryBlock();
  1469. for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
  1470. if (AllocaInst *A = dyn_cast<AllocaInst>(I)) {
  1471. // TODO: Only do this on basic types.
  1472. if (HLModule::HasPreciseAttributeWithMetadata(A)) {
  1473. HLModule::MarkPreciseAttributeOnPtrWithFunctionCall(A,
  1474. *(F.getParent()));
  1475. Changed = true;
  1476. }
  1477. }
  1478. return Changed;
  1479. }
  1480. /// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
  1481. /// recursively including all their operands that become trivially dead.
  1482. void SROA_HLSL::DeleteDeadInstructions() {
  1483. while (!DeadInsts.empty()) {
  1484. Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
  1485. for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
  1486. if (Instruction *U = dyn_cast<Instruction>(*OI)) {
  1487. // Zero out the operand and see if it becomes trivially dead.
  1488. // (But, don't add allocas to the dead instruction list -- they are
  1489. // already on the worklist and will be deleted separately.)
  1490. *OI = nullptr;
  1491. if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
  1492. DeadInsts.push_back(U);
  1493. }
  1494. I->eraseFromParent();
  1495. }
  1496. }
  1497. /// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
  1498. /// performing scalar replacement of alloca AI. The results are flagged in
  1499. /// the Info parameter. Offset indicates the position within AI that is
  1500. /// referenced by this instruction.
  1501. void SROA_HLSL::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
  1502. AllocaInfo &Info) {
  1503. if (I->getType()->isPointerTy()) {
  1504. // Don't check object pointers.
  1505. if (HLModule::IsHLSLObjectType(I->getType()->getPointerElementType()))
  1506. return;
  1507. }
  1508. const DataLayout &DL = I->getModule()->getDataLayout();
  1509. for (Use &U : I->uses()) {
  1510. Instruction *User = cast<Instruction>(U.getUser());
  1511. if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
  1512. isSafeForScalarRepl(BC, Offset, Info);
  1513. } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
  1514. uint64_t GEPOffset = Offset;
  1515. isSafeGEP(GEPI, GEPOffset, Info);
  1516. if (!Info.isUnsafe)
  1517. isSafeForScalarRepl(GEPI, GEPOffset, Info);
  1518. } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
  1519. ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
  1520. if (!Length || Length->isNegative())
  1521. return MarkUnsafe(Info, User);
  1522. isSafeMemAccess(Offset, Length->getZExtValue(), nullptr,
  1523. U.getOperandNo() == 0, Info, MI,
  1524. true /*AllowWholeAccess*/);
  1525. } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
  1526. if (!LI->isSimple())
  1527. return MarkUnsafe(Info, User);
  1528. Type *LIType = LI->getType();
  1529. isSafeMemAccess(Offset, DL.getTypeAllocSize(LIType), LIType, false, Info,
  1530. LI, true /*AllowWholeAccess*/);
  1531. Info.hasALoadOrStore = true;
  1532. } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
  1533. // Store is ok if storing INTO the pointer, not storing the pointer
  1534. if (!SI->isSimple() || SI->getOperand(0) == I)
  1535. return MarkUnsafe(Info, User);
  1536. Type *SIType = SI->getOperand(0)->getType();
  1537. isSafeMemAccess(Offset, DL.getTypeAllocSize(SIType), SIType, true, Info,
  1538. SI, true /*AllowWholeAccess*/);
  1539. Info.hasALoadOrStore = true;
  1540. } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
  1541. if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
  1542. II->getIntrinsicID() != Intrinsic::lifetime_end)
  1543. return MarkUnsafe(Info, User);
  1544. } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
  1545. isSafePHISelectUseForScalarRepl(User, Offset, Info);
  1546. } else if (CallInst *CI = dyn_cast<CallInst>(User)) {
  1547. HLOpcodeGroup group = GetHLOpcodeGroupByName(CI->getCalledFunction());
  1548. // Most HL functions are safe for scalar repl.
  1549. if (HLOpcodeGroup::NotHL == group)
  1550. return MarkUnsafe(Info, User);
  1551. else if (HLOpcodeGroup::HLIntrinsic == group) {
  1552. // TODO: should we check HL parameter type for UDT overload instead of basing on IOP?
  1553. IntrinsicOp opcode = static_cast<IntrinsicOp>(GetHLOpcode(CI));
  1554. if (IntrinsicOp::IOP_TraceRay == opcode ||
  1555. IntrinsicOp::IOP_ReportHit == opcode ||
  1556. IntrinsicOp::IOP_CallShader == opcode) {
  1557. return MarkUnsafe(Info, User);
  1558. }
  1559. }
  1560. } else {
  1561. return MarkUnsafe(Info, User);
  1562. }
  1563. if (Info.isUnsafe)
  1564. return;
  1565. }
  1566. }
  1567. /// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
  1568. /// derived from the alloca, we can often still split the alloca into elements.
  1569. /// This is useful if we have a large alloca where one element is phi'd
  1570. /// together somewhere: we can SRoA and promote all the other elements even if
  1571. /// we end up not being able to promote this one.
  1572. ///
  1573. /// All we require is that the uses of the PHI do not index into other parts of
  1574. /// the alloca. The most important use case for this is single load and stores
  1575. /// that are PHI'd together, which can happen due to code sinking.
  1576. void SROA_HLSL::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
  1577. AllocaInfo &Info) {
  1578. // If we've already checked this PHI, don't do it again.
  1579. if (PHINode *PN = dyn_cast<PHINode>(I))
  1580. if (!Info.CheckedPHIs.insert(PN).second)
  1581. return;
  1582. const DataLayout &DL = I->getModule()->getDataLayout();
  1583. for (User *U : I->users()) {
  1584. Instruction *UI = cast<Instruction>(U);
  1585. if (BitCastInst *BC = dyn_cast<BitCastInst>(UI)) {
  1586. isSafePHISelectUseForScalarRepl(BC, Offset, Info);
  1587. } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(UI)) {
  1588. // Only allow "bitcast" GEPs for simplicity. We could generalize this,
  1589. // but would have to prove that we're staying inside of an element being
  1590. // promoted.
  1591. if (!GEPI->hasAllZeroIndices())
  1592. return MarkUnsafe(Info, UI);
  1593. isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
  1594. } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
  1595. if (!LI->isSimple())
  1596. return MarkUnsafe(Info, UI);
  1597. Type *LIType = LI->getType();
  1598. isSafeMemAccess(Offset, DL.getTypeAllocSize(LIType), LIType, false, Info,
  1599. LI, false /*AllowWholeAccess*/);
  1600. Info.hasALoadOrStore = true;
  1601. } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
  1602. // Store is ok if storing INTO the pointer, not storing the pointer
  1603. if (!SI->isSimple() || SI->getOperand(0) == I)
  1604. return MarkUnsafe(Info, UI);
  1605. Type *SIType = SI->getOperand(0)->getType();
  1606. isSafeMemAccess(Offset, DL.getTypeAllocSize(SIType), SIType, true, Info,
  1607. SI, false /*AllowWholeAccess*/);
  1608. Info.hasALoadOrStore = true;
  1609. } else if (isa<PHINode>(UI) || isa<SelectInst>(UI)) {
  1610. isSafePHISelectUseForScalarRepl(UI, Offset, Info);
  1611. } else {
  1612. return MarkUnsafe(Info, UI);
  1613. }
  1614. if (Info.isUnsafe)
  1615. return;
  1616. }
  1617. }
  1618. /// isSafeGEP - Check if a GEP instruction can be handled for scalar
  1619. /// replacement. It is safe when all the indices are constant, in-bounds
  1620. /// references, and when the resulting offset corresponds to an element within
  1621. /// the alloca type. The results are flagged in the Info parameter. Upon
  1622. /// return, Offset is adjusted as specified by the GEP indices.
  1623. void SROA_HLSL::isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset,
  1624. AllocaInfo &Info) {
  1625. gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
  1626. if (GEPIt == E)
  1627. return;
  1628. bool NonConstant = false;
  1629. unsigned NonConstantIdxSize = 0;
  1630. // Compute the offset due to this GEP and check if the alloca has a
  1631. // component element at that offset.
  1632. SmallVector<Value *, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
  1633. auto indicesIt = Indices.begin();
  1634. // Walk through the GEP type indices, checking the types that this indexes
  1635. // into.
  1636. uint32_t arraySize = 0;
  1637. bool isArrayIndexing = false;
  1638. for (;GEPIt != E; ++GEPIt) {
  1639. Type *Ty = *GEPIt;
  1640. if (Ty->isStructTy() && !HLMatrixLower::IsMatrixType(Ty)) {
  1641. // Don't go inside struct when mark hasArrayIndexing and hasVectorIndexing.
  1642. // The following level won't affect scalar repl on the struct.
  1643. break;
  1644. }
  1645. if (GEPIt->isArrayTy()) {
  1646. arraySize = GEPIt->getArrayNumElements();
  1647. isArrayIndexing = true;
  1648. }
  1649. if (GEPIt->isVectorTy()) {
  1650. arraySize = GEPIt->getVectorNumElements();
  1651. isArrayIndexing = false;
  1652. }
  1653. // Allow dynamic indexing
  1654. ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
  1655. if (!IdxVal) {
  1656. // for dynamic index, use array size - 1 to check the offset
  1657. *indicesIt = Constant::getIntegerValue(
  1658. Type::getInt32Ty(GEPI->getContext()), APInt(32, arraySize - 1));
  1659. if (isArrayIndexing)
  1660. Info.hasArrayIndexing = true;
  1661. else
  1662. Info.hasVectorIndexing = true;
  1663. NonConstant = true;
  1664. }
  1665. indicesIt++;
  1666. }
  1667. // Continue iterate only for the NonConstant.
  1668. for (;GEPIt != E; ++GEPIt) {
  1669. Type *Ty = *GEPIt;
  1670. if (Ty->isArrayTy()) {
  1671. arraySize = GEPIt->getArrayNumElements();
  1672. }
  1673. if (Ty->isVectorTy()) {
  1674. arraySize = GEPIt->getVectorNumElements();
  1675. }
  1676. // Allow dynamic indexing
  1677. ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
  1678. if (!IdxVal) {
  1679. // for dynamic index, use array size - 1 to check the offset
  1680. *indicesIt = Constant::getIntegerValue(
  1681. Type::getInt32Ty(GEPI->getContext()), APInt(32, arraySize - 1));
  1682. NonConstant = true;
  1683. }
  1684. indicesIt++;
  1685. }
  1686. // If this GEP is non-constant then the last operand must have been a
  1687. // dynamic index into a vector. Pop this now as it has no impact on the
  1688. // constant part of the offset.
  1689. if (NonConstant)
  1690. Indices.pop_back();
  1691. const DataLayout &DL = GEPI->getModule()->getDataLayout();
  1692. Offset += DL.getIndexedOffset(GEPI->getPointerOperandType(), Indices);
  1693. if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset, NonConstantIdxSize,
  1694. DL))
  1695. MarkUnsafe(Info, GEPI);
  1696. }
  1697. /// isHomogeneousAggregate - Check if type T is a struct or array containing
  1698. /// elements of the same type (which is always true for arrays). If so,
  1699. /// return true with NumElts and EltTy set to the number of elements and the
  1700. /// element type, respectively.
  1701. static bool isHomogeneousAggregate(Type *T, unsigned &NumElts, Type *&EltTy) {
  1702. if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
  1703. NumElts = AT->getNumElements();
  1704. EltTy = (NumElts == 0 ? nullptr : AT->getElementType());
  1705. return true;
  1706. }
  1707. if (StructType *ST = dyn_cast<StructType>(T)) {
  1708. NumElts = ST->getNumContainedTypes();
  1709. EltTy = (NumElts == 0 ? nullptr : ST->getContainedType(0));
  1710. for (unsigned n = 1; n < NumElts; ++n) {
  1711. if (ST->getContainedType(n) != EltTy)
  1712. return false;
  1713. }
  1714. return true;
  1715. }
  1716. return false;
  1717. }
  1718. /// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
  1719. /// "homogeneous" aggregates with the same element type and number of elements.
  1720. static bool isCompatibleAggregate(Type *T1, Type *T2) {
  1721. if (T1 == T2)
  1722. return true;
  1723. unsigned NumElts1, NumElts2;
  1724. Type *EltTy1, *EltTy2;
  1725. if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
  1726. isHomogeneousAggregate(T2, NumElts2, EltTy2) && NumElts1 == NumElts2 &&
  1727. EltTy1 == EltTy2)
  1728. return true;
  1729. return false;
  1730. }
  1731. /// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
  1732. /// alloca or has an offset and size that corresponds to a component element
  1733. /// within it. The offset checked here may have been formed from a GEP with a
  1734. /// pointer bitcasted to a different type.
  1735. ///
  1736. /// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
  1737. /// unit. If false, it only allows accesses known to be in a single element.
  1738. void SROA_HLSL::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
  1739. Type *MemOpType, bool isStore, AllocaInfo &Info,
  1740. Instruction *TheAccess, bool AllowWholeAccess) {
  1741. // What hlsl cares is Info.hasVectorIndexing.
  1742. // Do nothing here.
  1743. }
  1744. /// TypeHasComponent - Return true if T has a component type with the
  1745. /// specified offset and size. If Size is zero, do not check the size.
  1746. bool SROA_HLSL::TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size,
  1747. const DataLayout &DL) {
  1748. Type *EltTy;
  1749. uint64_t EltSize;
  1750. if (StructType *ST = dyn_cast<StructType>(T)) {
  1751. const StructLayout *Layout = DL.getStructLayout(ST);
  1752. unsigned EltIdx = Layout->getElementContainingOffset(Offset);
  1753. EltTy = ST->getContainedType(EltIdx);
  1754. EltSize = DL.getTypeAllocSize(EltTy);
  1755. Offset -= Layout->getElementOffset(EltIdx);
  1756. } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
  1757. EltTy = AT->getElementType();
  1758. EltSize = DL.getTypeAllocSize(EltTy);
  1759. if (Offset >= AT->getNumElements() * EltSize)
  1760. return false;
  1761. Offset %= EltSize;
  1762. } else if (VectorType *VT = dyn_cast<VectorType>(T)) {
  1763. EltTy = VT->getElementType();
  1764. EltSize = DL.getTypeAllocSize(EltTy);
  1765. if (Offset >= VT->getNumElements() * EltSize)
  1766. return false;
  1767. Offset %= EltSize;
  1768. } else {
  1769. return false;
  1770. }
  1771. if (Offset == 0 && (Size == 0 || EltSize == Size))
  1772. return true;
  1773. // Check if the component spans multiple elements.
  1774. if (Offset + Size > EltSize)
  1775. return false;
  1776. return TypeHasComponent(EltTy, Offset, Size, DL);
  1777. }
  1778. /// LoadVectorArray - Load vector array like [2 x <4 x float>] from
  1779. /// arrays like 4 [2 x float] or struct array like
  1780. /// [2 x { <4 x float>, < 4 x uint> }]
  1781. /// from arrays like [ 2 x <4 x float> ], [ 2 x <4 x uint> ].
  1782. static Value *LoadVectorOrStructArray(ArrayType *AT, ArrayRef<Value *> NewElts,
  1783. SmallVector<Value *, 8> &idxList,
  1784. IRBuilder<> &Builder) {
  1785. Type *EltTy = AT->getElementType();
  1786. Value *retVal = llvm::UndefValue::get(AT);
  1787. Type *i32Ty = Type::getInt32Ty(EltTy->getContext());
  1788. uint32_t arraySize = AT->getNumElements();
  1789. for (uint32_t i = 0; i < arraySize; i++) {
  1790. Constant *idx = ConstantInt::get(i32Ty, i);
  1791. idxList.emplace_back(idx);
  1792. if (ArrayType *EltAT = dyn_cast<ArrayType>(EltTy)) {
  1793. Value *EltVal = LoadVectorOrStructArray(EltAT, NewElts, idxList, Builder);
  1794. retVal = Builder.CreateInsertValue(retVal, EltVal, i);
  1795. } else {
  1796. assert((EltTy->isVectorTy() ||
  1797. EltTy->isStructTy()) && "must be a vector or struct type");
  1798. bool isVectorTy = EltTy->isVectorTy();
  1799. Value *retVec = llvm::UndefValue::get(EltTy);
  1800. if (isVectorTy) {
  1801. for (uint32_t c = 0; c < EltTy->getVectorNumElements(); c++) {
  1802. Value *GEP = Builder.CreateInBoundsGEP(NewElts[c], idxList);
  1803. Value *elt = Builder.CreateLoad(GEP);
  1804. retVec = Builder.CreateInsertElement(retVec, elt, c);
  1805. }
  1806. } else {
  1807. for (uint32_t c = 0; c < EltTy->getStructNumElements(); c++) {
  1808. Value *GEP = Builder.CreateInBoundsGEP(NewElts[c], idxList);
  1809. Value *elt = Builder.CreateLoad(GEP);
  1810. retVec = Builder.CreateInsertValue(retVec, elt, c);
  1811. }
  1812. }
  1813. retVal = Builder.CreateInsertValue(retVal, retVec, i);
  1814. }
  1815. idxList.pop_back();
  1816. }
  1817. return retVal;
  1818. }
  1819. /// LoadVectorArray - Store vector array like [2 x <4 x float>] to
  1820. /// arrays like 4 [2 x float] or struct array like
  1821. /// [2 x { <4 x float>, < 4 x uint> }]
  1822. /// from arrays like [ 2 x <4 x float> ], [ 2 x <4 x uint> ].
  1823. static void StoreVectorOrStructArray(ArrayType *AT, Value *val,
  1824. ArrayRef<Value *> NewElts,
  1825. SmallVector<Value *, 8> &idxList,
  1826. IRBuilder<> &Builder) {
  1827. Type *EltTy = AT->getElementType();
  1828. Type *i32Ty = Type::getInt32Ty(EltTy->getContext());
  1829. uint32_t arraySize = AT->getNumElements();
  1830. for (uint32_t i = 0; i < arraySize; i++) {
  1831. Value *elt = Builder.CreateExtractValue(val, i);
  1832. Constant *idx = ConstantInt::get(i32Ty, i);
  1833. idxList.emplace_back(idx);
  1834. if (ArrayType *EltAT = dyn_cast<ArrayType>(EltTy)) {
  1835. StoreVectorOrStructArray(EltAT, elt, NewElts, idxList, Builder);
  1836. } else {
  1837. assert((EltTy->isVectorTy() ||
  1838. EltTy->isStructTy()) && "must be a vector or struct type");
  1839. bool isVectorTy = EltTy->isVectorTy();
  1840. if (isVectorTy) {
  1841. for (uint32_t c = 0; c < EltTy->getVectorNumElements(); c++) {
  1842. Value *component = Builder.CreateExtractElement(elt, c);
  1843. Value *GEP = Builder.CreateInBoundsGEP(NewElts[c], idxList);
  1844. Builder.CreateStore(component, GEP);
  1845. }
  1846. } else {
  1847. for (uint32_t c = 0; c < EltTy->getStructNumElements(); c++) {
  1848. Value *field = Builder.CreateExtractValue(elt, c);
  1849. Value *GEP = Builder.CreateInBoundsGEP(NewElts[c], idxList);
  1850. Builder.CreateStore(field, GEP);
  1851. }
  1852. }
  1853. }
  1854. idxList.pop_back();
  1855. }
  1856. }
  1857. /// HasPadding - Return true if the specified type has any structure or
  1858. /// alignment padding in between the elements that would be split apart
  1859. /// by SROA; return false otherwise.
  1860. static bool HasPadding(Type *Ty, const DataLayout &DL) {
  1861. if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
  1862. Ty = ATy->getElementType();
  1863. return DL.getTypeSizeInBits(Ty) != DL.getTypeAllocSizeInBits(Ty);
  1864. }
  1865. // SROA currently handles only Arrays and Structs.
  1866. StructType *STy = cast<StructType>(Ty);
  1867. const StructLayout *SL = DL.getStructLayout(STy);
  1868. unsigned PrevFieldBitOffset = 0;
  1869. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
  1870. unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
  1871. // Check to see if there is any padding between this element and the
  1872. // previous one.
  1873. if (i) {
  1874. unsigned PrevFieldEnd =
  1875. PrevFieldBitOffset + DL.getTypeSizeInBits(STy->getElementType(i - 1));
  1876. if (PrevFieldEnd < FieldBitOffset)
  1877. return true;
  1878. }
  1879. PrevFieldBitOffset = FieldBitOffset;
  1880. }
  1881. // Check for tail padding.
  1882. if (unsigned EltCount = STy->getNumElements()) {
  1883. unsigned PrevFieldEnd =
  1884. PrevFieldBitOffset +
  1885. DL.getTypeSizeInBits(STy->getElementType(EltCount - 1));
  1886. if (PrevFieldEnd < SL->getSizeInBits())
  1887. return true;
  1888. }
  1889. return false;
  1890. }
  1891. /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
  1892. /// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
  1893. /// or 1 if safe after canonicalization has been performed.
  1894. bool SROA_HLSL::isSafeAllocaToScalarRepl(AllocaInst *AI) {
  1895. // Loop over the use list of the alloca. We can only transform it if all of
  1896. // the users are safe to transform.
  1897. AllocaInfo Info(AI);
  1898. isSafeForScalarRepl(AI, 0, Info);
  1899. if (Info.isUnsafe) {
  1900. DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
  1901. return false;
  1902. }
  1903. // vector indexing need translate vector into array
  1904. if (Info.hasVectorIndexing)
  1905. return false;
  1906. const DataLayout &DL = AI->getModule()->getDataLayout();
  1907. // Okay, we know all the users are promotable. If the aggregate is a memcpy
  1908. // source and destination, we have to be careful. In particular, the memcpy
  1909. // could be moving around elements that live in structure padding of the LLVM
  1910. // types, but may actually be used. In these cases, we refuse to promote the
  1911. // struct.
  1912. if (Info.isMemCpySrc && Info.isMemCpyDst &&
  1913. HasPadding(AI->getAllocatedType(), DL))
  1914. return false;
  1915. return true;
  1916. }
  1917. // Copy data from srcPtr to destPtr.
  1918. static void SimplePtrCopy(Value *DestPtr, Value *SrcPtr,
  1919. llvm::SmallVector<llvm::Value *, 16> &idxList,
  1920. IRBuilder<> &Builder) {
  1921. if (idxList.size() > 1) {
  1922. DestPtr = Builder.CreateInBoundsGEP(DestPtr, idxList);
  1923. SrcPtr = Builder.CreateInBoundsGEP(SrcPtr, idxList);
  1924. }
  1925. llvm::LoadInst *ld = Builder.CreateLoad(SrcPtr);
  1926. Builder.CreateStore(ld, DestPtr);
  1927. }
  1928. // Copy srcVal to destPtr.
  1929. static void SimpleValCopy(Value *DestPtr, Value *SrcVal,
  1930. llvm::SmallVector<llvm::Value *, 16> &idxList,
  1931. IRBuilder<> &Builder) {
  1932. Value *DestGEP = Builder.CreateInBoundsGEP(DestPtr, idxList);
  1933. Value *Val = SrcVal;
  1934. // Skip beginning pointer type.
  1935. for (unsigned i = 1; i < idxList.size(); i++) {
  1936. ConstantInt *idx = cast<ConstantInt>(idxList[i]);
  1937. Type *Ty = Val->getType();
  1938. if (Ty->isAggregateType()) {
  1939. Val = Builder.CreateExtractValue(Val, idx->getLimitedValue());
  1940. }
  1941. }
  1942. Builder.CreateStore(Val, DestGEP);
  1943. }
  1944. static void SimpleCopy(Value *Dest, Value *Src,
  1945. llvm::SmallVector<llvm::Value *, 16> &idxList,
  1946. IRBuilder<> &Builder) {
  1947. if (Src->getType()->isPointerTy())
  1948. SimplePtrCopy(Dest, Src, idxList, Builder);
  1949. else
  1950. SimpleValCopy(Dest, Src, idxList, Builder);
  1951. }
  1952. static Value *CreateMergedGEP(Value *Ptr, SmallVector<Value *, 16> &idxList,
  1953. IRBuilder<> &Builder) {
  1954. if (GEPOperator *GEPPtr = dyn_cast<GEPOperator>(Ptr)) {
  1955. SmallVector<Value *, 2> IdxList(GEPPtr->idx_begin(), GEPPtr->idx_end());
  1956. // skip idxLIst.begin() because it is included in GEPPtr idx.
  1957. IdxList.append(idxList.begin() + 1, idxList.end());
  1958. return Builder.CreateInBoundsGEP(GEPPtr->getPointerOperand(), IdxList);
  1959. } else {
  1960. return Builder.CreateInBoundsGEP(Ptr, idxList);
  1961. }
  1962. }
  1963. static void EltMemCpy(Type *Ty, Value *Dest, Value *Src,
  1964. SmallVector<Value *, 16> &idxList, IRBuilder<> &Builder,
  1965. const DataLayout &DL) {
  1966. Value *DestGEP = CreateMergedGEP(Dest, idxList, Builder);
  1967. Value *SrcGEP = CreateMergedGEP(Src, idxList, Builder);
  1968. unsigned size = DL.getTypeAllocSize(Ty);
  1969. Builder.CreateMemCpy(DestGEP, SrcGEP, size, size);
  1970. }
  1971. static bool IsMemCpyTy(Type *Ty, DxilTypeSystem &typeSys) {
  1972. if (!Ty->isAggregateType())
  1973. return false;
  1974. if (HLMatrixLower::IsMatrixType(Ty))
  1975. return false;
  1976. if (HLModule::IsHLSLObjectType(Ty))
  1977. return false;
  1978. if (StructType *ST = dyn_cast<StructType>(Ty)) {
  1979. DxilStructAnnotation *STA = typeSys.GetStructAnnotation(ST);
  1980. DXASSERT(STA, "require annotation here");
  1981. if (STA->IsEmptyStruct())
  1982. return false;
  1983. // Skip 1 element struct which the element is basic type.
  1984. // Because create memcpy will create gep on the struct, memcpy the basic
  1985. // type only.
  1986. if (ST->getNumElements() == 1)
  1987. return IsMemCpyTy(ST->getElementType(0), typeSys);
  1988. }
  1989. return true;
  1990. }
  1991. // Split copy into ld/st.
  1992. static void SplitCpy(Type *Ty, Value *Dest, Value *Src,
  1993. SmallVector<Value *, 16> &idxList, IRBuilder<> &Builder,
  1994. const DataLayout &DL, DxilTypeSystem &typeSys,
  1995. DxilFieldAnnotation *fieldAnnotation, const bool bEltMemCpy = true) {
  1996. if (PointerType *PT = dyn_cast<PointerType>(Ty)) {
  1997. Constant *idx = Constant::getIntegerValue(
  1998. IntegerType::get(Ty->getContext(), 32), APInt(32, 0));
  1999. idxList.emplace_back(idx);
  2000. SplitCpy(PT->getElementType(), Dest, Src, idxList, Builder, DL, typeSys,
  2001. fieldAnnotation, bEltMemCpy);
  2002. idxList.pop_back();
  2003. } else if (HLMatrixLower::IsMatrixType(Ty)) {
  2004. // If no fieldAnnotation, use row major as default.
  2005. // Only load then store immediately should be fine.
  2006. bool bRowMajor = true;
  2007. if (fieldAnnotation) {
  2008. DXASSERT(fieldAnnotation->HasMatrixAnnotation(),
  2009. "must has matrix annotation");
  2010. bRowMajor = fieldAnnotation->GetMatrixAnnotation().Orientation ==
  2011. MatrixOrientation::RowMajor;
  2012. }
  2013. Module *M = Builder.GetInsertPoint()->getModule();
  2014. Value *DestGEP = Builder.CreateInBoundsGEP(Dest, idxList);
  2015. Value *SrcGEP = Builder.CreateInBoundsGEP(Src, idxList);
  2016. if (bRowMajor) {
  2017. Value *Load = HLModule::EmitHLOperationCall(
  2018. Builder, HLOpcodeGroup::HLMatLoadStore,
  2019. static_cast<unsigned>(HLMatLoadStoreOpcode::RowMatLoad), Ty, {SrcGEP},
  2020. *M);
  2021. // Generate Matrix Store.
  2022. HLModule::EmitHLOperationCall(
  2023. Builder, HLOpcodeGroup::HLMatLoadStore,
  2024. static_cast<unsigned>(HLMatLoadStoreOpcode::RowMatStore), Ty,
  2025. {DestGEP, Load}, *M);
  2026. } else {
  2027. Value *Load = HLModule::EmitHLOperationCall(
  2028. Builder, HLOpcodeGroup::HLMatLoadStore,
  2029. static_cast<unsigned>(HLMatLoadStoreOpcode::ColMatLoad), Ty, {SrcGEP},
  2030. *M);
  2031. // Generate Matrix Store.
  2032. HLModule::EmitHLOperationCall(
  2033. Builder, HLOpcodeGroup::HLMatLoadStore,
  2034. static_cast<unsigned>(HLMatLoadStoreOpcode::ColMatStore), Ty,
  2035. {DestGEP, Load}, *M);
  2036. }
  2037. } else if (StructType *ST = dyn_cast<StructType>(Ty)) {
  2038. if (HLModule::IsHLSLObjectType(ST)) {
  2039. // Avoid split HLSL object.
  2040. SimpleCopy(Dest, Src, idxList, Builder);
  2041. return;
  2042. }
  2043. DxilStructAnnotation *STA = typeSys.GetStructAnnotation(ST);
  2044. DXASSERT(STA, "require annotation here");
  2045. if (STA->IsEmptyStruct())
  2046. return;
  2047. for (uint32_t i = 0; i < ST->getNumElements(); i++) {
  2048. llvm::Type *ET = ST->getElementType(i);
  2049. Constant *idx = llvm::Constant::getIntegerValue(
  2050. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  2051. idxList.emplace_back(idx);
  2052. if (bEltMemCpy && IsMemCpyTy(ET, typeSys)) {
  2053. EltMemCpy(ET, Dest, Src, idxList, Builder, DL);
  2054. } else {
  2055. DxilFieldAnnotation &EltAnnotation = STA->GetFieldAnnotation(i);
  2056. SplitCpy(ET, Dest, Src, idxList, Builder, DL, typeSys, &EltAnnotation,
  2057. bEltMemCpy);
  2058. }
  2059. idxList.pop_back();
  2060. }
  2061. } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
  2062. Type *ET = AT->getElementType();
  2063. for (uint32_t i = 0; i < AT->getNumElements(); i++) {
  2064. Constant *idx = Constant::getIntegerValue(
  2065. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  2066. idxList.emplace_back(idx);
  2067. if (bEltMemCpy && IsMemCpyTy(ET, typeSys)) {
  2068. EltMemCpy(ET, Dest, Src, idxList, Builder, DL);
  2069. } else {
  2070. SplitCpy(ET, Dest, Src, idxList, Builder, DL, typeSys, fieldAnnotation,
  2071. bEltMemCpy);
  2072. }
  2073. idxList.pop_back();
  2074. }
  2075. } else {
  2076. SimpleCopy(Dest, Src, idxList, Builder);
  2077. }
  2078. }
  2079. static void SplitPtr(Type *Ty, Value *Ptr, SmallVector<Value *, 16> &idxList,
  2080. SmallVector<Value *, 16> &EltPtrList,
  2081. IRBuilder<> &Builder) {
  2082. if (PointerType *PT = dyn_cast<PointerType>(Ty)) {
  2083. Constant *idx = Constant::getIntegerValue(
  2084. IntegerType::get(Ty->getContext(), 32), APInt(32, 0));
  2085. idxList.emplace_back(idx);
  2086. SplitPtr(PT->getElementType(), Ptr, idxList, EltPtrList, Builder);
  2087. idxList.pop_back();
  2088. } else if (HLMatrixLower::IsMatrixType(Ty)) {
  2089. Value *GEP = Builder.CreateInBoundsGEP(Ptr, idxList);
  2090. EltPtrList.emplace_back(GEP);
  2091. } else if (StructType *ST = dyn_cast<StructType>(Ty)) {
  2092. if (HLModule::IsHLSLObjectType(ST)) {
  2093. // Avoid split HLSL object.
  2094. Value *GEP = Builder.CreateInBoundsGEP(Ptr, idxList);
  2095. EltPtrList.emplace_back(GEP);
  2096. return;
  2097. }
  2098. for (uint32_t i = 0; i < ST->getNumElements(); i++) {
  2099. llvm::Type *ET = ST->getElementType(i);
  2100. Constant *idx = llvm::Constant::getIntegerValue(
  2101. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  2102. idxList.emplace_back(idx);
  2103. SplitPtr(ET, Ptr, idxList, EltPtrList, Builder);
  2104. idxList.pop_back();
  2105. }
  2106. } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
  2107. if (AT->getNumContainedTypes() == 0) {
  2108. // Skip case like [0 x %struct].
  2109. return;
  2110. }
  2111. Type *ElTy = AT->getElementType();
  2112. SmallVector<ArrayType *, 4> nestArrayTys;
  2113. nestArrayTys.emplace_back(AT);
  2114. // support multi level of array
  2115. while (ElTy->isArrayTy()) {
  2116. ArrayType *ElAT = cast<ArrayType>(ElTy);
  2117. nestArrayTys.emplace_back(ElAT);
  2118. ElTy = ElAT->getElementType();
  2119. }
  2120. if (!ElTy->isStructTy() ||
  2121. HLMatrixLower::IsMatrixType(ElTy)) {
  2122. // Not split array of basic type.
  2123. Value *GEP = Builder.CreateInBoundsGEP(Ptr, idxList);
  2124. EltPtrList.emplace_back(GEP);
  2125. }
  2126. else {
  2127. DXASSERT(0, "Not support array of struct when split pointers.");
  2128. }
  2129. } else {
  2130. Value *GEP = Builder.CreateInBoundsGEP(Ptr, idxList);
  2131. EltPtrList.emplace_back(GEP);
  2132. }
  2133. }
  2134. // Support case when bitcast (gep ptr, 0,0) is transformed into bitcast ptr.
  2135. static unsigned MatchSizeByCheckElementType(Type *Ty, const DataLayout &DL, unsigned size, unsigned level) {
  2136. unsigned ptrSize = DL.getTypeAllocSize(Ty);
  2137. // Size match, return current level.
  2138. if (ptrSize == size) {
  2139. // Not go deeper for matrix.
  2140. if (HLMatrixLower::IsMatrixType(Ty))
  2141. return level;
  2142. // For struct, go deeper if size not change.
  2143. // This will leave memcpy to deeper level when flatten.
  2144. if (StructType *ST = dyn_cast<StructType>(Ty)) {
  2145. if (ST->getNumElements() == 1) {
  2146. return MatchSizeByCheckElementType(ST->getElementType(0), DL, size, level+1);
  2147. }
  2148. }
  2149. // Don't do this for array.
  2150. // Array will be flattened as struct of array.
  2151. return level;
  2152. }
  2153. // Add ZeroIdx cannot make ptrSize bigger.
  2154. if (ptrSize < size)
  2155. return 0;
  2156. // ptrSize > size.
  2157. // Try to use element type to make size match.
  2158. if (StructType *ST = dyn_cast<StructType>(Ty)) {
  2159. return MatchSizeByCheckElementType(ST->getElementType(0), DL, size, level+1);
  2160. } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
  2161. return MatchSizeByCheckElementType(AT->getElementType(), DL, size, level+1);
  2162. } else {
  2163. return 0;
  2164. }
  2165. }
  2166. static void PatchZeroIdxGEP(Value *Ptr, Value *RawPtr, MemCpyInst *MI,
  2167. unsigned level, IRBuilder<> &Builder) {
  2168. Value *zeroIdx = Builder.getInt32(0);
  2169. Value *GEP = nullptr;
  2170. if (GEPOperator *GEPPtr = dyn_cast<GEPOperator>(Ptr)) {
  2171. SmallVector<Value *, 2> IdxList(GEPPtr->idx_begin(), GEPPtr->idx_end());
  2172. // level not + 1 because it is included in GEPPtr idx.
  2173. IdxList.append(level, zeroIdx);
  2174. GEP = Builder.CreateInBoundsGEP(GEPPtr->getPointerOperand(), IdxList);
  2175. } else {
  2176. SmallVector<Value *, 2> IdxList(level + 1, zeroIdx);
  2177. GEP = Builder.CreateInBoundsGEP(Ptr, IdxList);
  2178. }
  2179. // Use BitCastInst::Create to prevent idxList from being optimized.
  2180. CastInst *Cast =
  2181. BitCastInst::Create(Instruction::BitCast, GEP, RawPtr->getType());
  2182. Builder.Insert(Cast);
  2183. MI->replaceUsesOfWith(RawPtr, Cast);
  2184. // Remove RawPtr if possible.
  2185. if (RawPtr->user_empty()) {
  2186. if (Instruction *I = dyn_cast<Instruction>(RawPtr)) {
  2187. I->eraseFromParent();
  2188. }
  2189. }
  2190. }
  2191. void MemcpySplitter::PatchMemCpyWithZeroIdxGEP(MemCpyInst *MI,
  2192. const DataLayout &DL) {
  2193. Value *Dest = MI->getRawDest();
  2194. Value *Src = MI->getRawSource();
  2195. // Only remove one level bitcast generated from inline.
  2196. if (BitCastOperator *BC = dyn_cast<BitCastOperator>(Dest))
  2197. Dest = BC->getOperand(0);
  2198. if (BitCastOperator *BC = dyn_cast<BitCastOperator>(Src))
  2199. Src = BC->getOperand(0);
  2200. IRBuilder<> Builder(MI);
  2201. ConstantInt *zero = Builder.getInt32(0);
  2202. Type *DestTy = Dest->getType()->getPointerElementType();
  2203. Type *SrcTy = Src->getType()->getPointerElementType();
  2204. // Support case when bitcast (gep ptr, 0,0) is transformed into
  2205. // bitcast ptr.
  2206. // Also replace (gep ptr, 0) with ptr.
  2207. ConstantInt *Length = cast<ConstantInt>(MI->getLength());
  2208. unsigned size = Length->getLimitedValue();
  2209. if (unsigned level = MatchSizeByCheckElementType(DestTy, DL, size, 0)) {
  2210. PatchZeroIdxGEP(Dest, MI->getRawDest(), MI, level, Builder);
  2211. } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(Dest)) {
  2212. if (GEP->getNumIndices() == 1) {
  2213. Value *idx = *GEP->idx_begin();
  2214. if (idx == zero) {
  2215. GEP->replaceAllUsesWith(GEP->getPointerOperand());
  2216. }
  2217. }
  2218. }
  2219. if (unsigned level = MatchSizeByCheckElementType(SrcTy, DL, size, 0)) {
  2220. PatchZeroIdxGEP(Src, MI->getRawSource(), MI, level, Builder);
  2221. } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
  2222. if (GEP->getNumIndices() == 1) {
  2223. Value *idx = *GEP->idx_begin();
  2224. if (idx == zero) {
  2225. GEP->replaceAllUsesWith(GEP->getPointerOperand());
  2226. }
  2227. }
  2228. }
  2229. }
  2230. void MemcpySplitter::PatchMemCpyWithZeroIdxGEP(Module &M) {
  2231. const DataLayout &DL = M.getDataLayout();
  2232. for (Function &F : M.functions()) {
  2233. for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
  2234. for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
  2235. // Avoid invalidating the iterator.
  2236. Instruction *I = BI++;
  2237. if (MemCpyInst *MI = dyn_cast<MemCpyInst>(I)) {
  2238. PatchMemCpyWithZeroIdxGEP(MI, DL);
  2239. }
  2240. }
  2241. }
  2242. }
  2243. }
  2244. static void DeleteMemcpy(MemCpyInst *MI) {
  2245. Value *Op0 = MI->getOperand(0);
  2246. Value *Op1 = MI->getOperand(1);
  2247. // delete memcpy
  2248. MI->eraseFromParent();
  2249. if (Instruction *op0 = dyn_cast<Instruction>(Op0)) {
  2250. if (op0->user_empty())
  2251. op0->eraseFromParent();
  2252. }
  2253. if (Instruction *op1 = dyn_cast<Instruction>(Op1)) {
  2254. if (op1->user_empty())
  2255. op1->eraseFromParent();
  2256. }
  2257. }
  2258. void MemcpySplitter::SplitMemCpy(MemCpyInst *MI, const DataLayout &DL,
  2259. DxilFieldAnnotation *fieldAnnotation,
  2260. DxilTypeSystem &typeSys, const bool bEltMemCpy) {
  2261. Value *Dest = MI->getRawDest();
  2262. Value *Src = MI->getRawSource();
  2263. // Only remove one level bitcast generated from inline.
  2264. if (BitCastOperator *BC = dyn_cast<BitCastOperator>(Dest))
  2265. Dest = BC->getOperand(0);
  2266. if (BitCastOperator *BC = dyn_cast<BitCastOperator>(Src))
  2267. Src = BC->getOperand(0);
  2268. if (Dest == Src) {
  2269. // delete self copy.
  2270. DeleteMemcpy(MI);
  2271. return;
  2272. }
  2273. IRBuilder<> Builder(MI);
  2274. Type *DestTy = Dest->getType()->getPointerElementType();
  2275. Type *SrcTy = Src->getType()->getPointerElementType();
  2276. // Allow copy between different address space.
  2277. if (DestTy != SrcTy) {
  2278. return;
  2279. }
  2280. // Try to find fieldAnnotation from user of Dest/Src.
  2281. if (!fieldAnnotation) {
  2282. Type *EltTy = dxilutil::GetArrayEltTy(DestTy);
  2283. if (HLMatrixLower::IsMatrixType(EltTy)) {
  2284. fieldAnnotation = HLMatrixLower::FindAnnotationFromMatUser(Dest, typeSys);
  2285. }
  2286. }
  2287. llvm::SmallVector<llvm::Value *, 16> idxList;
  2288. // split
  2289. // Matrix is treated as scalar type, will not use memcpy.
  2290. // So use nullptr for fieldAnnotation should be safe here.
  2291. SplitCpy(Dest->getType(), Dest, Src, idxList, Builder, DL, typeSys,
  2292. fieldAnnotation, bEltMemCpy);
  2293. // delete memcpy
  2294. DeleteMemcpy(MI);
  2295. }
  2296. void MemcpySplitter::Split(llvm::Function &F) {
  2297. const DataLayout &DL = F.getParent()->getDataLayout();
  2298. Function *memcpy = nullptr;
  2299. for (Function &Fn : F.getParent()->functions()) {
  2300. if (Fn.getIntrinsicID() == Intrinsic::memcpy) {
  2301. memcpy = &Fn;
  2302. break;
  2303. }
  2304. }
  2305. if (memcpy) {
  2306. for (auto U = memcpy->user_begin(); U != memcpy->user_end();) {
  2307. MemCpyInst *MI = cast<MemCpyInst>(*(U++));
  2308. if (MI->getParent()->getParent() != &F)
  2309. continue;
  2310. // Matrix is treated as scalar type, will not use memcpy.
  2311. // So use nullptr for fieldAnnotation should be safe here.
  2312. SplitMemCpy(MI, DL, /*fieldAnnotation*/ nullptr, m_typeSys,
  2313. /*bEltMemCpy*/ false);
  2314. }
  2315. }
  2316. }
  2317. //===----------------------------------------------------------------------===//
  2318. // SRoA Helper
  2319. //===----------------------------------------------------------------------===//
  2320. /// RewriteGEP - Rewrite the GEP to be relative to new element when can find a
  2321. /// new element which is struct field. If cannot find, create new element GEPs
  2322. /// and try to rewrite GEP with new GEPS.
  2323. void SROA_Helper::RewriteForGEP(GEPOperator *GEP, IRBuilder<> &Builder) {
  2324. assert(OldVal == GEP->getPointerOperand() && "");
  2325. Value *NewPointer = nullptr;
  2326. SmallVector<Value *, 8> NewArgs;
  2327. gep_type_iterator GEPIt = gep_type_begin(GEP), E = gep_type_end(GEP);
  2328. for (; GEPIt != E; ++GEPIt) {
  2329. if (GEPIt->isStructTy()) {
  2330. // must be const
  2331. ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
  2332. assert(IdxVal->getLimitedValue() < NewElts.size() && "");
  2333. NewPointer = NewElts[IdxVal->getLimitedValue()];
  2334. // The idx is used for NewPointer, not part of newGEP idx,
  2335. GEPIt++;
  2336. break;
  2337. } else if (GEPIt->isArrayTy()) {
  2338. // Add array idx.
  2339. NewArgs.push_back(GEPIt.getOperand());
  2340. } else if (GEPIt->isPointerTy()) {
  2341. // Add pointer idx.
  2342. NewArgs.push_back(GEPIt.getOperand());
  2343. } else if (GEPIt->isVectorTy()) {
  2344. // Add vector idx.
  2345. NewArgs.push_back(GEPIt.getOperand());
  2346. } else {
  2347. llvm_unreachable("should break from structTy");
  2348. }
  2349. }
  2350. if (NewPointer) {
  2351. // Struct split.
  2352. // Add rest of idx.
  2353. for (; GEPIt != E; ++GEPIt) {
  2354. NewArgs.push_back(GEPIt.getOperand());
  2355. }
  2356. // If only 1 level struct, just use the new pointer.
  2357. Value *NewGEP = NewPointer;
  2358. if (NewArgs.size() > 1) {
  2359. NewGEP = Builder.CreateInBoundsGEP(NewPointer, NewArgs);
  2360. NewGEP->takeName(GEP);
  2361. }
  2362. assert(NewGEP->getType() == GEP->getType() && "type mismatch");
  2363. GEP->replaceAllUsesWith(NewGEP);
  2364. if (isa<Instruction>(GEP))
  2365. DeadInsts.push_back(GEP);
  2366. } else {
  2367. // End at array of basic type.
  2368. Type *Ty = GEP->getType()->getPointerElementType();
  2369. if (Ty->isVectorTy() ||
  2370. (Ty->isStructTy() && !HLModule::IsHLSLObjectType(Ty)) ||
  2371. Ty->isArrayTy()) {
  2372. SmallVector<Value *, 8> NewArgs;
  2373. NewArgs.append(GEP->idx_begin(), GEP->idx_end());
  2374. SmallVector<Value *, 8> NewGEPs;
  2375. // create new geps
  2376. for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
  2377. Value *NewGEP = Builder.CreateGEP(nullptr, NewElts[i], NewArgs);
  2378. NewGEPs.emplace_back(NewGEP);
  2379. }
  2380. const bool bAllowReplace = isa<AllocaInst>(OldVal);
  2381. if (SROA_Helper::LowerMemcpy(GEP, /*annoation*/ nullptr, typeSys, DL,
  2382. bAllowReplace)) {
  2383. if (GEP->user_empty() && isa<Instruction>(GEP))
  2384. DeadInsts.push_back(GEP);
  2385. return;
  2386. }
  2387. SROA_Helper helper(GEP, NewGEPs, DeadInsts, typeSys, DL);
  2388. helper.RewriteForScalarRepl(GEP, Builder);
  2389. for (Value *NewGEP : NewGEPs) {
  2390. if (NewGEP->user_empty() && isa<Instruction>(NewGEP)) {
  2391. // Delete unused newGEP.
  2392. cast<Instruction>(NewGEP)->eraseFromParent();
  2393. }
  2394. }
  2395. if (GEP->user_empty() && isa<Instruction>(GEP))
  2396. DeadInsts.push_back(GEP);
  2397. } else {
  2398. Value *vecIdx = NewArgs.back();
  2399. if (ConstantInt *immVecIdx = dyn_cast<ConstantInt>(vecIdx)) {
  2400. // Replace vecArray[arrayIdx][immVecIdx]
  2401. // with scalarArray_immVecIdx[arrayIdx]
  2402. // Pop the vecIdx.
  2403. NewArgs.pop_back();
  2404. Value *NewGEP = NewElts[immVecIdx->getLimitedValue()];
  2405. if (NewArgs.size() > 1) {
  2406. NewGEP = Builder.CreateInBoundsGEP(NewGEP, NewArgs);
  2407. NewGEP->takeName(GEP);
  2408. }
  2409. assert(NewGEP->getType() == GEP->getType() && "type mismatch");
  2410. GEP->replaceAllUsesWith(NewGEP);
  2411. if (isa<Instruction>(GEP))
  2412. DeadInsts.push_back(GEP);
  2413. } else {
  2414. // dynamic vector indexing.
  2415. assert(0 && "should not reach here");
  2416. }
  2417. }
  2418. }
  2419. }
  2420. /// isVectorOrStructArray - Check if T is array of vector or struct.
  2421. static bool isVectorOrStructArray(Type *T) {
  2422. if (!T->isArrayTy())
  2423. return false;
  2424. T = dxilutil::GetArrayEltTy(T);
  2425. return T->isStructTy() || T->isVectorTy();
  2426. }
  2427. static void SimplifyStructValUsage(Value *StructVal, std::vector<Value *> Elts,
  2428. SmallVectorImpl<Value *> &DeadInsts) {
  2429. for (User *user : StructVal->users()) {
  2430. if (ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(user)) {
  2431. DXASSERT(Extract->getNumIndices() == 1, "only support 1 index case");
  2432. unsigned index = Extract->getIndices()[0];
  2433. Value *Elt = Elts[index];
  2434. Extract->replaceAllUsesWith(Elt);
  2435. DeadInsts.emplace_back(Extract);
  2436. } else if (InsertValueInst *Insert = dyn_cast<InsertValueInst>(user)) {
  2437. DXASSERT(Insert->getNumIndices() == 1, "only support 1 index case");
  2438. unsigned index = Insert->getIndices()[0];
  2439. if (Insert->getAggregateOperand() == StructVal) {
  2440. // Update field.
  2441. std::vector<Value *> NewElts = Elts;
  2442. NewElts[index] = Insert->getInsertedValueOperand();
  2443. SimplifyStructValUsage(Insert, NewElts, DeadInsts);
  2444. } else {
  2445. // Insert to another bigger struct.
  2446. IRBuilder<> Builder(Insert);
  2447. Value *TmpStructVal = UndefValue::get(StructVal->getType());
  2448. for (unsigned i = 0; i < Elts.size(); i++) {
  2449. TmpStructVal =
  2450. Builder.CreateInsertValue(TmpStructVal, Elts[i], {i});
  2451. }
  2452. Insert->replaceUsesOfWith(StructVal, TmpStructVal);
  2453. }
  2454. }
  2455. }
  2456. }
  2457. /// RewriteForLoad - Replace OldVal with flattened NewElts in LoadInst.
  2458. void SROA_Helper::RewriteForLoad(LoadInst *LI) {
  2459. Type *LIType = LI->getType();
  2460. Type *ValTy = OldVal->getType()->getPointerElementType();
  2461. IRBuilder<> Builder(LI);
  2462. if (LIType->isVectorTy()) {
  2463. // Replace:
  2464. // %res = load { 2 x i32 }* %alloc
  2465. // with:
  2466. // %load.0 = load i32* %alloc.0
  2467. // %insert.0 insertvalue { 2 x i32 } zeroinitializer, i32 %load.0, 0
  2468. // %load.1 = load i32* %alloc.1
  2469. // %insert = insertvalue { 2 x i32 } %insert.0, i32 %load.1, 1
  2470. Value *Insert = UndefValue::get(LIType);
  2471. for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
  2472. Value *Load = Builder.CreateLoad(NewElts[i], "load");
  2473. Insert = Builder.CreateInsertElement(Insert, Load, i, "insert");
  2474. }
  2475. LI->replaceAllUsesWith(Insert);
  2476. DeadInsts.push_back(LI);
  2477. } else if (isCompatibleAggregate(LIType, ValTy)) {
  2478. if (isVectorOrStructArray(LIType)) {
  2479. // Replace:
  2480. // %res = load [2 x <2 x float>] * %alloc
  2481. // with:
  2482. // %load.0 = load [4 x float]* %alloc.0
  2483. // %insert.0 insertvalue [4 x float] zeroinitializer,i32 %load.0,0
  2484. // %load.1 = load [4 x float]* %alloc.1
  2485. // %insert = insertvalue [4 x float] %insert.0, i32 %load.1, 1
  2486. // ...
  2487. Type *i32Ty = Type::getInt32Ty(LIType->getContext());
  2488. Value *zero = ConstantInt::get(i32Ty, 0);
  2489. SmallVector<Value *, 8> idxList;
  2490. idxList.emplace_back(zero);
  2491. Value *newLd =
  2492. LoadVectorOrStructArray(cast<ArrayType>(LIType), NewElts, idxList, Builder);
  2493. LI->replaceAllUsesWith(newLd);
  2494. DeadInsts.push_back(LI);
  2495. } else {
  2496. // Replace:
  2497. // %res = load { i32, i32 }* %alloc
  2498. // with:
  2499. // %load.0 = load i32* %alloc.0
  2500. // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0,
  2501. // 0
  2502. // %load.1 = load i32* %alloc.1
  2503. // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
  2504. // (Also works for arrays instead of structs)
  2505. Module *M = LI->getModule();
  2506. Value *Insert = UndefValue::get(LIType);
  2507. std::vector<Value *> LdElts(NewElts.size());
  2508. for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
  2509. Value *Ptr = NewElts[i];
  2510. Type *Ty = Ptr->getType()->getPointerElementType();
  2511. Value *Load = nullptr;
  2512. if (!HLMatrixLower::IsMatrixType(Ty))
  2513. Load = Builder.CreateLoad(Ptr, "load");
  2514. else {
  2515. // Generate Matrix Load.
  2516. Load = HLModule::EmitHLOperationCall(
  2517. Builder, HLOpcodeGroup::HLMatLoadStore,
  2518. static_cast<unsigned>(HLMatLoadStoreOpcode::RowMatLoad), Ty,
  2519. {Ptr}, *M);
  2520. }
  2521. LdElts[i] = Load;
  2522. Insert = Builder.CreateInsertValue(Insert, Load, i, "insert");
  2523. }
  2524. LI->replaceAllUsesWith(Insert);
  2525. if (LIType->isStructTy()) {
  2526. SimplifyStructValUsage(Insert, LdElts, DeadInsts);
  2527. }
  2528. DeadInsts.push_back(LI);
  2529. }
  2530. } else {
  2531. llvm_unreachable("other type don't need rewrite");
  2532. }
  2533. }
  2534. /// RewriteForStore - Replace OldVal with flattened NewElts in StoreInst.
  2535. void SROA_Helper::RewriteForStore(StoreInst *SI) {
  2536. Value *Val = SI->getOperand(0);
  2537. Type *SIType = Val->getType();
  2538. IRBuilder<> Builder(SI);
  2539. Type *ValTy = OldVal->getType()->getPointerElementType();
  2540. if (SIType->isVectorTy()) {
  2541. // Replace:
  2542. // store <2 x float> %val, <2 x float>* %alloc
  2543. // with:
  2544. // %val.0 = extractelement { 2 x float } %val, 0
  2545. // store i32 %val.0, i32* %alloc.0
  2546. // %val.1 = extractelement { 2 x float } %val, 1
  2547. // store i32 %val.1, i32* %alloc.1
  2548. for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
  2549. Value *Extract = Builder.CreateExtractElement(Val, i, Val->getName());
  2550. Builder.CreateStore(Extract, NewElts[i]);
  2551. }
  2552. DeadInsts.push_back(SI);
  2553. } else if (isCompatibleAggregate(SIType, ValTy)) {
  2554. if (isVectorOrStructArray(SIType)) {
  2555. // Replace:
  2556. // store [2 x <2 x i32>] %val, [2 x <2 x i32>]* %alloc, align 16
  2557. // with:
  2558. // %val.0 = extractvalue [2 x <2 x i32>] %val, 0
  2559. // %all0c.0.0 = getelementptr inbounds [2 x i32], [2 x i32]* %alloc.0,
  2560. // i32 0, i32 0
  2561. // %val.0.0 = extractelement <2 x i32> %243, i64 0
  2562. // store i32 %val.0.0, i32* %all0c.0.0
  2563. // %alloc.1.0 = getelementptr inbounds [2 x i32], [2 x i32]* %alloc.1,
  2564. // i32 0, i32 0
  2565. // %val.0.1 = extractelement <2 x i32> %243, i64 1
  2566. // store i32 %val.0.1, i32* %alloc.1.0
  2567. // %val.1 = extractvalue [2 x <2 x i32>] %val, 1
  2568. // %alloc.0.0 = getelementptr inbounds [2 x i32], [2 x i32]* %alloc.0,
  2569. // i32 0, i32 1
  2570. // %val.1.0 = extractelement <2 x i32> %248, i64 0
  2571. // store i32 %val.1.0, i32* %alloc.0.0
  2572. // %all0c.1.1 = getelementptr inbounds [2 x i32], [2 x i32]* %alloc.1,
  2573. // i32 0, i32 1
  2574. // %val.1.1 = extractelement <2 x i32> %248, i64 1
  2575. // store i32 %val.1.1, i32* %all0c.1.1
  2576. ArrayType *AT = cast<ArrayType>(SIType);
  2577. Type *i32Ty = Type::getInt32Ty(SIType->getContext());
  2578. Value *zero = ConstantInt::get(i32Ty, 0);
  2579. SmallVector<Value *, 8> idxList;
  2580. idxList.emplace_back(zero);
  2581. StoreVectorOrStructArray(AT, Val, NewElts, idxList, Builder);
  2582. DeadInsts.push_back(SI);
  2583. } else {
  2584. // Replace:
  2585. // store { i32, i32 } %val, { i32, i32 }* %alloc
  2586. // with:
  2587. // %val.0 = extractvalue { i32, i32 } %val, 0
  2588. // store i32 %val.0, i32* %alloc.0
  2589. // %val.1 = extractvalue { i32, i32 } %val, 1
  2590. // store i32 %val.1, i32* %alloc.1
  2591. // (Also works for arrays instead of structs)
  2592. Module *M = SI->getModule();
  2593. for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
  2594. Value *Extract = Builder.CreateExtractValue(Val, i, Val->getName());
  2595. if (!HLMatrixLower::IsMatrixType(Extract->getType())) {
  2596. Builder.CreateStore(Extract, NewElts[i]);
  2597. } else {
  2598. // Generate Matrix Store.
  2599. HLModule::EmitHLOperationCall(
  2600. Builder, HLOpcodeGroup::HLMatLoadStore,
  2601. static_cast<unsigned>(HLMatLoadStoreOpcode::RowMatStore),
  2602. Extract->getType(), {NewElts[i], Extract}, *M);
  2603. }
  2604. }
  2605. DeadInsts.push_back(SI);
  2606. }
  2607. } else {
  2608. llvm_unreachable("other type don't need rewrite");
  2609. }
  2610. }
  2611. /// RewriteMemIntrin - MI is a memcpy/memset/memmove from or to AI.
  2612. /// Rewrite it to copy or set the elements of the scalarized memory.
  2613. void SROA_Helper::RewriteMemIntrin(MemIntrinsic *MI, Value *OldV) {
  2614. // If this is a memcpy/memmove, construct the other pointer as the
  2615. // appropriate type. The "Other" pointer is the pointer that goes to memory
  2616. // that doesn't have anything to do with the alloca that we are promoting. For
  2617. // memset, this Value* stays null.
  2618. Value *OtherPtr = nullptr;
  2619. unsigned MemAlignment = MI->getAlignment();
  2620. if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
  2621. if (OldV == MTI->getRawDest())
  2622. OtherPtr = MTI->getRawSource();
  2623. else {
  2624. assert(OldV == MTI->getRawSource());
  2625. OtherPtr = MTI->getRawDest();
  2626. }
  2627. }
  2628. // If there is an other pointer, we want to convert it to the same pointer
  2629. // type as AI has, so we can GEP through it safely.
  2630. if (OtherPtr) {
  2631. unsigned AddrSpace =
  2632. cast<PointerType>(OtherPtr->getType())->getAddressSpace();
  2633. // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
  2634. // optimization, but it's also required to detect the corner case where
  2635. // both pointer operands are referencing the same memory, and where
  2636. // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
  2637. // function is only called for mem intrinsics that access the whole
  2638. // aggregate, so non-zero GEPs are not an issue here.)
  2639. OtherPtr = OtherPtr->stripPointerCasts();
  2640. // Copying the alloca to itself is a no-op: just delete it.
  2641. if (OtherPtr == OldVal || OtherPtr == NewElts[0]) {
  2642. // This code will run twice for a no-op memcpy -- once for each operand.
  2643. // Put only one reference to MI on the DeadInsts list.
  2644. for (SmallVectorImpl<Value *>::const_iterator I = DeadInsts.begin(),
  2645. E = DeadInsts.end();
  2646. I != E; ++I)
  2647. if (*I == MI)
  2648. return;
  2649. DeadInsts.push_back(MI);
  2650. return;
  2651. }
  2652. // If the pointer is not the right type, insert a bitcast to the right
  2653. // type.
  2654. Type *NewTy =
  2655. PointerType::get(OldVal->getType()->getPointerElementType(), AddrSpace);
  2656. if (OtherPtr->getType() != NewTy)
  2657. OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
  2658. }
  2659. // Process each element of the aggregate.
  2660. bool SROADest = MI->getRawDest() == OldV;
  2661. Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
  2662. const DataLayout &DL = MI->getModule()->getDataLayout();
  2663. for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
  2664. // If this is a memcpy/memmove, emit a GEP of the other element address.
  2665. Value *OtherElt = nullptr;
  2666. unsigned OtherEltAlign = MemAlignment;
  2667. if (OtherPtr) {
  2668. Value *Idx[2] = {Zero,
  2669. ConstantInt::get(Type::getInt32Ty(MI->getContext()), i)};
  2670. OtherElt = GetElementPtrInst::CreateInBounds(
  2671. OtherPtr, Idx, OtherPtr->getName() + "." + Twine(i), MI);
  2672. uint64_t EltOffset;
  2673. PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
  2674. Type *OtherTy = OtherPtrTy->getElementType();
  2675. if (StructType *ST = dyn_cast<StructType>(OtherTy)) {
  2676. EltOffset = DL.getStructLayout(ST)->getElementOffset(i);
  2677. } else {
  2678. Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
  2679. EltOffset = DL.getTypeAllocSize(EltTy) * i;
  2680. }
  2681. // The alignment of the other pointer is the guaranteed alignment of the
  2682. // element, which is affected by both the known alignment of the whole
  2683. // mem intrinsic and the alignment of the element. If the alignment of
  2684. // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
  2685. // known alignment is just 4 bytes.
  2686. OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
  2687. }
  2688. Value *EltPtr = NewElts[i];
  2689. Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
  2690. // If we got down to a scalar, insert a load or store as appropriate.
  2691. if (EltTy->isSingleValueType()) {
  2692. if (isa<MemTransferInst>(MI)) {
  2693. if (SROADest) {
  2694. // From Other to Alloca.
  2695. Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
  2696. new StoreInst(Elt, EltPtr, MI);
  2697. } else {
  2698. // From Alloca to Other.
  2699. Value *Elt = new LoadInst(EltPtr, "tmp", MI);
  2700. new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
  2701. }
  2702. continue;
  2703. }
  2704. assert(isa<MemSetInst>(MI));
  2705. // If the stored element is zero (common case), just store a null
  2706. // constant.
  2707. Constant *StoreVal;
  2708. if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
  2709. if (CI->isZero()) {
  2710. StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
  2711. } else {
  2712. // If EltTy is a vector type, get the element type.
  2713. Type *ValTy = EltTy->getScalarType();
  2714. // Construct an integer with the right value.
  2715. unsigned EltSize = DL.getTypeSizeInBits(ValTy);
  2716. APInt OneVal(EltSize, CI->getZExtValue());
  2717. APInt TotalVal(OneVal);
  2718. // Set each byte.
  2719. for (unsigned i = 0; 8 * i < EltSize; ++i) {
  2720. TotalVal = TotalVal.shl(8);
  2721. TotalVal |= OneVal;
  2722. }
  2723. // Convert the integer value to the appropriate type.
  2724. StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
  2725. if (ValTy->isPointerTy())
  2726. StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
  2727. else if (ValTy->isFloatingPointTy())
  2728. StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
  2729. assert(StoreVal->getType() == ValTy && "Type mismatch!");
  2730. // If the requested value was a vector constant, create it.
  2731. if (EltTy->isVectorTy()) {
  2732. unsigned NumElts = cast<VectorType>(EltTy)->getNumElements();
  2733. StoreVal = ConstantVector::getSplat(NumElts, StoreVal);
  2734. }
  2735. }
  2736. new StoreInst(StoreVal, EltPtr, MI);
  2737. continue;
  2738. }
  2739. // Otherwise, if we're storing a byte variable, use a memset call for
  2740. // this element.
  2741. }
  2742. unsigned EltSize = DL.getTypeAllocSize(EltTy);
  2743. if (!EltSize)
  2744. continue;
  2745. IRBuilder<> Builder(MI);
  2746. // Finally, insert the meminst for this element.
  2747. if (isa<MemSetInst>(MI)) {
  2748. Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
  2749. MI->isVolatile());
  2750. } else {
  2751. assert(isa<MemTransferInst>(MI));
  2752. Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr
  2753. Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr
  2754. if (isa<MemCpyInst>(MI))
  2755. Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,
  2756. MI->isVolatile());
  2757. else
  2758. Builder.CreateMemMove(Dst, Src, EltSize, OtherEltAlign,
  2759. MI->isVolatile());
  2760. }
  2761. }
  2762. DeadInsts.push_back(MI);
  2763. }
  2764. void SROA_Helper::RewriteBitCast(BitCastInst *BCI) {
  2765. Type *DstTy = BCI->getType();
  2766. Value *Val = BCI->getOperand(0);
  2767. Type *SrcTy = Val->getType();
  2768. if (!DstTy->isPointerTy()) {
  2769. assert(0 && "Type mismatch.");
  2770. return;
  2771. }
  2772. if (!SrcTy->isPointerTy()) {
  2773. assert(0 && "Type mismatch.");
  2774. return;
  2775. }
  2776. DstTy = DstTy->getPointerElementType();
  2777. SrcTy = SrcTy->getPointerElementType();
  2778. if (!DstTy->isStructTy()) {
  2779. assert(0 && "Type mismatch.");
  2780. return;
  2781. }
  2782. if (!SrcTy->isStructTy()) {
  2783. assert(0 && "Type mismatch.");
  2784. return;
  2785. }
  2786. // Only support bitcast to parent struct type.
  2787. StructType *DstST = cast<StructType>(DstTy);
  2788. StructType *SrcST = cast<StructType>(SrcTy);
  2789. bool bTypeMatch = false;
  2790. unsigned level = 0;
  2791. while (SrcST) {
  2792. level++;
  2793. Type *EltTy = SrcST->getElementType(0);
  2794. if (EltTy == DstST) {
  2795. bTypeMatch = true;
  2796. break;
  2797. }
  2798. SrcST = dyn_cast<StructType>(EltTy);
  2799. }
  2800. if (!bTypeMatch) {
  2801. assert(0 && "Type mismatch.");
  2802. return;
  2803. }
  2804. std::vector<Value*> idxList(level+1);
  2805. ConstantInt *zeroIdx = ConstantInt::get(Type::getInt32Ty(Val->getContext()), 0);
  2806. for (unsigned i=0;i<(level+1);i++)
  2807. idxList[i] = zeroIdx;
  2808. IRBuilder<> Builder(BCI);
  2809. Instruction *GEP = cast<Instruction>(Builder.CreateInBoundsGEP(Val, idxList));
  2810. BCI->replaceAllUsesWith(GEP);
  2811. BCI->eraseFromParent();
  2812. IRBuilder<> GEPBuilder(GEP);
  2813. RewriteForGEP(cast<GEPOperator>(GEP), GEPBuilder);
  2814. }
  2815. /// RewriteCallArg - For Functions which don't flat,
  2816. /// replace OldVal with alloca and
  2817. /// copy in copy out data between alloca and flattened NewElts
  2818. /// in CallInst.
  2819. void SROA_Helper::RewriteCallArg(CallInst *CI, unsigned ArgIdx, bool bIn,
  2820. bool bOut) {
  2821. Function *F = CI->getParent()->getParent();
  2822. IRBuilder<> AllocaBuilder(dxilutil::FindAllocaInsertionPt(F));
  2823. const DataLayout &DL = F->getParent()->getDataLayout();
  2824. Value *userTyV = CI->getArgOperand(ArgIdx);
  2825. PointerType *userTy = cast<PointerType>(userTyV->getType());
  2826. Type *userTyElt = userTy->getElementType();
  2827. Value *Alloca = AllocaBuilder.CreateAlloca(userTyElt);
  2828. IRBuilder<> Builder(CI);
  2829. if (bIn) {
  2830. MemCpyInst *cpy = cast<MemCpyInst>(Builder.CreateMemCpy(
  2831. Alloca, userTyV, DL.getTypeAllocSize(userTyElt), false));
  2832. RewriteMemIntrin(cpy, cpy->getRawSource());
  2833. }
  2834. CI->setArgOperand(ArgIdx, Alloca);
  2835. if (bOut) {
  2836. Builder.SetInsertPoint(CI->getNextNode());
  2837. MemCpyInst *cpy = cast<MemCpyInst>(Builder.CreateMemCpy(
  2838. userTyV, Alloca, DL.getTypeAllocSize(userTyElt), false));
  2839. RewriteMemIntrin(cpy, cpy->getRawSource());
  2840. }
  2841. }
  2842. /// RewriteCall - Replace OldVal with flattened NewElts in CallInst.
  2843. void SROA_Helper::RewriteCall(CallInst *CI) {
  2844. HLOpcodeGroup group = GetHLOpcodeGroupByName(CI->getCalledFunction());
  2845. Function *F = CI->getCalledFunction();
  2846. if (group != HLOpcodeGroup::NotHL) {
  2847. unsigned opcode = GetHLOpcode(CI);
  2848. if (group == HLOpcodeGroup::HLIntrinsic) {
  2849. IntrinsicOp IOP = static_cast<IntrinsicOp>(opcode);
  2850. switch (IOP) {
  2851. case IntrinsicOp::MOP_Append: {
  2852. // Buffer Append already expand in code gen.
  2853. // Must be OutputStream Append here.
  2854. SmallVector<Value *, 4> flatArgs;
  2855. for (Value *arg : CI->arg_operands()) {
  2856. if (arg == OldVal) {
  2857. // Flatten to arg.
  2858. // Every Elt has a pointer type.
  2859. // For Append, it's not a problem.
  2860. for (Value *Elt : NewElts)
  2861. flatArgs.emplace_back(Elt);
  2862. } else
  2863. flatArgs.emplace_back(arg);
  2864. }
  2865. SmallVector<Type *, 4> flatParamTys;
  2866. for (Value *arg : flatArgs)
  2867. flatParamTys.emplace_back(arg->getType());
  2868. // Don't need flat return type for Append.
  2869. FunctionType *flatFuncTy =
  2870. FunctionType::get(CI->getType(), flatParamTys, false);
  2871. Function *flatF =
  2872. GetOrCreateHLFunction(*F->getParent(), flatFuncTy, group, opcode);
  2873. IRBuilder<> Builder(CI);
  2874. // Append return void, don't need to replace CI with flatCI.
  2875. Builder.CreateCall(flatF, flatArgs);
  2876. DeadInsts.push_back(CI);
  2877. } break;
  2878. case IntrinsicOp::IOP_TraceRay: {
  2879. if (OldVal ==
  2880. CI->getArgOperand(HLOperandIndex::kTraceRayRayDescOpIdx)) {
  2881. RewriteCallArg(CI, HLOperandIndex::kTraceRayRayDescOpIdx,
  2882. /*bIn*/ true, /*bOut*/ false);
  2883. } else {
  2884. DXASSERT(OldVal ==
  2885. CI->getArgOperand(HLOperandIndex::kTraceRayPayLoadOpIdx),
  2886. "else invalid TraceRay");
  2887. RewriteCallArg(CI, HLOperandIndex::kTraceRayPayLoadOpIdx,
  2888. /*bIn*/ true, /*bOut*/ true);
  2889. }
  2890. } break;
  2891. case IntrinsicOp::IOP_ReportHit: {
  2892. RewriteCallArg(CI, HLOperandIndex::kReportIntersectionAttributeOpIdx,
  2893. /*bIn*/ true, /*bOut*/ false);
  2894. } break;
  2895. case IntrinsicOp::IOP_CallShader: {
  2896. RewriteCallArg(CI, HLOperandIndex::kBinaryOpSrc1Idx,
  2897. /*bIn*/ true, /*bOut*/ true);
  2898. } break;
  2899. default:
  2900. DXASSERT(0, "cannot flatten hlsl intrinsic.");
  2901. }
  2902. }
  2903. // TODO: check other high level dx operations if need to.
  2904. } else {
  2905. DXASSERT(0, "should done at inline");
  2906. }
  2907. }
  2908. /// RewriteForConstExpr - Rewrite the GEP which is ConstantExpr.
  2909. void SROA_Helper::RewriteForAddrSpaceCast(ConstantExpr *CE,
  2910. IRBuilder<> &Builder) {
  2911. SmallVector<Value *, 8> NewCasts;
  2912. // create new AddrSpaceCast.
  2913. for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
  2914. Value *NewGEP = Builder.CreateAddrSpaceCast(
  2915. NewElts[i],
  2916. PointerType::get(NewElts[i]->getType()->getPointerElementType(),
  2917. CE->getType()->getPointerAddressSpace()));
  2918. NewCasts.emplace_back(NewGEP);
  2919. }
  2920. SROA_Helper helper(CE, NewCasts, DeadInsts, typeSys, DL);
  2921. helper.RewriteForScalarRepl(CE, Builder);
  2922. }
  2923. /// RewriteForConstExpr - Rewrite the GEP which is ConstantExpr.
  2924. void SROA_Helper::RewriteForConstExpr(ConstantExpr *CE, IRBuilder<> &Builder) {
  2925. if (GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
  2926. if (OldVal == GEP->getPointerOperand()) {
  2927. // Flatten GEP.
  2928. RewriteForGEP(GEP, Builder);
  2929. return;
  2930. }
  2931. }
  2932. if (CE->getOpcode() == Instruction::AddrSpaceCast) {
  2933. if (OldVal == CE->getOperand(0)) {
  2934. // Flatten AddrSpaceCast.
  2935. RewriteForAddrSpaceCast(CE, Builder);
  2936. return;
  2937. }
  2938. }
  2939. // Skip unused CE.
  2940. if (CE->use_empty())
  2941. return;
  2942. for (Value::use_iterator UI = CE->use_begin(), E = CE->use_end(); UI != E;) {
  2943. Use &TheUse = *UI++;
  2944. if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
  2945. IRBuilder<> tmpBuilder(I);
  2946. // Replace CE with constInst.
  2947. Instruction *tmpInst = CE->getAsInstruction();
  2948. tmpBuilder.Insert(tmpInst);
  2949. TheUse.set(tmpInst);
  2950. }
  2951. else {
  2952. RewriteForConstExpr(cast<ConstantExpr>(TheUse.getUser()), Builder);
  2953. }
  2954. }
  2955. }
  2956. /// RewriteForScalarRepl - OldVal is being split into NewElts, so rewrite
  2957. /// users of V, which references it, to use the separate elements.
  2958. void SROA_Helper::RewriteForScalarRepl(Value *V, IRBuilder<> &Builder) {
  2959. for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
  2960. Use &TheUse = *UI++;
  2961. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(TheUse.getUser())) {
  2962. RewriteForConstExpr(CE, Builder);
  2963. continue;
  2964. }
  2965. Instruction *User = cast<Instruction>(TheUse.getUser());
  2966. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
  2967. IRBuilder<> Builder(GEP);
  2968. RewriteForGEP(cast<GEPOperator>(GEP), Builder);
  2969. } else if (LoadInst *ldInst = dyn_cast<LoadInst>(User))
  2970. RewriteForLoad(ldInst);
  2971. else if (StoreInst *stInst = dyn_cast<StoreInst>(User))
  2972. RewriteForStore(stInst);
  2973. else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User))
  2974. RewriteMemIntrin(MI, cast<Instruction>(V));
  2975. else if (CallInst *CI = dyn_cast<CallInst>(User))
  2976. RewriteCall(CI);
  2977. else if (BitCastInst *BCI = dyn_cast<BitCastInst>(User))
  2978. RewriteBitCast(BCI);
  2979. else {
  2980. assert(0 && "not support.");
  2981. }
  2982. }
  2983. }
  2984. static ArrayType *CreateNestArrayTy(Type *FinalEltTy,
  2985. ArrayRef<ArrayType *> nestArrayTys) {
  2986. Type *newAT = FinalEltTy;
  2987. for (auto ArrayTy = nestArrayTys.rbegin(), E=nestArrayTys.rend(); ArrayTy != E;
  2988. ++ArrayTy)
  2989. newAT = ArrayType::get(newAT, (*ArrayTy)->getNumElements());
  2990. return cast<ArrayType>(newAT);
  2991. }
  2992. /// DoScalarReplacement - Split V into AllocaInsts with Builder and save the new AllocaInsts into Elts.
  2993. /// Then do SROA on V.
  2994. bool SROA_Helper::DoScalarReplacement(Value *V, std::vector<Value *> &Elts,
  2995. IRBuilder<> &Builder, bool bFlatVector,
  2996. bool hasPrecise, DxilTypeSystem &typeSys,
  2997. const DataLayout &DL,
  2998. SmallVector<Value *, 32> &DeadInsts) {
  2999. DEBUG(dbgs() << "Found inst to SROA: " << *V << '\n');
  3000. Type *Ty = V->getType();
  3001. // Skip none pointer types.
  3002. if (!Ty->isPointerTy())
  3003. return false;
  3004. Ty = Ty->getPointerElementType();
  3005. // Skip none aggregate types.
  3006. if (!Ty->isAggregateType())
  3007. return false;
  3008. // Skip matrix types.
  3009. if (HLMatrixLower::IsMatrixType(Ty))
  3010. return false;
  3011. IRBuilder<> AllocaBuilder(dxilutil::FindAllocaInsertionPt(Builder.GetInsertPoint()));
  3012. if (StructType *ST = dyn_cast<StructType>(Ty)) {
  3013. // Skip HLSL object types.
  3014. if (HLModule::IsHLSLObjectType(ST)) {
  3015. return false;
  3016. }
  3017. unsigned numTypes = ST->getNumContainedTypes();
  3018. Elts.reserve(numTypes);
  3019. DxilStructAnnotation *SA = typeSys.GetStructAnnotation(ST);
  3020. // Skip empty struct.
  3021. if (SA && SA->IsEmptyStruct())
  3022. return true;
  3023. for (int i = 0, e = numTypes; i != e; ++i) {
  3024. AllocaInst *NA = AllocaBuilder.CreateAlloca(ST->getContainedType(i), nullptr, V->getName() + "." + Twine(i));
  3025. bool markPrecise = hasPrecise;
  3026. if (SA) {
  3027. DxilFieldAnnotation &FA = SA->GetFieldAnnotation(i);
  3028. markPrecise |= FA.IsPrecise();
  3029. }
  3030. if (markPrecise)
  3031. HLModule::MarkPreciseAttributeWithMetadata(NA);
  3032. Elts.push_back(NA);
  3033. }
  3034. } else {
  3035. ArrayType *AT = cast<ArrayType>(Ty);
  3036. if (AT->getNumContainedTypes() == 0) {
  3037. // Skip case like [0 x %struct].
  3038. return false;
  3039. }
  3040. Type *ElTy = AT->getElementType();
  3041. SmallVector<ArrayType *, 4> nestArrayTys;
  3042. nestArrayTys.emplace_back(AT);
  3043. // support multi level of array
  3044. while (ElTy->isArrayTy()) {
  3045. ArrayType *ElAT = cast<ArrayType>(ElTy);
  3046. nestArrayTys.emplace_back(ElAT);
  3047. ElTy = ElAT->getElementType();
  3048. }
  3049. if (ElTy->isStructTy() &&
  3050. // Skip Matrix type.
  3051. !HLMatrixLower::IsMatrixType(ElTy)) {
  3052. if (!HLModule::IsHLSLObjectType(ElTy)) {
  3053. // for array of struct
  3054. // split into arrays of struct elements
  3055. StructType *ElST = cast<StructType>(ElTy);
  3056. unsigned numTypes = ElST->getNumContainedTypes();
  3057. Elts.reserve(numTypes);
  3058. DxilStructAnnotation *SA = typeSys.GetStructAnnotation(ElST);
  3059. // Skip empty struct.
  3060. if (SA && SA->IsEmptyStruct())
  3061. return true;
  3062. for (int i = 0, e = numTypes; i != e; ++i) {
  3063. AllocaInst *NA = AllocaBuilder.CreateAlloca(
  3064. CreateNestArrayTy(ElST->getContainedType(i), nestArrayTys),
  3065. nullptr, V->getName() + "." + Twine(i));
  3066. bool markPrecise = hasPrecise;
  3067. if (SA) {
  3068. DxilFieldAnnotation &FA = SA->GetFieldAnnotation(i);
  3069. markPrecise |= FA.IsPrecise();
  3070. }
  3071. if (markPrecise)
  3072. HLModule::MarkPreciseAttributeWithMetadata(NA);
  3073. Elts.push_back(NA);
  3074. }
  3075. } else {
  3076. // For local resource array which not dynamic indexing,
  3077. // split it.
  3078. if (dxilutil::HasDynamicIndexing(V) ||
  3079. // Only support 1 dim split.
  3080. nestArrayTys.size() > 1)
  3081. return false;
  3082. for (int i = 0, e = AT->getNumElements(); i != e; ++i) {
  3083. AllocaInst *NA = AllocaBuilder.CreateAlloca(ElTy, nullptr,
  3084. V->getName() + "." + Twine(i));
  3085. Elts.push_back(NA);
  3086. }
  3087. }
  3088. } else if (ElTy->isVectorTy()) {
  3089. // Skip vector if required.
  3090. if (!bFlatVector)
  3091. return false;
  3092. // for array of vector
  3093. // split into arrays of scalar
  3094. VectorType *ElVT = cast<VectorType>(ElTy);
  3095. Elts.reserve(ElVT->getNumElements());
  3096. ArrayType *scalarArrayTy = CreateNestArrayTy(ElVT->getElementType(), nestArrayTys);
  3097. for (int i = 0, e = ElVT->getNumElements(); i != e; ++i) {
  3098. AllocaInst *NA = AllocaBuilder.CreateAlloca(scalarArrayTy, nullptr,
  3099. V->getName() + "." + Twine(i));
  3100. if (hasPrecise)
  3101. HLModule::MarkPreciseAttributeWithMetadata(NA);
  3102. Elts.push_back(NA);
  3103. }
  3104. } else
  3105. // Skip array of basic types.
  3106. return false;
  3107. }
  3108. // Now that we have created the new alloca instructions, rewrite all the
  3109. // uses of the old alloca.
  3110. SROA_Helper helper(V, Elts, DeadInsts, typeSys, DL);
  3111. helper.RewriteForScalarRepl(V, Builder);
  3112. return true;
  3113. }
  3114. static Constant *GetEltInit(Type *Ty, Constant *Init, unsigned idx,
  3115. Type *EltTy) {
  3116. if (isa<UndefValue>(Init))
  3117. return UndefValue::get(EltTy);
  3118. if (dyn_cast<StructType>(Ty)) {
  3119. return Init->getAggregateElement(idx);
  3120. } else if (dyn_cast<VectorType>(Ty)) {
  3121. return Init->getAggregateElement(idx);
  3122. } else {
  3123. ArrayType *AT = cast<ArrayType>(Ty);
  3124. ArrayType *EltArrayTy = cast<ArrayType>(EltTy);
  3125. std::vector<Constant *> Elts;
  3126. if (!AT->getElementType()->isArrayTy()) {
  3127. for (unsigned i = 0; i < AT->getNumElements(); i++) {
  3128. // Get Array[i]
  3129. Constant *InitArrayElt = Init->getAggregateElement(i);
  3130. // Get Array[i].idx
  3131. InitArrayElt = InitArrayElt->getAggregateElement(idx);
  3132. Elts.emplace_back(InitArrayElt);
  3133. }
  3134. return ConstantArray::get(EltArrayTy, Elts);
  3135. } else {
  3136. Type *EltTy = AT->getElementType();
  3137. ArrayType *NestEltArrayTy = cast<ArrayType>(EltArrayTy->getElementType());
  3138. // Nested array.
  3139. for (unsigned i = 0; i < AT->getNumElements(); i++) {
  3140. // Get Array[i]
  3141. Constant *InitArrayElt = Init->getAggregateElement(i);
  3142. // Get Array[i].idx
  3143. InitArrayElt = GetEltInit(EltTy, InitArrayElt, idx, NestEltArrayTy);
  3144. Elts.emplace_back(InitArrayElt);
  3145. }
  3146. return ConstantArray::get(EltArrayTy, Elts);
  3147. }
  3148. }
  3149. }
  3150. /// DoScalarReplacement - Split V into AllocaInsts with Builder and save the new AllocaInsts into Elts.
  3151. /// Then do SROA on V.
  3152. bool SROA_Helper::DoScalarReplacement(GlobalVariable *GV,
  3153. std::vector<Value *> &Elts,
  3154. IRBuilder<> &Builder, bool bFlatVector,
  3155. bool hasPrecise, DxilTypeSystem &typeSys,
  3156. const DataLayout &DL,
  3157. SmallVector<Value *, 32> &DeadInsts) {
  3158. DEBUG(dbgs() << "Found inst to SROA: " << *GV << '\n');
  3159. Type *Ty = GV->getType();
  3160. // Skip none pointer types.
  3161. if (!Ty->isPointerTy())
  3162. return false;
  3163. Ty = Ty->getPointerElementType();
  3164. // Skip none aggregate types.
  3165. if (!Ty->isAggregateType() && !bFlatVector)
  3166. return false;
  3167. // Skip basic types.
  3168. if (Ty->isSingleValueType() && !Ty->isVectorTy())
  3169. return false;
  3170. // Skip matrix types.
  3171. if (HLMatrixLower::IsMatrixType(Ty))
  3172. return false;
  3173. Module *M = GV->getParent();
  3174. Constant *Init = GV->getInitializer();
  3175. if (!Init)
  3176. Init = UndefValue::get(Ty);
  3177. bool isConst = GV->isConstant();
  3178. GlobalVariable::ThreadLocalMode TLMode = GV->getThreadLocalMode();
  3179. unsigned AddressSpace = GV->getType()->getAddressSpace();
  3180. GlobalValue::LinkageTypes linkage = GV->getLinkage();
  3181. if (StructType *ST = dyn_cast<StructType>(Ty)) {
  3182. // Skip HLSL object types.
  3183. if (HLModule::IsHLSLObjectType(ST))
  3184. return false;
  3185. unsigned numTypes = ST->getNumContainedTypes();
  3186. Elts.reserve(numTypes);
  3187. //DxilStructAnnotation *SA = typeSys.GetStructAnnotation(ST);
  3188. for (int i = 0, e = numTypes; i != e; ++i) {
  3189. Constant *EltInit = GetEltInit(Ty, Init, i, ST->getElementType(i));
  3190. GlobalVariable *EltGV = new llvm::GlobalVariable(
  3191. *M, ST->getContainedType(i), /*IsConstant*/ isConst, linkage,
  3192. /*InitVal*/ EltInit, GV->getName() + "." + Twine(i),
  3193. /*InsertBefore*/ nullptr, TLMode, AddressSpace);
  3194. //DxilFieldAnnotation &FA = SA->GetFieldAnnotation(i);
  3195. // TODO: set precise.
  3196. // if (hasPrecise || FA.IsPrecise())
  3197. // HLModule::MarkPreciseAttributeWithMetadata(NA);
  3198. Elts.push_back(EltGV);
  3199. }
  3200. } else if (VectorType *VT = dyn_cast<VectorType>(Ty)) {
  3201. // TODO: support dynamic indexing on vector by change it to array.
  3202. unsigned numElts = VT->getNumElements();
  3203. Elts.reserve(numElts);
  3204. Type *EltTy = VT->getElementType();
  3205. //DxilStructAnnotation *SA = typeSys.GetStructAnnotation(ST);
  3206. for (int i = 0, e = numElts; i != e; ++i) {
  3207. Constant *EltInit = GetEltInit(Ty, Init, i, EltTy);
  3208. GlobalVariable *EltGV = new llvm::GlobalVariable(
  3209. *M, EltTy, /*IsConstant*/ isConst, linkage,
  3210. /*InitVal*/ EltInit, GV->getName() + "." + Twine(i),
  3211. /*InsertBefore*/ nullptr, TLMode, AddressSpace);
  3212. //DxilFieldAnnotation &FA = SA->GetFieldAnnotation(i);
  3213. // TODO: set precise.
  3214. // if (hasPrecise || FA.IsPrecise())
  3215. // HLModule::MarkPreciseAttributeWithMetadata(NA);
  3216. Elts.push_back(EltGV);
  3217. }
  3218. } else {
  3219. ArrayType *AT = cast<ArrayType>(Ty);
  3220. if (AT->getNumContainedTypes() == 0) {
  3221. // Skip case like [0 x %struct].
  3222. return false;
  3223. }
  3224. Type *ElTy = AT->getElementType();
  3225. SmallVector<ArrayType *, 4> nestArrayTys;
  3226. nestArrayTys.emplace_back(AT);
  3227. // support multi level of array
  3228. while (ElTy->isArrayTy()) {
  3229. ArrayType *ElAT = cast<ArrayType>(ElTy);
  3230. nestArrayTys.emplace_back(ElAT);
  3231. ElTy = ElAT->getElementType();
  3232. }
  3233. if (ElTy->isStructTy() &&
  3234. // Skip Matrix type.
  3235. !HLMatrixLower::IsMatrixType(ElTy)) {
  3236. // for array of struct
  3237. // split into arrays of struct elements
  3238. StructType *ElST = cast<StructType>(ElTy);
  3239. unsigned numTypes = ElST->getNumContainedTypes();
  3240. Elts.reserve(numTypes);
  3241. //DxilStructAnnotation *SA = typeSys.GetStructAnnotation(ElST);
  3242. for (int i = 0, e = numTypes; i != e; ++i) {
  3243. Type *EltTy =
  3244. CreateNestArrayTy(ElST->getContainedType(i), nestArrayTys);
  3245. Constant *EltInit = GetEltInit(Ty, Init, i, EltTy);
  3246. GlobalVariable *EltGV = new llvm::GlobalVariable(
  3247. *M, EltTy, /*IsConstant*/ isConst, linkage,
  3248. /*InitVal*/ EltInit, GV->getName() + "." + Twine(i),
  3249. /*InsertBefore*/ nullptr, TLMode, AddressSpace);
  3250. //DxilFieldAnnotation &FA = SA->GetFieldAnnotation(i);
  3251. // TODO: set precise.
  3252. // if (hasPrecise || FA.IsPrecise())
  3253. // HLModule::MarkPreciseAttributeWithMetadata(NA);
  3254. Elts.push_back(EltGV);
  3255. }
  3256. } else if (ElTy->isVectorTy()) {
  3257. // Skip vector if required.
  3258. if (!bFlatVector)
  3259. return false;
  3260. // for array of vector
  3261. // split into arrays of scalar
  3262. VectorType *ElVT = cast<VectorType>(ElTy);
  3263. Elts.reserve(ElVT->getNumElements());
  3264. ArrayType *scalarArrayTy =
  3265. CreateNestArrayTy(ElVT->getElementType(), nestArrayTys);
  3266. for (int i = 0, e = ElVT->getNumElements(); i != e; ++i) {
  3267. Constant *EltInit = GetEltInit(Ty, Init, i, scalarArrayTy);
  3268. GlobalVariable *EltGV = new llvm::GlobalVariable(
  3269. *M, scalarArrayTy, /*IsConstant*/ isConst, linkage,
  3270. /*InitVal*/ EltInit, GV->getName() + "." + Twine(i),
  3271. /*InsertBefore*/ nullptr, TLMode, AddressSpace);
  3272. // TODO: set precise.
  3273. // if (hasPrecise)
  3274. // HLModule::MarkPreciseAttributeWithMetadata(NA);
  3275. Elts.push_back(EltGV);
  3276. }
  3277. } else
  3278. // Skip array of basic types.
  3279. return false;
  3280. }
  3281. // Now that we have created the new alloca instructions, rewrite all the
  3282. // uses of the old alloca.
  3283. SROA_Helper helper(GV, Elts, DeadInsts, typeSys, DL);
  3284. helper.RewriteForScalarRepl(GV, Builder);
  3285. return true;
  3286. }
  3287. struct PointerStatus {
  3288. /// Keep track of what stores to the pointer look like.
  3289. enum StoredType {
  3290. /// There is no store to this pointer. It can thus be marked constant.
  3291. NotStored,
  3292. /// This ptr is a global, and is stored to, but the only thing stored is the
  3293. /// constant it
  3294. /// was initialized with. This is only tracked for scalar globals.
  3295. InitializerStored,
  3296. /// This ptr is stored to, but only its initializer and one other value
  3297. /// is ever stored to it. If this global isStoredOnce, we track the value
  3298. /// stored to it in StoredOnceValue below. This is only tracked for scalar
  3299. /// globals.
  3300. StoredOnce,
  3301. /// This ptr is only assigned by a memcpy.
  3302. MemcopyDestOnce,
  3303. /// This ptr is stored to by multiple values or something else that we
  3304. /// cannot track.
  3305. Stored
  3306. } storedType;
  3307. /// Keep track of what loaded from the pointer look like.
  3308. enum LoadedType {
  3309. /// There is no load to this pointer. It can thus be marked constant.
  3310. NotLoaded,
  3311. /// This ptr is only used by a memcpy.
  3312. MemcopySrcOnce,
  3313. /// This ptr is loaded to by multiple instructions or something else that we
  3314. /// cannot track.
  3315. Loaded
  3316. } loadedType;
  3317. /// If only one value (besides the initializer constant) is ever stored to
  3318. /// this global, keep track of what value it is.
  3319. Value *StoredOnceValue;
  3320. /// Memcpy which this ptr is used.
  3321. std::unordered_set<MemCpyInst *> memcpySet;
  3322. /// Memcpy which use this ptr as dest.
  3323. MemCpyInst *StoringMemcpy;
  3324. /// Memcpy which use this ptr as src.
  3325. MemCpyInst *LoadingMemcpy;
  3326. /// These start out null/false. When the first accessing function is noticed,
  3327. /// it is recorded. When a second different accessing function is noticed,
  3328. /// HasMultipleAccessingFunctions is set to true.
  3329. const Function *AccessingFunction;
  3330. bool HasMultipleAccessingFunctions;
  3331. /// Size of the ptr.
  3332. unsigned Size;
  3333. /// Look at all uses of the global and fill in the GlobalStatus structure. If
  3334. /// the global has its address taken, return true to indicate we can't do
  3335. /// anything with it.
  3336. static void analyzePointer(const Value *V, PointerStatus &PS,
  3337. DxilTypeSystem &typeSys, bool bStructElt);
  3338. PointerStatus(unsigned size)
  3339. : storedType(StoredType::NotStored), loadedType(LoadedType::NotLoaded), StoredOnceValue(nullptr),
  3340. StoringMemcpy(nullptr), LoadingMemcpy(nullptr),
  3341. AccessingFunction(nullptr), HasMultipleAccessingFunctions(false),
  3342. Size(size) {}
  3343. void MarkAsStored() {
  3344. storedType = StoredType::Stored;
  3345. StoredOnceValue = nullptr;
  3346. }
  3347. void MarkAsLoaded() { loadedType = LoadedType::Loaded; }
  3348. };
  3349. void PointerStatus::analyzePointer(const Value *V, PointerStatus &PS,
  3350. DxilTypeSystem &typeSys, bool bStructElt) {
  3351. for (const User *U : V->users()) {
  3352. if (const Instruction *I = dyn_cast<Instruction>(U)) {
  3353. const Function *F = I->getParent()->getParent();
  3354. if (!PS.AccessingFunction) {
  3355. PS.AccessingFunction = F;
  3356. } else {
  3357. if (F != PS.AccessingFunction)
  3358. PS.HasMultipleAccessingFunctions = true;
  3359. }
  3360. }
  3361. if (const BitCastOperator *BC = dyn_cast<BitCastOperator>(U)) {
  3362. analyzePointer(BC, PS, typeSys, bStructElt);
  3363. } else if (const MemCpyInst *MC = dyn_cast<MemCpyInst>(U)) {
  3364. // Do not collect memcpy on struct GEP use.
  3365. // These memcpy will be flattened in next level.
  3366. if (!bStructElt) {
  3367. MemCpyInst *MI = const_cast<MemCpyInst *>(MC);
  3368. PS.memcpySet.insert(MI);
  3369. bool bFullCopy = false;
  3370. if (ConstantInt *Length = dyn_cast<ConstantInt>(MC->getLength())) {
  3371. bFullCopy = PS.Size == Length->getLimitedValue()
  3372. || PS.Size == 0 || Length->getLimitedValue() == 0; // handle unbounded arrays
  3373. }
  3374. if (MC->getRawDest() == V) {
  3375. if (bFullCopy &&
  3376. PS.storedType == StoredType::NotStored) {
  3377. PS.storedType = StoredType::MemcopyDestOnce;
  3378. PS.StoringMemcpy = MI;
  3379. } else {
  3380. PS.MarkAsStored();
  3381. PS.StoringMemcpy = nullptr;
  3382. }
  3383. } else if (MC->getRawSource() == V) {
  3384. if (bFullCopy &&
  3385. PS.loadedType == LoadedType::NotLoaded) {
  3386. PS.loadedType = LoadedType::MemcopySrcOnce;
  3387. PS.LoadingMemcpy = MI;
  3388. } else {
  3389. PS.MarkAsLoaded();
  3390. PS.LoadingMemcpy = nullptr;
  3391. }
  3392. }
  3393. } else {
  3394. if (MC->getRawDest() == V) {
  3395. PS.MarkAsStored();
  3396. } else {
  3397. DXASSERT(MC->getRawSource() == V, "must be source here");
  3398. PS.MarkAsLoaded();
  3399. }
  3400. }
  3401. } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
  3402. gep_type_iterator GEPIt = gep_type_begin(GEP);
  3403. gep_type_iterator GEPEnd = gep_type_end(GEP);
  3404. // Skip pointer idx.
  3405. GEPIt++;
  3406. // Struct elt will be flattened in next level.
  3407. bool bStructElt = (GEPIt != GEPEnd) && GEPIt->isStructTy();
  3408. analyzePointer(GEP, PS, typeSys, bStructElt);
  3409. } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
  3410. Value *V = SI->getOperand(0);
  3411. if (PS.storedType == StoredType::NotStored) {
  3412. PS.storedType = StoredType::StoredOnce;
  3413. PS.StoredOnceValue = V;
  3414. } else {
  3415. PS.MarkAsStored();
  3416. }
  3417. } else if (dyn_cast<LoadInst>(U)) {
  3418. PS.MarkAsLoaded();
  3419. } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
  3420. Function *F = CI->getCalledFunction();
  3421. DxilFunctionAnnotation *annotation = typeSys.GetFunctionAnnotation(F);
  3422. if (!annotation) {
  3423. HLOpcodeGroup group = hlsl::GetHLOpcodeGroupByName(F);
  3424. switch (group) {
  3425. case HLOpcodeGroup::HLMatLoadStore: {
  3426. HLMatLoadStoreOpcode opcode =
  3427. static_cast<HLMatLoadStoreOpcode>(hlsl::GetHLOpcode(CI));
  3428. switch (opcode) {
  3429. case HLMatLoadStoreOpcode::ColMatLoad:
  3430. case HLMatLoadStoreOpcode::RowMatLoad:
  3431. PS.MarkAsLoaded();
  3432. break;
  3433. case HLMatLoadStoreOpcode::ColMatStore:
  3434. case HLMatLoadStoreOpcode::RowMatStore:
  3435. PS.MarkAsStored();
  3436. break;
  3437. default:
  3438. DXASSERT(0, "invalid opcode");
  3439. PS.MarkAsStored();
  3440. PS.MarkAsLoaded();
  3441. }
  3442. } break;
  3443. case HLOpcodeGroup::HLSubscript: {
  3444. HLSubscriptOpcode opcode =
  3445. static_cast<HLSubscriptOpcode>(hlsl::GetHLOpcode(CI));
  3446. switch (opcode) {
  3447. case HLSubscriptOpcode::VectorSubscript:
  3448. case HLSubscriptOpcode::ColMatElement:
  3449. case HLSubscriptOpcode::ColMatSubscript:
  3450. case HLSubscriptOpcode::RowMatElement:
  3451. case HLSubscriptOpcode::RowMatSubscript:
  3452. analyzePointer(CI, PS, typeSys, bStructElt);
  3453. break;
  3454. default:
  3455. // Rest are resource ptr like buf[i].
  3456. // Only read of resource handle.
  3457. PS.MarkAsLoaded();
  3458. break;
  3459. }
  3460. } break;
  3461. default: {
  3462. // If not sure its out param or not. Take as out param.
  3463. PS.MarkAsStored();
  3464. PS.MarkAsLoaded();
  3465. }
  3466. }
  3467. continue;
  3468. }
  3469. unsigned argSize = F->arg_size();
  3470. for (unsigned i = 0; i < argSize; i++) {
  3471. Value *arg = CI->getArgOperand(i);
  3472. if (V == arg) {
  3473. // Do not replace struct arg.
  3474. // Mark stored and loaded to disable replace.
  3475. PS.MarkAsStored();
  3476. PS.MarkAsLoaded();
  3477. }
  3478. }
  3479. }
  3480. }
  3481. }
  3482. static void ReplaceConstantWithInst(Constant *C, Value *V, IRBuilder<> &Builder) {
  3483. for (auto it = C->user_begin(); it != C->user_end(); ) {
  3484. User *U = *(it++);
  3485. if (Instruction *I = dyn_cast<Instruction>(U)) {
  3486. I->replaceUsesOfWith(C, V);
  3487. } else {
  3488. // Skip unused ConstantExpr.
  3489. if (U->user_empty())
  3490. continue;
  3491. ConstantExpr *CE = cast<ConstantExpr>(U);
  3492. Instruction *Inst = CE->getAsInstruction();
  3493. Builder.Insert(Inst);
  3494. Inst->replaceUsesOfWith(C, V);
  3495. ReplaceConstantWithInst(CE, Inst, Builder);
  3496. }
  3497. }
  3498. C->removeDeadConstantUsers();
  3499. }
  3500. static void ReplaceUnboundedArrayUses(Value *V, Value *Src, IRBuilder<> &Builder) {
  3501. for (auto it = V->user_begin(); it != V->user_end(); ) {
  3502. User *U = *(it++);
  3503. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
  3504. SmallVector<Value *, 4> idxList(GEP->idx_begin(), GEP->idx_end());
  3505. Value *NewGEP = Builder.CreateGEP(Src, idxList);
  3506. GEP->replaceAllUsesWith(NewGEP);
  3507. } else if (BitCastInst *BC = dyn_cast<BitCastInst>(U)) {
  3508. BC->setOperand(0, Src);
  3509. } else {
  3510. DXASSERT(false, "otherwise unbounded array used in unexpected instruction");
  3511. }
  3512. }
  3513. }
  3514. static void ReplaceMemcpy(Value *V, Value *Src, MemCpyInst *MC) {
  3515. Type *TyV = V->getType()->getPointerElementType();
  3516. Type *TySrc = Src->getType()->getPointerElementType();
  3517. if (Constant *C = dyn_cast<Constant>(V)) {
  3518. if (TyV == TySrc) {
  3519. if (isa<Constant>(Src)) {
  3520. V->replaceAllUsesWith(Src);
  3521. } else {
  3522. // Replace Constant with a non-Constant.
  3523. IRBuilder<> Builder(MC);
  3524. ReplaceConstantWithInst(C, Src, Builder);
  3525. }
  3526. } else {
  3527. IRBuilder<> Builder(MC);
  3528. Src = Builder.CreateBitCast(Src, V->getType());
  3529. ReplaceConstantWithInst(C, Src, Builder);
  3530. }
  3531. } else {
  3532. if (TyV == TySrc) {
  3533. if (V != Src)
  3534. V->replaceAllUsesWith(Src);
  3535. } else {
  3536. DXASSERT((TyV->isArrayTy() && TySrc->isArrayTy()) &&
  3537. (TyV->getArrayNumElements() == 0 ||
  3538. TySrc->getArrayNumElements() == 0),
  3539. "otherwise mismatched types in memcpy are not unbounded array");
  3540. IRBuilder<> Builder(MC);
  3541. ReplaceUnboundedArrayUses(V, Src, Builder);
  3542. }
  3543. }
  3544. Value *RawDest = MC->getOperand(0);
  3545. Value *RawSrc = MC->getOperand(1);
  3546. MC->eraseFromParent();
  3547. if (Instruction *I = dyn_cast<Instruction>(RawDest)) {
  3548. if (I->user_empty())
  3549. I->eraseFromParent();
  3550. }
  3551. if (Instruction *I = dyn_cast<Instruction>(RawSrc)) {
  3552. if (I->user_empty())
  3553. I->eraseFromParent();
  3554. }
  3555. }
  3556. static bool ReplaceUseOfZeroInitEntry(Instruction *I, Value *V) {
  3557. BasicBlock *BB = I->getParent();
  3558. Function *F = I->getParent()->getParent();
  3559. for (auto U = V->user_begin(); U != V->user_end(); ) {
  3560. Instruction *UI = dyn_cast<Instruction>(*(U++));
  3561. if (!UI)
  3562. continue;
  3563. if (UI->getParent()->getParent() != F)
  3564. continue;
  3565. if (isa<GetElementPtrInst>(UI) || isa<BitCastInst>(UI)) {
  3566. if (!ReplaceUseOfZeroInitEntry(I, UI))
  3567. return false;
  3568. else
  3569. continue;
  3570. }
  3571. if (BB != UI->getParent() || UI == I)
  3572. continue;
  3573. // I is the last inst in the block after split.
  3574. // Any inst in current block is before I.
  3575. if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
  3576. LI->replaceAllUsesWith(ConstantAggregateZero::get(LI->getType()));
  3577. LI->eraseFromParent();
  3578. continue;
  3579. }
  3580. return false;
  3581. }
  3582. return true;
  3583. }
  3584. static bool ReplaceUseOfZeroInitPostDom(Instruction *I, Value *V,
  3585. PostDominatorTree &PDT) {
  3586. BasicBlock *BB = I->getParent();
  3587. Function *F = I->getParent()->getParent();
  3588. for (auto U = V->user_begin(); U != V->user_end(); ) {
  3589. Instruction *UI = dyn_cast<Instruction>(*(U++));
  3590. if (!UI)
  3591. continue;
  3592. if (UI->getParent()->getParent() != F)
  3593. continue;
  3594. if (!PDT.dominates(BB, UI->getParent()))
  3595. return false;
  3596. if (isa<GetElementPtrInst>(UI) || isa<BitCastInst>(UI)) {
  3597. if (!ReplaceUseOfZeroInitPostDom(I, UI, PDT))
  3598. return false;
  3599. else
  3600. continue;
  3601. }
  3602. if (BB != UI->getParent() || UI == I)
  3603. continue;
  3604. // I is the last inst in the block after split.
  3605. // Any inst in current block is before I.
  3606. if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
  3607. LI->replaceAllUsesWith(ConstantAggregateZero::get(LI->getType()));
  3608. LI->eraseFromParent();
  3609. continue;
  3610. }
  3611. return false;
  3612. }
  3613. return true;
  3614. }
  3615. // When zero initialized GV has only one define, all uses before the def should
  3616. // use zero.
  3617. static bool ReplaceUseOfZeroInitBeforeDef(Instruction *I, GlobalVariable *GV) {
  3618. BasicBlock *BB = I->getParent();
  3619. Function *F = I->getParent()->getParent();
  3620. // Make sure I is the last inst for BB.
  3621. if (I != BB->getTerminator())
  3622. BB->splitBasicBlock(I->getNextNode());
  3623. if (&F->getEntryBlock() == I->getParent()) {
  3624. return ReplaceUseOfZeroInitEntry(I, GV);
  3625. } else {
  3626. // Post dominator tree.
  3627. PostDominatorTree PDT;
  3628. PDT.runOnFunction(*F);
  3629. return ReplaceUseOfZeroInitPostDom(I, GV, PDT);
  3630. }
  3631. }
  3632. bool SROA_Helper::LowerMemcpy(Value *V, DxilFieldAnnotation *annotation,
  3633. DxilTypeSystem &typeSys, const DataLayout &DL,
  3634. bool bAllowReplace) {
  3635. Type *Ty = V->getType();
  3636. if (!Ty->isPointerTy()) {
  3637. return false;
  3638. }
  3639. // Get access status and collect memcpy uses.
  3640. // if MemcpyOnce, replace with dest with src if dest is not out param.
  3641. // else flat memcpy.
  3642. unsigned size = DL.getTypeAllocSize(Ty->getPointerElementType());
  3643. PointerStatus PS(size);
  3644. const bool bStructElt = false;
  3645. PointerStatus::analyzePointer(V, PS, typeSys, bStructElt);
  3646. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
  3647. if (GV->hasInitializer() && !isa<UndefValue>(GV->getInitializer())) {
  3648. if (PS.storedType == PointerStatus::StoredType::NotStored) {
  3649. PS.storedType = PointerStatus::StoredType::InitializerStored;
  3650. } else if (PS.storedType == PointerStatus::StoredType::MemcopyDestOnce) {
  3651. // For single mem store, if the store not dominator all users.
  3652. // Makr it as Stored.
  3653. // Case like:
  3654. // struct A { float4 x[25]; };
  3655. // A a;
  3656. // static A a2;
  3657. // void set(A aa) { aa = a; }
  3658. // call set inside entry function then use a2.
  3659. if (isa<ConstantAggregateZero>(GV->getInitializer())) {
  3660. Instruction * Memcpy = PS.StoringMemcpy;
  3661. if (!ReplaceUseOfZeroInitBeforeDef(Memcpy, GV)) {
  3662. PS.storedType = PointerStatus::StoredType::Stored;
  3663. }
  3664. }
  3665. } else {
  3666. PS.storedType = PointerStatus::StoredType::Stored;
  3667. }
  3668. }
  3669. }
  3670. if (bAllowReplace && !PS.HasMultipleAccessingFunctions) {
  3671. if (PS.storedType == PointerStatus::StoredType::MemcopyDestOnce &&
  3672. // Skip argument for input argument has input value, it is not dest once anymore.
  3673. !isa<Argument>(V)) {
  3674. // Replace with src of memcpy.
  3675. MemCpyInst *MC = PS.StoringMemcpy;
  3676. if (MC->getSourceAddressSpace() == MC->getDestAddressSpace()) {
  3677. Value *Src = MC->getOperand(1);
  3678. // Only remove one level bitcast generated from inline.
  3679. if (BitCastOperator *BC = dyn_cast<BitCastOperator>(Src))
  3680. Src = BC->getOperand(0);
  3681. if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
  3682. // For GEP, the ptr could have other GEP read/write.
  3683. // Only scan one GEP is not enough.
  3684. Value *Ptr = GEP->getPointerOperand();
  3685. if (CallInst *PtrCI = dyn_cast<CallInst>(Ptr)) {
  3686. hlsl::HLOpcodeGroup group =
  3687. hlsl::GetHLOpcodeGroup(PtrCI->getCalledFunction());
  3688. if (group == HLOpcodeGroup::HLSubscript) {
  3689. HLSubscriptOpcode opcode =
  3690. static_cast<HLSubscriptOpcode>(hlsl::GetHLOpcode(PtrCI));
  3691. if (opcode == HLSubscriptOpcode::CBufferSubscript) {
  3692. // Ptr from CBuffer is safe.
  3693. ReplaceMemcpy(V, Src, MC);
  3694. return true;
  3695. }
  3696. }
  3697. }
  3698. } else if (!isa<CallInst>(Src)) {
  3699. // Resource ptr should not be replaced.
  3700. // Need to make sure src not updated after current memcpy.
  3701. // Check Src only have 1 store now.
  3702. PointerStatus SrcPS(size);
  3703. PointerStatus::analyzePointer(Src, SrcPS, typeSys, bStructElt);
  3704. if (SrcPS.storedType != PointerStatus::StoredType::Stored) {
  3705. ReplaceMemcpy(V, Src, MC);
  3706. return true;
  3707. }
  3708. }
  3709. }
  3710. } else if (PS.loadedType == PointerStatus::LoadedType::MemcopySrcOnce) {
  3711. // Replace dst of memcpy.
  3712. MemCpyInst *MC = PS.LoadingMemcpy;
  3713. if (MC->getSourceAddressSpace() == MC->getDestAddressSpace()) {
  3714. Value *Dest = MC->getOperand(0);
  3715. // Only remove one level bitcast generated from inline.
  3716. if (BitCastOperator *BC = dyn_cast<BitCastOperator>(Dest))
  3717. Dest = BC->getOperand(0);
  3718. // For GEP, the ptr could have other GEP read/write.
  3719. // Only scan one GEP is not enough.
  3720. // And resource ptr should not be replaced.
  3721. if (!isa<GEPOperator>(Dest) && !isa<CallInst>(Dest) &&
  3722. !isa<BitCastOperator>(Dest)) {
  3723. // Need to make sure Dest not updated after current memcpy.
  3724. // Check Dest only have 1 store now.
  3725. PointerStatus DestPS(size);
  3726. PointerStatus::analyzePointer(Dest, DestPS, typeSys, bStructElt);
  3727. if (DestPS.storedType != PointerStatus::StoredType::Stored) {
  3728. ReplaceMemcpy(Dest, V, MC);
  3729. // V still need to be flatten.
  3730. // Lower memcpy come from Dest.
  3731. return LowerMemcpy(V, annotation, typeSys, DL, bAllowReplace);
  3732. }
  3733. }
  3734. }
  3735. }
  3736. }
  3737. for (MemCpyInst *MC : PS.memcpySet) {
  3738. MemcpySplitter::SplitMemCpy(MC, DL, annotation, typeSys);
  3739. }
  3740. return false;
  3741. }
  3742. /// MarkEmptyStructUsers - Add instruction related to Empty struct to DeadInsts.
  3743. void SROA_Helper::MarkEmptyStructUsers(Value *V, SmallVector<Value *, 32> &DeadInsts) {
  3744. for (User *U : V->users()) {
  3745. MarkEmptyStructUsers(U, DeadInsts);
  3746. }
  3747. if (Instruction *I = dyn_cast<Instruction>(V)) {
  3748. // Only need to add no use inst here.
  3749. // DeleteDeadInst will delete everything.
  3750. if (I->user_empty())
  3751. DeadInsts.emplace_back(I);
  3752. }
  3753. }
  3754. bool SROA_Helper::IsEmptyStructType(Type *Ty, DxilTypeSystem &typeSys) {
  3755. if (isa<ArrayType>(Ty))
  3756. Ty = Ty->getArrayElementType();
  3757. if (StructType *ST = dyn_cast<StructType>(Ty)) {
  3758. if (!HLMatrixLower::IsMatrixType(Ty)) {
  3759. DxilStructAnnotation *SA = typeSys.GetStructAnnotation(ST);
  3760. if (SA && SA->IsEmptyStruct())
  3761. return true;
  3762. }
  3763. }
  3764. return false;
  3765. }
  3766. //===----------------------------------------------------------------------===//
  3767. // SROA on function parameters.
  3768. //===----------------------------------------------------------------------===//
  3769. static void LegalizeDxilInputOutputs(Function *F,
  3770. DxilFunctionAnnotation *EntryAnnotation,
  3771. const DataLayout &DL,
  3772. DxilTypeSystem &typeSys);
  3773. static void InjectReturnAfterNoReturnPreserveOutput(HLModule &HLM);
  3774. namespace {
  3775. class SROA_Parameter_HLSL : public ModulePass {
  3776. HLModule *m_pHLModule;
  3777. public:
  3778. static char ID; // Pass identification, replacement for typeid
  3779. explicit SROA_Parameter_HLSL() : ModulePass(ID) {}
  3780. const char *getPassName() const override { return "SROA Parameter HLSL"; }
  3781. bool runOnModule(Module &M) override {
  3782. // Patch memcpy to cover case bitcast (gep ptr, 0,0) is transformed into
  3783. // bitcast ptr.
  3784. MemcpySplitter::PatchMemCpyWithZeroIdxGEP(M);
  3785. m_pHLModule = &M.GetOrCreateHLModule();
  3786. const DataLayout &DL = M.getDataLayout();
  3787. // Load up debug information, to cross-reference values and the instructions
  3788. // used to load them.
  3789. m_HasDbgInfo = getDebugMetadataVersionFromModule(M) != 0;
  3790. InjectReturnAfterNoReturnPreserveOutput(*m_pHLModule);
  3791. std::deque<Function *> WorkList;
  3792. std::vector<Function *> DeadHLFunctions;
  3793. for (Function &F : M.functions()) {
  3794. HLOpcodeGroup group = GetHLOpcodeGroup(&F);
  3795. // Skip HL operations.
  3796. if (group != HLOpcodeGroup::NotHL ||
  3797. group == HLOpcodeGroup::HLExtIntrinsic) {
  3798. if (F.user_empty())
  3799. DeadHLFunctions.emplace_back(&F);
  3800. continue;
  3801. }
  3802. if (F.isDeclaration()) {
  3803. // Skip llvm intrinsic.
  3804. if (F.isIntrinsic())
  3805. continue;
  3806. // Skip unused external function.
  3807. if (F.user_empty())
  3808. continue;
  3809. }
  3810. // Skip void(void) functions.
  3811. if (F.getReturnType()->isVoidTy() && F.arg_size() == 0)
  3812. continue;
  3813. // Skip library function, except to LegalizeDxilInputOutputs
  3814. if (&F != m_pHLModule->GetEntryFunction() &&
  3815. !m_pHLModule->IsEntryThatUsesSignatures(&F)) {
  3816. if (!F.isDeclaration())
  3817. LegalizeDxilInputOutputs(&F, m_pHLModule->GetFunctionAnnotation(&F),
  3818. DL, m_pHLModule->GetTypeSystem());
  3819. continue;
  3820. }
  3821. WorkList.emplace_back(&F);
  3822. }
  3823. // Remove dead hl functions here.
  3824. // This is for hl functions which has body and always inline.
  3825. for (Function *F : DeadHLFunctions) {
  3826. F->eraseFromParent();
  3827. }
  3828. // Preprocess aggregate function param used as function call arg.
  3829. for (Function *F : WorkList) {
  3830. preprocessArgUsedInCall(F);
  3831. }
  3832. // Process the worklist
  3833. while (!WorkList.empty()) {
  3834. Function *F = WorkList.front();
  3835. WorkList.pop_front();
  3836. createFlattenedFunction(F);
  3837. }
  3838. // Replace functions with flattened version when we flat all the functions.
  3839. for (auto Iter : funcMap)
  3840. replaceCall(Iter.first, Iter.second);
  3841. // Update patch constant function.
  3842. for (Function &F : M.functions()) {
  3843. if (F.isDeclaration())
  3844. continue;
  3845. if (!m_pHLModule->HasDxilFunctionProps(&F))
  3846. continue;
  3847. DxilFunctionProps &funcProps = m_pHLModule->GetDxilFunctionProps(&F);
  3848. if (funcProps.shaderKind == DXIL::ShaderKind::Hull) {
  3849. Function *oldPatchConstantFunc =
  3850. funcProps.ShaderProps.HS.patchConstantFunc;
  3851. if (funcMap.count(oldPatchConstantFunc))
  3852. m_pHLModule->SetPatchConstantFunctionForHS(&F, funcMap[oldPatchConstantFunc]);
  3853. }
  3854. }
  3855. // Remove flattened functions.
  3856. for (auto Iter : funcMap) {
  3857. Function *F = Iter.first;
  3858. Function *flatF = Iter.second;
  3859. flatF->takeName(F);
  3860. F->eraseFromParent();
  3861. }
  3862. // Flatten internal global.
  3863. std::vector<GlobalVariable *> staticGVs;
  3864. for (GlobalVariable &GV : M.globals()) {
  3865. if (dxilutil::IsStaticGlobal(&GV) ||
  3866. dxilutil::IsSharedMemoryGlobal(&GV)) {
  3867. staticGVs.emplace_back(&GV);
  3868. } else {
  3869. // merge GEP use for global.
  3870. HLModule::MergeGepUse(&GV);
  3871. }
  3872. }
  3873. for (GlobalVariable *GV : staticGVs)
  3874. flattenGlobal(GV);
  3875. // Remove unused internal global.
  3876. staticGVs.clear();
  3877. for (GlobalVariable &GV : M.globals()) {
  3878. if (dxilutil::IsStaticGlobal(&GV) ||
  3879. dxilutil::IsSharedMemoryGlobal(&GV)) {
  3880. staticGVs.emplace_back(&GV);
  3881. }
  3882. }
  3883. for (GlobalVariable *GV : staticGVs) {
  3884. bool onlyStoreUse = true;
  3885. for (User *user : GV->users()) {
  3886. if (isa<StoreInst>(user))
  3887. continue;
  3888. if (isa<ConstantExpr>(user) && user->user_empty())
  3889. continue;
  3890. // Check matrix store.
  3891. if (HLMatrixLower::IsMatrixType(
  3892. GV->getType()->getPointerElementType())) {
  3893. if (CallInst *CI = dyn_cast<CallInst>(user)) {
  3894. if (GetHLOpcodeGroupByName(CI->getCalledFunction()) ==
  3895. HLOpcodeGroup::HLMatLoadStore) {
  3896. HLMatLoadStoreOpcode opcode =
  3897. static_cast<HLMatLoadStoreOpcode>(GetHLOpcode(CI));
  3898. if (opcode == HLMatLoadStoreOpcode::ColMatStore ||
  3899. opcode == HLMatLoadStoreOpcode::RowMatStore)
  3900. continue;
  3901. }
  3902. }
  3903. }
  3904. onlyStoreUse = false;
  3905. break;
  3906. }
  3907. if (onlyStoreUse) {
  3908. for (auto UserIt = GV->user_begin(); UserIt != GV->user_end();) {
  3909. Value *User = *(UserIt++);
  3910. if (Instruction *I = dyn_cast<Instruction>(User)) {
  3911. I->eraseFromParent();
  3912. }
  3913. else {
  3914. ConstantExpr *CE = cast<ConstantExpr>(User);
  3915. CE->dropAllReferences();
  3916. }
  3917. }
  3918. GV->eraseFromParent();
  3919. }
  3920. }
  3921. return true;
  3922. }
  3923. private:
  3924. void DeleteDeadInstructions();
  3925. void preprocessArgUsedInCall(Function *F);
  3926. void moveFunctionBody(Function *F, Function *flatF);
  3927. void replaceCall(Function *F, Function *flatF);
  3928. void createFlattenedFunction(Function *F);
  3929. void
  3930. flattenArgument(Function *F, Value *Arg, bool bForParam,
  3931. DxilParameterAnnotation &paramAnnotation,
  3932. std::vector<Value *> &FlatParamList,
  3933. std::vector<DxilParameterAnnotation> &FlatRetAnnotationList,
  3934. IRBuilder<> &Builder, DbgDeclareInst *DDI);
  3935. Value *castResourceArgIfRequired(Value *V, Type *Ty, bool bOut,
  3936. DxilParamInputQual inputQual,
  3937. IRBuilder<> &Builder);
  3938. Value *castArgumentIfRequired(Value *V, Type *Ty, bool bOut,
  3939. DxilParamInputQual inputQual,
  3940. DxilFieldAnnotation &annotation,
  3941. std::deque<Value *> &WorkList,
  3942. IRBuilder<> &Builder);
  3943. // Replace use of parameter which changed type when flatten.
  3944. // Also add information to Arg if required.
  3945. void replaceCastParameter(Value *NewParam, Value *OldParam, Function &F,
  3946. Argument *Arg, const DxilParamInputQual inputQual,
  3947. IRBuilder<> &Builder);
  3948. void allocateSemanticIndex(
  3949. std::vector<DxilParameterAnnotation> &FlatAnnotationList,
  3950. unsigned startArgIndex, llvm::StringMap<Type *> &semanticTypeMap);
  3951. bool hasDynamicVectorIndexing(Value *V);
  3952. void flattenGlobal(GlobalVariable *GV);
  3953. /// DeadInsts - Keep track of instructions we have made dead, so that
  3954. /// we can remove them after we are done working.
  3955. SmallVector<Value *, 32> DeadInsts;
  3956. // Map from orginal function to the flatten version.
  3957. std::unordered_map<Function *, Function *> funcMap;
  3958. // Map from original arg/param to flatten cast version.
  3959. std::unordered_map<Value *, std::pair<Value*, DxilParamInputQual>> castParamMap;
  3960. // Map form first element of a vector the list of all elements of the vector.
  3961. std::unordered_map<Value *, SmallVector<Value*, 4> > vectorEltsMap;
  3962. // Set for row major matrix parameter.
  3963. std::unordered_set<Value *> castRowMajorParamMap;
  3964. bool m_HasDbgInfo;
  3965. };
  3966. }
  3967. char SROA_Parameter_HLSL::ID = 0;
  3968. INITIALIZE_PASS(SROA_Parameter_HLSL, "scalarrepl-param-hlsl",
  3969. "Scalar Replacement of Aggregates HLSL (parameters)", false,
  3970. false)
  3971. /// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
  3972. /// recursively including all their operands that become trivially dead.
  3973. void SROA_Parameter_HLSL::DeleteDeadInstructions() {
  3974. while (!DeadInsts.empty()) {
  3975. Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
  3976. for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
  3977. if (Instruction *U = dyn_cast<Instruction>(*OI)) {
  3978. // Zero out the operand and see if it becomes trivially dead.
  3979. // (But, don't add allocas to the dead instruction list -- they are
  3980. // already on the worklist and will be deleted separately.)
  3981. *OI = nullptr;
  3982. if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
  3983. DeadInsts.push_back(U);
  3984. }
  3985. I->eraseFromParent();
  3986. }
  3987. }
  3988. bool SROA_Parameter_HLSL::hasDynamicVectorIndexing(Value *V) {
  3989. for (User *U : V->users()) {
  3990. if (!U->getType()->isPointerTy())
  3991. continue;
  3992. if (dyn_cast<GEPOperator>(U)) {
  3993. gep_type_iterator GEPIt = gep_type_begin(U), E = gep_type_end(U);
  3994. for (; GEPIt != E; ++GEPIt) {
  3995. if (isa<VectorType>(*GEPIt)) {
  3996. Value *VecIdx = GEPIt.getOperand();
  3997. if (!isa<ConstantInt>(VecIdx))
  3998. return true;
  3999. }
  4000. }
  4001. }
  4002. }
  4003. return false;
  4004. }
  4005. void SROA_Parameter_HLSL::flattenGlobal(GlobalVariable *GV) {
  4006. Type *Ty = GV->getType()->getPointerElementType();
  4007. // Skip basic types.
  4008. if (!Ty->isAggregateType() && !Ty->isVectorTy())
  4009. return;
  4010. std::deque<Value *> WorkList;
  4011. WorkList.push_back(GV);
  4012. // merge GEP use for global.
  4013. HLModule::MergeGepUse(GV);
  4014. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  4015. // Only used to create ConstantExpr.
  4016. IRBuilder<> Builder(m_pHLModule->GetCtx());
  4017. std::vector<Instruction*> deadAllocas;
  4018. const DataLayout &DL = GV->getParent()->getDataLayout();
  4019. unsigned debugOffset = 0;
  4020. std::unordered_map<Value*, StringRef> EltNameMap;
  4021. // Process the worklist
  4022. while (!WorkList.empty()) {
  4023. GlobalVariable *EltGV = cast<GlobalVariable>(WorkList.front());
  4024. WorkList.pop_front();
  4025. const bool bAllowReplace = true;
  4026. if (SROA_Helper::LowerMemcpy(EltGV, /*annoation*/ nullptr, dxilTypeSys, DL,
  4027. bAllowReplace)) {
  4028. continue;
  4029. }
  4030. // Flat Global vector if no dynamic vector indexing.
  4031. bool bFlatVector = !hasDynamicVectorIndexing(EltGV);
  4032. std::vector<Value *> Elts;
  4033. bool SROAed = SROA_Helper::DoScalarReplacement(
  4034. EltGV, Elts, Builder, bFlatVector,
  4035. // TODO: set precise.
  4036. /*hasPrecise*/ false, dxilTypeSys, DL, DeadInsts);
  4037. if (SROAed) {
  4038. // Push Elts into workList.
  4039. // Use rbegin to make sure the order not change.
  4040. for (auto iter = Elts.rbegin(); iter != Elts.rend(); iter++) {
  4041. WorkList.push_front(*iter);
  4042. if (m_HasDbgInfo) {
  4043. StringRef EltName = (*iter)->getName().ltrim(GV->getName());
  4044. EltNameMap[*iter] = EltName;
  4045. }
  4046. }
  4047. EltGV->removeDeadConstantUsers();
  4048. // Now erase any instructions that were made dead while rewriting the
  4049. // alloca.
  4050. DeleteDeadInstructions();
  4051. ++NumReplaced;
  4052. } else {
  4053. // Add debug info for flattened globals.
  4054. if (m_HasDbgInfo && GV != EltGV) {
  4055. DebugInfoFinder &Finder = m_pHLModule->GetOrCreateDebugInfoFinder();
  4056. Type *Ty = EltGV->getType()->getElementType();
  4057. unsigned size = DL.getTypeAllocSizeInBits(Ty);
  4058. unsigned align = DL.getPrefTypeAlignment(Ty);
  4059. HLModule::CreateElementGlobalVariableDebugInfo(
  4060. GV, Finder, EltGV, size, align, debugOffset,
  4061. EltNameMap[EltGV]);
  4062. debugOffset += size;
  4063. }
  4064. }
  4065. }
  4066. DeleteDeadInstructions();
  4067. if (GV->user_empty()) {
  4068. GV->removeDeadConstantUsers();
  4069. GV->eraseFromParent();
  4070. }
  4071. }
  4072. static DxilFieldAnnotation &GetEltAnnotation(Type *Ty, unsigned idx, DxilFieldAnnotation &annotation, DxilTypeSystem &dxilTypeSys) {
  4073. while (Ty->isArrayTy())
  4074. Ty = Ty->getArrayElementType();
  4075. if (StructType *ST = dyn_cast<StructType>(Ty)) {
  4076. if (HLMatrixLower::IsMatrixType(Ty))
  4077. return annotation;
  4078. DxilStructAnnotation *SA = dxilTypeSys.GetStructAnnotation(ST);
  4079. if (SA) {
  4080. DxilFieldAnnotation &FA = SA->GetFieldAnnotation(idx);
  4081. return FA;
  4082. }
  4083. }
  4084. return annotation;
  4085. }
  4086. // Note: Semantic index allocation.
  4087. // Semantic index is allocated base on linear layout.
  4088. // For following code
  4089. /*
  4090. struct S {
  4091. float4 m;
  4092. float4 m2;
  4093. };
  4094. S s[2] : semantic;
  4095. struct S2 {
  4096. float4 m[2];
  4097. float4 m2[2];
  4098. };
  4099. S2 s2 : semantic;
  4100. */
  4101. // The semantic index is like this:
  4102. // s[0].m : semantic0
  4103. // s[0].m2 : semantic1
  4104. // s[1].m : semantic2
  4105. // s[1].m2 : semantic3
  4106. // s2.m[0] : semantic0
  4107. // s2.m[1] : semantic1
  4108. // s2.m2[0] : semantic2
  4109. // s2.m2[1] : semantic3
  4110. // But when flatten argument, the result is like this:
  4111. // float4 s_m[2], float4 s_m2[2].
  4112. // float4 s2_m[2], float4 s2_m2[2].
  4113. // To do the allocation, need to map from each element to its flattened argument.
  4114. // Say arg index of float4 s_m[2] is 0, float4 s_m2[2] is 1.
  4115. // Need to get 0 from s[0].m and s[1].m, get 1 from s[0].m2 and s[1].m2.
  4116. // Allocate the argments with same semantic string from type where the
  4117. // semantic starts( S2 for s2.m[2] and s2.m2[2]).
  4118. // Iterate each elements of the type, save the semantic index and update it.
  4119. // The map from element to the arg ( s[0].m2 -> s.m2[2]) is done by argIdx.
  4120. // ArgIdx only inc by 1 when finish a struct field.
  4121. static unsigned AllocateSemanticIndex(
  4122. Type *Ty, unsigned &semIndex, unsigned argIdx, unsigned endArgIdx,
  4123. std::vector<DxilParameterAnnotation> &FlatAnnotationList) {
  4124. if (Ty->isPointerTy()) {
  4125. return AllocateSemanticIndex(Ty->getPointerElementType(), semIndex, argIdx,
  4126. endArgIdx, FlatAnnotationList);
  4127. } else if (Ty->isArrayTy()) {
  4128. unsigned arraySize = Ty->getArrayNumElements();
  4129. unsigned updatedArgIdx = argIdx;
  4130. Type *EltTy = Ty->getArrayElementType();
  4131. for (unsigned i = 0; i < arraySize; i++) {
  4132. updatedArgIdx = AllocateSemanticIndex(EltTy, semIndex, argIdx, endArgIdx,
  4133. FlatAnnotationList);
  4134. }
  4135. return updatedArgIdx;
  4136. } else if (Ty->isStructTy() && !HLMatrixLower::IsMatrixType(Ty)) {
  4137. unsigned fieldsCount = Ty->getStructNumElements();
  4138. for (unsigned i = 0; i < fieldsCount; i++) {
  4139. Type *EltTy = Ty->getStructElementType(i);
  4140. argIdx = AllocateSemanticIndex(EltTy, semIndex, argIdx, endArgIdx,
  4141. FlatAnnotationList);
  4142. if (!(EltTy->isStructTy() && !HLMatrixLower::IsMatrixType(EltTy))) {
  4143. // Update argIdx only when it is a leaf node.
  4144. argIdx++;
  4145. }
  4146. }
  4147. return argIdx;
  4148. } else {
  4149. DXASSERT(argIdx < endArgIdx, "arg index out of bound");
  4150. DxilParameterAnnotation &paramAnnotation = FlatAnnotationList[argIdx];
  4151. // Get element size.
  4152. unsigned rows = 1;
  4153. if (paramAnnotation.HasMatrixAnnotation()) {
  4154. const DxilMatrixAnnotation &matrix =
  4155. paramAnnotation.GetMatrixAnnotation();
  4156. if (matrix.Orientation == MatrixOrientation::RowMajor) {
  4157. rows = matrix.Rows;
  4158. } else {
  4159. DXASSERT_NOMSG(matrix.Orientation == MatrixOrientation::ColumnMajor);
  4160. rows = matrix.Cols;
  4161. }
  4162. }
  4163. // Save semIndex.
  4164. for (unsigned i = 0; i < rows; i++)
  4165. paramAnnotation.AppendSemanticIndex(semIndex + i);
  4166. // Update semIndex.
  4167. semIndex += rows;
  4168. return argIdx;
  4169. }
  4170. }
  4171. void SROA_Parameter_HLSL::allocateSemanticIndex(
  4172. std::vector<DxilParameterAnnotation> &FlatAnnotationList,
  4173. unsigned startArgIndex, llvm::StringMap<Type *> &semanticTypeMap) {
  4174. unsigned endArgIndex = FlatAnnotationList.size();
  4175. // Allocate semantic index.
  4176. for (unsigned i = startArgIndex; i < endArgIndex; ++i) {
  4177. // Group by semantic names.
  4178. DxilParameterAnnotation &flatParamAnnotation = FlatAnnotationList[i];
  4179. const std::string &semantic = flatParamAnnotation.GetSemanticString();
  4180. // If semantic is undefined, an error will be emitted elsewhere. For now,
  4181. // we should avoid asserting.
  4182. if (semantic.empty())
  4183. continue;
  4184. unsigned semGroupEnd = i + 1;
  4185. while (semGroupEnd < endArgIndex &&
  4186. FlatAnnotationList[semGroupEnd].GetSemanticString() == semantic) {
  4187. ++semGroupEnd;
  4188. }
  4189. StringRef baseSemName; // The 'FOO' in 'FOO1'.
  4190. uint32_t semIndex; // The '1' in 'FOO1'
  4191. // Split semName and index.
  4192. Semantic::DecomposeNameAndIndex(semantic, &baseSemName, &semIndex);
  4193. DXASSERT(semanticTypeMap.count(semantic) > 0, "Must has semantic type");
  4194. Type *semanticTy = semanticTypeMap[semantic];
  4195. AllocateSemanticIndex(semanticTy, semIndex, /*argIdx*/ i,
  4196. /*endArgIdx*/ semGroupEnd, FlatAnnotationList);
  4197. // Update i.
  4198. i = semGroupEnd - 1;
  4199. }
  4200. }
  4201. //
  4202. // Cast parameters.
  4203. //
  4204. static void CopyHandleToResourcePtr(Value *Handle, Value *ResPtr, HLModule &HLM,
  4205. IRBuilder<> &Builder) {
  4206. // Cast it to resource.
  4207. Type *ResTy = ResPtr->getType()->getPointerElementType();
  4208. Value *Res = HLM.EmitHLOperationCall(Builder, HLOpcodeGroup::HLCast,
  4209. (unsigned)HLCastOpcode::HandleToResCast,
  4210. ResTy, {Handle}, *HLM.GetModule());
  4211. // Store casted resource to OldArg.
  4212. Builder.CreateStore(Res, ResPtr);
  4213. }
  4214. static void CopyHandlePtrToResourcePtr(Value *HandlePtr, Value *ResPtr,
  4215. HLModule &HLM, IRBuilder<> &Builder) {
  4216. // Load the handle.
  4217. Value *Handle = Builder.CreateLoad(HandlePtr);
  4218. CopyHandleToResourcePtr(Handle, ResPtr, HLM, Builder);
  4219. }
  4220. static Value *CastResourcePtrToHandle(Value *Res, Type *HandleTy, HLModule &HLM,
  4221. IRBuilder<> &Builder) {
  4222. // Load OldArg.
  4223. Value *LdRes = Builder.CreateLoad(Res);
  4224. Value *Handle = HLM.EmitHLOperationCall(
  4225. Builder, HLOpcodeGroup::HLCreateHandle,
  4226. /*opcode*/ 0, HandleTy, {LdRes}, *HLM.GetModule());
  4227. return Handle;
  4228. }
  4229. static void CopyResourcePtrToHandlePtr(Value *Res, Value *HandlePtr,
  4230. HLModule &HLM, IRBuilder<> &Builder) {
  4231. Type *HandleTy = HandlePtr->getType()->getPointerElementType();
  4232. Value *Handle = CastResourcePtrToHandle(Res, HandleTy, HLM, Builder);
  4233. Builder.CreateStore(Handle, HandlePtr);
  4234. }
  4235. static void CopyVectorPtrToEltsPtr(Value *VecPtr, ArrayRef<Value *> elts,
  4236. unsigned vecSize, IRBuilder<> &Builder) {
  4237. Value *Vec = Builder.CreateLoad(VecPtr);
  4238. for (unsigned i = 0; i < vecSize; i++) {
  4239. Value *Elt = Builder.CreateExtractElement(Vec, i);
  4240. Builder.CreateStore(Elt, elts[i]);
  4241. }
  4242. }
  4243. static void CopyEltsPtrToVectorPtr(ArrayRef<Value *> elts, Value *VecPtr,
  4244. Type *VecTy, unsigned vecSize,
  4245. IRBuilder<> &Builder) {
  4246. Value *Vec = UndefValue::get(VecTy);
  4247. for (unsigned i = 0; i < vecSize; i++) {
  4248. Value *Elt = Builder.CreateLoad(elts[i]);
  4249. Vec = Builder.CreateInsertElement(Vec, Elt, i);
  4250. }
  4251. Builder.CreateStore(Vec, VecPtr);
  4252. }
  4253. static void CopyMatToArrayPtr(Value *Mat, Value *ArrayPtr,
  4254. unsigned arrayBaseIdx, HLModule &HLM,
  4255. IRBuilder<> &Builder, bool bRowMajor) {
  4256. Type *Ty = Mat->getType();
  4257. // Mat val is row major.
  4258. unsigned col, row;
  4259. HLMatrixLower::GetMatrixInfo(Mat->getType(), col, row);
  4260. Type *VecTy = HLMatrixLower::LowerMatrixType(Ty);
  4261. Value *Vec =
  4262. HLM.EmitHLOperationCall(Builder, HLOpcodeGroup::HLCast,
  4263. (unsigned)HLCastOpcode::RowMatrixToVecCast, VecTy,
  4264. {Mat}, *HLM.GetModule());
  4265. Value *zero = Builder.getInt32(0);
  4266. for (unsigned r = 0; r < row; r++) {
  4267. for (unsigned c = 0; c < col; c++) {
  4268. unsigned rowMatIdx = HLMatrixLower::GetColMajorIdx(r, c, row);
  4269. Value *Elt = Builder.CreateExtractElement(Vec, rowMatIdx);
  4270. unsigned matIdx =
  4271. bRowMajor ? rowMatIdx : HLMatrixLower::GetColMajorIdx(r, c, row);
  4272. Value *Ptr = Builder.CreateInBoundsGEP(
  4273. ArrayPtr, {zero, Builder.getInt32(arrayBaseIdx + matIdx)});
  4274. Builder.CreateStore(Elt, Ptr);
  4275. }
  4276. }
  4277. }
  4278. static void CopyMatPtrToArrayPtr(Value *MatPtr, Value *ArrayPtr,
  4279. unsigned arrayBaseIdx, HLModule &HLM,
  4280. IRBuilder<> &Builder, bool bRowMajor) {
  4281. Type *Ty = MatPtr->getType()->getPointerElementType();
  4282. Value *Mat = nullptr;
  4283. if (bRowMajor) {
  4284. Mat = HLM.EmitHLOperationCall(Builder, HLOpcodeGroup::HLMatLoadStore,
  4285. (unsigned)HLMatLoadStoreOpcode::RowMatLoad,
  4286. Ty, {MatPtr}, *HLM.GetModule());
  4287. } else {
  4288. Mat = HLM.EmitHLOperationCall(Builder, HLOpcodeGroup::HLMatLoadStore,
  4289. (unsigned)HLMatLoadStoreOpcode::ColMatLoad,
  4290. Ty, {MatPtr}, *HLM.GetModule());
  4291. // Matrix value should be row major.
  4292. Mat = HLM.EmitHLOperationCall(Builder, HLOpcodeGroup::HLCast,
  4293. (unsigned)HLCastOpcode::ColMatrixToRowMatrix,
  4294. Ty, {Mat}, *HLM.GetModule());
  4295. }
  4296. CopyMatToArrayPtr(Mat, ArrayPtr, arrayBaseIdx, HLM, Builder, bRowMajor);
  4297. }
  4298. static Value *LoadArrayPtrToMat(Value *ArrayPtr, unsigned arrayBaseIdx,
  4299. Type *Ty, HLModule &HLM, IRBuilder<> &Builder,
  4300. bool bRowMajor) {
  4301. unsigned col, row;
  4302. HLMatrixLower::GetMatrixInfo(Ty, col, row);
  4303. // HLInit operands are in row major.
  4304. SmallVector<Value *, 16> Elts;
  4305. Value *zero = Builder.getInt32(0);
  4306. for (unsigned r = 0; r < row; r++) {
  4307. for (unsigned c = 0; c < col; c++) {
  4308. unsigned matIdx = bRowMajor ? HLMatrixLower::GetRowMajorIdx(r, c, col)
  4309. : HLMatrixLower::GetColMajorIdx(r, c, row);
  4310. Value *Ptr = Builder.CreateInBoundsGEP(
  4311. ArrayPtr, {zero, Builder.getInt32(arrayBaseIdx + matIdx)});
  4312. Value *Elt = Builder.CreateLoad(Ptr);
  4313. Elts.emplace_back(Elt);
  4314. }
  4315. }
  4316. return HLM.EmitHLOperationCall(Builder, HLOpcodeGroup::HLInit,
  4317. /*opcode*/ 0, Ty, {Elts}, *HLM.GetModule());
  4318. }
  4319. static void CopyArrayPtrToMatPtr(Value *ArrayPtr, unsigned arrayBaseIdx,
  4320. Value *MatPtr, HLModule &HLM,
  4321. IRBuilder<> &Builder, bool bRowMajor) {
  4322. Type *Ty = MatPtr->getType()->getPointerElementType();
  4323. Value *Mat =
  4324. LoadArrayPtrToMat(ArrayPtr, arrayBaseIdx, Ty, HLM, Builder, bRowMajor);
  4325. if (bRowMajor) {
  4326. HLM.EmitHLOperationCall(Builder, HLOpcodeGroup::HLMatLoadStore,
  4327. (unsigned)HLMatLoadStoreOpcode::RowMatStore, Ty,
  4328. {MatPtr, Mat}, *HLM.GetModule());
  4329. } else {
  4330. // Mat is row major.
  4331. // Cast it to col major before store.
  4332. Mat = HLM.EmitHLOperationCall(Builder, HLOpcodeGroup::HLCast,
  4333. (unsigned)HLCastOpcode::RowMatrixToColMatrix,
  4334. Ty, {Mat}, *HLM.GetModule());
  4335. HLM.EmitHLOperationCall(Builder, HLOpcodeGroup::HLMatLoadStore,
  4336. (unsigned)HLMatLoadStoreOpcode::ColMatStore, Ty,
  4337. {MatPtr, Mat}, *HLM.GetModule());
  4338. }
  4339. }
  4340. using CopyFunctionTy = void(Value *FromPtr, Value *ToPtr, HLModule &HLM,
  4341. Type *HandleTy, IRBuilder<> &Builder,
  4342. bool bRowMajor);
  4343. static void
  4344. CastCopyArrayMultiDimTo1Dim(Value *FromArray, Value *ToArray, Type *CurFromTy,
  4345. std::vector<Value *> &idxList, unsigned calcIdx,
  4346. Type *HandleTy, HLModule &HLM, IRBuilder<> &Builder,
  4347. CopyFunctionTy CastCopyFn, bool bRowMajor) {
  4348. if (CurFromTy->isVectorTy()) {
  4349. // Copy vector to array.
  4350. Value *FromPtr = Builder.CreateInBoundsGEP(FromArray, idxList);
  4351. Value *V = Builder.CreateLoad(FromPtr);
  4352. unsigned vecSize = CurFromTy->getVectorNumElements();
  4353. Value *zeroIdx = Builder.getInt32(0);
  4354. for (unsigned i = 0; i < vecSize; i++) {
  4355. Value *ToPtr = Builder.CreateInBoundsGEP(
  4356. ToArray, {zeroIdx, Builder.getInt32(calcIdx++)});
  4357. Value *Elt = Builder.CreateExtractElement(V, i);
  4358. Builder.CreateStore(Elt, ToPtr);
  4359. }
  4360. } else if (HLMatrixLower::IsMatrixType(CurFromTy)) {
  4361. // Copy matrix to array.
  4362. unsigned col, row;
  4363. HLMatrixLower::GetMatrixInfo(CurFromTy, col, row);
  4364. // Calculate the offset.
  4365. unsigned offset = calcIdx * col * row;
  4366. Value *FromPtr = Builder.CreateInBoundsGEP(FromArray, idxList);
  4367. CopyMatPtrToArrayPtr(FromPtr, ToArray, offset, HLM, Builder, bRowMajor);
  4368. } else if (!CurFromTy->isArrayTy()) {
  4369. Value *FromPtr = Builder.CreateInBoundsGEP(FromArray, idxList);
  4370. Value *ToPtr = Builder.CreateInBoundsGEP(
  4371. ToArray, {Builder.getInt32(0), Builder.getInt32(calcIdx)});
  4372. CastCopyFn(FromPtr, ToPtr, HLM, HandleTy, Builder, bRowMajor);
  4373. } else {
  4374. unsigned size = CurFromTy->getArrayNumElements();
  4375. Type *FromEltTy = CurFromTy->getArrayElementType();
  4376. for (unsigned i = 0; i < size; i++) {
  4377. idxList.push_back(Builder.getInt32(i));
  4378. unsigned idx = calcIdx * size + i;
  4379. CastCopyArrayMultiDimTo1Dim(FromArray, ToArray, FromEltTy, idxList, idx,
  4380. HandleTy, HLM, Builder, CastCopyFn,
  4381. bRowMajor);
  4382. idxList.pop_back();
  4383. }
  4384. }
  4385. }
  4386. static void
  4387. CastCopyArray1DimToMultiDim(Value *FromArray, Value *ToArray, Type *CurToTy,
  4388. std::vector<Value *> &idxList, unsigned calcIdx,
  4389. Type *HandleTy, HLModule &HLM, IRBuilder<> &Builder,
  4390. CopyFunctionTy CastCopyFn, bool bRowMajor) {
  4391. if (CurToTy->isVectorTy()) {
  4392. // Copy array to vector.
  4393. Value *V = UndefValue::get(CurToTy);
  4394. unsigned vecSize = CurToTy->getVectorNumElements();
  4395. // Calculate the offset.
  4396. unsigned offset = calcIdx * vecSize;
  4397. Value *zeroIdx = Builder.getInt32(0);
  4398. Value *ToPtr = Builder.CreateInBoundsGEP(ToArray, idxList);
  4399. for (unsigned i = 0; i < vecSize; i++) {
  4400. Value *FromPtr = Builder.CreateInBoundsGEP(
  4401. FromArray, {zeroIdx, Builder.getInt32(offset++)});
  4402. Value *Elt = Builder.CreateLoad(FromPtr);
  4403. V = Builder.CreateInsertElement(V, Elt, i);
  4404. }
  4405. Builder.CreateStore(V, ToPtr);
  4406. } else if (HLMatrixLower::IsMatrixType(CurToTy)) {
  4407. // Copy array to matrix.
  4408. unsigned col, row;
  4409. HLMatrixLower::GetMatrixInfo(CurToTy, col, row);
  4410. // Calculate the offset.
  4411. unsigned offset = calcIdx * col * row;
  4412. Value *ToPtr = Builder.CreateInBoundsGEP(ToArray, idxList);
  4413. CopyArrayPtrToMatPtr(FromArray, offset, ToPtr, HLM, Builder, bRowMajor);
  4414. } else if (!CurToTy->isArrayTy()) {
  4415. Value *FromPtr = Builder.CreateInBoundsGEP(
  4416. FromArray, {Builder.getInt32(0), Builder.getInt32(calcIdx)});
  4417. Value *ToPtr = Builder.CreateInBoundsGEP(ToArray, idxList);
  4418. CastCopyFn(FromPtr, ToPtr, HLM, HandleTy, Builder, bRowMajor);
  4419. } else {
  4420. unsigned size = CurToTy->getArrayNumElements();
  4421. Type *ToEltTy = CurToTy->getArrayElementType();
  4422. for (unsigned i = 0; i < size; i++) {
  4423. idxList.push_back(Builder.getInt32(i));
  4424. unsigned idx = calcIdx * size + i;
  4425. CastCopyArray1DimToMultiDim(FromArray, ToArray, ToEltTy, idxList, idx,
  4426. HandleTy, HLM, Builder, CastCopyFn,
  4427. bRowMajor);
  4428. idxList.pop_back();
  4429. }
  4430. }
  4431. }
  4432. static void CastCopyOldPtrToNewPtr(Value *OldPtr, Value *NewPtr, HLModule &HLM,
  4433. Type *HandleTy, IRBuilder<> &Builder,
  4434. bool bRowMajor) {
  4435. Type *NewTy = NewPtr->getType()->getPointerElementType();
  4436. Type *OldTy = OldPtr->getType()->getPointerElementType();
  4437. if (NewTy == HandleTy) {
  4438. CopyResourcePtrToHandlePtr(OldPtr, NewPtr, HLM, Builder);
  4439. } else if (OldTy->isVectorTy()) {
  4440. // Copy vector to array.
  4441. Value *V = Builder.CreateLoad(OldPtr);
  4442. unsigned vecSize = OldTy->getVectorNumElements();
  4443. Value *zeroIdx = Builder.getInt32(0);
  4444. for (unsigned i = 0; i < vecSize; i++) {
  4445. Value *EltPtr = Builder.CreateGEP(NewPtr, {zeroIdx, Builder.getInt32(i)});
  4446. Value *Elt = Builder.CreateExtractElement(V, i);
  4447. Builder.CreateStore(Elt, EltPtr);
  4448. }
  4449. } else if (HLMatrixLower::IsMatrixType(OldTy)) {
  4450. CopyMatPtrToArrayPtr(OldPtr, NewPtr, /*arrayBaseIdx*/ 0, HLM, Builder,
  4451. bRowMajor);
  4452. } else if (OldTy->isArrayTy()) {
  4453. std::vector<Value *> idxList;
  4454. idxList.emplace_back(Builder.getInt32(0));
  4455. CastCopyArrayMultiDimTo1Dim(OldPtr, NewPtr, OldTy, idxList, /*calcIdx*/ 0,
  4456. HandleTy, HLM, Builder, CastCopyOldPtrToNewPtr,
  4457. bRowMajor);
  4458. }
  4459. }
  4460. static void CastCopyNewPtrToOldPtr(Value *NewPtr, Value *OldPtr, HLModule &HLM,
  4461. Type *HandleTy, IRBuilder<> &Builder,
  4462. bool bRowMajor) {
  4463. Type *NewTy = NewPtr->getType()->getPointerElementType();
  4464. Type *OldTy = OldPtr->getType()->getPointerElementType();
  4465. if (NewTy == HandleTy) {
  4466. CopyHandlePtrToResourcePtr(NewPtr, OldPtr, HLM, Builder);
  4467. } else if (OldTy->isVectorTy()) {
  4468. // Copy array to vector.
  4469. Value *V = UndefValue::get(OldTy);
  4470. unsigned vecSize = OldTy->getVectorNumElements();
  4471. Value *zeroIdx = Builder.getInt32(0);
  4472. for (unsigned i = 0; i < vecSize; i++) {
  4473. Value *EltPtr = Builder.CreateGEP(NewPtr, {zeroIdx, Builder.getInt32(i)});
  4474. Value *Elt = Builder.CreateLoad(EltPtr);
  4475. V = Builder.CreateInsertElement(V, Elt, i);
  4476. }
  4477. Builder.CreateStore(V, OldPtr);
  4478. } else if (HLMatrixLower::IsMatrixType(OldTy)) {
  4479. CopyArrayPtrToMatPtr(NewPtr, /*arrayBaseIdx*/ 0, OldPtr, HLM, Builder,
  4480. bRowMajor);
  4481. } else if (OldTy->isArrayTy()) {
  4482. std::vector<Value *> idxList;
  4483. idxList.emplace_back(Builder.getInt32(0));
  4484. CastCopyArray1DimToMultiDim(NewPtr, OldPtr, OldTy, idxList, /*calcIdx*/ 0,
  4485. HandleTy, HLM, Builder, CastCopyNewPtrToOldPtr,
  4486. bRowMajor);
  4487. }
  4488. }
  4489. void SROA_Parameter_HLSL::replaceCastParameter(
  4490. Value *NewParam, Value *OldParam, Function &F, Argument *Arg,
  4491. const DxilParamInputQual inputQual, IRBuilder<> &Builder) {
  4492. Type *HandleTy = m_pHLModule->GetOP()->GetHandleType();
  4493. Type *HandlePtrTy = PointerType::get(HandleTy, 0);
  4494. Module &M = *m_pHLModule->GetModule();
  4495. Type *NewTy = NewParam->getType();
  4496. Type *OldTy = OldParam->getType();
  4497. bool bIn = inputQual == DxilParamInputQual::Inout ||
  4498. inputQual == DxilParamInputQual::In;
  4499. bool bOut = inputQual == DxilParamInputQual::Inout ||
  4500. inputQual == DxilParamInputQual::Out;
  4501. // Make sure InsertPoint after OldParam inst.
  4502. if (Instruction *I = dyn_cast<Instruction>(OldParam)) {
  4503. Builder.SetInsertPoint(I->getNextNode());
  4504. }
  4505. if (DbgDeclareInst *DDI = llvm::FindAllocaDbgDeclare(OldParam)) {
  4506. // Add debug info to new param.
  4507. DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
  4508. DIExpression *DDIExp = DDI->getExpression();
  4509. DIB.insertDeclare(NewParam, DDI->getVariable(), DDIExp, DDI->getDebugLoc(),
  4510. Builder.GetInsertPoint());
  4511. }
  4512. if (isa<Argument>(OldParam) && OldTy->isPointerTy()) {
  4513. // OldParam will be removed with Old function.
  4514. // Create alloca to replace it.
  4515. IRBuilder<> AllocaBuilder(dxilutil::FindAllocaInsertionPt(&F));
  4516. Value *AllocParam = AllocaBuilder.CreateAlloca(OldTy->getPointerElementType());
  4517. OldParam->replaceAllUsesWith(AllocParam);
  4518. OldParam = AllocParam;
  4519. }
  4520. if (NewTy == HandleTy) {
  4521. CopyHandleToResourcePtr(NewParam, OldParam, *m_pHLModule, Builder);
  4522. // Save resource attribute.
  4523. Type *ResTy = OldTy->getPointerElementType();
  4524. MDNode *MD = HLModule::GetDxilResourceAttrib(ResTy, M);
  4525. m_pHLModule->MarkDxilResourceAttrib(Arg, MD);
  4526. } else if (vectorEltsMap.count(NewParam)) {
  4527. // Vector is flattened to scalars.
  4528. Type *VecTy = OldTy;
  4529. if (VecTy->isPointerTy())
  4530. VecTy = VecTy->getPointerElementType();
  4531. // Flattened vector.
  4532. SmallVector<Value *, 4> &elts = vectorEltsMap[NewParam];
  4533. unsigned vecSize = elts.size();
  4534. if (NewTy->isPointerTy()) {
  4535. if (bIn) {
  4536. // Copy NewParam to OldParam at entry.
  4537. CopyEltsPtrToVectorPtr(elts, OldParam, VecTy, vecSize, Builder);
  4538. }
  4539. // bOut must be true here.
  4540. // Store the OldParam to NewParam before every return.
  4541. for (auto &BB : F.getBasicBlockList()) {
  4542. if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
  4543. IRBuilder<> RetBuilder(RI);
  4544. CopyVectorPtrToEltsPtr(OldParam, elts, vecSize, RetBuilder);
  4545. }
  4546. }
  4547. } else {
  4548. // Must be in parameter.
  4549. // Copy NewParam to OldParam at entry.
  4550. Value *Vec = UndefValue::get(VecTy);
  4551. for (unsigned i = 0; i < vecSize; i++) {
  4552. Vec = Builder.CreateInsertElement(Vec, elts[i], i);
  4553. }
  4554. if (OldTy->isPointerTy()) {
  4555. Builder.CreateStore(Vec, OldParam);
  4556. } else {
  4557. OldParam->replaceAllUsesWith(Vec);
  4558. }
  4559. }
  4560. // Don't need elts anymore.
  4561. vectorEltsMap.erase(NewParam);
  4562. } else if (!NewTy->isPointerTy()) {
  4563. // Ptr param is cast to non-ptr param.
  4564. // Must be in param.
  4565. // Store NewParam to OldParam at entry.
  4566. Builder.CreateStore(NewParam, OldParam);
  4567. } else if (HLMatrixLower::IsMatrixType(OldTy)) {
  4568. bool bRowMajor = castRowMajorParamMap.count(NewParam);
  4569. Value *Mat = LoadArrayPtrToMat(NewParam, /*arrayBaseIdx*/ 0, OldTy,
  4570. *m_pHLModule, Builder, bRowMajor);
  4571. OldParam->replaceAllUsesWith(Mat);
  4572. } else {
  4573. bool bRowMajor = castRowMajorParamMap.count(NewParam);
  4574. // NewTy is pointer type.
  4575. if (bIn) {
  4576. // Copy NewParam to OldParam at entry.
  4577. CastCopyNewPtrToOldPtr(NewParam, OldParam, *m_pHLModule, HandleTy,
  4578. Builder, bRowMajor);
  4579. }
  4580. if (bOut) {
  4581. // Store the OldParam to NewParam before every return.
  4582. for (auto &BB : F.getBasicBlockList()) {
  4583. if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
  4584. IRBuilder<> RetBuilder(RI);
  4585. CastCopyOldPtrToNewPtr(OldParam, NewParam, *m_pHLModule, HandleTy,
  4586. RetBuilder, bRowMajor);
  4587. }
  4588. }
  4589. }
  4590. Type *NewEltTy = dxilutil::GetArrayEltTy(NewTy);
  4591. Type *OldEltTy = dxilutil::GetArrayEltTy(OldTy);
  4592. if (NewEltTy == HandlePtrTy) {
  4593. // Save resource attribute.
  4594. Type *ResTy = OldEltTy;
  4595. MDNode *MD = HLModule::GetDxilResourceAttrib(ResTy, M);
  4596. m_pHLModule->MarkDxilResourceAttrib(Arg, MD);
  4597. }
  4598. }
  4599. }
  4600. Value *SROA_Parameter_HLSL::castResourceArgIfRequired(
  4601. Value *V, Type *Ty, bool bOut,
  4602. DxilParamInputQual inputQual,
  4603. IRBuilder<> &Builder) {
  4604. Type *HandleTy = m_pHLModule->GetOP()->GetHandleType();
  4605. Module &M = *m_pHLModule->GetModule();
  4606. IRBuilder<> AllocaBuilder(dxilutil::FindAllocaInsertionPt(Builder.GetInsertPoint()));
  4607. // Lower resource type to handle ty.
  4608. if (HLModule::IsHLSLObjectType(Ty) &&
  4609. !HLModule::IsStreamOutputPtrType(V->getType())) {
  4610. Value *Res = V;
  4611. if (!bOut) {
  4612. Value *LdRes = Builder.CreateLoad(Res);
  4613. V = m_pHLModule->EmitHLOperationCall(Builder,
  4614. HLOpcodeGroup::HLCreateHandle,
  4615. /*opcode*/ 0, HandleTy, { LdRes }, M);
  4616. }
  4617. else {
  4618. V = AllocaBuilder.CreateAlloca(HandleTy);
  4619. }
  4620. castParamMap[V] = std::make_pair(Res, inputQual);
  4621. }
  4622. else if (Ty->isArrayTy()) {
  4623. unsigned arraySize = 1;
  4624. Type *AT = Ty;
  4625. while (AT->isArrayTy()) {
  4626. arraySize *= AT->getArrayNumElements();
  4627. AT = AT->getArrayElementType();
  4628. }
  4629. if (HLModule::IsHLSLObjectType(AT)) {
  4630. Value *Res = V;
  4631. Type *Ty = ArrayType::get(HandleTy, arraySize);
  4632. V = AllocaBuilder.CreateAlloca(Ty);
  4633. castParamMap[V] = std::make_pair(Res, inputQual);
  4634. }
  4635. }
  4636. return V;
  4637. }
  4638. Value *SROA_Parameter_HLSL::castArgumentIfRequired(
  4639. Value *V, Type *Ty, bool bOut,
  4640. DxilParamInputQual inputQual, DxilFieldAnnotation &annotation,
  4641. std::deque<Value *> &WorkList, IRBuilder<> &Builder) {
  4642. Module &M = *m_pHLModule->GetModule();
  4643. IRBuilder<> AllocaBuilder(dxilutil::FindAllocaInsertionPt(Builder.GetInsertPoint()));
  4644. // Remove pointer for vector/scalar which is not out.
  4645. if (V->getType()->isPointerTy() && !Ty->isAggregateType() && !bOut) {
  4646. Value *Ptr = AllocaBuilder.CreateAlloca(Ty);
  4647. V->replaceAllUsesWith(Ptr);
  4648. // Create load here to make correct type.
  4649. // The Ptr will be store with correct value in replaceCastParameter.
  4650. if (Ptr->hasOneUse()) {
  4651. // Load after existing user for call arg replace.
  4652. // If not, call arg will load undef.
  4653. // This will not hurt parameter, new load is only after first load.
  4654. // It still before all the load users.
  4655. Instruction *User = cast<Instruction>(*(Ptr->user_begin()));
  4656. IRBuilder<> CallBuilder(User->getNextNode());
  4657. V = CallBuilder.CreateLoad(Ptr);
  4658. } else {
  4659. V = Builder.CreateLoad(Ptr);
  4660. }
  4661. castParamMap[V] = std::make_pair(Ptr, inputQual);
  4662. }
  4663. V = castResourceArgIfRequired(V, Ty, bOut, inputQual, Builder);
  4664. // Entry function matrix value parameter has major.
  4665. // Make sure its user use row major matrix value.
  4666. bool updateToColMajor = annotation.HasMatrixAnnotation() &&
  4667. annotation.GetMatrixAnnotation().Orientation ==
  4668. MatrixOrientation::ColumnMajor;
  4669. if (updateToColMajor) {
  4670. if (V->getType()->isPointerTy()) {
  4671. for (User *user : V->users()) {
  4672. CallInst *CI = dyn_cast<CallInst>(user);
  4673. if (!CI)
  4674. continue;
  4675. HLOpcodeGroup group = GetHLOpcodeGroupByName(CI->getCalledFunction());
  4676. if (group != HLOpcodeGroup::HLMatLoadStore)
  4677. continue;
  4678. HLMatLoadStoreOpcode opcode =
  4679. static_cast<HLMatLoadStoreOpcode>(GetHLOpcode(CI));
  4680. Type *opcodeTy = Builder.getInt32Ty();
  4681. switch (opcode) {
  4682. case HLMatLoadStoreOpcode::RowMatLoad: {
  4683. // Update matrix function opcode to col major version.
  4684. Value *rowOpArg = ConstantInt::get(
  4685. opcodeTy,
  4686. static_cast<unsigned>(HLMatLoadStoreOpcode::ColMatLoad));
  4687. CI->setOperand(HLOperandIndex::kOpcodeIdx, rowOpArg);
  4688. // Cast it to row major.
  4689. CallInst *RowMat = HLModule::EmitHLOperationCall(
  4690. Builder, HLOpcodeGroup::HLCast,
  4691. (unsigned)HLCastOpcode::ColMatrixToRowMatrix, Ty, {CI}, M);
  4692. CI->replaceAllUsesWith(RowMat);
  4693. // Set arg to CI again.
  4694. RowMat->setArgOperand(HLOperandIndex::kUnaryOpSrc0Idx, CI);
  4695. } break;
  4696. case HLMatLoadStoreOpcode::RowMatStore:
  4697. // Update matrix function opcode to col major version.
  4698. Value *rowOpArg = ConstantInt::get(
  4699. opcodeTy,
  4700. static_cast<unsigned>(HLMatLoadStoreOpcode::ColMatStore));
  4701. CI->setOperand(HLOperandIndex::kOpcodeIdx, rowOpArg);
  4702. Value *Mat = CI->getArgOperand(HLOperandIndex::kMatStoreValOpIdx);
  4703. // Cast it to col major.
  4704. CallInst *RowMat = HLModule::EmitHLOperationCall(
  4705. Builder, HLOpcodeGroup::HLCast,
  4706. (unsigned)HLCastOpcode::RowMatrixToColMatrix, Ty, {Mat}, M);
  4707. CI->setArgOperand(HLOperandIndex::kMatStoreValOpIdx, RowMat);
  4708. break;
  4709. }
  4710. }
  4711. } else {
  4712. CallInst *RowMat = HLModule::EmitHLOperationCall(
  4713. Builder, HLOpcodeGroup::HLCast,
  4714. (unsigned)HLCastOpcode::ColMatrixToRowMatrix, Ty, {V}, M);
  4715. V->replaceAllUsesWith(RowMat);
  4716. // Set arg to V again.
  4717. RowMat->setArgOperand(HLOperandIndex::kUnaryOpSrc0Idx, V);
  4718. }
  4719. }
  4720. return V;
  4721. }
  4722. void SROA_Parameter_HLSL::flattenArgument(
  4723. Function *F, Value *Arg, bool bForParam,
  4724. DxilParameterAnnotation &paramAnnotation,
  4725. std::vector<Value *> &FlatParamList,
  4726. std::vector<DxilParameterAnnotation> &FlatAnnotationList,
  4727. IRBuilder<> &Builder, DbgDeclareInst *DDI) {
  4728. IRBuilder<> AllocaBuilder(dxilutil::FindAllocaInsertionPt(Builder.GetInsertPoint()));
  4729. std::deque<Value *> WorkList;
  4730. WorkList.push_back(Arg);
  4731. unsigned startArgIndex = FlatAnnotationList.size();
  4732. // Map from value to annotation.
  4733. std::unordered_map<Value *, DxilFieldAnnotation> annotationMap;
  4734. annotationMap[Arg] = paramAnnotation;
  4735. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  4736. const std::string &semantic = paramAnnotation.GetSemanticString();
  4737. bool bSemOverride = !semantic.empty();
  4738. DxilParamInputQual inputQual = paramAnnotation.GetParamInputQual();
  4739. bool bOut = inputQual == DxilParamInputQual::Out ||
  4740. inputQual == DxilParamInputQual::Inout ||
  4741. inputQual == DxilParamInputQual::OutStream0 ||
  4742. inputQual == DxilParamInputQual::OutStream1 ||
  4743. inputQual == DxilParamInputQual::OutStream2 ||
  4744. inputQual == DxilParamInputQual::OutStream3;
  4745. // Map from semantic string to type.
  4746. llvm::StringMap<Type *> semanticTypeMap;
  4747. // Original semantic type.
  4748. if (!semantic.empty()) {
  4749. // Unwrap top-level array if primitive
  4750. if (inputQual == DxilParamInputQual::InputPatch ||
  4751. inputQual == DxilParamInputQual::OutputPatch ||
  4752. inputQual == DxilParamInputQual::InputPrimitive) {
  4753. Type *Ty = Arg->getType();
  4754. if (Ty->isPointerTy())
  4755. Ty = Ty->getPointerElementType();
  4756. if (Ty->isArrayTy())
  4757. semanticTypeMap[semantic] = Ty->getArrayElementType();
  4758. } else {
  4759. semanticTypeMap[semantic] = Arg->getType();
  4760. }
  4761. }
  4762. std::vector<Instruction*> deadAllocas;
  4763. DIBuilder DIB(*F->getParent(), /*AllowUnresolved*/ false);
  4764. unsigned debugOffset = 0;
  4765. const DataLayout &DL = F->getParent()->getDataLayout();
  4766. // Process the worklist
  4767. while (!WorkList.empty()) {
  4768. Value *V = WorkList.front();
  4769. WorkList.pop_front();
  4770. // Do not skip unused parameter.
  4771. DxilFieldAnnotation &annotation = annotationMap[V];
  4772. const bool bAllowReplace = !bOut;
  4773. SROA_Helper::LowerMemcpy(V, &annotation, dxilTypeSys, DL, bAllowReplace);
  4774. std::vector<Value *> Elts;
  4775. // Not flat vector for entry function currently.
  4776. bool SROAed = SROA_Helper::DoScalarReplacement(
  4777. V, Elts, Builder, /*bFlatVector*/ false, annotation.IsPrecise(),
  4778. dxilTypeSys, DL, DeadInsts);
  4779. if (SROAed) {
  4780. Type *Ty = V->getType()->getPointerElementType();
  4781. // Skip empty struct parameters.
  4782. if (SROA_Helper::IsEmptyStructType(Ty, dxilTypeSys)) {
  4783. SROA_Helper::MarkEmptyStructUsers(V, DeadInsts);
  4784. DeleteDeadInstructions();
  4785. continue;
  4786. }
  4787. // Push Elts into workList.
  4788. // Use rbegin to make sure the order not change.
  4789. for (auto iter = Elts.rbegin(); iter != Elts.rend(); iter++)
  4790. WorkList.push_front(*iter);
  4791. bool precise = annotation.IsPrecise();
  4792. const std::string &semantic = annotation.GetSemanticString();
  4793. hlsl::InterpolationMode interpMode = annotation.GetInterpolationMode();
  4794. for (unsigned i=0;i<Elts.size();i++) {
  4795. Value *Elt = Elts[i];
  4796. DxilFieldAnnotation EltAnnotation = GetEltAnnotation(Ty, i, annotation, dxilTypeSys);
  4797. const std::string &eltSem = EltAnnotation.GetSemanticString();
  4798. if (!semantic.empty()) {
  4799. if (!eltSem.empty()) {
  4800. // TODO: warning for override the semantic in EltAnnotation.
  4801. }
  4802. // Just save parent semantic here, allocate later.
  4803. EltAnnotation.SetSemanticString(semantic);
  4804. } else if (!eltSem.empty() &&
  4805. semanticTypeMap.count(eltSem) == 0) {
  4806. Type *EltTy = dxilutil::GetArrayEltTy(Ty);
  4807. DXASSERT(EltTy->isStructTy(), "must be a struct type to has semantic.");
  4808. semanticTypeMap[eltSem] = EltTy->getStructElementType(i);
  4809. }
  4810. if (precise)
  4811. EltAnnotation.SetPrecise();
  4812. if (EltAnnotation.GetInterpolationMode().GetKind() == DXIL::InterpolationMode::Undefined)
  4813. EltAnnotation.SetInterpolationMode(interpMode);
  4814. annotationMap[Elt] = EltAnnotation;
  4815. }
  4816. annotationMap.erase(V);
  4817. ++NumReplaced;
  4818. if (Instruction *I = dyn_cast<Instruction>(V))
  4819. deadAllocas.emplace_back(I);
  4820. } else {
  4821. if (bSemOverride) {
  4822. if (!annotation.GetSemanticString().empty()) {
  4823. // TODO: warning for override the semantic in EltAnnotation.
  4824. }
  4825. // Just save parent semantic here, allocate later.
  4826. annotation.SetSemanticString(semantic);
  4827. }
  4828. Type *Ty = V->getType();
  4829. if (Ty->isPointerTy())
  4830. Ty = Ty->getPointerElementType();
  4831. // Flatten array of SV_Target.
  4832. StringRef semanticStr = annotation.GetSemanticString();
  4833. if (semanticStr.upper().find("SV_TARGET") == 0 &&
  4834. Ty->isArrayTy()) {
  4835. Type *Ty = cast<ArrayType>(V->getType()->getPointerElementType());
  4836. StringRef targetStr;
  4837. unsigned targetIndex;
  4838. Semantic::DecomposeNameAndIndex(semanticStr, &targetStr, &targetIndex);
  4839. // Replace target parameter with local target.
  4840. AllocaInst *localTarget = AllocaBuilder.CreateAlloca(Ty);
  4841. V->replaceAllUsesWith(localTarget);
  4842. unsigned arraySize = 1;
  4843. std::vector<unsigned> arraySizeList;
  4844. while (Ty->isArrayTy()) {
  4845. unsigned size = Ty->getArrayNumElements();
  4846. arraySizeList.emplace_back(size);
  4847. arraySize *= size;
  4848. Ty = Ty->getArrayElementType();
  4849. }
  4850. unsigned arrayLevel = arraySizeList.size();
  4851. std::vector<unsigned> arrayIdxList(arrayLevel, 0);
  4852. // Create flattened target.
  4853. DxilFieldAnnotation EltAnnotation = annotation;
  4854. for (unsigned i=0;i<arraySize;i++) {
  4855. Value *Elt = AllocaBuilder.CreateAlloca(Ty);
  4856. EltAnnotation.SetSemanticString(targetStr.str()+std::to_string(targetIndex+i));
  4857. // Add semantic type.
  4858. semanticTypeMap[EltAnnotation.GetSemanticString()] = Ty;
  4859. annotationMap[Elt] = EltAnnotation;
  4860. WorkList.push_front(Elt);
  4861. // Copy local target to flattened target.
  4862. std::vector<Value*> idxList(arrayLevel+1);
  4863. idxList[0] = Builder.getInt32(0);
  4864. for (unsigned idx=0;idx<arrayLevel; idx++) {
  4865. idxList[idx+1] = Builder.getInt32(arrayIdxList[idx]);
  4866. }
  4867. if (bForParam) {
  4868. // If Argument, copy before each return.
  4869. for (auto &BB : F->getBasicBlockList()) {
  4870. TerminatorInst *TI = BB.getTerminator();
  4871. if (isa<ReturnInst>(TI)) {
  4872. IRBuilder<> RetBuilder(TI);
  4873. Value *Ptr = RetBuilder.CreateGEP(localTarget, idxList);
  4874. Value *V = RetBuilder.CreateLoad(Ptr);
  4875. RetBuilder.CreateStore(V, Elt);
  4876. }
  4877. }
  4878. } else {
  4879. // Else, copy with Builder.
  4880. Value *Ptr = Builder.CreateGEP(localTarget, idxList);
  4881. Value *V = Builder.CreateLoad(Ptr);
  4882. Builder.CreateStore(V, Elt);
  4883. }
  4884. // Update arrayIdxList.
  4885. for (unsigned idx=arrayLevel;idx>0;idx--) {
  4886. arrayIdxList[idx-1]++;
  4887. if (arrayIdxList[idx-1] < arraySizeList[idx-1])
  4888. break;
  4889. arrayIdxList[idx-1] = 0;
  4890. }
  4891. }
  4892. // Don't override flattened SV_Target.
  4893. if (V == Arg) {
  4894. bSemOverride = false;
  4895. }
  4896. continue;
  4897. }
  4898. // Cast vector/matrix/resource parameter.
  4899. V = castArgumentIfRequired(V, Ty, bOut, inputQual,
  4900. annotation, WorkList, Builder);
  4901. // Cannot SROA, save it to final parameter list.
  4902. FlatParamList.emplace_back(V);
  4903. // Create ParamAnnotation for V.
  4904. FlatAnnotationList.emplace_back(DxilParameterAnnotation());
  4905. DxilParameterAnnotation &flatParamAnnotation = FlatAnnotationList.back();
  4906. flatParamAnnotation.SetParamInputQual(paramAnnotation.GetParamInputQual());
  4907. flatParamAnnotation.SetInterpolationMode(annotation.GetInterpolationMode());
  4908. flatParamAnnotation.SetSemanticString(annotation.GetSemanticString());
  4909. flatParamAnnotation.SetCompType(annotation.GetCompType().GetKind());
  4910. flatParamAnnotation.SetMatrixAnnotation(annotation.GetMatrixAnnotation());
  4911. flatParamAnnotation.SetPrecise(annotation.IsPrecise());
  4912. flatParamAnnotation.SetResourceAttribute(annotation.GetResourceAttribute());
  4913. // Add debug info.
  4914. if (DDI && V != Arg) {
  4915. Value *TmpV = V;
  4916. // If V is casted, add debug into to original V.
  4917. if (castParamMap.count(V)) {
  4918. TmpV = castParamMap[V].first;
  4919. // One more level for ptr of input vector.
  4920. // It cast from ptr to non-ptr then cast to scalars.
  4921. if (castParamMap.count(TmpV)) {
  4922. TmpV = castParamMap[TmpV].first;
  4923. }
  4924. }
  4925. Type *Ty = TmpV->getType();
  4926. if (Ty->isPointerTy())
  4927. Ty = Ty->getPointerElementType();
  4928. unsigned size = DL.getTypeAllocSize(Ty);
  4929. DIExpression *DDIExp = DIB.createBitPieceExpression(debugOffset, size);
  4930. debugOffset += size;
  4931. DIB.insertDeclare(TmpV, DDI->getVariable(), DDIExp, DDI->getDebugLoc(),
  4932. Builder.GetInsertPoint());
  4933. }
  4934. // Flatten stream out.
  4935. if (HLModule::IsStreamOutputPtrType(V->getType())) {
  4936. // For stream output objects.
  4937. // Create a value as output value.
  4938. Type *outputType = V->getType()->getPointerElementType()->getStructElementType(0);
  4939. Value *outputVal = AllocaBuilder.CreateAlloca(outputType);
  4940. // For each stream.Append(data)
  4941. // transform into
  4942. // d = load data
  4943. // store outputVal, d
  4944. // stream.Append(outputVal)
  4945. for (User *user : V->users()) {
  4946. if (CallInst *CI = dyn_cast<CallInst>(user)) {
  4947. unsigned opcode = GetHLOpcode(CI);
  4948. if (opcode == static_cast<unsigned>(IntrinsicOp::MOP_Append)) {
  4949. if (CI->getNumArgOperands() == (HLOperandIndex::kStreamAppendDataOpIndex + 1)) {
  4950. Value *data =
  4951. CI->getArgOperand(HLOperandIndex::kStreamAppendDataOpIndex);
  4952. DXASSERT(data->getType()->isPointerTy(),
  4953. "Append value must be pointer.");
  4954. IRBuilder<> Builder(CI);
  4955. llvm::SmallVector<llvm::Value *, 16> idxList;
  4956. SplitCpy(data->getType(), outputVal, data, idxList, Builder, DL,
  4957. dxilTypeSys, &flatParamAnnotation);
  4958. CI->setArgOperand(HLOperandIndex::kStreamAppendDataOpIndex, outputVal);
  4959. }
  4960. else {
  4961. // Append has been flattened.
  4962. // Flatten store outputVal.
  4963. // Must be struct to be flatten.
  4964. IRBuilder<> Builder(CI);
  4965. llvm::SmallVector<llvm::Value *, 16> idxList;
  4966. llvm::SmallVector<llvm::Value *, 16> EltPtrList;
  4967. // split
  4968. SplitPtr(outputVal->getType(), outputVal, idxList, EltPtrList,
  4969. Builder);
  4970. unsigned eltCount = CI->getNumArgOperands()-2;
  4971. DXASSERT_LOCALVAR(eltCount, eltCount == EltPtrList.size(), "invalid element count");
  4972. for (unsigned i = HLOperandIndex::kStreamAppendDataOpIndex; i < CI->getNumArgOperands(); i++) {
  4973. Value *DataPtr = CI->getArgOperand(i);
  4974. Value *EltPtr =
  4975. EltPtrList[i - HLOperandIndex::kStreamAppendDataOpIndex];
  4976. llvm::SmallVector<llvm::Value *, 16> idxList;
  4977. SplitCpy(DataPtr->getType(), EltPtr, DataPtr, idxList,
  4978. Builder, DL, dxilTypeSys, &flatParamAnnotation);
  4979. CI->setArgOperand(i, EltPtr);
  4980. }
  4981. }
  4982. }
  4983. }
  4984. }
  4985. // Then split output value to generate ParamQual.
  4986. WorkList.push_front(outputVal);
  4987. }
  4988. }
  4989. }
  4990. // Now erase any instructions that were made dead while rewriting the
  4991. // alloca.
  4992. DeleteDeadInstructions();
  4993. // Erase dead allocas after all uses deleted.
  4994. for (Instruction *I : deadAllocas)
  4995. I->eraseFromParent();
  4996. unsigned endArgIndex = FlatAnnotationList.size();
  4997. if (bForParam && startArgIndex < endArgIndex) {
  4998. DxilParamInputQual inputQual = paramAnnotation.GetParamInputQual();
  4999. if (inputQual == DxilParamInputQual::OutStream0 ||
  5000. inputQual == DxilParamInputQual::OutStream1 ||
  5001. inputQual == DxilParamInputQual::OutStream2 ||
  5002. inputQual == DxilParamInputQual::OutStream3)
  5003. startArgIndex++;
  5004. DxilParameterAnnotation &flatParamAnnotation =
  5005. FlatAnnotationList[startArgIndex];
  5006. const std::string &semantic = flatParamAnnotation.GetSemanticString();
  5007. if (!semantic.empty())
  5008. allocateSemanticIndex(FlatAnnotationList, startArgIndex,
  5009. semanticTypeMap);
  5010. }
  5011. }
  5012. static bool IsUsedAsCallArg(Value *V) {
  5013. for (User *U : V->users()) {
  5014. if (CallInst *CI = dyn_cast<CallInst>(U)) {
  5015. Function *CalledF = CI->getCalledFunction();
  5016. HLOpcodeGroup group = GetHLOpcodeGroup(CalledF);
  5017. // Skip HL operations.
  5018. if (group != HLOpcodeGroup::NotHL ||
  5019. group == HLOpcodeGroup::HLExtIntrinsic) {
  5020. continue;
  5021. }
  5022. // Skip llvm intrinsic.
  5023. if (CalledF->isIntrinsic())
  5024. continue;
  5025. return true;
  5026. }
  5027. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
  5028. if (IsUsedAsCallArg(GEP))
  5029. return true;
  5030. }
  5031. }
  5032. return false;
  5033. }
  5034. // For function parameter which used in function call and need to be flattened.
  5035. // Replace with tmp alloca.
  5036. void SROA_Parameter_HLSL::preprocessArgUsedInCall(Function *F) {
  5037. if (F->isDeclaration())
  5038. return;
  5039. const DataLayout &DL = m_pHLModule->GetModule()->getDataLayout();
  5040. DxilTypeSystem &typeSys = m_pHLModule->GetTypeSystem();
  5041. DxilFunctionAnnotation *pFuncAnnot = typeSys.GetFunctionAnnotation(F);
  5042. DXASSERT(pFuncAnnot, "else invalid function");
  5043. IRBuilder<> AllocaBuilder(dxilutil::FindAllocaInsertionPt(F));
  5044. IRBuilder<> Builder(dxilutil::FirstNonAllocaInsertionPt(F));
  5045. SmallVector<ReturnInst*, 2> retList;
  5046. for (BasicBlock &bb : F->getBasicBlockList()) {
  5047. if (ReturnInst *RI = dyn_cast<ReturnInst>(bb.getTerminator())) {
  5048. retList.emplace_back(RI);
  5049. }
  5050. }
  5051. for (Argument &arg : F->args()) {
  5052. Type *Ty = arg.getType();
  5053. // Only check pointer types.
  5054. if (!Ty->isPointerTy())
  5055. continue;
  5056. Ty = Ty->getPointerElementType();
  5057. // Skip scalar types.
  5058. if (!Ty->isAggregateType() &&
  5059. Ty->getScalarType() == Ty)
  5060. continue;
  5061. bool bUsedInCall = IsUsedAsCallArg(&arg);
  5062. if (bUsedInCall) {
  5063. // Create tmp.
  5064. Value *TmpArg = AllocaBuilder.CreateAlloca(Ty);
  5065. // Replace arg with tmp.
  5066. arg.replaceAllUsesWith(TmpArg);
  5067. DxilParameterAnnotation &paramAnnot = pFuncAnnot->GetParameterAnnotation(arg.getArgNo());
  5068. DxilParamInputQual inputQual = paramAnnot.GetParamInputQual();
  5069. unsigned size = DL.getTypeAllocSize(Ty);
  5070. // Copy between arg and tmp.
  5071. if (inputQual == DxilParamInputQual::In ||
  5072. inputQual == DxilParamInputQual::Inout) {
  5073. // copy arg to tmp.
  5074. CallInst *argToTmp = Builder.CreateMemCpy(TmpArg, &arg, size, 0);
  5075. // Split the memcpy.
  5076. MemcpySplitter::SplitMemCpy(cast<MemCpyInst>(argToTmp), DL, nullptr,
  5077. typeSys);
  5078. }
  5079. if (inputQual == DxilParamInputQual::Out ||
  5080. inputQual == DxilParamInputQual::Inout) {
  5081. for (ReturnInst *RI : retList) {
  5082. IRBuilder<> RetBuilder(RI);
  5083. // copy tmp to arg.
  5084. CallInst *tmpToArg =
  5085. RetBuilder.CreateMemCpy(&arg, TmpArg, size, 0);
  5086. // Split the memcpy.
  5087. MemcpySplitter::SplitMemCpy(cast<MemCpyInst>(tmpToArg), DL, nullptr,
  5088. typeSys);
  5089. }
  5090. }
  5091. // TODO: support other DxilParamInputQual.
  5092. }
  5093. }
  5094. }
  5095. /// moveFunctionBlocks - Move body of F to flatF.
  5096. void SROA_Parameter_HLSL::moveFunctionBody(Function *F, Function *flatF) {
  5097. bool updateRetType = F->getReturnType() != flatF->getReturnType();
  5098. // Splice the body of the old function right into the new function.
  5099. flatF->getBasicBlockList().splice(flatF->begin(), F->getBasicBlockList());
  5100. // Update Block uses.
  5101. if (updateRetType) {
  5102. for (BasicBlock &BB : flatF->getBasicBlockList()) {
  5103. if (updateRetType) {
  5104. // Replace ret with ret void.
  5105. if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
  5106. // Create store for return.
  5107. IRBuilder<> Builder(RI);
  5108. Builder.CreateRetVoid();
  5109. RI->eraseFromParent();
  5110. }
  5111. }
  5112. }
  5113. }
  5114. }
  5115. static void SplitArrayCopy(Value *V, const DataLayout &DL,
  5116. DxilTypeSystem &typeSys,
  5117. DxilFieldAnnotation *fieldAnnotation) {
  5118. for (auto U = V->user_begin(); U != V->user_end();) {
  5119. User *user = *(U++);
  5120. if (StoreInst *ST = dyn_cast<StoreInst>(user)) {
  5121. Value *ptr = ST->getPointerOperand();
  5122. Value *val = ST->getValueOperand();
  5123. IRBuilder<> Builder(ST);
  5124. SmallVector<Value *, 16> idxList;
  5125. SplitCpy(ptr->getType(), ptr, val, idxList, Builder, DL, typeSys,
  5126. fieldAnnotation);
  5127. ST->eraseFromParent();
  5128. }
  5129. }
  5130. }
  5131. static void CheckArgUsage(Value *V, bool &bLoad, bool &bStore) {
  5132. if (bLoad && bStore)
  5133. return;
  5134. for (User *user : V->users()) {
  5135. if (dyn_cast<LoadInst>(user)) {
  5136. bLoad = true;
  5137. } else if (dyn_cast<StoreInst>(user)) {
  5138. bStore = true;
  5139. } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(user)) {
  5140. CheckArgUsage(GEP, bLoad, bStore);
  5141. } else if (CallInst *CI = dyn_cast<CallInst>(user)) {
  5142. if (CI->getType()->isPointerTy())
  5143. CheckArgUsage(CI, bLoad, bStore);
  5144. else {
  5145. HLOpcodeGroup group = GetHLOpcodeGroupByName(CI->getCalledFunction());
  5146. if (group == HLOpcodeGroup::HLMatLoadStore) {
  5147. HLMatLoadStoreOpcode opcode =
  5148. static_cast<HLMatLoadStoreOpcode>(GetHLOpcode(CI));
  5149. switch (opcode) {
  5150. case HLMatLoadStoreOpcode::ColMatLoad:
  5151. case HLMatLoadStoreOpcode::RowMatLoad:
  5152. bLoad = true;
  5153. break;
  5154. case HLMatLoadStoreOpcode::ColMatStore:
  5155. case HLMatLoadStoreOpcode::RowMatStore:
  5156. bStore = true;
  5157. break;
  5158. }
  5159. }
  5160. }
  5161. }
  5162. }
  5163. }
  5164. // AcceptHitAndEndSearch and IgnoreHit both will not return, but require
  5165. // outputs to have been written before the call. Do this by:
  5166. // - inject a return immediately after the call if not there already
  5167. // - LegalizeDxilInputOutputs will inject writes from temp alloca to
  5168. // outputs before each return.
  5169. // - in HLOperationLower, after lowering the intrinsic, move the intrinsic
  5170. // to just before the return.
  5171. static void InjectReturnAfterNoReturnPreserveOutput(HLModule &HLM) {
  5172. for (Function &F : HLM.GetModule()->functions()) {
  5173. if (GetHLOpcodeGroup(&F) == HLOpcodeGroup::HLIntrinsic) {
  5174. for (auto U : F.users()) {
  5175. if (CallInst *CI = dyn_cast<CallInst>(U)) {
  5176. unsigned OpCode = GetHLOpcode(CI);
  5177. if (OpCode == (unsigned)IntrinsicOp::IOP_AcceptHitAndEndSearch ||
  5178. OpCode == (unsigned)IntrinsicOp::IOP_IgnoreHit) {
  5179. Instruction *pNextI = CI->getNextNode();
  5180. // Skip if already has a return immediatly following call
  5181. if (isa<ReturnInst>(pNextI))
  5182. continue;
  5183. // split block and add return:
  5184. BasicBlock *BB = CI->getParent();
  5185. BB->splitBasicBlock(pNextI);
  5186. TerminatorInst *Term = BB->getTerminator();
  5187. Term->eraseFromParent();
  5188. IRBuilder<> Builder(BB);
  5189. llvm::Type *RetTy = CI->getParent()->getParent()->getReturnType();
  5190. if (RetTy->isVoidTy())
  5191. Builder.CreateRetVoid();
  5192. else
  5193. Builder.CreateRet(UndefValue::get(RetTy));
  5194. }
  5195. }
  5196. }
  5197. }
  5198. }
  5199. }
  5200. // Support store to input and load from output.
  5201. static void LegalizeDxilInputOutputs(Function *F,
  5202. DxilFunctionAnnotation *EntryAnnotation,
  5203. const DataLayout &DL,
  5204. DxilTypeSystem &typeSys) {
  5205. BasicBlock &EntryBlk = F->getEntryBlock();
  5206. Module *M = F->getParent();
  5207. // Map from output to the temp created for it.
  5208. std::unordered_map<Argument *, Value*> outputTempMap;
  5209. for (Argument &arg : F->args()) {
  5210. Type *Ty = arg.getType();
  5211. DxilParameterAnnotation &paramAnnotation = EntryAnnotation->GetParameterAnnotation(arg.getArgNo());
  5212. DxilParamInputQual qual = paramAnnotation.GetParamInputQual();
  5213. bool isColMajor = false;
  5214. // Skip arg which is not a pointer.
  5215. if (!Ty->isPointerTy()) {
  5216. if (HLMatrixLower::IsMatrixType(Ty)) {
  5217. // Replace matrix arg with cast to vec. It will be lowered in
  5218. // DxilGenerationPass.
  5219. isColMajor = paramAnnotation.GetMatrixAnnotation().Orientation ==
  5220. MatrixOrientation::ColumnMajor;
  5221. IRBuilder<> Builder(dxilutil::FirstNonAllocaInsertionPt(F));
  5222. HLCastOpcode opcode = isColMajor ? HLCastOpcode::ColMatrixToVecCast
  5223. : HLCastOpcode::RowMatrixToVecCast;
  5224. Value *undefVal = UndefValue::get(Ty);
  5225. Value *Cast = HLModule::EmitHLOperationCall(
  5226. Builder, HLOpcodeGroup::HLCast, static_cast<unsigned>(opcode), Ty,
  5227. {undefVal}, *M);
  5228. arg.replaceAllUsesWith(Cast);
  5229. // Set arg as the operand.
  5230. CallInst *CI = cast<CallInst>(Cast);
  5231. CI->setArgOperand(HLOperandIndex::kUnaryOpSrc0Idx, &arg);
  5232. }
  5233. continue;
  5234. }
  5235. Ty = Ty->getPointerElementType();
  5236. bool bLoad = false;
  5237. bool bStore = false;
  5238. CheckArgUsage(&arg, bLoad, bStore);
  5239. bool bNeedTemp = false;
  5240. bool bStoreInputToTemp = false;
  5241. bool bLoadOutputFromTemp = false;
  5242. if (qual == DxilParamInputQual::In && bStore) {
  5243. bNeedTemp = true;
  5244. bStoreInputToTemp = true;
  5245. } else if (qual == DxilParamInputQual::Out && bLoad) {
  5246. bNeedTemp = true;
  5247. bLoadOutputFromTemp = true;
  5248. } else if (bLoad && bStore) {
  5249. switch (qual) {
  5250. case DxilParamInputQual::InputPrimitive:
  5251. case DxilParamInputQual::InputPatch:
  5252. case DxilParamInputQual::OutputPatch: {
  5253. bNeedTemp = true;
  5254. bStoreInputToTemp = true;
  5255. } break;
  5256. case DxilParamInputQual::Inout:
  5257. break;
  5258. default:
  5259. DXASSERT(0, "invalid input qual here");
  5260. }
  5261. } else if (qual == DxilParamInputQual::Inout) {
  5262. // Only replace inout when (bLoad && bStore) == false.
  5263. bNeedTemp = true;
  5264. bLoadOutputFromTemp = true;
  5265. bStoreInputToTemp = true;
  5266. }
  5267. if (HLMatrixLower::IsMatrixType(Ty)) {
  5268. bNeedTemp = true;
  5269. if (qual == DxilParamInputQual::In)
  5270. bStoreInputToTemp = bLoad;
  5271. else if (qual == DxilParamInputQual::Out)
  5272. bLoadOutputFromTemp = bStore;
  5273. else if (qual == DxilParamInputQual::Inout) {
  5274. bStoreInputToTemp = true;
  5275. bLoadOutputFromTemp = true;
  5276. }
  5277. }
  5278. if (bNeedTemp) {
  5279. IRBuilder<> AllocaBuilder(EntryBlk.getFirstInsertionPt());
  5280. IRBuilder<> Builder(dxilutil::FirstNonAllocaInsertionPt(&EntryBlk));
  5281. AllocaInst *temp = AllocaBuilder.CreateAlloca(Ty);
  5282. // Replace all uses with temp.
  5283. arg.replaceAllUsesWith(temp);
  5284. // Copy input to temp.
  5285. if (bStoreInputToTemp) {
  5286. llvm::SmallVector<llvm::Value *, 16> idxList;
  5287. // split copy.
  5288. SplitCpy(temp->getType(), temp, &arg, idxList, Builder, DL, typeSys,
  5289. &paramAnnotation);
  5290. }
  5291. // Generate store output, temp later.
  5292. if (bLoadOutputFromTemp) {
  5293. outputTempMap[&arg] = temp;
  5294. }
  5295. }
  5296. }
  5297. for (BasicBlock &BB : F->getBasicBlockList()) {
  5298. if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
  5299. IRBuilder<> Builder(RI);
  5300. // Copy temp to output.
  5301. for (auto It : outputTempMap) {
  5302. Argument *output = It.first;
  5303. Value *temp = It.second;
  5304. llvm::SmallVector<llvm::Value *, 16> idxList;
  5305. DxilParameterAnnotation &paramAnnotation =
  5306. EntryAnnotation->GetParameterAnnotation(output->getArgNo());
  5307. auto Iter = Builder.GetInsertPoint();
  5308. if (RI != BB.begin())
  5309. Iter--;
  5310. // split copy.
  5311. SplitCpy(output->getType(), output, temp, idxList, Builder, DL, typeSys,
  5312. &paramAnnotation);
  5313. }
  5314. // Clone the return.
  5315. Builder.CreateRet(RI->getReturnValue());
  5316. RI->eraseFromParent();
  5317. }
  5318. }
  5319. }
  5320. void SROA_Parameter_HLSL::createFlattenedFunction(Function *F) {
  5321. DxilTypeSystem &typeSys = m_pHLModule->GetTypeSystem();
  5322. DXASSERT(F == m_pHLModule->GetEntryFunction() ||
  5323. m_pHLModule->IsEntryThatUsesSignatures(F),
  5324. "otherwise, createFlattenedFunction called on library function "
  5325. "that should not be flattened.");
  5326. const DataLayout &DL = m_pHLModule->GetModule()->getDataLayout();
  5327. // Skip void (void) function.
  5328. if (F->getReturnType()->isVoidTy() && F->getArgumentList().empty()) {
  5329. return;
  5330. }
  5331. // Clear maps for cast.
  5332. castParamMap.clear();
  5333. vectorEltsMap.clear();
  5334. DxilFunctionAnnotation *funcAnnotation = m_pHLModule->GetFunctionAnnotation(F);
  5335. DXASSERT(funcAnnotation, "must find annotation for function");
  5336. std::deque<Value *> WorkList;
  5337. LLVMContext &Ctx = m_pHLModule->GetCtx();
  5338. std::unique_ptr<BasicBlock> TmpBlockForFuncDecl;
  5339. if (F->isDeclaration()) {
  5340. TmpBlockForFuncDecl.reset(BasicBlock::Create(Ctx));
  5341. // Create return as terminator.
  5342. IRBuilder<> RetBuilder(TmpBlockForFuncDecl.get());
  5343. RetBuilder.CreateRetVoid();
  5344. }
  5345. std::vector<Value *> FlatParamList;
  5346. std::vector<DxilParameterAnnotation> FlatParamAnnotationList;
  5347. std::vector<int> FlatParamOriArgNoList;
  5348. const bool bForParamTrue = true;
  5349. // Add all argument to worklist.
  5350. for (Argument &Arg : F->args()) {
  5351. // merge GEP use for arg.
  5352. HLModule::MergeGepUse(&Arg);
  5353. // Insert point may be removed. So recreate builder every time.
  5354. IRBuilder<> Builder(Ctx);
  5355. if (!F->isDeclaration()) {
  5356. Builder.SetInsertPoint(dxilutil::FirstNonAllocaInsertionPt(F));
  5357. } else {
  5358. Builder.SetInsertPoint(dxilutil::FirstNonAllocaInsertionPt(TmpBlockForFuncDecl.get()));
  5359. }
  5360. unsigned prevFlatParamCount = FlatParamList.size();
  5361. DxilParameterAnnotation &paramAnnotation =
  5362. funcAnnotation->GetParameterAnnotation(Arg.getArgNo());
  5363. DbgDeclareInst *DDI = llvm::FindAllocaDbgDeclare(&Arg);
  5364. flattenArgument(F, &Arg, bForParamTrue, paramAnnotation, FlatParamList,
  5365. FlatParamAnnotationList, Builder, DDI);
  5366. unsigned newFlatParamCount = FlatParamList.size() - prevFlatParamCount;
  5367. for (unsigned i = 0; i < newFlatParamCount; i++) {
  5368. FlatParamOriArgNoList.emplace_back(Arg.getArgNo());
  5369. }
  5370. }
  5371. Type *retType = F->getReturnType();
  5372. std::vector<Value *> FlatRetList;
  5373. std::vector<DxilParameterAnnotation> FlatRetAnnotationList;
  5374. // Split and change to out parameter.
  5375. if (!retType->isVoidTy()) {
  5376. IRBuilder<> Builder(Ctx);
  5377. IRBuilder<> AllocaBuilder(Ctx);
  5378. if (!F->isDeclaration()) {
  5379. Builder.SetInsertPoint(dxilutil::FirstNonAllocaInsertionPt(F));
  5380. AllocaBuilder.SetInsertPoint(dxilutil::FindAllocaInsertionPt(F));
  5381. } else {
  5382. Builder.SetInsertPoint(dxilutil::FirstNonAllocaInsertionPt(TmpBlockForFuncDecl.get()));
  5383. AllocaBuilder.SetInsertPoint(TmpBlockForFuncDecl->getFirstInsertionPt());
  5384. }
  5385. Value *retValAddr = AllocaBuilder.CreateAlloca(retType);
  5386. DxilParameterAnnotation &retAnnotation =
  5387. funcAnnotation->GetRetTypeAnnotation();
  5388. Module &M = *m_pHLModule->GetModule();
  5389. Type *voidTy = Type::getVoidTy(m_pHLModule->GetCtx());
  5390. // Create DbgDecl for the ret value.
  5391. if (DISubprogram *funcDI = getDISubprogram(F)) {
  5392. DITypeRef RetDITyRef = funcDI->getType()->getTypeArray()[0];
  5393. DITypeIdentifierMap EmptyMap;
  5394. DIType * RetDIType = RetDITyRef.resolve(EmptyMap);
  5395. DIBuilder DIB(*F->getParent(), /*AllowUnresolved*/ false);
  5396. DILocalVariable *RetVar = DIB.createLocalVariable(llvm::dwarf::Tag::DW_TAG_arg_variable, funcDI, F->getName().str() + ".Ret", funcDI->getFile(),
  5397. funcDI->getLine(), RetDIType);
  5398. DIExpression *Expr = nullptr;
  5399. // TODO: how to get col?
  5400. DILocation *DL = DILocation::get(F->getContext(), funcDI->getLine(), 0, funcDI);
  5401. DIB.insertDeclare(retValAddr, RetVar, Expr, DL, Builder.GetInsertPoint());
  5402. }
  5403. for (BasicBlock &BB : F->getBasicBlockList()) {
  5404. if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
  5405. // Create store for return.
  5406. IRBuilder<> RetBuilder(RI);
  5407. if (!retAnnotation.HasMatrixAnnotation()) {
  5408. RetBuilder.CreateStore(RI->getReturnValue(), retValAddr);
  5409. } else {
  5410. bool isRowMajor = retAnnotation.GetMatrixAnnotation().Orientation ==
  5411. MatrixOrientation::RowMajor;
  5412. Value *RetVal = RI->getReturnValue();
  5413. if (!isRowMajor) {
  5414. // Matrix value is row major. ColMatStore require col major.
  5415. // Cast before store.
  5416. RetVal = HLModule::EmitHLOperationCall(
  5417. RetBuilder, HLOpcodeGroup::HLCast,
  5418. static_cast<unsigned>(HLCastOpcode::RowMatrixToColMatrix),
  5419. RetVal->getType(), {RetVal}, M);
  5420. }
  5421. unsigned opcode = static_cast<unsigned>(
  5422. isRowMajor ? HLMatLoadStoreOpcode::RowMatStore
  5423. : HLMatLoadStoreOpcode::ColMatStore);
  5424. HLModule::EmitHLOperationCall(RetBuilder,
  5425. HLOpcodeGroup::HLMatLoadStore, opcode,
  5426. voidTy, {retValAddr, RetVal}, M);
  5427. }
  5428. }
  5429. }
  5430. // Create a fake store to keep retValAddr so it can be flattened.
  5431. if (retValAddr->user_empty()) {
  5432. Builder.CreateStore(UndefValue::get(retType), retValAddr);
  5433. }
  5434. DbgDeclareInst *DDI = llvm::FindAllocaDbgDeclare(retValAddr);
  5435. flattenArgument(F, retValAddr, bForParamTrue,
  5436. funcAnnotation->GetRetTypeAnnotation(), FlatRetList,
  5437. FlatRetAnnotationList, Builder, DDI);
  5438. const int kRetArgNo = -1;
  5439. for (unsigned i = 0; i < FlatRetList.size(); i++) {
  5440. FlatParamOriArgNoList.emplace_back(kRetArgNo);
  5441. }
  5442. }
  5443. // Always change return type as parameter.
  5444. // By doing this, no need to check return when generate storeOutput.
  5445. if (FlatRetList.size() ||
  5446. // For empty struct return type.
  5447. !retType->isVoidTy()) {
  5448. // Return value is flattened.
  5449. // Change return value into out parameter.
  5450. retType = Type::getVoidTy(retType->getContext());
  5451. // Merge return data info param data.
  5452. FlatParamList.insert(FlatParamList.end(), FlatRetList.begin(), FlatRetList.end());
  5453. FlatParamAnnotationList.insert(FlatParamAnnotationList.end(),
  5454. FlatRetAnnotationList.begin(),
  5455. FlatRetAnnotationList.end());
  5456. }
  5457. std::vector<Type *> FinalTypeList;
  5458. for (Value * arg : FlatParamList) {
  5459. FinalTypeList.emplace_back(arg->getType());
  5460. }
  5461. unsigned extraParamSize = 0;
  5462. if (m_pHLModule->HasDxilFunctionProps(F)) {
  5463. DxilFunctionProps &funcProps = m_pHLModule->GetDxilFunctionProps(F);
  5464. if (funcProps.shaderKind == ShaderModel::Kind::Vertex) {
  5465. auto &VS = funcProps.ShaderProps.VS;
  5466. Type *outFloatTy = Type::getFloatPtrTy(F->getContext());
  5467. // Add out float parameter for each clip plane.
  5468. unsigned i=0;
  5469. for (; i < DXIL::kNumClipPlanes; i++) {
  5470. if (!VS.clipPlanes[i])
  5471. break;
  5472. FinalTypeList.emplace_back(outFloatTy);
  5473. }
  5474. extraParamSize = i;
  5475. }
  5476. }
  5477. FunctionType *flatFuncTy = FunctionType::get(retType, FinalTypeList, false);
  5478. // Return if nothing changed.
  5479. if (flatFuncTy == F->getFunctionType()) {
  5480. // Copy semantic allocation.
  5481. if (!FlatParamAnnotationList.empty()) {
  5482. if (!FlatParamAnnotationList[0].GetSemanticString().empty()) {
  5483. for (unsigned i = 0; i < FlatParamAnnotationList.size(); i++) {
  5484. DxilParameterAnnotation &paramAnnotation = funcAnnotation->GetParameterAnnotation(i);
  5485. DxilParameterAnnotation &flatParamAnnotation = FlatParamAnnotationList[i];
  5486. paramAnnotation.SetSemanticIndexVec(flatParamAnnotation.GetSemanticIndexVec());
  5487. paramAnnotation.SetSemanticString(flatParamAnnotation.GetSemanticString());
  5488. }
  5489. }
  5490. }
  5491. if (!F->isDeclaration()) {
  5492. // Support store to input and load from output.
  5493. LegalizeDxilInputOutputs(F, funcAnnotation, DL, typeSys);
  5494. }
  5495. return;
  5496. }
  5497. std::string flatName = F->getName().str() + ".flat";
  5498. DXASSERT(nullptr == F->getParent()->getFunction(flatName),
  5499. "else overwriting existing function");
  5500. Function *flatF =
  5501. cast<Function>(F->getParent()->getOrInsertFunction(flatName, flatFuncTy));
  5502. funcMap[F] = flatF;
  5503. // Update function debug info.
  5504. if (DISubprogram *funcDI = getDISubprogram(F))
  5505. funcDI->replaceFunction(flatF);
  5506. // Create FunctionAnnotation for flatF.
  5507. DxilFunctionAnnotation *flatFuncAnnotation = m_pHLModule->AddFunctionAnnotation(flatF);
  5508. // Don't need to set Ret Info, flatF always return void now.
  5509. // Param Info
  5510. for (unsigned ArgNo = 0; ArgNo < FlatParamAnnotationList.size(); ++ArgNo) {
  5511. DxilParameterAnnotation &paramAnnotation = flatFuncAnnotation->GetParameterAnnotation(ArgNo);
  5512. paramAnnotation = FlatParamAnnotationList[ArgNo];
  5513. }
  5514. // Function Attr and Parameter Attr.
  5515. // Remove sret first.
  5516. if (F->hasStructRetAttr())
  5517. F->removeFnAttr(Attribute::StructRet);
  5518. for (Argument &arg : F->args()) {
  5519. if (arg.hasStructRetAttr()) {
  5520. Attribute::AttrKind SRet [] = {Attribute::StructRet};
  5521. AttributeSet SRetAS = AttributeSet::get(Ctx, arg.getArgNo() + 1, SRet);
  5522. arg.removeAttr(SRetAS);
  5523. }
  5524. }
  5525. AttributeSet AS = F->getAttributes();
  5526. AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
  5527. AttributeSet flatAS;
  5528. flatAS = flatAS.addAttributes(
  5529. Ctx, AttributeSet::FunctionIndex,
  5530. AttributeSet::get(Ctx, AttributeSet::FunctionIndex, FnAttrs));
  5531. if (!F->isDeclaration()) {
  5532. // Only set Param attribute for function has a body.
  5533. for (unsigned ArgNo = 0; ArgNo < FlatParamAnnotationList.size(); ++ArgNo) {
  5534. unsigned oriArgNo = FlatParamOriArgNoList[ArgNo] + 1;
  5535. AttrBuilder paramAttr(AS, oriArgNo);
  5536. if (oriArgNo == AttributeSet::ReturnIndex)
  5537. paramAttr.addAttribute(Attribute::AttrKind::NoAlias);
  5538. flatAS = flatAS.addAttributes(
  5539. Ctx, ArgNo + 1, AttributeSet::get(Ctx, ArgNo + 1, paramAttr));
  5540. }
  5541. }
  5542. flatF->setAttributes(flatAS);
  5543. DXASSERT_LOCALVAR(extraParamSize, flatF->arg_size() == (extraParamSize + FlatParamAnnotationList.size()), "parameter count mismatch");
  5544. // ShaderProps.
  5545. if (m_pHLModule->HasDxilFunctionProps(F)) {
  5546. DxilFunctionProps &funcProps = m_pHLModule->GetDxilFunctionProps(F);
  5547. std::unique_ptr<DxilFunctionProps> flatFuncProps = llvm::make_unique<DxilFunctionProps>();
  5548. flatFuncProps->shaderKind = funcProps.shaderKind;
  5549. flatFuncProps->ShaderProps = funcProps.ShaderProps;
  5550. m_pHLModule->AddDxilFunctionProps(flatF, flatFuncProps);
  5551. if (funcProps.shaderKind == ShaderModel::Kind::Vertex) {
  5552. auto &VS = funcProps.ShaderProps.VS;
  5553. unsigned clipArgIndex = FlatParamAnnotationList.size();
  5554. // Add out float SV_ClipDistance for each clip plane.
  5555. for (unsigned i = 0; i < DXIL::kNumClipPlanes; i++) {
  5556. if (!VS.clipPlanes[i])
  5557. break;
  5558. DxilParameterAnnotation &paramAnnotation =
  5559. flatFuncAnnotation->GetParameterAnnotation(clipArgIndex+i);
  5560. paramAnnotation.SetParamInputQual(DxilParamInputQual::Out);
  5561. Twine semName = Twine("SV_ClipDistance") + Twine(i);
  5562. paramAnnotation.SetSemanticString(semName.str());
  5563. paramAnnotation.SetCompType(DXIL::ComponentType::F32);
  5564. paramAnnotation.AppendSemanticIndex(i);
  5565. }
  5566. }
  5567. }
  5568. if (!F->isDeclaration()) {
  5569. // Move function body into flatF.
  5570. moveFunctionBody(F, flatF);
  5571. // Replace old parameters with flatF Arguments.
  5572. auto argIter = flatF->arg_begin();
  5573. auto flatArgIter = FlatParamList.begin();
  5574. LLVMContext &Context = F->getContext();
  5575. // Parameter cast come from begining of entry block.
  5576. IRBuilder<> AllocaBuilder(dxilutil::FindAllocaInsertionPt(flatF));
  5577. IRBuilder<> Builder(dxilutil::FirstNonAllocaInsertionPt(flatF));
  5578. while (argIter != flatF->arg_end()) {
  5579. Argument *Arg = argIter++;
  5580. if (flatArgIter == FlatParamList.end()) {
  5581. DXASSERT(extraParamSize > 0, "parameter count mismatch");
  5582. break;
  5583. }
  5584. Value *flatArg = *(flatArgIter++);
  5585. if (castParamMap.count(flatArg)) {
  5586. replaceCastParameter(flatArg, castParamMap[flatArg].first, *flatF, Arg,
  5587. castParamMap[flatArg].second, Builder);
  5588. }
  5589. // Update arg debug info.
  5590. DbgDeclareInst *DDI = llvm::FindAllocaDbgDeclare(flatArg);
  5591. if (DDI) {
  5592. if (!flatArg->getType()->isPointerTy()) {
  5593. // Create alloca to hold the debug info.
  5594. Value *allocaArg = nullptr;
  5595. if (flatArg->hasOneUse() && isa<StoreInst>(*flatArg->user_begin())) {
  5596. StoreInst *SI = cast<StoreInst>(*flatArg->user_begin());
  5597. allocaArg = SI->getPointerOperand();
  5598. } else {
  5599. allocaArg = AllocaBuilder.CreateAlloca(flatArg->getType());
  5600. StoreInst *initArg = Builder.CreateStore(flatArg, allocaArg);
  5601. Value *ldArg = Builder.CreateLoad(allocaArg);
  5602. flatArg->replaceAllUsesWith(ldArg);
  5603. initArg->setOperand(0, flatArg);
  5604. }
  5605. Value *VMD = MetadataAsValue::get(Context, ValueAsMetadata::get(allocaArg));
  5606. DDI->setArgOperand(0, VMD);
  5607. } else {
  5608. Value *VMD = MetadataAsValue::get(Context, ValueAsMetadata::get(Arg));
  5609. DDI->setArgOperand(0, VMD);
  5610. }
  5611. }
  5612. flatArg->replaceAllUsesWith(Arg);
  5613. HLModule::MergeGepUse(Arg);
  5614. // Flatten store of array parameter.
  5615. if (Arg->getType()->isPointerTy()) {
  5616. Type *Ty = Arg->getType()->getPointerElementType();
  5617. if (Ty->isArrayTy())
  5618. SplitArrayCopy(
  5619. Arg, DL, typeSys,
  5620. &flatFuncAnnotation->GetParameterAnnotation(Arg->getArgNo()));
  5621. }
  5622. }
  5623. // Support store to input and load from output.
  5624. LegalizeDxilInputOutputs(flatF, flatFuncAnnotation, DL, typeSys);
  5625. }
  5626. }
  5627. void SROA_Parameter_HLSL::replaceCall(Function *F, Function *flatF) {
  5628. // Update entry function.
  5629. if (F == m_pHLModule->GetEntryFunction()) {
  5630. m_pHLModule->SetEntryFunction(flatF);
  5631. }
  5632. DXASSERT(F->user_empty(), "otherwise we flattened a library function.");
  5633. }
  5634. // Public interface to the SROA_Parameter_HLSL pass
  5635. ModulePass *llvm::createSROA_Parameter_HLSL() {
  5636. return new SROA_Parameter_HLSL();
  5637. }
  5638. //===----------------------------------------------------------------------===//
  5639. // Lower static global into Alloca.
  5640. //===----------------------------------------------------------------------===//
  5641. namespace {
  5642. class LowerStaticGlobalIntoAlloca : public ModulePass {
  5643. HLModule *m_pHLModule;
  5644. public:
  5645. static char ID; // Pass identification, replacement for typeid
  5646. explicit LowerStaticGlobalIntoAlloca() : ModulePass(ID) {}
  5647. const char *getPassName() const override { return "Lower static global into Alloca"; }
  5648. bool runOnModule(Module &M) override {
  5649. m_pHLModule = &M.GetOrCreateHLModule();
  5650. // Lower static global into allocas.
  5651. std::vector<GlobalVariable *> staticGVs;
  5652. for (GlobalVariable &GV : M.globals()) {
  5653. bool isStaticGlobal =
  5654. dxilutil::IsStaticGlobal(&GV) &&
  5655. GV.getType()->getAddressSpace() == DXIL::kDefaultAddrSpace;
  5656. if (isStaticGlobal &&
  5657. !GV.getType()->getElementType()->isAggregateType()) {
  5658. staticGVs.emplace_back(&GV);
  5659. }
  5660. }
  5661. bool bUpdated = false;
  5662. const DataLayout &DL = M.getDataLayout();
  5663. for (GlobalVariable *GV : staticGVs) {
  5664. bUpdated |= lowerStaticGlobalIntoAlloca(GV, DL);
  5665. }
  5666. return bUpdated;
  5667. }
  5668. private:
  5669. bool lowerStaticGlobalIntoAlloca(GlobalVariable *GV, const DataLayout &DL);
  5670. };
  5671. }
  5672. bool LowerStaticGlobalIntoAlloca::lowerStaticGlobalIntoAlloca(GlobalVariable *GV, const DataLayout &DL) {
  5673. DxilTypeSystem &typeSys = m_pHLModule->GetTypeSystem();
  5674. unsigned size = DL.getTypeAllocSize(GV->getType()->getElementType());
  5675. PointerStatus PS(size);
  5676. GV->removeDeadConstantUsers();
  5677. PS.analyzePointer(GV, PS, typeSys, /*bStructElt*/ false);
  5678. bool NotStored = (PS.storedType == PointerStatus::StoredType::NotStored) ||
  5679. (PS.storedType == PointerStatus::StoredType::InitializerStored);
  5680. // Make sure GV only used in one function.
  5681. // Skip GV which don't have store.
  5682. if (PS.HasMultipleAccessingFunctions || NotStored)
  5683. return false;
  5684. Function *F = const_cast<Function*>(PS.AccessingFunction);
  5685. IRBuilder<> AllocaBuilder(dxilutil::FindAllocaInsertionPt(F));
  5686. AllocaInst *AI = AllocaBuilder.CreateAlloca(GV->getType()->getElementType());
  5687. IRBuilder<> Builder(dxilutil::FirstNonAllocaInsertionPt(F));
  5688. // Store initializer is exist.
  5689. if (GV->hasInitializer() && !isa<UndefValue>(GV->getInitializer())) {
  5690. Builder.CreateStore(GV->getInitializer(), GV);
  5691. }
  5692. ReplaceConstantWithInst(GV, AI, Builder);
  5693. GV->eraseFromParent();
  5694. return true;
  5695. }
  5696. char LowerStaticGlobalIntoAlloca::ID = 0;
  5697. INITIALIZE_PASS(LowerStaticGlobalIntoAlloca, "static-global-to-alloca",
  5698. "Lower static global into Alloca", false,
  5699. false)
  5700. // Public interface to the LowerStaticGlobalIntoAlloca pass
  5701. ModulePass *llvm::createLowerStaticGlobalIntoAlloca() {
  5702. return new LowerStaticGlobalIntoAlloca();
  5703. }
  5704. //===----------------------------------------------------------------------===//
  5705. // Lower one type to another type.
  5706. //===----------------------------------------------------------------------===//
  5707. namespace {
  5708. class LowerTypePass : public ModulePass {
  5709. public:
  5710. explicit LowerTypePass(char &ID)
  5711. : ModulePass(ID) {}
  5712. bool runOnModule(Module &M) override;
  5713. private:
  5714. bool runOnFunction(Function &F, bool HasDbgInfo);
  5715. AllocaInst *lowerAlloca(AllocaInst *A);
  5716. GlobalVariable *lowerInternalGlobal(GlobalVariable *GV);
  5717. protected:
  5718. virtual bool needToLower(Value *V) = 0;
  5719. virtual void lowerUseWithNewValue(Value *V, Value *NewV) = 0;
  5720. virtual Type *lowerType(Type *Ty) = 0;
  5721. virtual Constant *lowerInitVal(Constant *InitVal, Type *NewTy) = 0;
  5722. virtual StringRef getGlobalPrefix() = 0;
  5723. virtual void initialize(Module &M) {};
  5724. };
  5725. AllocaInst *LowerTypePass::lowerAlloca(AllocaInst *A) {
  5726. IRBuilder<> AllocaBuilder(A);
  5727. Type *NewTy = lowerType(A->getAllocatedType());
  5728. return AllocaBuilder.CreateAlloca(NewTy);
  5729. }
  5730. GlobalVariable *LowerTypePass::lowerInternalGlobal(GlobalVariable *GV) {
  5731. Type *NewTy = lowerType(GV->getType()->getPointerElementType());
  5732. // So set init val to undef.
  5733. Constant *InitVal = UndefValue::get(NewTy);
  5734. if (GV->hasInitializer()) {
  5735. Constant *OldInitVal = GV->getInitializer();
  5736. if (isa<ConstantAggregateZero>(OldInitVal))
  5737. InitVal = ConstantAggregateZero::get(NewTy);
  5738. else if (!isa<UndefValue>(OldInitVal)) {
  5739. InitVal = lowerInitVal(OldInitVal, NewTy);
  5740. }
  5741. }
  5742. bool isConst = GV->isConstant();
  5743. GlobalVariable::ThreadLocalMode TLMode = GV->getThreadLocalMode();
  5744. unsigned AddressSpace = GV->getType()->getAddressSpace();
  5745. GlobalValue::LinkageTypes linkage = GV->getLinkage();
  5746. Module *M = GV->getParent();
  5747. GlobalVariable *NewGV = new llvm::GlobalVariable(
  5748. *M, NewTy, /*IsConstant*/ isConst, linkage,
  5749. /*InitVal*/ InitVal, GV->getName() + getGlobalPrefix(),
  5750. /*InsertBefore*/ nullptr, TLMode, AddressSpace);
  5751. return NewGV;
  5752. }
  5753. bool LowerTypePass::runOnFunction(Function &F, bool HasDbgInfo) {
  5754. std::vector<AllocaInst *> workList;
  5755. // Scan the entry basic block, adding allocas to the worklist.
  5756. BasicBlock &BB = F.getEntryBlock();
  5757. for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
  5758. if (!isa<AllocaInst>(I))
  5759. continue;
  5760. AllocaInst *A = cast<AllocaInst>(I);
  5761. if (needToLower(A))
  5762. workList.emplace_back(A);
  5763. }
  5764. LLVMContext &Context = F.getContext();
  5765. for (AllocaInst *A : workList) {
  5766. AllocaInst *NewA = lowerAlloca(A);
  5767. if (HasDbgInfo) {
  5768. // Add debug info.
  5769. DbgDeclareInst *DDI = llvm::FindAllocaDbgDeclare(A);
  5770. if (DDI) {
  5771. Value *DDIVar = MetadataAsValue::get(Context, DDI->getRawVariable());
  5772. Value *DDIExp = MetadataAsValue::get(Context, DDI->getRawExpression());
  5773. Value *VMD = MetadataAsValue::get(Context, ValueAsMetadata::get(NewA));
  5774. IRBuilder<> debugBuilder(DDI);
  5775. debugBuilder.CreateCall(DDI->getCalledFunction(),
  5776. {VMD, DDIVar, DDIExp});
  5777. }
  5778. }
  5779. // Replace users.
  5780. lowerUseWithNewValue(A, NewA);
  5781. // Remove alloca.
  5782. A->eraseFromParent();
  5783. }
  5784. return true;
  5785. }
  5786. bool LowerTypePass::runOnModule(Module &M) {
  5787. initialize(M);
  5788. // Load up debug information, to cross-reference values and the instructions
  5789. // used to load them.
  5790. bool HasDbgInfo = getDebugMetadataVersionFromModule(M) != 0;
  5791. llvm::DebugInfoFinder Finder;
  5792. if (HasDbgInfo) {
  5793. Finder.processModule(M);
  5794. }
  5795. std::vector<AllocaInst*> multiDimAllocas;
  5796. for (Function &F : M.functions()) {
  5797. if (F.isDeclaration())
  5798. continue;
  5799. runOnFunction(F, HasDbgInfo);
  5800. }
  5801. // Work on internal global.
  5802. std::vector<GlobalVariable *> vecGVs;
  5803. for (GlobalVariable &GV : M.globals()) {
  5804. if (dxilutil::IsStaticGlobal(&GV) || dxilutil::IsSharedMemoryGlobal(&GV)) {
  5805. if (needToLower(&GV) && !GV.user_empty())
  5806. vecGVs.emplace_back(&GV);
  5807. }
  5808. }
  5809. for (GlobalVariable *GV : vecGVs) {
  5810. GlobalVariable *NewGV = lowerInternalGlobal(GV);
  5811. // Add debug info.
  5812. if (HasDbgInfo) {
  5813. HLModule::UpdateGlobalVariableDebugInfo(GV, Finder, NewGV);
  5814. }
  5815. // Replace users.
  5816. lowerUseWithNewValue(GV, NewGV);
  5817. // Remove GV.
  5818. GV->removeDeadConstantUsers();
  5819. GV->eraseFromParent();
  5820. }
  5821. return true;
  5822. }
  5823. }
  5824. //===----------------------------------------------------------------------===//
  5825. // DynamicIndexingVector to Array.
  5826. //===----------------------------------------------------------------------===//
  5827. namespace {
  5828. class DynamicIndexingVectorToArray : public LowerTypePass {
  5829. bool ReplaceAllVectors;
  5830. public:
  5831. explicit DynamicIndexingVectorToArray(bool ReplaceAll = false)
  5832. : LowerTypePass(ID), ReplaceAllVectors(ReplaceAll) {}
  5833. static char ID; // Pass identification, replacement for typeid
  5834. void applyOptions(PassOptions O) override;
  5835. void dumpConfig(raw_ostream &OS) override;
  5836. protected:
  5837. bool needToLower(Value *V) override;
  5838. void lowerUseWithNewValue(Value *V, Value *NewV) override;
  5839. Type *lowerType(Type *Ty) override;
  5840. Constant *lowerInitVal(Constant *InitVal, Type *NewTy) override;
  5841. StringRef getGlobalPrefix() override { return ".v"; }
  5842. private:
  5843. bool HasVectorDynamicIndexing(Value *V);
  5844. void ReplaceVecGEP(Value *GEP, ArrayRef<Value *> idxList, Value *A,
  5845. IRBuilder<> &Builder);
  5846. void ReplaceVecArrayGEP(Value *GEP, ArrayRef<Value *> idxList, Value *A,
  5847. IRBuilder<> &Builder);
  5848. void ReplaceVectorWithArray(Value *Vec, Value *Array);
  5849. void ReplaceVectorArrayWithArray(Value *VecArray, Value *Array);
  5850. void ReplaceStaticIndexingOnVector(Value *V);
  5851. };
  5852. void DynamicIndexingVectorToArray::applyOptions(PassOptions O) {
  5853. GetPassOptionBool(O, "ReplaceAllVectors", &ReplaceAllVectors,
  5854. ReplaceAllVectors);
  5855. }
  5856. void DynamicIndexingVectorToArray::dumpConfig(raw_ostream &OS) {
  5857. ModulePass::dumpConfig(OS);
  5858. OS << ",ReplaceAllVectors=" << ReplaceAllVectors;
  5859. }
  5860. void DynamicIndexingVectorToArray::ReplaceStaticIndexingOnVector(Value *V) {
  5861. for (auto U = V->user_begin(), E = V->user_end(); U != E;) {
  5862. Value *User = *(U++);
  5863. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
  5864. // Only work on element access for vector.
  5865. if (GEP->getNumOperands() == 3) {
  5866. auto Idx = GEP->idx_begin();
  5867. // Skip the pointer idx.
  5868. Idx++;
  5869. ConstantInt *constIdx = cast<ConstantInt>(Idx);
  5870. for (auto GEPU = GEP->user_begin(), GEPE = GEP->user_end();
  5871. GEPU != GEPE;) {
  5872. Instruction *GEPUser = cast<Instruction>(*(GEPU++));
  5873. IRBuilder<> Builder(GEPUser);
  5874. if (LoadInst *ldInst = dyn_cast<LoadInst>(GEPUser)) {
  5875. // Change
  5876. // ld a->x
  5877. // into
  5878. // b = ld a
  5879. // b.x
  5880. Value *ldVal = Builder.CreateLoad(V);
  5881. Value *Elt = Builder.CreateExtractElement(ldVal, constIdx);
  5882. ldInst->replaceAllUsesWith(Elt);
  5883. ldInst->eraseFromParent();
  5884. } else {
  5885. // Change
  5886. // st val, a->x
  5887. // into
  5888. // tmp = ld a
  5889. // tmp.x = val
  5890. // st tmp, a
  5891. // Must be store inst here.
  5892. StoreInst *stInst = cast<StoreInst>(GEPUser);
  5893. Value *val = stInst->getValueOperand();
  5894. Value *ldVal = Builder.CreateLoad(V);
  5895. ldVal = Builder.CreateInsertElement(ldVal, val, constIdx);
  5896. Builder.CreateStore(ldVal, V);
  5897. stInst->eraseFromParent();
  5898. }
  5899. }
  5900. GEP->eraseFromParent();
  5901. } else if (GEP->getNumIndices() == 1) {
  5902. Value *Idx = *GEP->idx_begin();
  5903. if (ConstantInt *C = dyn_cast<ConstantInt>(Idx)) {
  5904. if (C->getLimitedValue() == 0) {
  5905. GEP->replaceAllUsesWith(V);
  5906. GEP->eraseFromParent();
  5907. }
  5908. }
  5909. }
  5910. }
  5911. }
  5912. }
  5913. bool DynamicIndexingVectorToArray::needToLower(Value *V) {
  5914. Type *Ty = V->getType()->getPointerElementType();
  5915. if (dyn_cast<VectorType>(Ty)) {
  5916. if (isa<GlobalVariable>(V) || ReplaceAllVectors) {
  5917. return true;
  5918. }
  5919. // Don't lower local vector which only static indexing.
  5920. if (HasVectorDynamicIndexing(V)) {
  5921. return true;
  5922. } else {
  5923. // Change vector indexing with ld st.
  5924. ReplaceStaticIndexingOnVector(V);
  5925. return false;
  5926. }
  5927. } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
  5928. // Array must be replaced even without dynamic indexing to remove vector
  5929. // type in dxil.
  5930. // TODO: optimize static array index in later pass.
  5931. Type *EltTy = dxilutil::GetArrayEltTy(AT);
  5932. return isa<VectorType>(EltTy);
  5933. }
  5934. return false;
  5935. }
  5936. void DynamicIndexingVectorToArray::ReplaceVecGEP(Value *GEP, ArrayRef<Value *> idxList,
  5937. Value *A, IRBuilder<> &Builder) {
  5938. Value *newGEP = Builder.CreateGEP(A, idxList);
  5939. if (GEP->getType()->getPointerElementType()->isVectorTy()) {
  5940. ReplaceVectorWithArray(GEP, newGEP);
  5941. } else {
  5942. GEP->replaceAllUsesWith(newGEP);
  5943. }
  5944. }
  5945. void DynamicIndexingVectorToArray::ReplaceVectorWithArray(Value *Vec, Value *A) {
  5946. unsigned size = Vec->getType()->getPointerElementType()->getVectorNumElements();
  5947. for (auto U = Vec->user_begin(); U != Vec->user_end();) {
  5948. User *User = (*U++);
  5949. // GlobalVariable user.
  5950. if (isa<ConstantExpr>(User)) {
  5951. if (User->user_empty())
  5952. continue;
  5953. if (GEPOperator *GEP = dyn_cast<GEPOperator>(User)) {
  5954. IRBuilder<> Builder(Vec->getContext());
  5955. SmallVector<Value *, 4> idxList(GEP->idx_begin(), GEP->idx_end());
  5956. ReplaceVecGEP(GEP, idxList, A, Builder);
  5957. continue;
  5958. }
  5959. }
  5960. // Instrution user.
  5961. Instruction *UserInst = cast<Instruction>(User);
  5962. IRBuilder<> Builder(UserInst);
  5963. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
  5964. SmallVector<Value *, 4> idxList(GEP->idx_begin(), GEP->idx_end());
  5965. ReplaceVecGEP(cast<GEPOperator>(GEP), idxList, A, Builder);
  5966. GEP->eraseFromParent();
  5967. } else if (LoadInst *ldInst = dyn_cast<LoadInst>(User)) {
  5968. // If ld whole struct, need to split the load.
  5969. Value *newLd = UndefValue::get(ldInst->getType());
  5970. Value *zero = Builder.getInt32(0);
  5971. for (unsigned i = 0; i < size; i++) {
  5972. Value *idx = Builder.getInt32(i);
  5973. Value *GEP = Builder.CreateInBoundsGEP(A, {zero, idx});
  5974. Value *Elt = Builder.CreateLoad(GEP);
  5975. newLd = Builder.CreateInsertElement(newLd, Elt, i);
  5976. }
  5977. ldInst->replaceAllUsesWith(newLd);
  5978. ldInst->eraseFromParent();
  5979. } else if (StoreInst *stInst = dyn_cast<StoreInst>(User)) {
  5980. Value *val = stInst->getValueOperand();
  5981. Value *zero = Builder.getInt32(0);
  5982. for (unsigned i = 0; i < size; i++) {
  5983. Value *Elt = Builder.CreateExtractElement(val, i);
  5984. Value *idx = Builder.getInt32(i);
  5985. Value *GEP = Builder.CreateInBoundsGEP(A, {zero, idx});
  5986. Builder.CreateStore(Elt, GEP);
  5987. }
  5988. stInst->eraseFromParent();
  5989. } else {
  5990. // Vector parameter should be lowered.
  5991. // No function call should use vector.
  5992. DXASSERT(0, "not implement yet");
  5993. }
  5994. }
  5995. }
  5996. void DynamicIndexingVectorToArray::ReplaceVecArrayGEP(Value *GEP,
  5997. ArrayRef<Value *> idxList, Value *A,
  5998. IRBuilder<> &Builder) {
  5999. Value *newGEP = Builder.CreateGEP(A, idxList);
  6000. Type *Ty = GEP->getType()->getPointerElementType();
  6001. if (Ty->isVectorTy()) {
  6002. ReplaceVectorWithArray(GEP, newGEP);
  6003. } else if (Ty->isArrayTy()) {
  6004. ReplaceVectorArrayWithArray(GEP, newGEP);
  6005. } else {
  6006. DXASSERT(Ty->isSingleValueType(), "must be vector subscript here");
  6007. GEP->replaceAllUsesWith(newGEP);
  6008. }
  6009. }
  6010. void DynamicIndexingVectorToArray::ReplaceVectorArrayWithArray(Value *VA, Value *A) {
  6011. for (auto U = VA->user_begin(); U != VA->user_end();) {
  6012. User *User = *(U++);
  6013. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
  6014. IRBuilder<> Builder(GEP);
  6015. SmallVector<Value *, 4> idxList(GEP->idx_begin(), GEP->idx_end());
  6016. ReplaceVecArrayGEP(GEP, idxList, A, Builder);
  6017. GEP->eraseFromParent();
  6018. } else if (GEPOperator *GEPOp = dyn_cast<GEPOperator>(User)) {
  6019. IRBuilder<> Builder(GEPOp->getContext());
  6020. SmallVector<Value *, 4> idxList(GEPOp->idx_begin(), GEPOp->idx_end());
  6021. ReplaceVecArrayGEP(GEPOp, idxList, A, Builder);
  6022. } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
  6023. BCI->setOperand(0, A);
  6024. } else {
  6025. DXASSERT(0, "Array pointer should only used by GEP");
  6026. }
  6027. }
  6028. }
  6029. void DynamicIndexingVectorToArray::lowerUseWithNewValue(Value *V, Value *NewV) {
  6030. Type *Ty = V->getType()->getPointerElementType();
  6031. // Replace V with NewV.
  6032. if (Ty->isVectorTy()) {
  6033. ReplaceVectorWithArray(V, NewV);
  6034. } else {
  6035. ReplaceVectorArrayWithArray(V, NewV);
  6036. }
  6037. }
  6038. Type *DynamicIndexingVectorToArray::lowerType(Type *Ty) {
  6039. if (VectorType *VT = dyn_cast<VectorType>(Ty)) {
  6040. return ArrayType::get(VT->getElementType(), VT->getNumElements());
  6041. } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
  6042. SmallVector<ArrayType *, 4> nestArrayTys;
  6043. nestArrayTys.emplace_back(AT);
  6044. Type *EltTy = AT->getElementType();
  6045. // support multi level of array
  6046. while (EltTy->isArrayTy()) {
  6047. ArrayType *ElAT = cast<ArrayType>(EltTy);
  6048. nestArrayTys.emplace_back(ElAT);
  6049. EltTy = ElAT->getElementType();
  6050. }
  6051. if (EltTy->isVectorTy()) {
  6052. Type *vecAT = ArrayType::get(EltTy->getVectorElementType(),
  6053. EltTy->getVectorNumElements());
  6054. return CreateNestArrayTy(vecAT, nestArrayTys);
  6055. }
  6056. return nullptr;
  6057. }
  6058. return nullptr;
  6059. }
  6060. Constant *DynamicIndexingVectorToArray::lowerInitVal(Constant *InitVal, Type *NewTy) {
  6061. Type *VecTy = InitVal->getType();
  6062. ArrayType *ArrayTy = cast<ArrayType>(NewTy);
  6063. if (VecTy->isVectorTy()) {
  6064. SmallVector<Constant *, 4> Elts;
  6065. for (unsigned i = 0; i < VecTy->getVectorNumElements(); i++) {
  6066. Elts.emplace_back(InitVal->getAggregateElement(i));
  6067. }
  6068. return ConstantArray::get(ArrayTy, Elts);
  6069. } else {
  6070. ArrayType *AT = cast<ArrayType>(VecTy);
  6071. ArrayType *EltArrayTy = cast<ArrayType>(ArrayTy->getElementType());
  6072. SmallVector<Constant *, 4> Elts;
  6073. for (unsigned i = 0; i < AT->getNumElements(); i++) {
  6074. Constant *Elt = lowerInitVal(InitVal->getAggregateElement(i), EltArrayTy);
  6075. Elts.emplace_back(Elt);
  6076. }
  6077. return ConstantArray::get(ArrayTy, Elts);
  6078. }
  6079. }
  6080. bool DynamicIndexingVectorToArray::HasVectorDynamicIndexing(Value *V) {
  6081. return dxilutil::HasDynamicIndexing(V);
  6082. }
  6083. }
  6084. char DynamicIndexingVectorToArray::ID = 0;
  6085. INITIALIZE_PASS(DynamicIndexingVectorToArray, "dynamic-vector-to-array",
  6086. "Replace dynamic indexing vector with array", false,
  6087. false)
  6088. // Public interface to the DynamicIndexingVectorToArray pass
  6089. ModulePass *llvm::createDynamicIndexingVectorToArrayPass(bool ReplaceAllVector) {
  6090. return new DynamicIndexingVectorToArray(ReplaceAllVector);
  6091. }
  6092. //===----------------------------------------------------------------------===//
  6093. // Flatten multi dim array into 1 dim.
  6094. //===----------------------------------------------------------------------===//
  6095. namespace {
  6096. class MultiDimArrayToOneDimArray : public LowerTypePass {
  6097. public:
  6098. explicit MultiDimArrayToOneDimArray() : LowerTypePass(ID) {}
  6099. static char ID; // Pass identification, replacement for typeid
  6100. protected:
  6101. bool needToLower(Value *V) override;
  6102. void lowerUseWithNewValue(Value *V, Value *NewV) override;
  6103. Type *lowerType(Type *Ty) override;
  6104. Constant *lowerInitVal(Constant *InitVal, Type *NewTy) override;
  6105. StringRef getGlobalPrefix() override { return ".1dim"; }
  6106. };
  6107. bool MultiDimArrayToOneDimArray::needToLower(Value *V) {
  6108. Type *Ty = V->getType()->getPointerElementType();
  6109. ArrayType *AT = dyn_cast<ArrayType>(Ty);
  6110. if (!AT)
  6111. return false;
  6112. if (!isa<ArrayType>(AT->getElementType())) {
  6113. return false;
  6114. } else {
  6115. // Merge all GEP.
  6116. HLModule::MergeGepUse(V);
  6117. return true;
  6118. }
  6119. }
  6120. void ReplaceMultiDimGEP(User *GEP, Value *OneDim, IRBuilder<> &Builder) {
  6121. gep_type_iterator GEPIt = gep_type_begin(GEP), E = gep_type_end(GEP);
  6122. Value *PtrOffset = GEPIt.getOperand();
  6123. ++GEPIt;
  6124. Value *ArrayIdx = GEPIt.getOperand();
  6125. ++GEPIt;
  6126. Value *VecIdx = nullptr;
  6127. for (; GEPIt != E; ++GEPIt) {
  6128. if (GEPIt->isArrayTy()) {
  6129. unsigned arraySize = GEPIt->getArrayNumElements();
  6130. Value *V = GEPIt.getOperand();
  6131. ArrayIdx = Builder.CreateMul(ArrayIdx, Builder.getInt32(arraySize));
  6132. ArrayIdx = Builder.CreateAdd(V, ArrayIdx);
  6133. } else {
  6134. DXASSERT_NOMSG(isa<VectorType>(*GEPIt));
  6135. VecIdx = GEPIt.getOperand();
  6136. }
  6137. }
  6138. Value *NewGEP = nullptr;
  6139. if (!VecIdx)
  6140. NewGEP = Builder.CreateGEP(OneDim, {PtrOffset, ArrayIdx});
  6141. else
  6142. NewGEP = Builder.CreateGEP(OneDim, {PtrOffset, ArrayIdx, VecIdx});
  6143. GEP->replaceAllUsesWith(NewGEP);
  6144. }
  6145. void MultiDimArrayToOneDimArray::lowerUseWithNewValue(Value *MultiDim, Value *OneDim) {
  6146. LLVMContext &Context = MultiDim->getContext();
  6147. // All users should be element type.
  6148. // Replace users of AI.
  6149. for (auto it = MultiDim->user_begin(); it != MultiDim->user_end();) {
  6150. User *U = *(it++);
  6151. if (U->user_empty())
  6152. continue;
  6153. if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
  6154. BCI->setOperand(0, OneDim);
  6155. continue;
  6156. }
  6157. // Must be GEP.
  6158. GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U);
  6159. if (!GEP) {
  6160. DXASSERT_NOMSG(isa<GEPOperator>(U));
  6161. // NewGEP must be GEPOperator too.
  6162. // No instruction will be build.
  6163. IRBuilder<> Builder(Context);
  6164. ReplaceMultiDimGEP(U, OneDim, Builder);
  6165. } else {
  6166. IRBuilder<> Builder(GEP);
  6167. ReplaceMultiDimGEP(U, OneDim, Builder);
  6168. }
  6169. if (GEP)
  6170. GEP->eraseFromParent();
  6171. }
  6172. }
  6173. Type *MultiDimArrayToOneDimArray::lowerType(Type *Ty) {
  6174. ArrayType *AT = cast<ArrayType>(Ty);
  6175. unsigned arraySize = AT->getNumElements();
  6176. Type *EltTy = AT->getElementType();
  6177. // support multi level of array
  6178. while (EltTy->isArrayTy()) {
  6179. ArrayType *ElAT = cast<ArrayType>(EltTy);
  6180. arraySize *= ElAT->getNumElements();
  6181. EltTy = ElAT->getElementType();
  6182. }
  6183. return ArrayType::get(EltTy, arraySize);
  6184. }
  6185. void FlattenMultiDimConstArray(Constant *V, std::vector<Constant *> &Elts) {
  6186. if (!V->getType()->isArrayTy()) {
  6187. Elts.emplace_back(V);
  6188. } else {
  6189. ArrayType *AT = cast<ArrayType>(V->getType());
  6190. for (unsigned i = 0; i < AT->getNumElements(); i++) {
  6191. FlattenMultiDimConstArray(V->getAggregateElement(i), Elts);
  6192. }
  6193. }
  6194. }
  6195. Constant *MultiDimArrayToOneDimArray::lowerInitVal(Constant *InitVal, Type *NewTy) {
  6196. if (InitVal) {
  6197. // MultiDim array init should be done by store.
  6198. if (isa<ConstantAggregateZero>(InitVal))
  6199. InitVal = ConstantAggregateZero::get(NewTy);
  6200. else if (isa<UndefValue>(InitVal))
  6201. InitVal = UndefValue::get(NewTy);
  6202. else {
  6203. std::vector<Constant *> Elts;
  6204. FlattenMultiDimConstArray(InitVal, Elts);
  6205. InitVal = ConstantArray::get(cast<ArrayType>(NewTy), Elts);
  6206. }
  6207. } else {
  6208. InitVal = UndefValue::get(NewTy);
  6209. }
  6210. return InitVal;
  6211. }
  6212. }
  6213. char MultiDimArrayToOneDimArray::ID = 0;
  6214. INITIALIZE_PASS(MultiDimArrayToOneDimArray, "multi-dim-one-dim",
  6215. "Flatten multi-dim array into one-dim array", false,
  6216. false)
  6217. // Public interface to the SROA_Parameter_HLSL pass
  6218. ModulePass *llvm::createMultiDimArrayToOneDimArrayPass() {
  6219. return new MultiDimArrayToOneDimArray();
  6220. }
  6221. //===----------------------------------------------------------------------===//
  6222. // Lower resource into handle.
  6223. //===----------------------------------------------------------------------===//
  6224. namespace {
  6225. class ResourceToHandle : public LowerTypePass {
  6226. public:
  6227. explicit ResourceToHandle() : LowerTypePass(ID) {}
  6228. static char ID; // Pass identification, replacement for typeid
  6229. protected:
  6230. bool needToLower(Value *V) override;
  6231. void lowerUseWithNewValue(Value *V, Value *NewV) override;
  6232. Type *lowerType(Type *Ty) override;
  6233. Constant *lowerInitVal(Constant *InitVal, Type *NewTy) override;
  6234. StringRef getGlobalPrefix() override { return ".res"; }
  6235. void initialize(Module &M) override;
  6236. private:
  6237. void ReplaceResourceWithHandle(Value *ResPtr, Value *HandlePtr);
  6238. void ReplaceResourceGEPWithHandleGEP(Value *GEP, ArrayRef<Value *> idxList,
  6239. Value *A, IRBuilder<> &Builder);
  6240. void ReplaceResourceArrayWithHandleArray(Value *VA, Value *A);
  6241. Type *m_HandleTy;
  6242. HLModule *m_pHLM;
  6243. bool m_bIsLib;
  6244. };
  6245. void ResourceToHandle::initialize(Module &M) {
  6246. DXASSERT(M.HasHLModule(), "require HLModule");
  6247. m_pHLM = &M.GetHLModule();
  6248. m_HandleTy = m_pHLM->GetOP()->GetHandleType();
  6249. m_bIsLib = m_pHLM->GetShaderModel()->IsLib();
  6250. }
  6251. bool ResourceToHandle::needToLower(Value *V) {
  6252. Type *Ty = V->getType()->getPointerElementType();
  6253. Ty = dxilutil::GetArrayEltTy(Ty);
  6254. return (HLModule::IsHLSLObjectType(Ty) &&
  6255. !HLModule::IsStreamOutputType(Ty)) &&
  6256. // Skip lib profile.
  6257. !m_bIsLib;
  6258. }
  6259. Type *ResourceToHandle::lowerType(Type *Ty) {
  6260. if ((HLModule::IsHLSLObjectType(Ty) && !HLModule::IsStreamOutputType(Ty))) {
  6261. return m_HandleTy;
  6262. }
  6263. ArrayType *AT = cast<ArrayType>(Ty);
  6264. SmallVector<ArrayType *, 4> nestArrayTys;
  6265. nestArrayTys.emplace_back(AT);
  6266. Type *EltTy = AT->getElementType();
  6267. // support multi level of array
  6268. while (EltTy->isArrayTy()) {
  6269. ArrayType *ElAT = cast<ArrayType>(EltTy);
  6270. nestArrayTys.emplace_back(ElAT);
  6271. EltTy = ElAT->getElementType();
  6272. }
  6273. return CreateNestArrayTy(m_HandleTy, nestArrayTys);
  6274. }
  6275. Constant *ResourceToHandle::lowerInitVal(Constant *InitVal, Type *NewTy) {
  6276. DXASSERT(isa<UndefValue>(InitVal), "resource cannot have real init val");
  6277. return UndefValue::get(NewTy);
  6278. }
  6279. void ResourceToHandle::ReplaceResourceWithHandle(Value *ResPtr,
  6280. Value *HandlePtr) {
  6281. for (auto it = ResPtr->user_begin(); it != ResPtr->user_end();) {
  6282. User *U = *(it++);
  6283. if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
  6284. IRBuilder<> Builder(LI);
  6285. Value *Handle = Builder.CreateLoad(HandlePtr);
  6286. Type *ResTy = LI->getType();
  6287. // Used by createHandle or Store.
  6288. for (auto ldIt = LI->user_begin(); ldIt != LI->user_end();) {
  6289. User *ldU = *(ldIt++);
  6290. if (StoreInst *SI = dyn_cast<StoreInst>(ldU)) {
  6291. Value *TmpRes = HLModule::EmitHLOperationCall(
  6292. Builder, HLOpcodeGroup::HLCast,
  6293. (unsigned)HLCastOpcode::HandleToResCast, ResTy, {Handle},
  6294. *m_pHLM->GetModule());
  6295. SI->replaceUsesOfWith(LI, TmpRes);
  6296. } else {
  6297. CallInst *CI = cast<CallInst>(ldU);
  6298. DXASSERT(hlsl::GetHLOpcodeGroupByName(CI->getCalledFunction()) == HLOpcodeGroup::HLCreateHandle,
  6299. "must be createHandle");
  6300. CI->replaceAllUsesWith(Handle);
  6301. CI->eraseFromParent();
  6302. }
  6303. }
  6304. LI->eraseFromParent();
  6305. } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  6306. Value *Res = SI->getValueOperand();
  6307. IRBuilder<> Builder(SI);
  6308. // CreateHandle from Res.
  6309. Value *Handle = HLModule::EmitHLOperationCall(
  6310. Builder, HLOpcodeGroup::HLCreateHandle,
  6311. /*opcode*/ 0, m_HandleTy, {Res}, *m_pHLM->GetModule());
  6312. // Store Handle to HandlePtr.
  6313. Builder.CreateStore(Handle, HandlePtr);
  6314. // Remove resource Store.
  6315. SI->eraseFromParent();
  6316. } else if (U->user_empty() && isa<GEPOperator>(U)) {
  6317. continue;
  6318. } else {
  6319. CallInst *CI = cast<CallInst>(U);
  6320. IRBuilder<> Builder(CI);
  6321. HLOpcodeGroup group = GetHLOpcodeGroupByName(CI->getCalledFunction());
  6322. // Allow user function to use res ptr as argument.
  6323. if (group == HLOpcodeGroup::NotHL) {
  6324. Value *TmpResPtr = Builder.CreateBitCast(HandlePtr, ResPtr->getType());
  6325. CI->replaceUsesOfWith(ResPtr, TmpResPtr);
  6326. } else {
  6327. DXASSERT(0, "invalid operation on resource");
  6328. }
  6329. }
  6330. }
  6331. }
  6332. void ResourceToHandle::ReplaceResourceGEPWithHandleGEP(
  6333. Value *GEP, ArrayRef<Value *> idxList, Value *A, IRBuilder<> &Builder) {
  6334. Value *newGEP = Builder.CreateGEP(A, idxList);
  6335. Type *Ty = GEP->getType()->getPointerElementType();
  6336. if (Ty->isArrayTy()) {
  6337. ReplaceResourceArrayWithHandleArray(GEP, newGEP);
  6338. } else {
  6339. DXASSERT(HLModule::IsHLSLObjectType(Ty), "must be resource type here");
  6340. ReplaceResourceWithHandle(GEP, newGEP);
  6341. }
  6342. }
  6343. void ResourceToHandle::ReplaceResourceArrayWithHandleArray(Value *VA,
  6344. Value *A) {
  6345. for (auto U = VA->user_begin(); U != VA->user_end();) {
  6346. User *User = *(U++);
  6347. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
  6348. IRBuilder<> Builder(GEP);
  6349. SmallVector<Value *, 4> idxList(GEP->idx_begin(), GEP->idx_end());
  6350. ReplaceResourceGEPWithHandleGEP(GEP, idxList, A, Builder);
  6351. GEP->eraseFromParent();
  6352. } else if (GEPOperator *GEPOp = dyn_cast<GEPOperator>(User)) {
  6353. IRBuilder<> Builder(GEPOp->getContext());
  6354. SmallVector<Value *, 4> idxList(GEPOp->idx_begin(), GEPOp->idx_end());
  6355. ReplaceResourceGEPWithHandleGEP(GEPOp, idxList, A, Builder);
  6356. } else {
  6357. DXASSERT(0, "Array pointer should only used by GEP");
  6358. }
  6359. }
  6360. }
  6361. void ResourceToHandle::lowerUseWithNewValue(Value *V, Value *NewV) {
  6362. Type *Ty = V->getType()->getPointerElementType();
  6363. // Replace V with NewV.
  6364. if (Ty->isArrayTy()) {
  6365. ReplaceResourceArrayWithHandleArray(V, NewV);
  6366. } else {
  6367. ReplaceResourceWithHandle(V, NewV);
  6368. }
  6369. }
  6370. }
  6371. char ResourceToHandle::ID = 0;
  6372. INITIALIZE_PASS(ResourceToHandle, "resource-handle",
  6373. "Lower resource into handle", false,
  6374. false)
  6375. // Public interface to the ResourceToHandle pass
  6376. ModulePass *llvm::createResourceToHandlePass() {
  6377. return new ResourceToHandle();
  6378. }