CodeGenPrepare.cpp 274 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358
  1. //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This pass munges the code in the input function to better prepare it for
  10. // SelectionDAG-based code generation. This works around limitations in it's
  11. // basic-block-at-a-time approach. It should eventually be removed.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/ADT/APInt.h"
  15. #include "llvm/ADT/ArrayRef.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/MapVector.h"
  18. #include "llvm/ADT/PointerIntPair.h"
  19. #include "llvm/ADT/STLExtras.h"
  20. #include "llvm/ADT/SmallPtrSet.h"
  21. #include "llvm/ADT/SmallVector.h"
  22. #include "llvm/ADT/Statistic.h"
  23. #include "llvm/Analysis/BlockFrequencyInfo.h"
  24. #include "llvm/Analysis/BranchProbabilityInfo.h"
  25. #include "llvm/Analysis/ConstantFolding.h"
  26. #include "llvm/Analysis/InstructionSimplify.h"
  27. #include "llvm/Analysis/LoopInfo.h"
  28. #include "llvm/Analysis/MemoryBuiltins.h"
  29. #include "llvm/Analysis/ProfileSummaryInfo.h"
  30. #include "llvm/Analysis/TargetLibraryInfo.h"
  31. #include "llvm/Analysis/TargetTransformInfo.h"
  32. #include "llvm/Transforms/Utils/Local.h"
  33. #include "llvm/Analysis/ValueTracking.h"
  34. #include "llvm/Analysis/VectorUtils.h"
  35. #include "llvm/CodeGen/Analysis.h"
  36. #include "llvm/CodeGen/ISDOpcodes.h"
  37. #include "llvm/CodeGen/SelectionDAGNodes.h"
  38. #include "llvm/CodeGen/TargetLowering.h"
  39. #include "llvm/CodeGen/TargetPassConfig.h"
  40. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  41. #include "llvm/CodeGen/ValueTypes.h"
  42. #include "llvm/Config/llvm-config.h"
  43. #include "llvm/IR/Argument.h"
  44. #include "llvm/IR/Attributes.h"
  45. #include "llvm/IR/BasicBlock.h"
  46. #include "llvm/IR/CallSite.h"
  47. #include "llvm/IR/Constant.h"
  48. #include "llvm/IR/Constants.h"
  49. #include "llvm/IR/DataLayout.h"
  50. #include "llvm/IR/DerivedTypes.h"
  51. #include "llvm/IR/Dominators.h"
  52. #include "llvm/IR/Function.h"
  53. #include "llvm/IR/GetElementPtrTypeIterator.h"
  54. #include "llvm/IR/GlobalValue.h"
  55. #include "llvm/IR/GlobalVariable.h"
  56. #include "llvm/IR/IRBuilder.h"
  57. #include "llvm/IR/InlineAsm.h"
  58. #include "llvm/IR/InstrTypes.h"
  59. #include "llvm/IR/Instruction.h"
  60. #include "llvm/IR/Instructions.h"
  61. #include "llvm/IR/IntrinsicInst.h"
  62. #include "llvm/IR/Intrinsics.h"
  63. #include "llvm/IR/LLVMContext.h"
  64. #include "llvm/IR/MDBuilder.h"
  65. #include "llvm/IR/Module.h"
  66. #include "llvm/IR/Operator.h"
  67. #include "llvm/IR/PatternMatch.h"
  68. #include "llvm/IR/Statepoint.h"
  69. #include "llvm/IR/Type.h"
  70. #include "llvm/IR/Use.h"
  71. #include "llvm/IR/User.h"
  72. #include "llvm/IR/Value.h"
  73. #include "llvm/IR/ValueHandle.h"
  74. #include "llvm/IR/ValueMap.h"
  75. #include "llvm/Pass.h"
  76. #include "llvm/Support/BlockFrequency.h"
  77. #include "llvm/Support/BranchProbability.h"
  78. #include "llvm/Support/Casting.h"
  79. #include "llvm/Support/CommandLine.h"
  80. #include "llvm/Support/Compiler.h"
  81. #include "llvm/Support/Debug.h"
  82. #include "llvm/Support/ErrorHandling.h"
  83. #include "llvm/Support/MachineValueType.h"
  84. #include "llvm/Support/MathExtras.h"
  85. #include "llvm/Support/raw_ostream.h"
  86. #include "llvm/Target/TargetMachine.h"
  87. #include "llvm/Target/TargetOptions.h"
  88. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  89. #include "llvm/Transforms/Utils/BypassSlowDivision.h"
  90. #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
  91. #include <algorithm>
  92. #include <cassert>
  93. #include <cstdint>
  94. #include <iterator>
  95. #include <limits>
  96. #include <memory>
  97. #include <utility>
  98. #include <vector>
  99. using namespace llvm;
  100. using namespace llvm::PatternMatch;
  101. #define DEBUG_TYPE "codegenprepare"
  102. STATISTIC(NumBlocksElim, "Number of blocks eliminated");
  103. STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
  104. STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
  105. STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
  106. "sunken Cmps");
  107. STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
  108. "of sunken Casts");
  109. STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
  110. "computations were sunk");
  111. STATISTIC(NumMemoryInstsPhiCreated,
  112. "Number of phis created when address "
  113. "computations were sunk to memory instructions");
  114. STATISTIC(NumMemoryInstsSelectCreated,
  115. "Number of select created when address "
  116. "computations were sunk to memory instructions");
  117. STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
  118. STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
  119. STATISTIC(NumAndsAdded,
  120. "Number of and mask instructions added to form ext loads");
  121. STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
  122. STATISTIC(NumRetsDup, "Number of return instructions duplicated");
  123. STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
  124. STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
  125. STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
  126. static cl::opt<bool> DisableBranchOpts(
  127. "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
  128. cl::desc("Disable branch optimizations in CodeGenPrepare"));
  129. static cl::opt<bool>
  130. DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
  131. cl::desc("Disable GC optimizations in CodeGenPrepare"));
  132. static cl::opt<bool> DisableSelectToBranch(
  133. "disable-cgp-select2branch", cl::Hidden, cl::init(false),
  134. cl::desc("Disable select to branch conversion."));
  135. static cl::opt<bool> AddrSinkUsingGEPs(
  136. "addr-sink-using-gep", cl::Hidden, cl::init(true),
  137. cl::desc("Address sinking in CGP using GEPs."));
  138. static cl::opt<bool> EnableAndCmpSinking(
  139. "enable-andcmp-sinking", cl::Hidden, cl::init(true),
  140. cl::desc("Enable sinkinig and/cmp into branches."));
  141. static cl::opt<bool> DisableStoreExtract(
  142. "disable-cgp-store-extract", cl::Hidden, cl::init(false),
  143. cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
  144. static cl::opt<bool> StressStoreExtract(
  145. "stress-cgp-store-extract", cl::Hidden, cl::init(false),
  146. cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
  147. static cl::opt<bool> DisableExtLdPromotion(
  148. "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
  149. cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
  150. "CodeGenPrepare"));
  151. static cl::opt<bool> StressExtLdPromotion(
  152. "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
  153. cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
  154. "optimization in CodeGenPrepare"));
  155. static cl::opt<bool> DisablePreheaderProtect(
  156. "disable-preheader-prot", cl::Hidden, cl::init(false),
  157. cl::desc("Disable protection against removing loop preheaders"));
  158. static cl::opt<bool> ProfileGuidedSectionPrefix(
  159. "profile-guided-section-prefix", cl::Hidden, cl::init(true), cl::ZeroOrMore,
  160. cl::desc("Use profile info to add section prefix for hot/cold functions"));
  161. static cl::opt<unsigned> FreqRatioToSkipMerge(
  162. "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
  163. cl::desc("Skip merging empty blocks if (frequency of empty block) / "
  164. "(frequency of destination block) is greater than this ratio"));
  165. static cl::opt<bool> ForceSplitStore(
  166. "force-split-store", cl::Hidden, cl::init(false),
  167. cl::desc("Force store splitting no matter what the target query says."));
  168. static cl::opt<bool>
  169. EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden,
  170. cl::desc("Enable merging of redundant sexts when one is dominating"
  171. " the other."), cl::init(true));
  172. static cl::opt<bool> DisableComplexAddrModes(
  173. "disable-complex-addr-modes", cl::Hidden, cl::init(false),
  174. cl::desc("Disables combining addressing modes with different parts "
  175. "in optimizeMemoryInst."));
  176. static cl::opt<bool>
  177. AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false),
  178. cl::desc("Allow creation of Phis in Address sinking."));
  179. static cl::opt<bool>
  180. AddrSinkNewSelects("addr-sink-new-select", cl::Hidden, cl::init(true),
  181. cl::desc("Allow creation of selects in Address sinking."));
  182. static cl::opt<bool> AddrSinkCombineBaseReg(
  183. "addr-sink-combine-base-reg", cl::Hidden, cl::init(true),
  184. cl::desc("Allow combining of BaseReg field in Address sinking."));
  185. static cl::opt<bool> AddrSinkCombineBaseGV(
  186. "addr-sink-combine-base-gv", cl::Hidden, cl::init(true),
  187. cl::desc("Allow combining of BaseGV field in Address sinking."));
  188. static cl::opt<bool> AddrSinkCombineBaseOffs(
  189. "addr-sink-combine-base-offs", cl::Hidden, cl::init(true),
  190. cl::desc("Allow combining of BaseOffs field in Address sinking."));
  191. static cl::opt<bool> AddrSinkCombineScaledReg(
  192. "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true),
  193. cl::desc("Allow combining of ScaledReg field in Address sinking."));
  194. static cl::opt<bool>
  195. EnableGEPOffsetSplit("cgp-split-large-offset-gep", cl::Hidden,
  196. cl::init(true),
  197. cl::desc("Enable splitting large offset of GEP."));
  198. namespace {
  199. enum ExtType {
  200. ZeroExtension, // Zero extension has been seen.
  201. SignExtension, // Sign extension has been seen.
  202. BothExtension // This extension type is used if we saw sext after
  203. // ZeroExtension had been set, or if we saw zext after
  204. // SignExtension had been set. It makes the type
  205. // information of a promoted instruction invalid.
  206. };
  207. using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
  208. using TypeIsSExt = PointerIntPair<Type *, 2, ExtType>;
  209. using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
  210. using SExts = SmallVector<Instruction *, 16>;
  211. using ValueToSExts = DenseMap<Value *, SExts>;
  212. class TypePromotionTransaction;
  213. class CodeGenPrepare : public FunctionPass {
  214. const TargetMachine *TM = nullptr;
  215. const TargetSubtargetInfo *SubtargetInfo;
  216. const TargetLowering *TLI = nullptr;
  217. const TargetRegisterInfo *TRI;
  218. const TargetTransformInfo *TTI = nullptr;
  219. const TargetLibraryInfo *TLInfo;
  220. const LoopInfo *LI;
  221. std::unique_ptr<BlockFrequencyInfo> BFI;
  222. std::unique_ptr<BranchProbabilityInfo> BPI;
  223. /// As we scan instructions optimizing them, this is the next instruction
  224. /// to optimize. Transforms that can invalidate this should update it.
  225. BasicBlock::iterator CurInstIterator;
  226. /// Keeps track of non-local addresses that have been sunk into a block.
  227. /// This allows us to avoid inserting duplicate code for blocks with
  228. /// multiple load/stores of the same address. The usage of WeakTrackingVH
  229. /// enables SunkAddrs to be treated as a cache whose entries can be
  230. /// invalidated if a sunken address computation has been erased.
  231. ValueMap<Value*, WeakTrackingVH> SunkAddrs;
  232. /// Keeps track of all instructions inserted for the current function.
  233. SetOfInstrs InsertedInsts;
  234. /// Keeps track of the type of the related instruction before their
  235. /// promotion for the current function.
  236. InstrToOrigTy PromotedInsts;
  237. /// Keep track of instructions removed during promotion.
  238. SetOfInstrs RemovedInsts;
  239. /// Keep track of sext chains based on their initial value.
  240. DenseMap<Value *, Instruction *> SeenChainsForSExt;
  241. /// Keep track of GEPs accessing the same data structures such as structs or
  242. /// arrays that are candidates to be split later because of their large
  243. /// size.
  244. MapVector<
  245. AssertingVH<Value>,
  246. SmallVector<std::pair<AssertingVH<GetElementPtrInst>, int64_t>, 32>>
  247. LargeOffsetGEPMap;
  248. /// Keep track of new GEP base after splitting the GEPs having large offset.
  249. SmallSet<AssertingVH<Value>, 2> NewGEPBases;
  250. /// Map serial numbers to Large offset GEPs.
  251. DenseMap<AssertingVH<GetElementPtrInst>, int> LargeOffsetGEPID;
  252. /// Keep track of SExt promoted.
  253. ValueToSExts ValToSExtendedUses;
  254. /// True if optimizing for size.
  255. bool OptSize;
  256. /// DataLayout for the Function being processed.
  257. const DataLayout *DL = nullptr;
  258. /// Building the dominator tree can be expensive, so we only build it
  259. /// lazily and update it when required.
  260. std::unique_ptr<DominatorTree> DT;
  261. public:
  262. static char ID; // Pass identification, replacement for typeid
  263. CodeGenPrepare() : FunctionPass(ID) {
  264. initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
  265. }
  266. bool runOnFunction(Function &F) override;
  267. StringRef getPassName() const override { return "CodeGen Prepare"; }
  268. void getAnalysisUsage(AnalysisUsage &AU) const override {
  269. // FIXME: When we can selectively preserve passes, preserve the domtree.
  270. AU.addRequired<ProfileSummaryInfoWrapperPass>();
  271. AU.addRequired<TargetLibraryInfoWrapperPass>();
  272. AU.addRequired<TargetTransformInfoWrapperPass>();
  273. AU.addRequired<LoopInfoWrapperPass>();
  274. }
  275. private:
  276. template <typename F>
  277. void resetIteratorIfInvalidatedWhileCalling(BasicBlock *BB, F f) {
  278. // Substituting can cause recursive simplifications, which can invalidate
  279. // our iterator. Use a WeakTrackingVH to hold onto it in case this
  280. // happens.
  281. Value *CurValue = &*CurInstIterator;
  282. WeakTrackingVH IterHandle(CurValue);
  283. f();
  284. // If the iterator instruction was recursively deleted, start over at the
  285. // start of the block.
  286. if (IterHandle != CurValue) {
  287. CurInstIterator = BB->begin();
  288. SunkAddrs.clear();
  289. }
  290. }
  291. // Get the DominatorTree, building if necessary.
  292. DominatorTree &getDT(Function &F) {
  293. if (!DT)
  294. DT = std::make_unique<DominatorTree>(F);
  295. return *DT;
  296. }
  297. bool eliminateFallThrough(Function &F);
  298. bool eliminateMostlyEmptyBlocks(Function &F);
  299. BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
  300. bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
  301. void eliminateMostlyEmptyBlock(BasicBlock *BB);
  302. bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
  303. bool isPreheader);
  304. bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT);
  305. bool optimizeInst(Instruction *I, bool &ModifiedDT);
  306. bool optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
  307. Type *AccessTy, unsigned AddrSpace);
  308. bool optimizeInlineAsmInst(CallInst *CS);
  309. bool optimizeCallInst(CallInst *CI, bool &ModifiedDT);
  310. bool optimizeExt(Instruction *&I);
  311. bool optimizeExtUses(Instruction *I);
  312. bool optimizeLoadExt(LoadInst *Load);
  313. bool optimizeShiftInst(BinaryOperator *BO);
  314. bool optimizeSelectInst(SelectInst *SI);
  315. bool optimizeShuffleVectorInst(ShuffleVectorInst *SVI);
  316. bool optimizeSwitchInst(SwitchInst *SI);
  317. bool optimizeExtractElementInst(Instruction *Inst);
  318. bool dupRetToEnableTailCallOpts(BasicBlock *BB, bool &ModifiedDT);
  319. bool placeDbgValues(Function &F);
  320. bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
  321. LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
  322. bool tryToPromoteExts(TypePromotionTransaction &TPT,
  323. const SmallVectorImpl<Instruction *> &Exts,
  324. SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
  325. unsigned CreatedInstsCost = 0);
  326. bool mergeSExts(Function &F);
  327. bool splitLargeGEPOffsets();
  328. bool performAddressTypePromotion(
  329. Instruction *&Inst,
  330. bool AllowPromotionWithoutCommonHeader,
  331. bool HasPromoted, TypePromotionTransaction &TPT,
  332. SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
  333. bool splitBranchCondition(Function &F, bool &ModifiedDT);
  334. bool simplifyOffsetableRelocate(Instruction &I);
  335. bool tryToSinkFreeOperands(Instruction *I);
  336. bool replaceMathCmpWithIntrinsic(BinaryOperator *BO, CmpInst *Cmp,
  337. Intrinsic::ID IID);
  338. bool optimizeCmp(CmpInst *Cmp, bool &ModifiedDT);
  339. bool combineToUSubWithOverflow(CmpInst *Cmp, bool &ModifiedDT);
  340. bool combineToUAddWithOverflow(CmpInst *Cmp, bool &ModifiedDT);
  341. };
  342. } // end anonymous namespace
  343. char CodeGenPrepare::ID = 0;
  344. INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE,
  345. "Optimize for code generation", false, false)
  346. INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
  347. INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE,
  348. "Optimize for code generation", false, false)
  349. FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); }
  350. bool CodeGenPrepare::runOnFunction(Function &F) {
  351. if (skipFunction(F))
  352. return false;
  353. DL = &F.getParent()->getDataLayout();
  354. bool EverMadeChange = false;
  355. // Clear per function information.
  356. InsertedInsts.clear();
  357. PromotedInsts.clear();
  358. if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
  359. TM = &TPC->getTM<TargetMachine>();
  360. SubtargetInfo = TM->getSubtargetImpl(F);
  361. TLI = SubtargetInfo->getTargetLowering();
  362. TRI = SubtargetInfo->getRegisterInfo();
  363. }
  364. TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
  365. TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  366. LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  367. BPI.reset(new BranchProbabilityInfo(F, *LI));
  368. BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI));
  369. OptSize = F.hasOptSize();
  370. ProfileSummaryInfo *PSI =
  371. &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
  372. if (ProfileGuidedSectionPrefix) {
  373. if (PSI->isFunctionHotInCallGraph(&F, *BFI))
  374. F.setSectionPrefix(".hot");
  375. else if (PSI->isFunctionColdInCallGraph(&F, *BFI))
  376. F.setSectionPrefix(".unlikely");
  377. }
  378. /// This optimization identifies DIV instructions that can be
  379. /// profitably bypassed and carried out with a shorter, faster divide.
  380. if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI &&
  381. TLI->isSlowDivBypassed()) {
  382. const DenseMap<unsigned int, unsigned int> &BypassWidths =
  383. TLI->getBypassSlowDivWidths();
  384. BasicBlock* BB = &*F.begin();
  385. while (BB != nullptr) {
  386. // bypassSlowDivision may create new BBs, but we don't want to reapply the
  387. // optimization to those blocks.
  388. BasicBlock* Next = BB->getNextNode();
  389. EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
  390. BB = Next;
  391. }
  392. }
  393. // Eliminate blocks that contain only PHI nodes and an
  394. // unconditional branch.
  395. EverMadeChange |= eliminateMostlyEmptyBlocks(F);
  396. bool ModifiedDT = false;
  397. if (!DisableBranchOpts)
  398. EverMadeChange |= splitBranchCondition(F, ModifiedDT);
  399. // Split some critical edges where one of the sources is an indirect branch,
  400. // to help generate sane code for PHIs involving such edges.
  401. EverMadeChange |= SplitIndirectBrCriticalEdges(F);
  402. bool MadeChange = true;
  403. while (MadeChange) {
  404. MadeChange = false;
  405. DT.reset();
  406. for (Function::iterator I = F.begin(); I != F.end(); ) {
  407. BasicBlock *BB = &*I++;
  408. bool ModifiedDTOnIteration = false;
  409. MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
  410. // Restart BB iteration if the dominator tree of the Function was changed
  411. if (ModifiedDTOnIteration)
  412. break;
  413. }
  414. if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
  415. MadeChange |= mergeSExts(F);
  416. if (!LargeOffsetGEPMap.empty())
  417. MadeChange |= splitLargeGEPOffsets();
  418. // Really free removed instructions during promotion.
  419. for (Instruction *I : RemovedInsts)
  420. I->deleteValue();
  421. EverMadeChange |= MadeChange;
  422. SeenChainsForSExt.clear();
  423. ValToSExtendedUses.clear();
  424. RemovedInsts.clear();
  425. LargeOffsetGEPMap.clear();
  426. LargeOffsetGEPID.clear();
  427. }
  428. SunkAddrs.clear();
  429. if (!DisableBranchOpts) {
  430. MadeChange = false;
  431. // Use a set vector to get deterministic iteration order. The order the
  432. // blocks are removed may affect whether or not PHI nodes in successors
  433. // are removed.
  434. SmallSetVector<BasicBlock*, 8> WorkList;
  435. for (BasicBlock &BB : F) {
  436. SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
  437. MadeChange |= ConstantFoldTerminator(&BB, true);
  438. if (!MadeChange) continue;
  439. for (SmallVectorImpl<BasicBlock*>::iterator
  440. II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
  441. if (pred_begin(*II) == pred_end(*II))
  442. WorkList.insert(*II);
  443. }
  444. // Delete the dead blocks and any of their dead successors.
  445. MadeChange |= !WorkList.empty();
  446. while (!WorkList.empty()) {
  447. BasicBlock *BB = WorkList.pop_back_val();
  448. SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
  449. DeleteDeadBlock(BB);
  450. for (SmallVectorImpl<BasicBlock*>::iterator
  451. II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
  452. if (pred_begin(*II) == pred_end(*II))
  453. WorkList.insert(*II);
  454. }
  455. // Merge pairs of basic blocks with unconditional branches, connected by
  456. // a single edge.
  457. if (EverMadeChange || MadeChange)
  458. MadeChange |= eliminateFallThrough(F);
  459. EverMadeChange |= MadeChange;
  460. }
  461. if (!DisableGCOpts) {
  462. SmallVector<Instruction *, 2> Statepoints;
  463. for (BasicBlock &BB : F)
  464. for (Instruction &I : BB)
  465. if (isStatepoint(I))
  466. Statepoints.push_back(&I);
  467. for (auto &I : Statepoints)
  468. EverMadeChange |= simplifyOffsetableRelocate(*I);
  469. }
  470. // Do this last to clean up use-before-def scenarios introduced by other
  471. // preparatory transforms.
  472. EverMadeChange |= placeDbgValues(F);
  473. return EverMadeChange;
  474. }
  475. /// Merge basic blocks which are connected by a single edge, where one of the
  476. /// basic blocks has a single successor pointing to the other basic block,
  477. /// which has a single predecessor.
  478. bool CodeGenPrepare::eliminateFallThrough(Function &F) {
  479. bool Changed = false;
  480. // Scan all of the blocks in the function, except for the entry block.
  481. // Use a temporary array to avoid iterator being invalidated when
  482. // deleting blocks.
  483. SmallVector<WeakTrackingVH, 16> Blocks;
  484. for (auto &Block : llvm::make_range(std::next(F.begin()), F.end()))
  485. Blocks.push_back(&Block);
  486. for (auto &Block : Blocks) {
  487. auto *BB = cast_or_null<BasicBlock>(Block);
  488. if (!BB)
  489. continue;
  490. // If the destination block has a single pred, then this is a trivial
  491. // edge, just collapse it.
  492. BasicBlock *SinglePred = BB->getSinglePredecessor();
  493. // Don't merge if BB's address is taken.
  494. if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
  495. BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
  496. if (Term && !Term->isConditional()) {
  497. Changed = true;
  498. LLVM_DEBUG(dbgs() << "To merge:\n" << *BB << "\n\n\n");
  499. // Merge BB into SinglePred and delete it.
  500. MergeBlockIntoPredecessor(BB);
  501. }
  502. }
  503. return Changed;
  504. }
  505. /// Find a destination block from BB if BB is mergeable empty block.
  506. BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
  507. // If this block doesn't end with an uncond branch, ignore it.
  508. BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
  509. if (!BI || !BI->isUnconditional())
  510. return nullptr;
  511. // If the instruction before the branch (skipping debug info) isn't a phi
  512. // node, then other stuff is happening here.
  513. BasicBlock::iterator BBI = BI->getIterator();
  514. if (BBI != BB->begin()) {
  515. --BBI;
  516. while (isa<DbgInfoIntrinsic>(BBI)) {
  517. if (BBI == BB->begin())
  518. break;
  519. --BBI;
  520. }
  521. if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
  522. return nullptr;
  523. }
  524. // Do not break infinite loops.
  525. BasicBlock *DestBB = BI->getSuccessor(0);
  526. if (DestBB == BB)
  527. return nullptr;
  528. if (!canMergeBlocks(BB, DestBB))
  529. DestBB = nullptr;
  530. return DestBB;
  531. }
  532. /// Eliminate blocks that contain only PHI nodes, debug info directives, and an
  533. /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
  534. /// edges in ways that are non-optimal for isel. Start by eliminating these
  535. /// blocks so we can split them the way we want them.
  536. bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
  537. SmallPtrSet<BasicBlock *, 16> Preheaders;
  538. SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
  539. while (!LoopList.empty()) {
  540. Loop *L = LoopList.pop_back_val();
  541. LoopList.insert(LoopList.end(), L->begin(), L->end());
  542. if (BasicBlock *Preheader = L->getLoopPreheader())
  543. Preheaders.insert(Preheader);
  544. }
  545. bool MadeChange = false;
  546. // Copy blocks into a temporary array to avoid iterator invalidation issues
  547. // as we remove them.
  548. // Note that this intentionally skips the entry block.
  549. SmallVector<WeakTrackingVH, 16> Blocks;
  550. for (auto &Block : llvm::make_range(std::next(F.begin()), F.end()))
  551. Blocks.push_back(&Block);
  552. for (auto &Block : Blocks) {
  553. BasicBlock *BB = cast_or_null<BasicBlock>(Block);
  554. if (!BB)
  555. continue;
  556. BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
  557. if (!DestBB ||
  558. !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
  559. continue;
  560. eliminateMostlyEmptyBlock(BB);
  561. MadeChange = true;
  562. }
  563. return MadeChange;
  564. }
  565. bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
  566. BasicBlock *DestBB,
  567. bool isPreheader) {
  568. // Do not delete loop preheaders if doing so would create a critical edge.
  569. // Loop preheaders can be good locations to spill registers. If the
  570. // preheader is deleted and we create a critical edge, registers may be
  571. // spilled in the loop body instead.
  572. if (!DisablePreheaderProtect && isPreheader &&
  573. !(BB->getSinglePredecessor() &&
  574. BB->getSinglePredecessor()->getSingleSuccessor()))
  575. return false;
  576. // Skip merging if the block's successor is also a successor to any callbr
  577. // that leads to this block.
  578. // FIXME: Is this really needed? Is this a correctness issue?
  579. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
  580. if (auto *CBI = dyn_cast<CallBrInst>((*PI)->getTerminator()))
  581. for (unsigned i = 0, e = CBI->getNumSuccessors(); i != e; ++i)
  582. if (DestBB == CBI->getSuccessor(i))
  583. return false;
  584. }
  585. // Try to skip merging if the unique predecessor of BB is terminated by a
  586. // switch or indirect branch instruction, and BB is used as an incoming block
  587. // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
  588. // add COPY instructions in the predecessor of BB instead of BB (if it is not
  589. // merged). Note that the critical edge created by merging such blocks wont be
  590. // split in MachineSink because the jump table is not analyzable. By keeping
  591. // such empty block (BB), ISel will place COPY instructions in BB, not in the
  592. // predecessor of BB.
  593. BasicBlock *Pred = BB->getUniquePredecessor();
  594. if (!Pred ||
  595. !(isa<SwitchInst>(Pred->getTerminator()) ||
  596. isa<IndirectBrInst>(Pred->getTerminator())))
  597. return true;
  598. if (BB->getTerminator() != BB->getFirstNonPHIOrDbg())
  599. return true;
  600. // We use a simple cost heuristic which determine skipping merging is
  601. // profitable if the cost of skipping merging is less than the cost of
  602. // merging : Cost(skipping merging) < Cost(merging BB), where the
  603. // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
  604. // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
  605. // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
  606. // Freq(Pred) / Freq(BB) > 2.
  607. // Note that if there are multiple empty blocks sharing the same incoming
  608. // value for the PHIs in the DestBB, we consider them together. In such
  609. // case, Cost(merging BB) will be the sum of their frequencies.
  610. if (!isa<PHINode>(DestBB->begin()))
  611. return true;
  612. SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
  613. // Find all other incoming blocks from which incoming values of all PHIs in
  614. // DestBB are the same as the ones from BB.
  615. for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
  616. ++PI) {
  617. BasicBlock *DestBBPred = *PI;
  618. if (DestBBPred == BB)
  619. continue;
  620. if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) {
  621. return DestPN.getIncomingValueForBlock(BB) ==
  622. DestPN.getIncomingValueForBlock(DestBBPred);
  623. }))
  624. SameIncomingValueBBs.insert(DestBBPred);
  625. }
  626. // See if all BB's incoming values are same as the value from Pred. In this
  627. // case, no reason to skip merging because COPYs are expected to be place in
  628. // Pred already.
  629. if (SameIncomingValueBBs.count(Pred))
  630. return true;
  631. BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
  632. BlockFrequency BBFreq = BFI->getBlockFreq(BB);
  633. for (auto SameValueBB : SameIncomingValueBBs)
  634. if (SameValueBB->getUniquePredecessor() == Pred &&
  635. DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
  636. BBFreq += BFI->getBlockFreq(SameValueBB);
  637. return PredFreq.getFrequency() <=
  638. BBFreq.getFrequency() * FreqRatioToSkipMerge;
  639. }
  640. /// Return true if we can merge BB into DestBB if there is a single
  641. /// unconditional branch between them, and BB contains no other non-phi
  642. /// instructions.
  643. bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
  644. const BasicBlock *DestBB) const {
  645. // We only want to eliminate blocks whose phi nodes are used by phi nodes in
  646. // the successor. If there are more complex condition (e.g. preheaders),
  647. // don't mess around with them.
  648. for (const PHINode &PN : BB->phis()) {
  649. for (const User *U : PN.users()) {
  650. const Instruction *UI = cast<Instruction>(U);
  651. if (UI->getParent() != DestBB || !isa<PHINode>(UI))
  652. return false;
  653. // If User is inside DestBB block and it is a PHINode then check
  654. // incoming value. If incoming value is not from BB then this is
  655. // a complex condition (e.g. preheaders) we want to avoid here.
  656. if (UI->getParent() == DestBB) {
  657. if (const PHINode *UPN = dyn_cast<PHINode>(UI))
  658. for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
  659. Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
  660. if (Insn && Insn->getParent() == BB &&
  661. Insn->getParent() != UPN->getIncomingBlock(I))
  662. return false;
  663. }
  664. }
  665. }
  666. }
  667. // If BB and DestBB contain any common predecessors, then the phi nodes in BB
  668. // and DestBB may have conflicting incoming values for the block. If so, we
  669. // can't merge the block.
  670. const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
  671. if (!DestBBPN) return true; // no conflict.
  672. // Collect the preds of BB.
  673. SmallPtrSet<const BasicBlock*, 16> BBPreds;
  674. if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
  675. // It is faster to get preds from a PHI than with pred_iterator.
  676. for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
  677. BBPreds.insert(BBPN->getIncomingBlock(i));
  678. } else {
  679. BBPreds.insert(pred_begin(BB), pred_end(BB));
  680. }
  681. // Walk the preds of DestBB.
  682. for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
  683. BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
  684. if (BBPreds.count(Pred)) { // Common predecessor?
  685. for (const PHINode &PN : DestBB->phis()) {
  686. const Value *V1 = PN.getIncomingValueForBlock(Pred);
  687. const Value *V2 = PN.getIncomingValueForBlock(BB);
  688. // If V2 is a phi node in BB, look up what the mapped value will be.
  689. if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
  690. if (V2PN->getParent() == BB)
  691. V2 = V2PN->getIncomingValueForBlock(Pred);
  692. // If there is a conflict, bail out.
  693. if (V1 != V2) return false;
  694. }
  695. }
  696. }
  697. return true;
  698. }
  699. /// Eliminate a basic block that has only phi's and an unconditional branch in
  700. /// it.
  701. void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
  702. BranchInst *BI = cast<BranchInst>(BB->getTerminator());
  703. BasicBlock *DestBB = BI->getSuccessor(0);
  704. LLVM_DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n"
  705. << *BB << *DestBB);
  706. // If the destination block has a single pred, then this is a trivial edge,
  707. // just collapse it.
  708. if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
  709. if (SinglePred != DestBB) {
  710. assert(SinglePred == BB &&
  711. "Single predecessor not the same as predecessor");
  712. // Merge DestBB into SinglePred/BB and delete it.
  713. MergeBlockIntoPredecessor(DestBB);
  714. // Note: BB(=SinglePred) will not be deleted on this path.
  715. // DestBB(=its single successor) is the one that was deleted.
  716. LLVM_DEBUG(dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n");
  717. return;
  718. }
  719. }
  720. // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
  721. // to handle the new incoming edges it is about to have.
  722. for (PHINode &PN : DestBB->phis()) {
  723. // Remove the incoming value for BB, and remember it.
  724. Value *InVal = PN.removeIncomingValue(BB, false);
  725. // Two options: either the InVal is a phi node defined in BB or it is some
  726. // value that dominates BB.
  727. PHINode *InValPhi = dyn_cast<PHINode>(InVal);
  728. if (InValPhi && InValPhi->getParent() == BB) {
  729. // Add all of the input values of the input PHI as inputs of this phi.
  730. for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
  731. PN.addIncoming(InValPhi->getIncomingValue(i),
  732. InValPhi->getIncomingBlock(i));
  733. } else {
  734. // Otherwise, add one instance of the dominating value for each edge that
  735. // we will be adding.
  736. if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
  737. for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
  738. PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
  739. } else {
  740. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
  741. PN.addIncoming(InVal, *PI);
  742. }
  743. }
  744. }
  745. // The PHIs are now updated, change everything that refers to BB to use
  746. // DestBB and remove BB.
  747. BB->replaceAllUsesWith(DestBB);
  748. BB->eraseFromParent();
  749. ++NumBlocksElim;
  750. LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
  751. }
  752. // Computes a map of base pointer relocation instructions to corresponding
  753. // derived pointer relocation instructions given a vector of all relocate calls
  754. static void computeBaseDerivedRelocateMap(
  755. const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
  756. DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
  757. &RelocateInstMap) {
  758. // Collect information in two maps: one primarily for locating the base object
  759. // while filling the second map; the second map is the final structure holding
  760. // a mapping between Base and corresponding Derived relocate calls
  761. DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
  762. for (auto *ThisRelocate : AllRelocateCalls) {
  763. auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
  764. ThisRelocate->getDerivedPtrIndex());
  765. RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
  766. }
  767. for (auto &Item : RelocateIdxMap) {
  768. std::pair<unsigned, unsigned> Key = Item.first;
  769. if (Key.first == Key.second)
  770. // Base relocation: nothing to insert
  771. continue;
  772. GCRelocateInst *I = Item.second;
  773. auto BaseKey = std::make_pair(Key.first, Key.first);
  774. // We're iterating over RelocateIdxMap so we cannot modify it.
  775. auto MaybeBase = RelocateIdxMap.find(BaseKey);
  776. if (MaybeBase == RelocateIdxMap.end())
  777. // TODO: We might want to insert a new base object relocate and gep off
  778. // that, if there are enough derived object relocates.
  779. continue;
  780. RelocateInstMap[MaybeBase->second].push_back(I);
  781. }
  782. }
  783. // Accepts a GEP and extracts the operands into a vector provided they're all
  784. // small integer constants
  785. static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
  786. SmallVectorImpl<Value *> &OffsetV) {
  787. for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
  788. // Only accept small constant integer operands
  789. auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
  790. if (!Op || Op->getZExtValue() > 20)
  791. return false;
  792. }
  793. for (unsigned i = 1; i < GEP->getNumOperands(); i++)
  794. OffsetV.push_back(GEP->getOperand(i));
  795. return true;
  796. }
  797. // Takes a RelocatedBase (base pointer relocation instruction) and Targets to
  798. // replace, computes a replacement, and affects it.
  799. static bool
  800. simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
  801. const SmallVectorImpl<GCRelocateInst *> &Targets) {
  802. bool MadeChange = false;
  803. // We must ensure the relocation of derived pointer is defined after
  804. // relocation of base pointer. If we find a relocation corresponding to base
  805. // defined earlier than relocation of base then we move relocation of base
  806. // right before found relocation. We consider only relocation in the same
  807. // basic block as relocation of base. Relocations from other basic block will
  808. // be skipped by optimization and we do not care about them.
  809. for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
  810. &*R != RelocatedBase; ++R)
  811. if (auto RI = dyn_cast<GCRelocateInst>(R))
  812. if (RI->getStatepoint() == RelocatedBase->getStatepoint())
  813. if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
  814. RelocatedBase->moveBefore(RI);
  815. break;
  816. }
  817. for (GCRelocateInst *ToReplace : Targets) {
  818. assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
  819. "Not relocating a derived object of the original base object");
  820. if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
  821. // A duplicate relocate call. TODO: coalesce duplicates.
  822. continue;
  823. }
  824. if (RelocatedBase->getParent() != ToReplace->getParent()) {
  825. // Base and derived relocates are in different basic blocks.
  826. // In this case transform is only valid when base dominates derived
  827. // relocate. However it would be too expensive to check dominance
  828. // for each such relocate, so we skip the whole transformation.
  829. continue;
  830. }
  831. Value *Base = ToReplace->getBasePtr();
  832. auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
  833. if (!Derived || Derived->getPointerOperand() != Base)
  834. continue;
  835. SmallVector<Value *, 2> OffsetV;
  836. if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
  837. continue;
  838. // Create a Builder and replace the target callsite with a gep
  839. assert(RelocatedBase->getNextNode() &&
  840. "Should always have one since it's not a terminator");
  841. // Insert after RelocatedBase
  842. IRBuilder<> Builder(RelocatedBase->getNextNode());
  843. Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
  844. // If gc_relocate does not match the actual type, cast it to the right type.
  845. // In theory, there must be a bitcast after gc_relocate if the type does not
  846. // match, and we should reuse it to get the derived pointer. But it could be
  847. // cases like this:
  848. // bb1:
  849. // ...
  850. // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
  851. // br label %merge
  852. //
  853. // bb2:
  854. // ...
  855. // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
  856. // br label %merge
  857. //
  858. // merge:
  859. // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
  860. // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
  861. //
  862. // In this case, we can not find the bitcast any more. So we insert a new bitcast
  863. // no matter there is already one or not. In this way, we can handle all cases, and
  864. // the extra bitcast should be optimized away in later passes.
  865. Value *ActualRelocatedBase = RelocatedBase;
  866. if (RelocatedBase->getType() != Base->getType()) {
  867. ActualRelocatedBase =
  868. Builder.CreateBitCast(RelocatedBase, Base->getType());
  869. }
  870. Value *Replacement = Builder.CreateGEP(
  871. Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
  872. Replacement->takeName(ToReplace);
  873. // If the newly generated derived pointer's type does not match the original derived
  874. // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
  875. Value *ActualReplacement = Replacement;
  876. if (Replacement->getType() != ToReplace->getType()) {
  877. ActualReplacement =
  878. Builder.CreateBitCast(Replacement, ToReplace->getType());
  879. }
  880. ToReplace->replaceAllUsesWith(ActualReplacement);
  881. ToReplace->eraseFromParent();
  882. MadeChange = true;
  883. }
  884. return MadeChange;
  885. }
  886. // Turns this:
  887. //
  888. // %base = ...
  889. // %ptr = gep %base + 15
  890. // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
  891. // %base' = relocate(%tok, i32 4, i32 4)
  892. // %ptr' = relocate(%tok, i32 4, i32 5)
  893. // %val = load %ptr'
  894. //
  895. // into this:
  896. //
  897. // %base = ...
  898. // %ptr = gep %base + 15
  899. // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
  900. // %base' = gc.relocate(%tok, i32 4, i32 4)
  901. // %ptr' = gep %base' + 15
  902. // %val = load %ptr'
  903. bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
  904. bool MadeChange = false;
  905. SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
  906. for (auto *U : I.users())
  907. if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
  908. // Collect all the relocate calls associated with a statepoint
  909. AllRelocateCalls.push_back(Relocate);
  910. // We need atleast one base pointer relocation + one derived pointer
  911. // relocation to mangle
  912. if (AllRelocateCalls.size() < 2)
  913. return false;
  914. // RelocateInstMap is a mapping from the base relocate instruction to the
  915. // corresponding derived relocate instructions
  916. DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
  917. computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
  918. if (RelocateInstMap.empty())
  919. return false;
  920. for (auto &Item : RelocateInstMap)
  921. // Item.first is the RelocatedBase to offset against
  922. // Item.second is the vector of Targets to replace
  923. MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
  924. return MadeChange;
  925. }
  926. /// Sink the specified cast instruction into its user blocks.
  927. static bool SinkCast(CastInst *CI) {
  928. BasicBlock *DefBB = CI->getParent();
  929. /// InsertedCasts - Only insert a cast in each block once.
  930. DenseMap<BasicBlock*, CastInst*> InsertedCasts;
  931. bool MadeChange = false;
  932. for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
  933. UI != E; ) {
  934. Use &TheUse = UI.getUse();
  935. Instruction *User = cast<Instruction>(*UI);
  936. // Figure out which BB this cast is used in. For PHI's this is the
  937. // appropriate predecessor block.
  938. BasicBlock *UserBB = User->getParent();
  939. if (PHINode *PN = dyn_cast<PHINode>(User)) {
  940. UserBB = PN->getIncomingBlock(TheUse);
  941. }
  942. // Preincrement use iterator so we don't invalidate it.
  943. ++UI;
  944. // The first insertion point of a block containing an EH pad is after the
  945. // pad. If the pad is the user, we cannot sink the cast past the pad.
  946. if (User->isEHPad())
  947. continue;
  948. // If the block selected to receive the cast is an EH pad that does not
  949. // allow non-PHI instructions before the terminator, we can't sink the
  950. // cast.
  951. if (UserBB->getTerminator()->isEHPad())
  952. continue;
  953. // If this user is in the same block as the cast, don't change the cast.
  954. if (UserBB == DefBB) continue;
  955. // If we have already inserted a cast into this block, use it.
  956. CastInst *&InsertedCast = InsertedCasts[UserBB];
  957. if (!InsertedCast) {
  958. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  959. assert(InsertPt != UserBB->end());
  960. InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
  961. CI->getType(), "", &*InsertPt);
  962. InsertedCast->setDebugLoc(CI->getDebugLoc());
  963. }
  964. // Replace a use of the cast with a use of the new cast.
  965. TheUse = InsertedCast;
  966. MadeChange = true;
  967. ++NumCastUses;
  968. }
  969. // If we removed all uses, nuke the cast.
  970. if (CI->use_empty()) {
  971. salvageDebugInfo(*CI);
  972. CI->eraseFromParent();
  973. MadeChange = true;
  974. }
  975. return MadeChange;
  976. }
  977. /// If the specified cast instruction is a noop copy (e.g. it's casting from
  978. /// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
  979. /// reduce the number of virtual registers that must be created and coalesced.
  980. ///
  981. /// Return true if any changes are made.
  982. static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
  983. const DataLayout &DL) {
  984. // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
  985. // than sinking only nop casts, but is helpful on some platforms.
  986. if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
  987. if (!TLI.isFreeAddrSpaceCast(ASC->getSrcAddressSpace(),
  988. ASC->getDestAddressSpace()))
  989. return false;
  990. }
  991. // If this is a noop copy,
  992. EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
  993. EVT DstVT = TLI.getValueType(DL, CI->getType());
  994. // This is an fp<->int conversion?
  995. if (SrcVT.isInteger() != DstVT.isInteger())
  996. return false;
  997. // If this is an extension, it will be a zero or sign extension, which
  998. // isn't a noop.
  999. if (SrcVT.bitsLT(DstVT)) return false;
  1000. // If these values will be promoted, find out what they will be promoted
  1001. // to. This helps us consider truncates on PPC as noop copies when they
  1002. // are.
  1003. if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
  1004. TargetLowering::TypePromoteInteger)
  1005. SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
  1006. if (TLI.getTypeAction(CI->getContext(), DstVT) ==
  1007. TargetLowering::TypePromoteInteger)
  1008. DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
  1009. // If, after promotion, these are the same types, this is a noop copy.
  1010. if (SrcVT != DstVT)
  1011. return false;
  1012. return SinkCast(CI);
  1013. }
  1014. bool CodeGenPrepare::replaceMathCmpWithIntrinsic(BinaryOperator *BO,
  1015. CmpInst *Cmp,
  1016. Intrinsic::ID IID) {
  1017. if (BO->getParent() != Cmp->getParent()) {
  1018. // We used to use a dominator tree here to allow multi-block optimization.
  1019. // But that was problematic because:
  1020. // 1. It could cause a perf regression by hoisting the math op into the
  1021. // critical path.
  1022. // 2. It could cause a perf regression by creating a value that was live
  1023. // across multiple blocks and increasing register pressure.
  1024. // 3. Use of a dominator tree could cause large compile-time regression.
  1025. // This is because we recompute the DT on every change in the main CGP
  1026. // run-loop. The recomputing is probably unnecessary in many cases, so if
  1027. // that was fixed, using a DT here would be ok.
  1028. return false;
  1029. }
  1030. // We allow matching the canonical IR (add X, C) back to (usubo X, -C).
  1031. Value *Arg0 = BO->getOperand(0);
  1032. Value *Arg1 = BO->getOperand(1);
  1033. if (BO->getOpcode() == Instruction::Add &&
  1034. IID == Intrinsic::usub_with_overflow) {
  1035. assert(isa<Constant>(Arg1) && "Unexpected input for usubo");
  1036. Arg1 = ConstantExpr::getNeg(cast<Constant>(Arg1));
  1037. }
  1038. // Insert at the first instruction of the pair.
  1039. Instruction *InsertPt = nullptr;
  1040. for (Instruction &Iter : *Cmp->getParent()) {
  1041. if (&Iter == BO || &Iter == Cmp) {
  1042. InsertPt = &Iter;
  1043. break;
  1044. }
  1045. }
  1046. assert(InsertPt != nullptr && "Parent block did not contain cmp or binop");
  1047. IRBuilder<> Builder(InsertPt);
  1048. Value *MathOV = Builder.CreateBinaryIntrinsic(IID, Arg0, Arg1);
  1049. Value *Math = Builder.CreateExtractValue(MathOV, 0, "math");
  1050. Value *OV = Builder.CreateExtractValue(MathOV, 1, "ov");
  1051. BO->replaceAllUsesWith(Math);
  1052. Cmp->replaceAllUsesWith(OV);
  1053. BO->eraseFromParent();
  1054. Cmp->eraseFromParent();
  1055. return true;
  1056. }
  1057. /// Match special-case patterns that check for unsigned add overflow.
  1058. static bool matchUAddWithOverflowConstantEdgeCases(CmpInst *Cmp,
  1059. BinaryOperator *&Add) {
  1060. // Add = add A, 1; Cmp = icmp eq A,-1 (overflow if A is max val)
  1061. // Add = add A,-1; Cmp = icmp ne A, 0 (overflow if A is non-zero)
  1062. Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1);
  1063. // We are not expecting non-canonical/degenerate code. Just bail out.
  1064. if (isa<Constant>(A))
  1065. return false;
  1066. ICmpInst::Predicate Pred = Cmp->getPredicate();
  1067. if (Pred == ICmpInst::ICMP_EQ && match(B, m_AllOnes()))
  1068. B = ConstantInt::get(B->getType(), 1);
  1069. else if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt()))
  1070. B = ConstantInt::get(B->getType(), -1);
  1071. else
  1072. return false;
  1073. // Check the users of the variable operand of the compare looking for an add
  1074. // with the adjusted constant.
  1075. for (User *U : A->users()) {
  1076. if (match(U, m_Add(m_Specific(A), m_Specific(B)))) {
  1077. Add = cast<BinaryOperator>(U);
  1078. return true;
  1079. }
  1080. }
  1081. return false;
  1082. }
  1083. /// Try to combine the compare into a call to the llvm.uadd.with.overflow
  1084. /// intrinsic. Return true if any changes were made.
  1085. bool CodeGenPrepare::combineToUAddWithOverflow(CmpInst *Cmp,
  1086. bool &ModifiedDT) {
  1087. Value *A, *B;
  1088. BinaryOperator *Add;
  1089. if (!match(Cmp, m_UAddWithOverflow(m_Value(A), m_Value(B), m_BinOp(Add))))
  1090. if (!matchUAddWithOverflowConstantEdgeCases(Cmp, Add))
  1091. return false;
  1092. if (!TLI->shouldFormOverflowOp(ISD::UADDO,
  1093. TLI->getValueType(*DL, Add->getType())))
  1094. return false;
  1095. // We don't want to move around uses of condition values this late, so we
  1096. // check if it is legal to create the call to the intrinsic in the basic
  1097. // block containing the icmp.
  1098. if (Add->getParent() != Cmp->getParent() && !Add->hasOneUse())
  1099. return false;
  1100. if (!replaceMathCmpWithIntrinsic(Add, Cmp, Intrinsic::uadd_with_overflow))
  1101. return false;
  1102. // Reset callers - do not crash by iterating over a dead instruction.
  1103. ModifiedDT = true;
  1104. return true;
  1105. }
  1106. bool CodeGenPrepare::combineToUSubWithOverflow(CmpInst *Cmp,
  1107. bool &ModifiedDT) {
  1108. // We are not expecting non-canonical/degenerate code. Just bail out.
  1109. Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1);
  1110. if (isa<Constant>(A) && isa<Constant>(B))
  1111. return false;
  1112. // Convert (A u> B) to (A u< B) to simplify pattern matching.
  1113. ICmpInst::Predicate Pred = Cmp->getPredicate();
  1114. if (Pred == ICmpInst::ICMP_UGT) {
  1115. std::swap(A, B);
  1116. Pred = ICmpInst::ICMP_ULT;
  1117. }
  1118. // Convert special-case: (A == 0) is the same as (A u< 1).
  1119. if (Pred == ICmpInst::ICMP_EQ && match(B, m_ZeroInt())) {
  1120. B = ConstantInt::get(B->getType(), 1);
  1121. Pred = ICmpInst::ICMP_ULT;
  1122. }
  1123. // Convert special-case: (A != 0) is the same as (0 u< A).
  1124. if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt())) {
  1125. std::swap(A, B);
  1126. Pred = ICmpInst::ICMP_ULT;
  1127. }
  1128. if (Pred != ICmpInst::ICMP_ULT)
  1129. return false;
  1130. // Walk the users of a variable operand of a compare looking for a subtract or
  1131. // add with that same operand. Also match the 2nd operand of the compare to
  1132. // the add/sub, but that may be a negated constant operand of an add.
  1133. Value *CmpVariableOperand = isa<Constant>(A) ? B : A;
  1134. BinaryOperator *Sub = nullptr;
  1135. for (User *U : CmpVariableOperand->users()) {
  1136. // A - B, A u< B --> usubo(A, B)
  1137. if (match(U, m_Sub(m_Specific(A), m_Specific(B)))) {
  1138. Sub = cast<BinaryOperator>(U);
  1139. break;
  1140. }
  1141. // A + (-C), A u< C (canonicalized form of (sub A, C))
  1142. const APInt *CmpC, *AddC;
  1143. if (match(U, m_Add(m_Specific(A), m_APInt(AddC))) &&
  1144. match(B, m_APInt(CmpC)) && *AddC == -(*CmpC)) {
  1145. Sub = cast<BinaryOperator>(U);
  1146. break;
  1147. }
  1148. }
  1149. if (!Sub)
  1150. return false;
  1151. if (!TLI->shouldFormOverflowOp(ISD::USUBO,
  1152. TLI->getValueType(*DL, Sub->getType())))
  1153. return false;
  1154. if (!replaceMathCmpWithIntrinsic(Sub, Cmp, Intrinsic::usub_with_overflow))
  1155. return false;
  1156. // Reset callers - do not crash by iterating over a dead instruction.
  1157. ModifiedDT = true;
  1158. return true;
  1159. }
  1160. /// Sink the given CmpInst into user blocks to reduce the number of virtual
  1161. /// registers that must be created and coalesced. This is a clear win except on
  1162. /// targets with multiple condition code registers (PowerPC), where it might
  1163. /// lose; some adjustment may be wanted there.
  1164. ///
  1165. /// Return true if any changes are made.
  1166. static bool sinkCmpExpression(CmpInst *Cmp, const TargetLowering &TLI) {
  1167. if (TLI.hasMultipleConditionRegisters())
  1168. return false;
  1169. // Avoid sinking soft-FP comparisons, since this can move them into a loop.
  1170. if (TLI.useSoftFloat() && isa<FCmpInst>(Cmp))
  1171. return false;
  1172. // Only insert a cmp in each block once.
  1173. DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
  1174. bool MadeChange = false;
  1175. for (Value::user_iterator UI = Cmp->user_begin(), E = Cmp->user_end();
  1176. UI != E; ) {
  1177. Use &TheUse = UI.getUse();
  1178. Instruction *User = cast<Instruction>(*UI);
  1179. // Preincrement use iterator so we don't invalidate it.
  1180. ++UI;
  1181. // Don't bother for PHI nodes.
  1182. if (isa<PHINode>(User))
  1183. continue;
  1184. // Figure out which BB this cmp is used in.
  1185. BasicBlock *UserBB = User->getParent();
  1186. BasicBlock *DefBB = Cmp->getParent();
  1187. // If this user is in the same block as the cmp, don't change the cmp.
  1188. if (UserBB == DefBB) continue;
  1189. // If we have already inserted a cmp into this block, use it.
  1190. CmpInst *&InsertedCmp = InsertedCmps[UserBB];
  1191. if (!InsertedCmp) {
  1192. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  1193. assert(InsertPt != UserBB->end());
  1194. InsertedCmp =
  1195. CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(),
  1196. Cmp->getOperand(0), Cmp->getOperand(1), "",
  1197. &*InsertPt);
  1198. // Propagate the debug info.
  1199. InsertedCmp->setDebugLoc(Cmp->getDebugLoc());
  1200. }
  1201. // Replace a use of the cmp with a use of the new cmp.
  1202. TheUse = InsertedCmp;
  1203. MadeChange = true;
  1204. ++NumCmpUses;
  1205. }
  1206. // If we removed all uses, nuke the cmp.
  1207. if (Cmp->use_empty()) {
  1208. Cmp->eraseFromParent();
  1209. MadeChange = true;
  1210. }
  1211. return MadeChange;
  1212. }
  1213. bool CodeGenPrepare::optimizeCmp(CmpInst *Cmp, bool &ModifiedDT) {
  1214. if (sinkCmpExpression(Cmp, *TLI))
  1215. return true;
  1216. if (combineToUAddWithOverflow(Cmp, ModifiedDT))
  1217. return true;
  1218. if (combineToUSubWithOverflow(Cmp, ModifiedDT))
  1219. return true;
  1220. return false;
  1221. }
  1222. /// Duplicate and sink the given 'and' instruction into user blocks where it is
  1223. /// used in a compare to allow isel to generate better code for targets where
  1224. /// this operation can be combined.
  1225. ///
  1226. /// Return true if any changes are made.
  1227. static bool sinkAndCmp0Expression(Instruction *AndI,
  1228. const TargetLowering &TLI,
  1229. SetOfInstrs &InsertedInsts) {
  1230. // Double-check that we're not trying to optimize an instruction that was
  1231. // already optimized by some other part of this pass.
  1232. assert(!InsertedInsts.count(AndI) &&
  1233. "Attempting to optimize already optimized and instruction");
  1234. (void) InsertedInsts;
  1235. // Nothing to do for single use in same basic block.
  1236. if (AndI->hasOneUse() &&
  1237. AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
  1238. return false;
  1239. // Try to avoid cases where sinking/duplicating is likely to increase register
  1240. // pressure.
  1241. if (!isa<ConstantInt>(AndI->getOperand(0)) &&
  1242. !isa<ConstantInt>(AndI->getOperand(1)) &&
  1243. AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
  1244. return false;
  1245. for (auto *U : AndI->users()) {
  1246. Instruction *User = cast<Instruction>(U);
  1247. // Only sink 'and' feeding icmp with 0.
  1248. if (!isa<ICmpInst>(User))
  1249. return false;
  1250. auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
  1251. if (!CmpC || !CmpC->isZero())
  1252. return false;
  1253. }
  1254. if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
  1255. return false;
  1256. LLVM_DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
  1257. LLVM_DEBUG(AndI->getParent()->dump());
  1258. // Push the 'and' into the same block as the icmp 0. There should only be
  1259. // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
  1260. // others, so we don't need to keep track of which BBs we insert into.
  1261. for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
  1262. UI != E; ) {
  1263. Use &TheUse = UI.getUse();
  1264. Instruction *User = cast<Instruction>(*UI);
  1265. // Preincrement use iterator so we don't invalidate it.
  1266. ++UI;
  1267. LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
  1268. // Keep the 'and' in the same place if the use is already in the same block.
  1269. Instruction *InsertPt =
  1270. User->getParent() == AndI->getParent() ? AndI : User;
  1271. Instruction *InsertedAnd =
  1272. BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
  1273. AndI->getOperand(1), "", InsertPt);
  1274. // Propagate the debug info.
  1275. InsertedAnd->setDebugLoc(AndI->getDebugLoc());
  1276. // Replace a use of the 'and' with a use of the new 'and'.
  1277. TheUse = InsertedAnd;
  1278. ++NumAndUses;
  1279. LLVM_DEBUG(User->getParent()->dump());
  1280. }
  1281. // We removed all uses, nuke the and.
  1282. AndI->eraseFromParent();
  1283. return true;
  1284. }
  1285. /// Check if the candidates could be combined with a shift instruction, which
  1286. /// includes:
  1287. /// 1. Truncate instruction
  1288. /// 2. And instruction and the imm is a mask of the low bits:
  1289. /// imm & (imm+1) == 0
  1290. static bool isExtractBitsCandidateUse(Instruction *User) {
  1291. if (!isa<TruncInst>(User)) {
  1292. if (User->getOpcode() != Instruction::And ||
  1293. !isa<ConstantInt>(User->getOperand(1)))
  1294. return false;
  1295. const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
  1296. if ((Cimm & (Cimm + 1)).getBoolValue())
  1297. return false;
  1298. }
  1299. return true;
  1300. }
  1301. /// Sink both shift and truncate instruction to the use of truncate's BB.
  1302. static bool
  1303. SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
  1304. DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
  1305. const TargetLowering &TLI, const DataLayout &DL) {
  1306. BasicBlock *UserBB = User->getParent();
  1307. DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
  1308. auto *TruncI = cast<TruncInst>(User);
  1309. bool MadeChange = false;
  1310. for (Value::user_iterator TruncUI = TruncI->user_begin(),
  1311. TruncE = TruncI->user_end();
  1312. TruncUI != TruncE;) {
  1313. Use &TruncTheUse = TruncUI.getUse();
  1314. Instruction *TruncUser = cast<Instruction>(*TruncUI);
  1315. // Preincrement use iterator so we don't invalidate it.
  1316. ++TruncUI;
  1317. int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
  1318. if (!ISDOpcode)
  1319. continue;
  1320. // If the use is actually a legal node, there will not be an
  1321. // implicit truncate.
  1322. // FIXME: always querying the result type is just an
  1323. // approximation; some nodes' legality is determined by the
  1324. // operand or other means. There's no good way to find out though.
  1325. if (TLI.isOperationLegalOrCustom(
  1326. ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
  1327. continue;
  1328. // Don't bother for PHI nodes.
  1329. if (isa<PHINode>(TruncUser))
  1330. continue;
  1331. BasicBlock *TruncUserBB = TruncUser->getParent();
  1332. if (UserBB == TruncUserBB)
  1333. continue;
  1334. BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
  1335. CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
  1336. if (!InsertedShift && !InsertedTrunc) {
  1337. BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
  1338. assert(InsertPt != TruncUserBB->end());
  1339. // Sink the shift
  1340. if (ShiftI->getOpcode() == Instruction::AShr)
  1341. InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
  1342. "", &*InsertPt);
  1343. else
  1344. InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
  1345. "", &*InsertPt);
  1346. InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
  1347. // Sink the trunc
  1348. BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
  1349. TruncInsertPt++;
  1350. assert(TruncInsertPt != TruncUserBB->end());
  1351. InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
  1352. TruncI->getType(), "", &*TruncInsertPt);
  1353. InsertedTrunc->setDebugLoc(TruncI->getDebugLoc());
  1354. MadeChange = true;
  1355. TruncTheUse = InsertedTrunc;
  1356. }
  1357. }
  1358. return MadeChange;
  1359. }
  1360. /// Sink the shift *right* instruction into user blocks if the uses could
  1361. /// potentially be combined with this shift instruction and generate BitExtract
  1362. /// instruction. It will only be applied if the architecture supports BitExtract
  1363. /// instruction. Here is an example:
  1364. /// BB1:
  1365. /// %x.extract.shift = lshr i64 %arg1, 32
  1366. /// BB2:
  1367. /// %x.extract.trunc = trunc i64 %x.extract.shift to i16
  1368. /// ==>
  1369. ///
  1370. /// BB2:
  1371. /// %x.extract.shift.1 = lshr i64 %arg1, 32
  1372. /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
  1373. ///
  1374. /// CodeGen will recognize the pattern in BB2 and generate BitExtract
  1375. /// instruction.
  1376. /// Return true if any changes are made.
  1377. static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
  1378. const TargetLowering &TLI,
  1379. const DataLayout &DL) {
  1380. BasicBlock *DefBB = ShiftI->getParent();
  1381. /// Only insert instructions in each block once.
  1382. DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
  1383. bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
  1384. bool MadeChange = false;
  1385. for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
  1386. UI != E;) {
  1387. Use &TheUse = UI.getUse();
  1388. Instruction *User = cast<Instruction>(*UI);
  1389. // Preincrement use iterator so we don't invalidate it.
  1390. ++UI;
  1391. // Don't bother for PHI nodes.
  1392. if (isa<PHINode>(User))
  1393. continue;
  1394. if (!isExtractBitsCandidateUse(User))
  1395. continue;
  1396. BasicBlock *UserBB = User->getParent();
  1397. if (UserBB == DefBB) {
  1398. // If the shift and truncate instruction are in the same BB. The use of
  1399. // the truncate(TruncUse) may still introduce another truncate if not
  1400. // legal. In this case, we would like to sink both shift and truncate
  1401. // instruction to the BB of TruncUse.
  1402. // for example:
  1403. // BB1:
  1404. // i64 shift.result = lshr i64 opnd, imm
  1405. // trunc.result = trunc shift.result to i16
  1406. //
  1407. // BB2:
  1408. // ----> We will have an implicit truncate here if the architecture does
  1409. // not have i16 compare.
  1410. // cmp i16 trunc.result, opnd2
  1411. //
  1412. if (isa<TruncInst>(User) && shiftIsLegal
  1413. // If the type of the truncate is legal, no truncate will be
  1414. // introduced in other basic blocks.
  1415. &&
  1416. (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
  1417. MadeChange =
  1418. SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
  1419. continue;
  1420. }
  1421. // If we have already inserted a shift into this block, use it.
  1422. BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
  1423. if (!InsertedShift) {
  1424. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  1425. assert(InsertPt != UserBB->end());
  1426. if (ShiftI->getOpcode() == Instruction::AShr)
  1427. InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
  1428. "", &*InsertPt);
  1429. else
  1430. InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
  1431. "", &*InsertPt);
  1432. InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
  1433. MadeChange = true;
  1434. }
  1435. // Replace a use of the shift with a use of the new shift.
  1436. TheUse = InsertedShift;
  1437. }
  1438. // If we removed all uses, or there are none, nuke the shift.
  1439. if (ShiftI->use_empty()) {
  1440. salvageDebugInfo(*ShiftI);
  1441. ShiftI->eraseFromParent();
  1442. MadeChange = true;
  1443. }
  1444. return MadeChange;
  1445. }
  1446. /// If counting leading or trailing zeros is an expensive operation and a zero
  1447. /// input is defined, add a check for zero to avoid calling the intrinsic.
  1448. ///
  1449. /// We want to transform:
  1450. /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
  1451. ///
  1452. /// into:
  1453. /// entry:
  1454. /// %cmpz = icmp eq i64 %A, 0
  1455. /// br i1 %cmpz, label %cond.end, label %cond.false
  1456. /// cond.false:
  1457. /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
  1458. /// br label %cond.end
  1459. /// cond.end:
  1460. /// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
  1461. ///
  1462. /// If the transform is performed, return true and set ModifiedDT to true.
  1463. static bool despeculateCountZeros(IntrinsicInst *CountZeros,
  1464. const TargetLowering *TLI,
  1465. const DataLayout *DL,
  1466. bool &ModifiedDT) {
  1467. if (!TLI || !DL)
  1468. return false;
  1469. // If a zero input is undefined, it doesn't make sense to despeculate that.
  1470. if (match(CountZeros->getOperand(1), m_One()))
  1471. return false;
  1472. // If it's cheap to speculate, there's nothing to do.
  1473. auto IntrinsicID = CountZeros->getIntrinsicID();
  1474. if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
  1475. (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
  1476. return false;
  1477. // Only handle legal scalar cases. Anything else requires too much work.
  1478. Type *Ty = CountZeros->getType();
  1479. unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
  1480. if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
  1481. return false;
  1482. // The intrinsic will be sunk behind a compare against zero and branch.
  1483. BasicBlock *StartBlock = CountZeros->getParent();
  1484. BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
  1485. // Create another block after the count zero intrinsic. A PHI will be added
  1486. // in this block to select the result of the intrinsic or the bit-width
  1487. // constant if the input to the intrinsic is zero.
  1488. BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
  1489. BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
  1490. // Set up a builder to create a compare, conditional branch, and PHI.
  1491. IRBuilder<> Builder(CountZeros->getContext());
  1492. Builder.SetInsertPoint(StartBlock->getTerminator());
  1493. Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
  1494. // Replace the unconditional branch that was created by the first split with
  1495. // a compare against zero and a conditional branch.
  1496. Value *Zero = Constant::getNullValue(Ty);
  1497. Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
  1498. Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
  1499. StartBlock->getTerminator()->eraseFromParent();
  1500. // Create a PHI in the end block to select either the output of the intrinsic
  1501. // or the bit width of the operand.
  1502. Builder.SetInsertPoint(&EndBlock->front());
  1503. PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
  1504. CountZeros->replaceAllUsesWith(PN);
  1505. Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
  1506. PN->addIncoming(BitWidth, StartBlock);
  1507. PN->addIncoming(CountZeros, CallBlock);
  1508. // We are explicitly handling the zero case, so we can set the intrinsic's
  1509. // undefined zero argument to 'true'. This will also prevent reprocessing the
  1510. // intrinsic; we only despeculate when a zero input is defined.
  1511. CountZeros->setArgOperand(1, Builder.getTrue());
  1512. ModifiedDT = true;
  1513. return true;
  1514. }
  1515. bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) {
  1516. BasicBlock *BB = CI->getParent();
  1517. // Lower inline assembly if we can.
  1518. // If we found an inline asm expession, and if the target knows how to
  1519. // lower it to normal LLVM code, do so now.
  1520. if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
  1521. if (TLI->ExpandInlineAsm(CI)) {
  1522. // Avoid invalidating the iterator.
  1523. CurInstIterator = BB->begin();
  1524. // Avoid processing instructions out of order, which could cause
  1525. // reuse before a value is defined.
  1526. SunkAddrs.clear();
  1527. return true;
  1528. }
  1529. // Sink address computing for memory operands into the block.
  1530. if (optimizeInlineAsmInst(CI))
  1531. return true;
  1532. }
  1533. // Align the pointer arguments to this call if the target thinks it's a good
  1534. // idea
  1535. unsigned MinSize, PrefAlign;
  1536. if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
  1537. for (auto &Arg : CI->arg_operands()) {
  1538. // We want to align both objects whose address is used directly and
  1539. // objects whose address is used in casts and GEPs, though it only makes
  1540. // sense for GEPs if the offset is a multiple of the desired alignment and
  1541. // if size - offset meets the size threshold.
  1542. if (!Arg->getType()->isPointerTy())
  1543. continue;
  1544. APInt Offset(DL->getIndexSizeInBits(
  1545. cast<PointerType>(Arg->getType())->getAddressSpace()),
  1546. 0);
  1547. Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
  1548. uint64_t Offset2 = Offset.getLimitedValue();
  1549. if ((Offset2 & (PrefAlign-1)) != 0)
  1550. continue;
  1551. AllocaInst *AI;
  1552. if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
  1553. DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
  1554. AI->setAlignment(MaybeAlign(PrefAlign));
  1555. // Global variables can only be aligned if they are defined in this
  1556. // object (i.e. they are uniquely initialized in this object), and
  1557. // over-aligning global variables that have an explicit section is
  1558. // forbidden.
  1559. GlobalVariable *GV;
  1560. if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
  1561. GV->getPointerAlignment(*DL) < PrefAlign &&
  1562. DL->getTypeAllocSize(GV->getValueType()) >=
  1563. MinSize + Offset2)
  1564. GV->setAlignment(PrefAlign);
  1565. }
  1566. // If this is a memcpy (or similar) then we may be able to improve the
  1567. // alignment
  1568. if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
  1569. unsigned DestAlign = getKnownAlignment(MI->getDest(), *DL);
  1570. if (DestAlign > MI->getDestAlignment())
  1571. MI->setDestAlignment(DestAlign);
  1572. if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
  1573. unsigned SrcAlign = getKnownAlignment(MTI->getSource(), *DL);
  1574. if (SrcAlign > MTI->getSourceAlignment())
  1575. MTI->setSourceAlignment(SrcAlign);
  1576. }
  1577. }
  1578. }
  1579. // If we have a cold call site, try to sink addressing computation into the
  1580. // cold block. This interacts with our handling for loads and stores to
  1581. // ensure that we can fold all uses of a potential addressing computation
  1582. // into their uses. TODO: generalize this to work over profiling data
  1583. if (!OptSize && CI->hasFnAttr(Attribute::Cold))
  1584. for (auto &Arg : CI->arg_operands()) {
  1585. if (!Arg->getType()->isPointerTy())
  1586. continue;
  1587. unsigned AS = Arg->getType()->getPointerAddressSpace();
  1588. return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
  1589. }
  1590. IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
  1591. if (II) {
  1592. switch (II->getIntrinsicID()) {
  1593. default: break;
  1594. case Intrinsic::experimental_widenable_condition: {
  1595. // Give up on future widening oppurtunties so that we can fold away dead
  1596. // paths and merge blocks before going into block-local instruction
  1597. // selection.
  1598. if (II->use_empty()) {
  1599. II->eraseFromParent();
  1600. return true;
  1601. }
  1602. Constant *RetVal = ConstantInt::getTrue(II->getContext());
  1603. resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
  1604. replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
  1605. });
  1606. return true;
  1607. }
  1608. case Intrinsic::objectsize: {
  1609. // Lower all uses of llvm.objectsize.*
  1610. Value *RetVal =
  1611. lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true);
  1612. resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
  1613. replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
  1614. });
  1615. return true;
  1616. }
  1617. case Intrinsic::is_constant: {
  1618. // If is_constant hasn't folded away yet, lower it to false now.
  1619. Constant *RetVal = ConstantInt::get(II->getType(), 0);
  1620. resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
  1621. replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
  1622. });
  1623. return true;
  1624. }
  1625. case Intrinsic::aarch64_stlxr:
  1626. case Intrinsic::aarch64_stxr: {
  1627. ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
  1628. if (!ExtVal || !ExtVal->hasOneUse() ||
  1629. ExtVal->getParent() == CI->getParent())
  1630. return false;
  1631. // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
  1632. ExtVal->moveBefore(CI);
  1633. // Mark this instruction as "inserted by CGP", so that other
  1634. // optimizations don't touch it.
  1635. InsertedInsts.insert(ExtVal);
  1636. return true;
  1637. }
  1638. case Intrinsic::launder_invariant_group:
  1639. case Intrinsic::strip_invariant_group: {
  1640. Value *ArgVal = II->getArgOperand(0);
  1641. auto it = LargeOffsetGEPMap.find(II);
  1642. if (it != LargeOffsetGEPMap.end()) {
  1643. // Merge entries in LargeOffsetGEPMap to reflect the RAUW.
  1644. // Make sure not to have to deal with iterator invalidation
  1645. // after possibly adding ArgVal to LargeOffsetGEPMap.
  1646. auto GEPs = std::move(it->second);
  1647. LargeOffsetGEPMap[ArgVal].append(GEPs.begin(), GEPs.end());
  1648. LargeOffsetGEPMap.erase(II);
  1649. }
  1650. II->replaceAllUsesWith(ArgVal);
  1651. II->eraseFromParent();
  1652. return true;
  1653. }
  1654. case Intrinsic::cttz:
  1655. case Intrinsic::ctlz:
  1656. // If counting zeros is expensive, try to avoid it.
  1657. return despeculateCountZeros(II, TLI, DL, ModifiedDT);
  1658. }
  1659. if (TLI) {
  1660. SmallVector<Value*, 2> PtrOps;
  1661. Type *AccessTy;
  1662. if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
  1663. while (!PtrOps.empty()) {
  1664. Value *PtrVal = PtrOps.pop_back_val();
  1665. unsigned AS = PtrVal->getType()->getPointerAddressSpace();
  1666. if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
  1667. return true;
  1668. }
  1669. }
  1670. }
  1671. // From here on out we're working with named functions.
  1672. if (!CI->getCalledFunction()) return false;
  1673. // Lower all default uses of _chk calls. This is very similar
  1674. // to what InstCombineCalls does, but here we are only lowering calls
  1675. // to fortified library functions (e.g. __memcpy_chk) that have the default
  1676. // "don't know" as the objectsize. Anything else should be left alone.
  1677. FortifiedLibCallSimplifier Simplifier(TLInfo, true);
  1678. if (Value *V = Simplifier.optimizeCall(CI)) {
  1679. CI->replaceAllUsesWith(V);
  1680. CI->eraseFromParent();
  1681. return true;
  1682. }
  1683. return false;
  1684. }
  1685. /// Look for opportunities to duplicate return instructions to the predecessor
  1686. /// to enable tail call optimizations. The case it is currently looking for is:
  1687. /// @code
  1688. /// bb0:
  1689. /// %tmp0 = tail call i32 @f0()
  1690. /// br label %return
  1691. /// bb1:
  1692. /// %tmp1 = tail call i32 @f1()
  1693. /// br label %return
  1694. /// bb2:
  1695. /// %tmp2 = tail call i32 @f2()
  1696. /// br label %return
  1697. /// return:
  1698. /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
  1699. /// ret i32 %retval
  1700. /// @endcode
  1701. ///
  1702. /// =>
  1703. ///
  1704. /// @code
  1705. /// bb0:
  1706. /// %tmp0 = tail call i32 @f0()
  1707. /// ret i32 %tmp0
  1708. /// bb1:
  1709. /// %tmp1 = tail call i32 @f1()
  1710. /// ret i32 %tmp1
  1711. /// bb2:
  1712. /// %tmp2 = tail call i32 @f2()
  1713. /// ret i32 %tmp2
  1714. /// @endcode
  1715. bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB, bool &ModifiedDT) {
  1716. if (!TLI)
  1717. return false;
  1718. ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
  1719. if (!RetI)
  1720. return false;
  1721. PHINode *PN = nullptr;
  1722. BitCastInst *BCI = nullptr;
  1723. Value *V = RetI->getReturnValue();
  1724. if (V) {
  1725. BCI = dyn_cast<BitCastInst>(V);
  1726. if (BCI)
  1727. V = BCI->getOperand(0);
  1728. PN = dyn_cast<PHINode>(V);
  1729. if (!PN)
  1730. return false;
  1731. }
  1732. if (PN && PN->getParent() != BB)
  1733. return false;
  1734. // Make sure there are no instructions between the PHI and return, or that the
  1735. // return is the first instruction in the block.
  1736. if (PN) {
  1737. BasicBlock::iterator BI = BB->begin();
  1738. // Skip over debug and the bitcast.
  1739. do { ++BI; } while (isa<DbgInfoIntrinsic>(BI) || &*BI == BCI);
  1740. if (&*BI != RetI)
  1741. return false;
  1742. } else {
  1743. BasicBlock::iterator BI = BB->begin();
  1744. while (isa<DbgInfoIntrinsic>(BI)) ++BI;
  1745. if (&*BI != RetI)
  1746. return false;
  1747. }
  1748. /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
  1749. /// call.
  1750. const Function *F = BB->getParent();
  1751. SmallVector<BasicBlock*, 4> TailCallBBs;
  1752. if (PN) {
  1753. for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
  1754. // Look through bitcasts.
  1755. Value *IncomingVal = PN->getIncomingValue(I)->stripPointerCasts();
  1756. CallInst *CI = dyn_cast<CallInst>(IncomingVal);
  1757. BasicBlock *PredBB = PN->getIncomingBlock(I);
  1758. // Make sure the phi value is indeed produced by the tail call.
  1759. if (CI && CI->hasOneUse() && CI->getParent() == PredBB &&
  1760. TLI->mayBeEmittedAsTailCall(CI) &&
  1761. attributesPermitTailCall(F, CI, RetI, *TLI))
  1762. TailCallBBs.push_back(PredBB);
  1763. }
  1764. } else {
  1765. SmallPtrSet<BasicBlock*, 4> VisitedBBs;
  1766. for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
  1767. if (!VisitedBBs.insert(*PI).second)
  1768. continue;
  1769. BasicBlock::InstListType &InstList = (*PI)->getInstList();
  1770. BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
  1771. BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
  1772. do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
  1773. if (RI == RE)
  1774. continue;
  1775. CallInst *CI = dyn_cast<CallInst>(&*RI);
  1776. if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
  1777. attributesPermitTailCall(F, CI, RetI, *TLI))
  1778. TailCallBBs.push_back(*PI);
  1779. }
  1780. }
  1781. bool Changed = false;
  1782. for (auto const &TailCallBB : TailCallBBs) {
  1783. // Make sure the call instruction is followed by an unconditional branch to
  1784. // the return block.
  1785. BranchInst *BI = dyn_cast<BranchInst>(TailCallBB->getTerminator());
  1786. if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
  1787. continue;
  1788. // Duplicate the return into TailCallBB.
  1789. (void)FoldReturnIntoUncondBranch(RetI, BB, TailCallBB);
  1790. ModifiedDT = Changed = true;
  1791. ++NumRetsDup;
  1792. }
  1793. // If we eliminated all predecessors of the block, delete the block now.
  1794. if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
  1795. BB->eraseFromParent();
  1796. return Changed;
  1797. }
  1798. //===----------------------------------------------------------------------===//
  1799. // Memory Optimization
  1800. //===----------------------------------------------------------------------===//
  1801. namespace {
  1802. /// This is an extended version of TargetLowering::AddrMode
  1803. /// which holds actual Value*'s for register values.
  1804. struct ExtAddrMode : public TargetLowering::AddrMode {
  1805. Value *BaseReg = nullptr;
  1806. Value *ScaledReg = nullptr;
  1807. Value *OriginalValue = nullptr;
  1808. bool InBounds = true;
  1809. enum FieldName {
  1810. NoField = 0x00,
  1811. BaseRegField = 0x01,
  1812. BaseGVField = 0x02,
  1813. BaseOffsField = 0x04,
  1814. ScaledRegField = 0x08,
  1815. ScaleField = 0x10,
  1816. MultipleFields = 0xff
  1817. };
  1818. ExtAddrMode() = default;
  1819. void print(raw_ostream &OS) const;
  1820. void dump() const;
  1821. FieldName compare(const ExtAddrMode &other) {
  1822. // First check that the types are the same on each field, as differing types
  1823. // is something we can't cope with later on.
  1824. if (BaseReg && other.BaseReg &&
  1825. BaseReg->getType() != other.BaseReg->getType())
  1826. return MultipleFields;
  1827. if (BaseGV && other.BaseGV &&
  1828. BaseGV->getType() != other.BaseGV->getType())
  1829. return MultipleFields;
  1830. if (ScaledReg && other.ScaledReg &&
  1831. ScaledReg->getType() != other.ScaledReg->getType())
  1832. return MultipleFields;
  1833. // Conservatively reject 'inbounds' mismatches.
  1834. if (InBounds != other.InBounds)
  1835. return MultipleFields;
  1836. // Check each field to see if it differs.
  1837. unsigned Result = NoField;
  1838. if (BaseReg != other.BaseReg)
  1839. Result |= BaseRegField;
  1840. if (BaseGV != other.BaseGV)
  1841. Result |= BaseGVField;
  1842. if (BaseOffs != other.BaseOffs)
  1843. Result |= BaseOffsField;
  1844. if (ScaledReg != other.ScaledReg)
  1845. Result |= ScaledRegField;
  1846. // Don't count 0 as being a different scale, because that actually means
  1847. // unscaled (which will already be counted by having no ScaledReg).
  1848. if (Scale && other.Scale && Scale != other.Scale)
  1849. Result |= ScaleField;
  1850. if (countPopulation(Result) > 1)
  1851. return MultipleFields;
  1852. else
  1853. return static_cast<FieldName>(Result);
  1854. }
  1855. // An AddrMode is trivial if it involves no calculation i.e. it is just a base
  1856. // with no offset.
  1857. bool isTrivial() {
  1858. // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
  1859. // trivial if at most one of these terms is nonzero, except that BaseGV and
  1860. // BaseReg both being zero actually means a null pointer value, which we
  1861. // consider to be 'non-zero' here.
  1862. return !BaseOffs && !Scale && !(BaseGV && BaseReg);
  1863. }
  1864. Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
  1865. switch (Field) {
  1866. default:
  1867. return nullptr;
  1868. case BaseRegField:
  1869. return BaseReg;
  1870. case BaseGVField:
  1871. return BaseGV;
  1872. case ScaledRegField:
  1873. return ScaledReg;
  1874. case BaseOffsField:
  1875. return ConstantInt::get(IntPtrTy, BaseOffs);
  1876. }
  1877. }
  1878. void SetCombinedField(FieldName Field, Value *V,
  1879. const SmallVectorImpl<ExtAddrMode> &AddrModes) {
  1880. switch (Field) {
  1881. default:
  1882. llvm_unreachable("Unhandled fields are expected to be rejected earlier");
  1883. break;
  1884. case ExtAddrMode::BaseRegField:
  1885. BaseReg = V;
  1886. break;
  1887. case ExtAddrMode::BaseGVField:
  1888. // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
  1889. // in the BaseReg field.
  1890. assert(BaseReg == nullptr);
  1891. BaseReg = V;
  1892. BaseGV = nullptr;
  1893. break;
  1894. case ExtAddrMode::ScaledRegField:
  1895. ScaledReg = V;
  1896. // If we have a mix of scaled and unscaled addrmodes then we want scale
  1897. // to be the scale and not zero.
  1898. if (!Scale)
  1899. for (const ExtAddrMode &AM : AddrModes)
  1900. if (AM.Scale) {
  1901. Scale = AM.Scale;
  1902. break;
  1903. }
  1904. break;
  1905. case ExtAddrMode::BaseOffsField:
  1906. // The offset is no longer a constant, so it goes in ScaledReg with a
  1907. // scale of 1.
  1908. assert(ScaledReg == nullptr);
  1909. ScaledReg = V;
  1910. Scale = 1;
  1911. BaseOffs = 0;
  1912. break;
  1913. }
  1914. }
  1915. };
  1916. } // end anonymous namespace
  1917. #ifndef NDEBUG
  1918. static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
  1919. AM.print(OS);
  1920. return OS;
  1921. }
  1922. #endif
  1923. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1924. void ExtAddrMode::print(raw_ostream &OS) const {
  1925. bool NeedPlus = false;
  1926. OS << "[";
  1927. if (InBounds)
  1928. OS << "inbounds ";
  1929. if (BaseGV) {
  1930. OS << (NeedPlus ? " + " : "")
  1931. << "GV:";
  1932. BaseGV->printAsOperand(OS, /*PrintType=*/false);
  1933. NeedPlus = true;
  1934. }
  1935. if (BaseOffs) {
  1936. OS << (NeedPlus ? " + " : "")
  1937. << BaseOffs;
  1938. NeedPlus = true;
  1939. }
  1940. if (BaseReg) {
  1941. OS << (NeedPlus ? " + " : "")
  1942. << "Base:";
  1943. BaseReg->printAsOperand(OS, /*PrintType=*/false);
  1944. NeedPlus = true;
  1945. }
  1946. if (Scale) {
  1947. OS << (NeedPlus ? " + " : "")
  1948. << Scale << "*";
  1949. ScaledReg->printAsOperand(OS, /*PrintType=*/false);
  1950. }
  1951. OS << ']';
  1952. }
  1953. LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
  1954. print(dbgs());
  1955. dbgs() << '\n';
  1956. }
  1957. #endif
  1958. namespace {
  1959. /// This class provides transaction based operation on the IR.
  1960. /// Every change made through this class is recorded in the internal state and
  1961. /// can be undone (rollback) until commit is called.
  1962. class TypePromotionTransaction {
  1963. /// This represents the common interface of the individual transaction.
  1964. /// Each class implements the logic for doing one specific modification on
  1965. /// the IR via the TypePromotionTransaction.
  1966. class TypePromotionAction {
  1967. protected:
  1968. /// The Instruction modified.
  1969. Instruction *Inst;
  1970. public:
  1971. /// Constructor of the action.
  1972. /// The constructor performs the related action on the IR.
  1973. TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
  1974. virtual ~TypePromotionAction() = default;
  1975. /// Undo the modification done by this action.
  1976. /// When this method is called, the IR must be in the same state as it was
  1977. /// before this action was applied.
  1978. /// \pre Undoing the action works if and only if the IR is in the exact same
  1979. /// state as it was directly after this action was applied.
  1980. virtual void undo() = 0;
  1981. /// Advocate every change made by this action.
  1982. /// When the results on the IR of the action are to be kept, it is important
  1983. /// to call this function, otherwise hidden information may be kept forever.
  1984. virtual void commit() {
  1985. // Nothing to be done, this action is not doing anything.
  1986. }
  1987. };
  1988. /// Utility to remember the position of an instruction.
  1989. class InsertionHandler {
  1990. /// Position of an instruction.
  1991. /// Either an instruction:
  1992. /// - Is the first in a basic block: BB is used.
  1993. /// - Has a previous instruction: PrevInst is used.
  1994. union {
  1995. Instruction *PrevInst;
  1996. BasicBlock *BB;
  1997. } Point;
  1998. /// Remember whether or not the instruction had a previous instruction.
  1999. bool HasPrevInstruction;
  2000. public:
  2001. /// Record the position of \p Inst.
  2002. InsertionHandler(Instruction *Inst) {
  2003. BasicBlock::iterator It = Inst->getIterator();
  2004. HasPrevInstruction = (It != (Inst->getParent()->begin()));
  2005. if (HasPrevInstruction)
  2006. Point.PrevInst = &*--It;
  2007. else
  2008. Point.BB = Inst->getParent();
  2009. }
  2010. /// Insert \p Inst at the recorded position.
  2011. void insert(Instruction *Inst) {
  2012. if (HasPrevInstruction) {
  2013. if (Inst->getParent())
  2014. Inst->removeFromParent();
  2015. Inst->insertAfter(Point.PrevInst);
  2016. } else {
  2017. Instruction *Position = &*Point.BB->getFirstInsertionPt();
  2018. if (Inst->getParent())
  2019. Inst->moveBefore(Position);
  2020. else
  2021. Inst->insertBefore(Position);
  2022. }
  2023. }
  2024. };
  2025. /// Move an instruction before another.
  2026. class InstructionMoveBefore : public TypePromotionAction {
  2027. /// Original position of the instruction.
  2028. InsertionHandler Position;
  2029. public:
  2030. /// Move \p Inst before \p Before.
  2031. InstructionMoveBefore(Instruction *Inst, Instruction *Before)
  2032. : TypePromotionAction(Inst), Position(Inst) {
  2033. LLVM_DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before
  2034. << "\n");
  2035. Inst->moveBefore(Before);
  2036. }
  2037. /// Move the instruction back to its original position.
  2038. void undo() override {
  2039. LLVM_DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
  2040. Position.insert(Inst);
  2041. }
  2042. };
  2043. /// Set the operand of an instruction with a new value.
  2044. class OperandSetter : public TypePromotionAction {
  2045. /// Original operand of the instruction.
  2046. Value *Origin;
  2047. /// Index of the modified instruction.
  2048. unsigned Idx;
  2049. public:
  2050. /// Set \p Idx operand of \p Inst with \p NewVal.
  2051. OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
  2052. : TypePromotionAction(Inst), Idx(Idx) {
  2053. LLVM_DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
  2054. << "for:" << *Inst << "\n"
  2055. << "with:" << *NewVal << "\n");
  2056. Origin = Inst->getOperand(Idx);
  2057. Inst->setOperand(Idx, NewVal);
  2058. }
  2059. /// Restore the original value of the instruction.
  2060. void undo() override {
  2061. LLVM_DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
  2062. << "for: " << *Inst << "\n"
  2063. << "with: " << *Origin << "\n");
  2064. Inst->setOperand(Idx, Origin);
  2065. }
  2066. };
  2067. /// Hide the operands of an instruction.
  2068. /// Do as if this instruction was not using any of its operands.
  2069. class OperandsHider : public TypePromotionAction {
  2070. /// The list of original operands.
  2071. SmallVector<Value *, 4> OriginalValues;
  2072. public:
  2073. /// Remove \p Inst from the uses of the operands of \p Inst.
  2074. OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
  2075. LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
  2076. unsigned NumOpnds = Inst->getNumOperands();
  2077. OriginalValues.reserve(NumOpnds);
  2078. for (unsigned It = 0; It < NumOpnds; ++It) {
  2079. // Save the current operand.
  2080. Value *Val = Inst->getOperand(It);
  2081. OriginalValues.push_back(Val);
  2082. // Set a dummy one.
  2083. // We could use OperandSetter here, but that would imply an overhead
  2084. // that we are not willing to pay.
  2085. Inst->setOperand(It, UndefValue::get(Val->getType()));
  2086. }
  2087. }
  2088. /// Restore the original list of uses.
  2089. void undo() override {
  2090. LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
  2091. for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
  2092. Inst->setOperand(It, OriginalValues[It]);
  2093. }
  2094. };
  2095. /// Build a truncate instruction.
  2096. class TruncBuilder : public TypePromotionAction {
  2097. Value *Val;
  2098. public:
  2099. /// Build a truncate instruction of \p Opnd producing a \p Ty
  2100. /// result.
  2101. /// trunc Opnd to Ty.
  2102. TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
  2103. IRBuilder<> Builder(Opnd);
  2104. Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
  2105. LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
  2106. }
  2107. /// Get the built value.
  2108. Value *getBuiltValue() { return Val; }
  2109. /// Remove the built instruction.
  2110. void undo() override {
  2111. LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
  2112. if (Instruction *IVal = dyn_cast<Instruction>(Val))
  2113. IVal->eraseFromParent();
  2114. }
  2115. };
  2116. /// Build a sign extension instruction.
  2117. class SExtBuilder : public TypePromotionAction {
  2118. Value *Val;
  2119. public:
  2120. /// Build a sign extension instruction of \p Opnd producing a \p Ty
  2121. /// result.
  2122. /// sext Opnd to Ty.
  2123. SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
  2124. : TypePromotionAction(InsertPt) {
  2125. IRBuilder<> Builder(InsertPt);
  2126. Val = Builder.CreateSExt(Opnd, Ty, "promoted");
  2127. LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
  2128. }
  2129. /// Get the built value.
  2130. Value *getBuiltValue() { return Val; }
  2131. /// Remove the built instruction.
  2132. void undo() override {
  2133. LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
  2134. if (Instruction *IVal = dyn_cast<Instruction>(Val))
  2135. IVal->eraseFromParent();
  2136. }
  2137. };
  2138. /// Build a zero extension instruction.
  2139. class ZExtBuilder : public TypePromotionAction {
  2140. Value *Val;
  2141. public:
  2142. /// Build a zero extension instruction of \p Opnd producing a \p Ty
  2143. /// result.
  2144. /// zext Opnd to Ty.
  2145. ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
  2146. : TypePromotionAction(InsertPt) {
  2147. IRBuilder<> Builder(InsertPt);
  2148. Val = Builder.CreateZExt(Opnd, Ty, "promoted");
  2149. LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
  2150. }
  2151. /// Get the built value.
  2152. Value *getBuiltValue() { return Val; }
  2153. /// Remove the built instruction.
  2154. void undo() override {
  2155. LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
  2156. if (Instruction *IVal = dyn_cast<Instruction>(Val))
  2157. IVal->eraseFromParent();
  2158. }
  2159. };
  2160. /// Mutate an instruction to another type.
  2161. class TypeMutator : public TypePromotionAction {
  2162. /// Record the original type.
  2163. Type *OrigTy;
  2164. public:
  2165. /// Mutate the type of \p Inst into \p NewTy.
  2166. TypeMutator(Instruction *Inst, Type *NewTy)
  2167. : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
  2168. LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
  2169. << "\n");
  2170. Inst->mutateType(NewTy);
  2171. }
  2172. /// Mutate the instruction back to its original type.
  2173. void undo() override {
  2174. LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
  2175. << "\n");
  2176. Inst->mutateType(OrigTy);
  2177. }
  2178. };
  2179. /// Replace the uses of an instruction by another instruction.
  2180. class UsesReplacer : public TypePromotionAction {
  2181. /// Helper structure to keep track of the replaced uses.
  2182. struct InstructionAndIdx {
  2183. /// The instruction using the instruction.
  2184. Instruction *Inst;
  2185. /// The index where this instruction is used for Inst.
  2186. unsigned Idx;
  2187. InstructionAndIdx(Instruction *Inst, unsigned Idx)
  2188. : Inst(Inst), Idx(Idx) {}
  2189. };
  2190. /// Keep track of the original uses (pair Instruction, Index).
  2191. SmallVector<InstructionAndIdx, 4> OriginalUses;
  2192. /// Keep track of the debug users.
  2193. SmallVector<DbgValueInst *, 1> DbgValues;
  2194. using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator;
  2195. public:
  2196. /// Replace all the use of \p Inst by \p New.
  2197. UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
  2198. LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
  2199. << "\n");
  2200. // Record the original uses.
  2201. for (Use &U : Inst->uses()) {
  2202. Instruction *UserI = cast<Instruction>(U.getUser());
  2203. OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
  2204. }
  2205. // Record the debug uses separately. They are not in the instruction's
  2206. // use list, but they are replaced by RAUW.
  2207. findDbgValues(DbgValues, Inst);
  2208. // Now, we can replace the uses.
  2209. Inst->replaceAllUsesWith(New);
  2210. }
  2211. /// Reassign the original uses of Inst to Inst.
  2212. void undo() override {
  2213. LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
  2214. for (use_iterator UseIt = OriginalUses.begin(),
  2215. EndIt = OriginalUses.end();
  2216. UseIt != EndIt; ++UseIt) {
  2217. UseIt->Inst->setOperand(UseIt->Idx, Inst);
  2218. }
  2219. // RAUW has replaced all original uses with references to the new value,
  2220. // including the debug uses. Since we are undoing the replacements,
  2221. // the original debug uses must also be reinstated to maintain the
  2222. // correctness and utility of debug value instructions.
  2223. for (auto *DVI: DbgValues) {
  2224. LLVMContext &Ctx = Inst->getType()->getContext();
  2225. auto *MV = MetadataAsValue::get(Ctx, ValueAsMetadata::get(Inst));
  2226. DVI->setOperand(0, MV);
  2227. }
  2228. }
  2229. };
  2230. /// Remove an instruction from the IR.
  2231. class InstructionRemover : public TypePromotionAction {
  2232. /// Original position of the instruction.
  2233. InsertionHandler Inserter;
  2234. /// Helper structure to hide all the link to the instruction. In other
  2235. /// words, this helps to do as if the instruction was removed.
  2236. OperandsHider Hider;
  2237. /// Keep track of the uses replaced, if any.
  2238. UsesReplacer *Replacer = nullptr;
  2239. /// Keep track of instructions removed.
  2240. SetOfInstrs &RemovedInsts;
  2241. public:
  2242. /// Remove all reference of \p Inst and optionally replace all its
  2243. /// uses with New.
  2244. /// \p RemovedInsts Keep track of the instructions removed by this Action.
  2245. /// \pre If !Inst->use_empty(), then New != nullptr
  2246. InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
  2247. Value *New = nullptr)
  2248. : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
  2249. RemovedInsts(RemovedInsts) {
  2250. if (New)
  2251. Replacer = new UsesReplacer(Inst, New);
  2252. LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
  2253. RemovedInsts.insert(Inst);
  2254. /// The instructions removed here will be freed after completing
  2255. /// optimizeBlock() for all blocks as we need to keep track of the
  2256. /// removed instructions during promotion.
  2257. Inst->removeFromParent();
  2258. }
  2259. ~InstructionRemover() override { delete Replacer; }
  2260. /// Resurrect the instruction and reassign it to the proper uses if
  2261. /// new value was provided when build this action.
  2262. void undo() override {
  2263. LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
  2264. Inserter.insert(Inst);
  2265. if (Replacer)
  2266. Replacer->undo();
  2267. Hider.undo();
  2268. RemovedInsts.erase(Inst);
  2269. }
  2270. };
  2271. public:
  2272. /// Restoration point.
  2273. /// The restoration point is a pointer to an action instead of an iterator
  2274. /// because the iterator may be invalidated but not the pointer.
  2275. using ConstRestorationPt = const TypePromotionAction *;
  2276. TypePromotionTransaction(SetOfInstrs &RemovedInsts)
  2277. : RemovedInsts(RemovedInsts) {}
  2278. /// Advocate every changes made in that transaction.
  2279. void commit();
  2280. /// Undo all the changes made after the given point.
  2281. void rollback(ConstRestorationPt Point);
  2282. /// Get the current restoration point.
  2283. ConstRestorationPt getRestorationPoint() const;
  2284. /// \name API for IR modification with state keeping to support rollback.
  2285. /// @{
  2286. /// Same as Instruction::setOperand.
  2287. void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
  2288. /// Same as Instruction::eraseFromParent.
  2289. void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
  2290. /// Same as Value::replaceAllUsesWith.
  2291. void replaceAllUsesWith(Instruction *Inst, Value *New);
  2292. /// Same as Value::mutateType.
  2293. void mutateType(Instruction *Inst, Type *NewTy);
  2294. /// Same as IRBuilder::createTrunc.
  2295. Value *createTrunc(Instruction *Opnd, Type *Ty);
  2296. /// Same as IRBuilder::createSExt.
  2297. Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
  2298. /// Same as IRBuilder::createZExt.
  2299. Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
  2300. /// Same as Instruction::moveBefore.
  2301. void moveBefore(Instruction *Inst, Instruction *Before);
  2302. /// @}
  2303. private:
  2304. /// The ordered list of actions made so far.
  2305. SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
  2306. using CommitPt = SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator;
  2307. SetOfInstrs &RemovedInsts;
  2308. };
  2309. } // end anonymous namespace
  2310. void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
  2311. Value *NewVal) {
  2312. Actions.push_back(std::make_unique<TypePromotionTransaction::OperandSetter>(
  2313. Inst, Idx, NewVal));
  2314. }
  2315. void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
  2316. Value *NewVal) {
  2317. Actions.push_back(
  2318. std::make_unique<TypePromotionTransaction::InstructionRemover>(
  2319. Inst, RemovedInsts, NewVal));
  2320. }
  2321. void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
  2322. Value *New) {
  2323. Actions.push_back(
  2324. std::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
  2325. }
  2326. void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
  2327. Actions.push_back(
  2328. std::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
  2329. }
  2330. Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
  2331. Type *Ty) {
  2332. std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
  2333. Value *Val = Ptr->getBuiltValue();
  2334. Actions.push_back(std::move(Ptr));
  2335. return Val;
  2336. }
  2337. Value *TypePromotionTransaction::createSExt(Instruction *Inst,
  2338. Value *Opnd, Type *Ty) {
  2339. std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
  2340. Value *Val = Ptr->getBuiltValue();
  2341. Actions.push_back(std::move(Ptr));
  2342. return Val;
  2343. }
  2344. Value *TypePromotionTransaction::createZExt(Instruction *Inst,
  2345. Value *Opnd, Type *Ty) {
  2346. std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
  2347. Value *Val = Ptr->getBuiltValue();
  2348. Actions.push_back(std::move(Ptr));
  2349. return Val;
  2350. }
  2351. void TypePromotionTransaction::moveBefore(Instruction *Inst,
  2352. Instruction *Before) {
  2353. Actions.push_back(
  2354. std::make_unique<TypePromotionTransaction::InstructionMoveBefore>(
  2355. Inst, Before));
  2356. }
  2357. TypePromotionTransaction::ConstRestorationPt
  2358. TypePromotionTransaction::getRestorationPoint() const {
  2359. return !Actions.empty() ? Actions.back().get() : nullptr;
  2360. }
  2361. void TypePromotionTransaction::commit() {
  2362. for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
  2363. ++It)
  2364. (*It)->commit();
  2365. Actions.clear();
  2366. }
  2367. void TypePromotionTransaction::rollback(
  2368. TypePromotionTransaction::ConstRestorationPt Point) {
  2369. while (!Actions.empty() && Point != Actions.back().get()) {
  2370. std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
  2371. Curr->undo();
  2372. }
  2373. }
  2374. namespace {
  2375. /// A helper class for matching addressing modes.
  2376. ///
  2377. /// This encapsulates the logic for matching the target-legal addressing modes.
  2378. class AddressingModeMatcher {
  2379. SmallVectorImpl<Instruction*> &AddrModeInsts;
  2380. const TargetLowering &TLI;
  2381. const TargetRegisterInfo &TRI;
  2382. const DataLayout &DL;
  2383. /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
  2384. /// the memory instruction that we're computing this address for.
  2385. Type *AccessTy;
  2386. unsigned AddrSpace;
  2387. Instruction *MemoryInst;
  2388. /// This is the addressing mode that we're building up. This is
  2389. /// part of the return value of this addressing mode matching stuff.
  2390. ExtAddrMode &AddrMode;
  2391. /// The instructions inserted by other CodeGenPrepare optimizations.
  2392. const SetOfInstrs &InsertedInsts;
  2393. /// A map from the instructions to their type before promotion.
  2394. InstrToOrigTy &PromotedInsts;
  2395. /// The ongoing transaction where every action should be registered.
  2396. TypePromotionTransaction &TPT;
  2397. // A GEP which has too large offset to be folded into the addressing mode.
  2398. std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP;
  2399. /// This is set to true when we should not do profitability checks.
  2400. /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
  2401. bool IgnoreProfitability;
  2402. AddressingModeMatcher(
  2403. SmallVectorImpl<Instruction *> &AMI, const TargetLowering &TLI,
  2404. const TargetRegisterInfo &TRI, Type *AT, unsigned AS, Instruction *MI,
  2405. ExtAddrMode &AM, const SetOfInstrs &InsertedInsts,
  2406. InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT,
  2407. std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP)
  2408. : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
  2409. DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
  2410. MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
  2411. PromotedInsts(PromotedInsts), TPT(TPT), LargeOffsetGEP(LargeOffsetGEP) {
  2412. IgnoreProfitability = false;
  2413. }
  2414. public:
  2415. /// Find the maximal addressing mode that a load/store of V can fold,
  2416. /// give an access type of AccessTy. This returns a list of involved
  2417. /// instructions in AddrModeInsts.
  2418. /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
  2419. /// optimizations.
  2420. /// \p PromotedInsts maps the instructions to their type before promotion.
  2421. /// \p The ongoing transaction where every action should be registered.
  2422. static ExtAddrMode
  2423. Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst,
  2424. SmallVectorImpl<Instruction *> &AddrModeInsts,
  2425. const TargetLowering &TLI, const TargetRegisterInfo &TRI,
  2426. const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts,
  2427. TypePromotionTransaction &TPT,
  2428. std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP) {
  2429. ExtAddrMode Result;
  2430. bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI, AccessTy, AS,
  2431. MemoryInst, Result, InsertedInsts,
  2432. PromotedInsts, TPT, LargeOffsetGEP)
  2433. .matchAddr(V, 0);
  2434. (void)Success; assert(Success && "Couldn't select *anything*?");
  2435. return Result;
  2436. }
  2437. private:
  2438. bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
  2439. bool matchAddr(Value *Addr, unsigned Depth);
  2440. bool matchOperationAddr(User *AddrInst, unsigned Opcode, unsigned Depth,
  2441. bool *MovedAway = nullptr);
  2442. bool isProfitableToFoldIntoAddressingMode(Instruction *I,
  2443. ExtAddrMode &AMBefore,
  2444. ExtAddrMode &AMAfter);
  2445. bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
  2446. bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
  2447. Value *PromotedOperand) const;
  2448. };
  2449. class PhiNodeSet;
  2450. /// An iterator for PhiNodeSet.
  2451. class PhiNodeSetIterator {
  2452. PhiNodeSet * const Set;
  2453. size_t CurrentIndex = 0;
  2454. public:
  2455. /// The constructor. Start should point to either a valid element, or be equal
  2456. /// to the size of the underlying SmallVector of the PhiNodeSet.
  2457. PhiNodeSetIterator(PhiNodeSet * const Set, size_t Start);
  2458. PHINode * operator*() const;
  2459. PhiNodeSetIterator& operator++();
  2460. bool operator==(const PhiNodeSetIterator &RHS) const;
  2461. bool operator!=(const PhiNodeSetIterator &RHS) const;
  2462. };
  2463. /// Keeps a set of PHINodes.
  2464. ///
  2465. /// This is a minimal set implementation for a specific use case:
  2466. /// It is very fast when there are very few elements, but also provides good
  2467. /// performance when there are many. It is similar to SmallPtrSet, but also
  2468. /// provides iteration by insertion order, which is deterministic and stable
  2469. /// across runs. It is also similar to SmallSetVector, but provides removing
  2470. /// elements in O(1) time. This is achieved by not actually removing the element
  2471. /// from the underlying vector, so comes at the cost of using more memory, but
  2472. /// that is fine, since PhiNodeSets are used as short lived objects.
  2473. class PhiNodeSet {
  2474. friend class PhiNodeSetIterator;
  2475. using MapType = SmallDenseMap<PHINode *, size_t, 32>;
  2476. using iterator = PhiNodeSetIterator;
  2477. /// Keeps the elements in the order of their insertion in the underlying
  2478. /// vector. To achieve constant time removal, it never deletes any element.
  2479. SmallVector<PHINode *, 32> NodeList;
  2480. /// Keeps the elements in the underlying set implementation. This (and not the
  2481. /// NodeList defined above) is the source of truth on whether an element
  2482. /// is actually in the collection.
  2483. MapType NodeMap;
  2484. /// Points to the first valid (not deleted) element when the set is not empty
  2485. /// and the value is not zero. Equals to the size of the underlying vector
  2486. /// when the set is empty. When the value is 0, as in the beginning, the
  2487. /// first element may or may not be valid.
  2488. size_t FirstValidElement = 0;
  2489. public:
  2490. /// Inserts a new element to the collection.
  2491. /// \returns true if the element is actually added, i.e. was not in the
  2492. /// collection before the operation.
  2493. bool insert(PHINode *Ptr) {
  2494. if (NodeMap.insert(std::make_pair(Ptr, NodeList.size())).second) {
  2495. NodeList.push_back(Ptr);
  2496. return true;
  2497. }
  2498. return false;
  2499. }
  2500. /// Removes the element from the collection.
  2501. /// \returns whether the element is actually removed, i.e. was in the
  2502. /// collection before the operation.
  2503. bool erase(PHINode *Ptr) {
  2504. auto it = NodeMap.find(Ptr);
  2505. if (it != NodeMap.end()) {
  2506. NodeMap.erase(Ptr);
  2507. SkipRemovedElements(FirstValidElement);
  2508. return true;
  2509. }
  2510. return false;
  2511. }
  2512. /// Removes all elements and clears the collection.
  2513. void clear() {
  2514. NodeMap.clear();
  2515. NodeList.clear();
  2516. FirstValidElement = 0;
  2517. }
  2518. /// \returns an iterator that will iterate the elements in the order of
  2519. /// insertion.
  2520. iterator begin() {
  2521. if (FirstValidElement == 0)
  2522. SkipRemovedElements(FirstValidElement);
  2523. return PhiNodeSetIterator(this, FirstValidElement);
  2524. }
  2525. /// \returns an iterator that points to the end of the collection.
  2526. iterator end() { return PhiNodeSetIterator(this, NodeList.size()); }
  2527. /// Returns the number of elements in the collection.
  2528. size_t size() const {
  2529. return NodeMap.size();
  2530. }
  2531. /// \returns 1 if the given element is in the collection, and 0 if otherwise.
  2532. size_t count(PHINode *Ptr) const {
  2533. return NodeMap.count(Ptr);
  2534. }
  2535. private:
  2536. /// Updates the CurrentIndex so that it will point to a valid element.
  2537. ///
  2538. /// If the element of NodeList at CurrentIndex is valid, it does not
  2539. /// change it. If there are no more valid elements, it updates CurrentIndex
  2540. /// to point to the end of the NodeList.
  2541. void SkipRemovedElements(size_t &CurrentIndex) {
  2542. while (CurrentIndex < NodeList.size()) {
  2543. auto it = NodeMap.find(NodeList[CurrentIndex]);
  2544. // If the element has been deleted and added again later, NodeMap will
  2545. // point to a different index, so CurrentIndex will still be invalid.
  2546. if (it != NodeMap.end() && it->second == CurrentIndex)
  2547. break;
  2548. ++CurrentIndex;
  2549. }
  2550. }
  2551. };
  2552. PhiNodeSetIterator::PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start)
  2553. : Set(Set), CurrentIndex(Start) {}
  2554. PHINode * PhiNodeSetIterator::operator*() const {
  2555. assert(CurrentIndex < Set->NodeList.size() &&
  2556. "PhiNodeSet access out of range");
  2557. return Set->NodeList[CurrentIndex];
  2558. }
  2559. PhiNodeSetIterator& PhiNodeSetIterator::operator++() {
  2560. assert(CurrentIndex < Set->NodeList.size() &&
  2561. "PhiNodeSet access out of range");
  2562. ++CurrentIndex;
  2563. Set->SkipRemovedElements(CurrentIndex);
  2564. return *this;
  2565. }
  2566. bool PhiNodeSetIterator::operator==(const PhiNodeSetIterator &RHS) const {
  2567. return CurrentIndex == RHS.CurrentIndex;
  2568. }
  2569. bool PhiNodeSetIterator::operator!=(const PhiNodeSetIterator &RHS) const {
  2570. return !((*this) == RHS);
  2571. }
  2572. /// Keep track of simplification of Phi nodes.
  2573. /// Accept the set of all phi nodes and erase phi node from this set
  2574. /// if it is simplified.
  2575. class SimplificationTracker {
  2576. DenseMap<Value *, Value *> Storage;
  2577. const SimplifyQuery &SQ;
  2578. // Tracks newly created Phi nodes. The elements are iterated by insertion
  2579. // order.
  2580. PhiNodeSet AllPhiNodes;
  2581. // Tracks newly created Select nodes.
  2582. SmallPtrSet<SelectInst *, 32> AllSelectNodes;
  2583. public:
  2584. SimplificationTracker(const SimplifyQuery &sq)
  2585. : SQ(sq) {}
  2586. Value *Get(Value *V) {
  2587. do {
  2588. auto SV = Storage.find(V);
  2589. if (SV == Storage.end())
  2590. return V;
  2591. V = SV->second;
  2592. } while (true);
  2593. }
  2594. Value *Simplify(Value *Val) {
  2595. SmallVector<Value *, 32> WorkList;
  2596. SmallPtrSet<Value *, 32> Visited;
  2597. WorkList.push_back(Val);
  2598. while (!WorkList.empty()) {
  2599. auto P = WorkList.pop_back_val();
  2600. if (!Visited.insert(P).second)
  2601. continue;
  2602. if (auto *PI = dyn_cast<Instruction>(P))
  2603. if (Value *V = SimplifyInstruction(cast<Instruction>(PI), SQ)) {
  2604. for (auto *U : PI->users())
  2605. WorkList.push_back(cast<Value>(U));
  2606. Put(PI, V);
  2607. PI->replaceAllUsesWith(V);
  2608. if (auto *PHI = dyn_cast<PHINode>(PI))
  2609. AllPhiNodes.erase(PHI);
  2610. if (auto *Select = dyn_cast<SelectInst>(PI))
  2611. AllSelectNodes.erase(Select);
  2612. PI->eraseFromParent();
  2613. }
  2614. }
  2615. return Get(Val);
  2616. }
  2617. void Put(Value *From, Value *To) {
  2618. Storage.insert({ From, To });
  2619. }
  2620. void ReplacePhi(PHINode *From, PHINode *To) {
  2621. Value* OldReplacement = Get(From);
  2622. while (OldReplacement != From) {
  2623. From = To;
  2624. To = dyn_cast<PHINode>(OldReplacement);
  2625. OldReplacement = Get(From);
  2626. }
  2627. assert(To && Get(To) == To && "Replacement PHI node is already replaced.");
  2628. Put(From, To);
  2629. From->replaceAllUsesWith(To);
  2630. AllPhiNodes.erase(From);
  2631. From->eraseFromParent();
  2632. }
  2633. PhiNodeSet& newPhiNodes() { return AllPhiNodes; }
  2634. void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); }
  2635. void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); }
  2636. unsigned countNewPhiNodes() const { return AllPhiNodes.size(); }
  2637. unsigned countNewSelectNodes() const { return AllSelectNodes.size(); }
  2638. void destroyNewNodes(Type *CommonType) {
  2639. // For safe erasing, replace the uses with dummy value first.
  2640. auto Dummy = UndefValue::get(CommonType);
  2641. for (auto I : AllPhiNodes) {
  2642. I->replaceAllUsesWith(Dummy);
  2643. I->eraseFromParent();
  2644. }
  2645. AllPhiNodes.clear();
  2646. for (auto I : AllSelectNodes) {
  2647. I->replaceAllUsesWith(Dummy);
  2648. I->eraseFromParent();
  2649. }
  2650. AllSelectNodes.clear();
  2651. }
  2652. };
  2653. /// A helper class for combining addressing modes.
  2654. class AddressingModeCombiner {
  2655. typedef DenseMap<Value *, Value *> FoldAddrToValueMapping;
  2656. typedef std::pair<PHINode *, PHINode *> PHIPair;
  2657. private:
  2658. /// The addressing modes we've collected.
  2659. SmallVector<ExtAddrMode, 16> AddrModes;
  2660. /// The field in which the AddrModes differ, when we have more than one.
  2661. ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
  2662. /// Are the AddrModes that we have all just equal to their original values?
  2663. bool AllAddrModesTrivial = true;
  2664. /// Common Type for all different fields in addressing modes.
  2665. Type *CommonType;
  2666. /// SimplifyQuery for simplifyInstruction utility.
  2667. const SimplifyQuery &SQ;
  2668. /// Original Address.
  2669. Value *Original;
  2670. public:
  2671. AddressingModeCombiner(const SimplifyQuery &_SQ, Value *OriginalValue)
  2672. : CommonType(nullptr), SQ(_SQ), Original(OriginalValue) {}
  2673. /// Get the combined AddrMode
  2674. const ExtAddrMode &getAddrMode() const {
  2675. return AddrModes[0];
  2676. }
  2677. /// Add a new AddrMode if it's compatible with the AddrModes we already
  2678. /// have.
  2679. /// \return True iff we succeeded in doing so.
  2680. bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
  2681. // Take note of if we have any non-trivial AddrModes, as we need to detect
  2682. // when all AddrModes are trivial as then we would introduce a phi or select
  2683. // which just duplicates what's already there.
  2684. AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
  2685. // If this is the first addrmode then everything is fine.
  2686. if (AddrModes.empty()) {
  2687. AddrModes.emplace_back(NewAddrMode);
  2688. return true;
  2689. }
  2690. // Figure out how different this is from the other address modes, which we
  2691. // can do just by comparing against the first one given that we only care
  2692. // about the cumulative difference.
  2693. ExtAddrMode::FieldName ThisDifferentField =
  2694. AddrModes[0].compare(NewAddrMode);
  2695. if (DifferentField == ExtAddrMode::NoField)
  2696. DifferentField = ThisDifferentField;
  2697. else if (DifferentField != ThisDifferentField)
  2698. DifferentField = ExtAddrMode::MultipleFields;
  2699. // If NewAddrMode differs in more than one dimension we cannot handle it.
  2700. bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
  2701. // If Scale Field is different then we reject.
  2702. CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
  2703. // We also must reject the case when base offset is different and
  2704. // scale reg is not null, we cannot handle this case due to merge of
  2705. // different offsets will be used as ScaleReg.
  2706. CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
  2707. !NewAddrMode.ScaledReg);
  2708. // We also must reject the case when GV is different and BaseReg installed
  2709. // due to we want to use base reg as a merge of GV values.
  2710. CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
  2711. !NewAddrMode.HasBaseReg);
  2712. // Even if NewAddMode is the same we still need to collect it due to
  2713. // original value is different. And later we will need all original values
  2714. // as anchors during finding the common Phi node.
  2715. if (CanHandle)
  2716. AddrModes.emplace_back(NewAddrMode);
  2717. else
  2718. AddrModes.clear();
  2719. return CanHandle;
  2720. }
  2721. /// Combine the addressing modes we've collected into a single
  2722. /// addressing mode.
  2723. /// \return True iff we successfully combined them or we only had one so
  2724. /// didn't need to combine them anyway.
  2725. bool combineAddrModes() {
  2726. // If we have no AddrModes then they can't be combined.
  2727. if (AddrModes.size() == 0)
  2728. return false;
  2729. // A single AddrMode can trivially be combined.
  2730. if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
  2731. return true;
  2732. // If the AddrModes we collected are all just equal to the value they are
  2733. // derived from then combining them wouldn't do anything useful.
  2734. if (AllAddrModesTrivial)
  2735. return false;
  2736. if (!addrModeCombiningAllowed())
  2737. return false;
  2738. // Build a map between <original value, basic block where we saw it> to
  2739. // value of base register.
  2740. // Bail out if there is no common type.
  2741. FoldAddrToValueMapping Map;
  2742. if (!initializeMap(Map))
  2743. return false;
  2744. Value *CommonValue = findCommon(Map);
  2745. if (CommonValue)
  2746. AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
  2747. return CommonValue != nullptr;
  2748. }
  2749. private:
  2750. /// Initialize Map with anchor values. For address seen
  2751. /// we set the value of different field saw in this address.
  2752. /// At the same time we find a common type for different field we will
  2753. /// use to create new Phi/Select nodes. Keep it in CommonType field.
  2754. /// Return false if there is no common type found.
  2755. bool initializeMap(FoldAddrToValueMapping &Map) {
  2756. // Keep track of keys where the value is null. We will need to replace it
  2757. // with constant null when we know the common type.
  2758. SmallVector<Value *, 2> NullValue;
  2759. Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
  2760. for (auto &AM : AddrModes) {
  2761. Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
  2762. if (DV) {
  2763. auto *Type = DV->getType();
  2764. if (CommonType && CommonType != Type)
  2765. return false;
  2766. CommonType = Type;
  2767. Map[AM.OriginalValue] = DV;
  2768. } else {
  2769. NullValue.push_back(AM.OriginalValue);
  2770. }
  2771. }
  2772. assert(CommonType && "At least one non-null value must be!");
  2773. for (auto *V : NullValue)
  2774. Map[V] = Constant::getNullValue(CommonType);
  2775. return true;
  2776. }
  2777. /// We have mapping between value A and other value B where B was a field in
  2778. /// addressing mode represented by A. Also we have an original value C
  2779. /// representing an address we start with. Traversing from C through phi and
  2780. /// selects we ended up with A's in a map. This utility function tries to find
  2781. /// a value V which is a field in addressing mode C and traversing through phi
  2782. /// nodes and selects we will end up in corresponded values B in a map.
  2783. /// The utility will create a new Phi/Selects if needed.
  2784. // The simple example looks as follows:
  2785. // BB1:
  2786. // p1 = b1 + 40
  2787. // br cond BB2, BB3
  2788. // BB2:
  2789. // p2 = b2 + 40
  2790. // br BB3
  2791. // BB3:
  2792. // p = phi [p1, BB1], [p2, BB2]
  2793. // v = load p
  2794. // Map is
  2795. // p1 -> b1
  2796. // p2 -> b2
  2797. // Request is
  2798. // p -> ?
  2799. // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3.
  2800. Value *findCommon(FoldAddrToValueMapping &Map) {
  2801. // Tracks the simplification of newly created phi nodes. The reason we use
  2802. // this mapping is because we will add new created Phi nodes in AddrToBase.
  2803. // Simplification of Phi nodes is recursive, so some Phi node may
  2804. // be simplified after we added it to AddrToBase. In reality this
  2805. // simplification is possible only if original phi/selects were not
  2806. // simplified yet.
  2807. // Using this mapping we can find the current value in AddrToBase.
  2808. SimplificationTracker ST(SQ);
  2809. // First step, DFS to create PHI nodes for all intermediate blocks.
  2810. // Also fill traverse order for the second step.
  2811. SmallVector<Value *, 32> TraverseOrder;
  2812. InsertPlaceholders(Map, TraverseOrder, ST);
  2813. // Second Step, fill new nodes by merged values and simplify if possible.
  2814. FillPlaceholders(Map, TraverseOrder, ST);
  2815. if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) {
  2816. ST.destroyNewNodes(CommonType);
  2817. return nullptr;
  2818. }
  2819. // Now we'd like to match New Phi nodes to existed ones.
  2820. unsigned PhiNotMatchedCount = 0;
  2821. if (!MatchPhiSet(ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
  2822. ST.destroyNewNodes(CommonType);
  2823. return nullptr;
  2824. }
  2825. auto *Result = ST.Get(Map.find(Original)->second);
  2826. if (Result) {
  2827. NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
  2828. NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
  2829. }
  2830. return Result;
  2831. }
  2832. /// Try to match PHI node to Candidate.
  2833. /// Matcher tracks the matched Phi nodes.
  2834. bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
  2835. SmallSetVector<PHIPair, 8> &Matcher,
  2836. PhiNodeSet &PhiNodesToMatch) {
  2837. SmallVector<PHIPair, 8> WorkList;
  2838. Matcher.insert({ PHI, Candidate });
  2839. SmallSet<PHINode *, 8> MatchedPHIs;
  2840. MatchedPHIs.insert(PHI);
  2841. WorkList.push_back({ PHI, Candidate });
  2842. SmallSet<PHIPair, 8> Visited;
  2843. while (!WorkList.empty()) {
  2844. auto Item = WorkList.pop_back_val();
  2845. if (!Visited.insert(Item).second)
  2846. continue;
  2847. // We iterate over all incoming values to Phi to compare them.
  2848. // If values are different and both of them Phi and the first one is a
  2849. // Phi we added (subject to match) and both of them is in the same basic
  2850. // block then we can match our pair if values match. So we state that
  2851. // these values match and add it to work list to verify that.
  2852. for (auto B : Item.first->blocks()) {
  2853. Value *FirstValue = Item.first->getIncomingValueForBlock(B);
  2854. Value *SecondValue = Item.second->getIncomingValueForBlock(B);
  2855. if (FirstValue == SecondValue)
  2856. continue;
  2857. PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
  2858. PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
  2859. // One of them is not Phi or
  2860. // The first one is not Phi node from the set we'd like to match or
  2861. // Phi nodes from different basic blocks then
  2862. // we will not be able to match.
  2863. if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
  2864. FirstPhi->getParent() != SecondPhi->getParent())
  2865. return false;
  2866. // If we already matched them then continue.
  2867. if (Matcher.count({ FirstPhi, SecondPhi }))
  2868. continue;
  2869. // So the values are different and does not match. So we need them to
  2870. // match. (But we register no more than one match per PHI node, so that
  2871. // we won't later try to replace them twice.)
  2872. if (MatchedPHIs.insert(FirstPhi).second)
  2873. Matcher.insert({ FirstPhi, SecondPhi });
  2874. // But me must check it.
  2875. WorkList.push_back({ FirstPhi, SecondPhi });
  2876. }
  2877. }
  2878. return true;
  2879. }
  2880. /// For the given set of PHI nodes (in the SimplificationTracker) try
  2881. /// to find their equivalents.
  2882. /// Returns false if this matching fails and creation of new Phi is disabled.
  2883. bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes,
  2884. unsigned &PhiNotMatchedCount) {
  2885. // Matched and PhiNodesToMatch iterate their elements in a deterministic
  2886. // order, so the replacements (ReplacePhi) are also done in a deterministic
  2887. // order.
  2888. SmallSetVector<PHIPair, 8> Matched;
  2889. SmallPtrSet<PHINode *, 8> WillNotMatch;
  2890. PhiNodeSet &PhiNodesToMatch = ST.newPhiNodes();
  2891. while (PhiNodesToMatch.size()) {
  2892. PHINode *PHI = *PhiNodesToMatch.begin();
  2893. // Add us, if no Phi nodes in the basic block we do not match.
  2894. WillNotMatch.clear();
  2895. WillNotMatch.insert(PHI);
  2896. // Traverse all Phis until we found equivalent or fail to do that.
  2897. bool IsMatched = false;
  2898. for (auto &P : PHI->getParent()->phis()) {
  2899. if (&P == PHI)
  2900. continue;
  2901. if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
  2902. break;
  2903. // If it does not match, collect all Phi nodes from matcher.
  2904. // if we end up with no match, them all these Phi nodes will not match
  2905. // later.
  2906. for (auto M : Matched)
  2907. WillNotMatch.insert(M.first);
  2908. Matched.clear();
  2909. }
  2910. if (IsMatched) {
  2911. // Replace all matched values and erase them.
  2912. for (auto MV : Matched)
  2913. ST.ReplacePhi(MV.first, MV.second);
  2914. Matched.clear();
  2915. continue;
  2916. }
  2917. // If we are not allowed to create new nodes then bail out.
  2918. if (!AllowNewPhiNodes)
  2919. return false;
  2920. // Just remove all seen values in matcher. They will not match anything.
  2921. PhiNotMatchedCount += WillNotMatch.size();
  2922. for (auto *P : WillNotMatch)
  2923. PhiNodesToMatch.erase(P);
  2924. }
  2925. return true;
  2926. }
  2927. /// Fill the placeholders with values from predecessors and simplify them.
  2928. void FillPlaceholders(FoldAddrToValueMapping &Map,
  2929. SmallVectorImpl<Value *> &TraverseOrder,
  2930. SimplificationTracker &ST) {
  2931. while (!TraverseOrder.empty()) {
  2932. Value *Current = TraverseOrder.pop_back_val();
  2933. assert(Map.find(Current) != Map.end() && "No node to fill!!!");
  2934. Value *V = Map[Current];
  2935. if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
  2936. // CurrentValue also must be Select.
  2937. auto *CurrentSelect = cast<SelectInst>(Current);
  2938. auto *TrueValue = CurrentSelect->getTrueValue();
  2939. assert(Map.find(TrueValue) != Map.end() && "No True Value!");
  2940. Select->setTrueValue(ST.Get(Map[TrueValue]));
  2941. auto *FalseValue = CurrentSelect->getFalseValue();
  2942. assert(Map.find(FalseValue) != Map.end() && "No False Value!");
  2943. Select->setFalseValue(ST.Get(Map[FalseValue]));
  2944. } else {
  2945. // Must be a Phi node then.
  2946. auto *PHI = cast<PHINode>(V);
  2947. // Fill the Phi node with values from predecessors.
  2948. for (auto B : predecessors(PHI->getParent())) {
  2949. Value *PV = cast<PHINode>(Current)->getIncomingValueForBlock(B);
  2950. assert(Map.find(PV) != Map.end() && "No predecessor Value!");
  2951. PHI->addIncoming(ST.Get(Map[PV]), B);
  2952. }
  2953. }
  2954. Map[Current] = ST.Simplify(V);
  2955. }
  2956. }
  2957. /// Starting from original value recursively iterates over def-use chain up to
  2958. /// known ending values represented in a map. For each traversed phi/select
  2959. /// inserts a placeholder Phi or Select.
  2960. /// Reports all new created Phi/Select nodes by adding them to set.
  2961. /// Also reports and order in what values have been traversed.
  2962. void InsertPlaceholders(FoldAddrToValueMapping &Map,
  2963. SmallVectorImpl<Value *> &TraverseOrder,
  2964. SimplificationTracker &ST) {
  2965. SmallVector<Value *, 32> Worklist;
  2966. assert((isa<PHINode>(Original) || isa<SelectInst>(Original)) &&
  2967. "Address must be a Phi or Select node");
  2968. auto *Dummy = UndefValue::get(CommonType);
  2969. Worklist.push_back(Original);
  2970. while (!Worklist.empty()) {
  2971. Value *Current = Worklist.pop_back_val();
  2972. // if it is already visited or it is an ending value then skip it.
  2973. if (Map.find(Current) != Map.end())
  2974. continue;
  2975. TraverseOrder.push_back(Current);
  2976. // CurrentValue must be a Phi node or select. All others must be covered
  2977. // by anchors.
  2978. if (SelectInst *CurrentSelect = dyn_cast<SelectInst>(Current)) {
  2979. // Is it OK to get metadata from OrigSelect?!
  2980. // Create a Select placeholder with dummy value.
  2981. SelectInst *Select = SelectInst::Create(
  2982. CurrentSelect->getCondition(), Dummy, Dummy,
  2983. CurrentSelect->getName(), CurrentSelect, CurrentSelect);
  2984. Map[Current] = Select;
  2985. ST.insertNewSelect(Select);
  2986. // We are interested in True and False values.
  2987. Worklist.push_back(CurrentSelect->getTrueValue());
  2988. Worklist.push_back(CurrentSelect->getFalseValue());
  2989. } else {
  2990. // It must be a Phi node then.
  2991. PHINode *CurrentPhi = cast<PHINode>(Current);
  2992. unsigned PredCount = CurrentPhi->getNumIncomingValues();
  2993. PHINode *PHI =
  2994. PHINode::Create(CommonType, PredCount, "sunk_phi", CurrentPhi);
  2995. Map[Current] = PHI;
  2996. ST.insertNewPhi(PHI);
  2997. for (Value *P : CurrentPhi->incoming_values())
  2998. Worklist.push_back(P);
  2999. }
  3000. }
  3001. }
  3002. bool addrModeCombiningAllowed() {
  3003. if (DisableComplexAddrModes)
  3004. return false;
  3005. switch (DifferentField) {
  3006. default:
  3007. return false;
  3008. case ExtAddrMode::BaseRegField:
  3009. return AddrSinkCombineBaseReg;
  3010. case ExtAddrMode::BaseGVField:
  3011. return AddrSinkCombineBaseGV;
  3012. case ExtAddrMode::BaseOffsField:
  3013. return AddrSinkCombineBaseOffs;
  3014. case ExtAddrMode::ScaledRegField:
  3015. return AddrSinkCombineScaledReg;
  3016. }
  3017. }
  3018. };
  3019. } // end anonymous namespace
  3020. /// Try adding ScaleReg*Scale to the current addressing mode.
  3021. /// Return true and update AddrMode if this addr mode is legal for the target,
  3022. /// false if not.
  3023. bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
  3024. unsigned Depth) {
  3025. // If Scale is 1, then this is the same as adding ScaleReg to the addressing
  3026. // mode. Just process that directly.
  3027. if (Scale == 1)
  3028. return matchAddr(ScaleReg, Depth);
  3029. // If the scale is 0, it takes nothing to add this.
  3030. if (Scale == 0)
  3031. return true;
  3032. // If we already have a scale of this value, we can add to it, otherwise, we
  3033. // need an available scale field.
  3034. if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
  3035. return false;
  3036. ExtAddrMode TestAddrMode = AddrMode;
  3037. // Add scale to turn X*4+X*3 -> X*7. This could also do things like
  3038. // [A+B + A*7] -> [B+A*8].
  3039. TestAddrMode.Scale += Scale;
  3040. TestAddrMode.ScaledReg = ScaleReg;
  3041. // If the new address isn't legal, bail out.
  3042. if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
  3043. return false;
  3044. // It was legal, so commit it.
  3045. AddrMode = TestAddrMode;
  3046. // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
  3047. // to see if ScaleReg is actually X+C. If so, we can turn this into adding
  3048. // X*Scale + C*Scale to addr mode.
  3049. ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
  3050. if (isa<Instruction>(ScaleReg) && // not a constant expr.
  3051. match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
  3052. TestAddrMode.InBounds = false;
  3053. TestAddrMode.ScaledReg = AddLHS;
  3054. TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
  3055. // If this addressing mode is legal, commit it and remember that we folded
  3056. // this instruction.
  3057. if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
  3058. AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
  3059. AddrMode = TestAddrMode;
  3060. return true;
  3061. }
  3062. }
  3063. // Otherwise, not (x+c)*scale, just return what we have.
  3064. return true;
  3065. }
  3066. /// This is a little filter, which returns true if an addressing computation
  3067. /// involving I might be folded into a load/store accessing it.
  3068. /// This doesn't need to be perfect, but needs to accept at least
  3069. /// the set of instructions that MatchOperationAddr can.
  3070. static bool MightBeFoldableInst(Instruction *I) {
  3071. switch (I->getOpcode()) {
  3072. case Instruction::BitCast:
  3073. case Instruction::AddrSpaceCast:
  3074. // Don't touch identity bitcasts.
  3075. if (I->getType() == I->getOperand(0)->getType())
  3076. return false;
  3077. return I->getType()->isIntOrPtrTy();
  3078. case Instruction::PtrToInt:
  3079. // PtrToInt is always a noop, as we know that the int type is pointer sized.
  3080. return true;
  3081. case Instruction::IntToPtr:
  3082. // We know the input is intptr_t, so this is foldable.
  3083. return true;
  3084. case Instruction::Add:
  3085. return true;
  3086. case Instruction::Mul:
  3087. case Instruction::Shl:
  3088. // Can only handle X*C and X << C.
  3089. return isa<ConstantInt>(I->getOperand(1));
  3090. case Instruction::GetElementPtr:
  3091. return true;
  3092. default:
  3093. return false;
  3094. }
  3095. }
  3096. /// Check whether or not \p Val is a legal instruction for \p TLI.
  3097. /// \note \p Val is assumed to be the product of some type promotion.
  3098. /// Therefore if \p Val has an undefined state in \p TLI, this is assumed
  3099. /// to be legal, as the non-promoted value would have had the same state.
  3100. static bool isPromotedInstructionLegal(const TargetLowering &TLI,
  3101. const DataLayout &DL, Value *Val) {
  3102. Instruction *PromotedInst = dyn_cast<Instruction>(Val);
  3103. if (!PromotedInst)
  3104. return false;
  3105. int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
  3106. // If the ISDOpcode is undefined, it was undefined before the promotion.
  3107. if (!ISDOpcode)
  3108. return true;
  3109. // Otherwise, check if the promoted instruction is legal or not.
  3110. return TLI.isOperationLegalOrCustom(
  3111. ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
  3112. }
  3113. namespace {
  3114. /// Hepler class to perform type promotion.
  3115. class TypePromotionHelper {
  3116. /// Utility function to add a promoted instruction \p ExtOpnd to
  3117. /// \p PromotedInsts and record the type of extension we have seen.
  3118. static void addPromotedInst(InstrToOrigTy &PromotedInsts,
  3119. Instruction *ExtOpnd,
  3120. bool IsSExt) {
  3121. ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
  3122. InstrToOrigTy::iterator It = PromotedInsts.find(ExtOpnd);
  3123. if (It != PromotedInsts.end()) {
  3124. // If the new extension is same as original, the information in
  3125. // PromotedInsts[ExtOpnd] is still correct.
  3126. if (It->second.getInt() == ExtTy)
  3127. return;
  3128. // Now the new extension is different from old extension, we make
  3129. // the type information invalid by setting extension type to
  3130. // BothExtension.
  3131. ExtTy = BothExtension;
  3132. }
  3133. PromotedInsts[ExtOpnd] = TypeIsSExt(ExtOpnd->getType(), ExtTy);
  3134. }
  3135. /// Utility function to query the original type of instruction \p Opnd
  3136. /// with a matched extension type. If the extension doesn't match, we
  3137. /// cannot use the information we had on the original type.
  3138. /// BothExtension doesn't match any extension type.
  3139. static const Type *getOrigType(const InstrToOrigTy &PromotedInsts,
  3140. Instruction *Opnd,
  3141. bool IsSExt) {
  3142. ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
  3143. InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
  3144. if (It != PromotedInsts.end() && It->second.getInt() == ExtTy)
  3145. return It->second.getPointer();
  3146. return nullptr;
  3147. }
  3148. /// Utility function to check whether or not a sign or zero extension
  3149. /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
  3150. /// either using the operands of \p Inst or promoting \p Inst.
  3151. /// The type of the extension is defined by \p IsSExt.
  3152. /// In other words, check if:
  3153. /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
  3154. /// #1 Promotion applies:
  3155. /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
  3156. /// #2 Operand reuses:
  3157. /// ext opnd1 to ConsideredExtType.
  3158. /// \p PromotedInsts maps the instructions to their type before promotion.
  3159. static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
  3160. const InstrToOrigTy &PromotedInsts, bool IsSExt);
  3161. /// Utility function to determine if \p OpIdx should be promoted when
  3162. /// promoting \p Inst.
  3163. static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
  3164. return !(isa<SelectInst>(Inst) && OpIdx == 0);
  3165. }
  3166. /// Utility function to promote the operand of \p Ext when this
  3167. /// operand is a promotable trunc or sext or zext.
  3168. /// \p PromotedInsts maps the instructions to their type before promotion.
  3169. /// \p CreatedInstsCost[out] contains the cost of all instructions
  3170. /// created to promote the operand of Ext.
  3171. /// Newly added extensions are inserted in \p Exts.
  3172. /// Newly added truncates are inserted in \p Truncs.
  3173. /// Should never be called directly.
  3174. /// \return The promoted value which is used instead of Ext.
  3175. static Value *promoteOperandForTruncAndAnyExt(
  3176. Instruction *Ext, TypePromotionTransaction &TPT,
  3177. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  3178. SmallVectorImpl<Instruction *> *Exts,
  3179. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
  3180. /// Utility function to promote the operand of \p Ext when this
  3181. /// operand is promotable and is not a supported trunc or sext.
  3182. /// \p PromotedInsts maps the instructions to their type before promotion.
  3183. /// \p CreatedInstsCost[out] contains the cost of all the instructions
  3184. /// created to promote the operand of Ext.
  3185. /// Newly added extensions are inserted in \p Exts.
  3186. /// Newly added truncates are inserted in \p Truncs.
  3187. /// Should never be called directly.
  3188. /// \return The promoted value which is used instead of Ext.
  3189. static Value *promoteOperandForOther(Instruction *Ext,
  3190. TypePromotionTransaction &TPT,
  3191. InstrToOrigTy &PromotedInsts,
  3192. unsigned &CreatedInstsCost,
  3193. SmallVectorImpl<Instruction *> *Exts,
  3194. SmallVectorImpl<Instruction *> *Truncs,
  3195. const TargetLowering &TLI, bool IsSExt);
  3196. /// \see promoteOperandForOther.
  3197. static Value *signExtendOperandForOther(
  3198. Instruction *Ext, TypePromotionTransaction &TPT,
  3199. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  3200. SmallVectorImpl<Instruction *> *Exts,
  3201. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
  3202. return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
  3203. Exts, Truncs, TLI, true);
  3204. }
  3205. /// \see promoteOperandForOther.
  3206. static Value *zeroExtendOperandForOther(
  3207. Instruction *Ext, TypePromotionTransaction &TPT,
  3208. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  3209. SmallVectorImpl<Instruction *> *Exts,
  3210. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
  3211. return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
  3212. Exts, Truncs, TLI, false);
  3213. }
  3214. public:
  3215. /// Type for the utility function that promotes the operand of Ext.
  3216. using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
  3217. InstrToOrigTy &PromotedInsts,
  3218. unsigned &CreatedInstsCost,
  3219. SmallVectorImpl<Instruction *> *Exts,
  3220. SmallVectorImpl<Instruction *> *Truncs,
  3221. const TargetLowering &TLI);
  3222. /// Given a sign/zero extend instruction \p Ext, return the appropriate
  3223. /// action to promote the operand of \p Ext instead of using Ext.
  3224. /// \return NULL if no promotable action is possible with the current
  3225. /// sign extension.
  3226. /// \p InsertedInsts keeps track of all the instructions inserted by the
  3227. /// other CodeGenPrepare optimizations. This information is important
  3228. /// because we do not want to promote these instructions as CodeGenPrepare
  3229. /// will reinsert them later. Thus creating an infinite loop: create/remove.
  3230. /// \p PromotedInsts maps the instructions to their type before promotion.
  3231. static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
  3232. const TargetLowering &TLI,
  3233. const InstrToOrigTy &PromotedInsts);
  3234. };
  3235. } // end anonymous namespace
  3236. bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
  3237. Type *ConsideredExtType,
  3238. const InstrToOrigTy &PromotedInsts,
  3239. bool IsSExt) {
  3240. // The promotion helper does not know how to deal with vector types yet.
  3241. // To be able to fix that, we would need to fix the places where we
  3242. // statically extend, e.g., constants and such.
  3243. if (Inst->getType()->isVectorTy())
  3244. return false;
  3245. // We can always get through zext.
  3246. if (isa<ZExtInst>(Inst))
  3247. return true;
  3248. // sext(sext) is ok too.
  3249. if (IsSExt && isa<SExtInst>(Inst))
  3250. return true;
  3251. // We can get through binary operator, if it is legal. In other words, the
  3252. // binary operator must have a nuw or nsw flag.
  3253. const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
  3254. if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
  3255. ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
  3256. (IsSExt && BinOp->hasNoSignedWrap())))
  3257. return true;
  3258. // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst))
  3259. if ((Inst->getOpcode() == Instruction::And ||
  3260. Inst->getOpcode() == Instruction::Or))
  3261. return true;
  3262. // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst))
  3263. if (Inst->getOpcode() == Instruction::Xor) {
  3264. const ConstantInt *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1));
  3265. // Make sure it is not a NOT.
  3266. if (Cst && !Cst->getValue().isAllOnesValue())
  3267. return true;
  3268. }
  3269. // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst))
  3270. // It may change a poisoned value into a regular value, like
  3271. // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12
  3272. // poisoned value regular value
  3273. // It should be OK since undef covers valid value.
  3274. if (Inst->getOpcode() == Instruction::LShr && !IsSExt)
  3275. return true;
  3276. // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst)
  3277. // It may change a poisoned value into a regular value, like
  3278. // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12
  3279. // poisoned value regular value
  3280. // It should be OK since undef covers valid value.
  3281. if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) {
  3282. const auto *ExtInst = cast<const Instruction>(*Inst->user_begin());
  3283. if (ExtInst->hasOneUse()) {
  3284. const auto *AndInst = dyn_cast<const Instruction>(*ExtInst->user_begin());
  3285. if (AndInst && AndInst->getOpcode() == Instruction::And) {
  3286. const auto *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1));
  3287. if (Cst &&
  3288. Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth()))
  3289. return true;
  3290. }
  3291. }
  3292. }
  3293. // Check if we can do the following simplification.
  3294. // ext(trunc(opnd)) --> ext(opnd)
  3295. if (!isa<TruncInst>(Inst))
  3296. return false;
  3297. Value *OpndVal = Inst->getOperand(0);
  3298. // Check if we can use this operand in the extension.
  3299. // If the type is larger than the result type of the extension, we cannot.
  3300. if (!OpndVal->getType()->isIntegerTy() ||
  3301. OpndVal->getType()->getIntegerBitWidth() >
  3302. ConsideredExtType->getIntegerBitWidth())
  3303. return false;
  3304. // If the operand of the truncate is not an instruction, we will not have
  3305. // any information on the dropped bits.
  3306. // (Actually we could for constant but it is not worth the extra logic).
  3307. Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
  3308. if (!Opnd)
  3309. return false;
  3310. // Check if the source of the type is narrow enough.
  3311. // I.e., check that trunc just drops extended bits of the same kind of
  3312. // the extension.
  3313. // #1 get the type of the operand and check the kind of the extended bits.
  3314. const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt);
  3315. if (OpndType)
  3316. ;
  3317. else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
  3318. OpndType = Opnd->getOperand(0)->getType();
  3319. else
  3320. return false;
  3321. // #2 check that the truncate just drops extended bits.
  3322. return Inst->getType()->getIntegerBitWidth() >=
  3323. OpndType->getIntegerBitWidth();
  3324. }
  3325. TypePromotionHelper::Action TypePromotionHelper::getAction(
  3326. Instruction *Ext, const SetOfInstrs &InsertedInsts,
  3327. const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
  3328. assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
  3329. "Unexpected instruction type");
  3330. Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
  3331. Type *ExtTy = Ext->getType();
  3332. bool IsSExt = isa<SExtInst>(Ext);
  3333. // If the operand of the extension is not an instruction, we cannot
  3334. // get through.
  3335. // If it, check we can get through.
  3336. if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
  3337. return nullptr;
  3338. // Do not promote if the operand has been added by codegenprepare.
  3339. // Otherwise, it means we are undoing an optimization that is likely to be
  3340. // redone, thus causing potential infinite loop.
  3341. if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
  3342. return nullptr;
  3343. // SExt or Trunc instructions.
  3344. // Return the related handler.
  3345. if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
  3346. isa<ZExtInst>(ExtOpnd))
  3347. return promoteOperandForTruncAndAnyExt;
  3348. // Regular instruction.
  3349. // Abort early if we will have to insert non-free instructions.
  3350. if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
  3351. return nullptr;
  3352. return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
  3353. }
  3354. Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
  3355. Instruction *SExt, TypePromotionTransaction &TPT,
  3356. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  3357. SmallVectorImpl<Instruction *> *Exts,
  3358. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
  3359. // By construction, the operand of SExt is an instruction. Otherwise we cannot
  3360. // get through it and this method should not be called.
  3361. Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
  3362. Value *ExtVal = SExt;
  3363. bool HasMergedNonFreeExt = false;
  3364. if (isa<ZExtInst>(SExtOpnd)) {
  3365. // Replace s|zext(zext(opnd))
  3366. // => zext(opnd).
  3367. HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
  3368. Value *ZExt =
  3369. TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
  3370. TPT.replaceAllUsesWith(SExt, ZExt);
  3371. TPT.eraseInstruction(SExt);
  3372. ExtVal = ZExt;
  3373. } else {
  3374. // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
  3375. // => z|sext(opnd).
  3376. TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
  3377. }
  3378. CreatedInstsCost = 0;
  3379. // Remove dead code.
  3380. if (SExtOpnd->use_empty())
  3381. TPT.eraseInstruction(SExtOpnd);
  3382. // Check if the extension is still needed.
  3383. Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
  3384. if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
  3385. if (ExtInst) {
  3386. if (Exts)
  3387. Exts->push_back(ExtInst);
  3388. CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
  3389. }
  3390. return ExtVal;
  3391. }
  3392. // At this point we have: ext ty opnd to ty.
  3393. // Reassign the uses of ExtInst to the opnd and remove ExtInst.
  3394. Value *NextVal = ExtInst->getOperand(0);
  3395. TPT.eraseInstruction(ExtInst, NextVal);
  3396. return NextVal;
  3397. }
  3398. Value *TypePromotionHelper::promoteOperandForOther(
  3399. Instruction *Ext, TypePromotionTransaction &TPT,
  3400. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  3401. SmallVectorImpl<Instruction *> *Exts,
  3402. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
  3403. bool IsSExt) {
  3404. // By construction, the operand of Ext is an instruction. Otherwise we cannot
  3405. // get through it and this method should not be called.
  3406. Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
  3407. CreatedInstsCost = 0;
  3408. if (!ExtOpnd->hasOneUse()) {
  3409. // ExtOpnd will be promoted.
  3410. // All its uses, but Ext, will need to use a truncated value of the
  3411. // promoted version.
  3412. // Create the truncate now.
  3413. Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
  3414. if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
  3415. // Insert it just after the definition.
  3416. ITrunc->moveAfter(ExtOpnd);
  3417. if (Truncs)
  3418. Truncs->push_back(ITrunc);
  3419. }
  3420. TPT.replaceAllUsesWith(ExtOpnd, Trunc);
  3421. // Restore the operand of Ext (which has been replaced by the previous call
  3422. // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
  3423. TPT.setOperand(Ext, 0, ExtOpnd);
  3424. }
  3425. // Get through the Instruction:
  3426. // 1. Update its type.
  3427. // 2. Replace the uses of Ext by Inst.
  3428. // 3. Extend each operand that needs to be extended.
  3429. // Remember the original type of the instruction before promotion.
  3430. // This is useful to know that the high bits are sign extended bits.
  3431. addPromotedInst(PromotedInsts, ExtOpnd, IsSExt);
  3432. // Step #1.
  3433. TPT.mutateType(ExtOpnd, Ext->getType());
  3434. // Step #2.
  3435. TPT.replaceAllUsesWith(Ext, ExtOpnd);
  3436. // Step #3.
  3437. Instruction *ExtForOpnd = Ext;
  3438. LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n");
  3439. for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
  3440. ++OpIdx) {
  3441. LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
  3442. if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
  3443. !shouldExtOperand(ExtOpnd, OpIdx)) {
  3444. LLVM_DEBUG(dbgs() << "No need to propagate\n");
  3445. continue;
  3446. }
  3447. // Check if we can statically extend the operand.
  3448. Value *Opnd = ExtOpnd->getOperand(OpIdx);
  3449. if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
  3450. LLVM_DEBUG(dbgs() << "Statically extend\n");
  3451. unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
  3452. APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
  3453. : Cst->getValue().zext(BitWidth);
  3454. TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
  3455. continue;
  3456. }
  3457. // UndefValue are typed, so we have to statically sign extend them.
  3458. if (isa<UndefValue>(Opnd)) {
  3459. LLVM_DEBUG(dbgs() << "Statically extend\n");
  3460. TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
  3461. continue;
  3462. }
  3463. // Otherwise we have to explicitly sign extend the operand.
  3464. // Check if Ext was reused to extend an operand.
  3465. if (!ExtForOpnd) {
  3466. // If yes, create a new one.
  3467. LLVM_DEBUG(dbgs() << "More operands to ext\n");
  3468. Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
  3469. : TPT.createZExt(Ext, Opnd, Ext->getType());
  3470. if (!isa<Instruction>(ValForExtOpnd)) {
  3471. TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
  3472. continue;
  3473. }
  3474. ExtForOpnd = cast<Instruction>(ValForExtOpnd);
  3475. }
  3476. if (Exts)
  3477. Exts->push_back(ExtForOpnd);
  3478. TPT.setOperand(ExtForOpnd, 0, Opnd);
  3479. // Move the sign extension before the insertion point.
  3480. TPT.moveBefore(ExtForOpnd, ExtOpnd);
  3481. TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
  3482. CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
  3483. // If more sext are required, new instructions will have to be created.
  3484. ExtForOpnd = nullptr;
  3485. }
  3486. if (ExtForOpnd == Ext) {
  3487. LLVM_DEBUG(dbgs() << "Extension is useless now\n");
  3488. TPT.eraseInstruction(Ext);
  3489. }
  3490. return ExtOpnd;
  3491. }
  3492. /// Check whether or not promoting an instruction to a wider type is profitable.
  3493. /// \p NewCost gives the cost of extension instructions created by the
  3494. /// promotion.
  3495. /// \p OldCost gives the cost of extension instructions before the promotion
  3496. /// plus the number of instructions that have been
  3497. /// matched in the addressing mode the promotion.
  3498. /// \p PromotedOperand is the value that has been promoted.
  3499. /// \return True if the promotion is profitable, false otherwise.
  3500. bool AddressingModeMatcher::isPromotionProfitable(
  3501. unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
  3502. LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost
  3503. << '\n');
  3504. // The cost of the new extensions is greater than the cost of the
  3505. // old extension plus what we folded.
  3506. // This is not profitable.
  3507. if (NewCost > OldCost)
  3508. return false;
  3509. if (NewCost < OldCost)
  3510. return true;
  3511. // The promotion is neutral but it may help folding the sign extension in
  3512. // loads for instance.
  3513. // Check that we did not create an illegal instruction.
  3514. return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
  3515. }
  3516. /// Given an instruction or constant expr, see if we can fold the operation
  3517. /// into the addressing mode. If so, update the addressing mode and return
  3518. /// true, otherwise return false without modifying AddrMode.
  3519. /// If \p MovedAway is not NULL, it contains the information of whether or
  3520. /// not AddrInst has to be folded into the addressing mode on success.
  3521. /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
  3522. /// because it has been moved away.
  3523. /// Thus AddrInst must not be added in the matched instructions.
  3524. /// This state can happen when AddrInst is a sext, since it may be moved away.
  3525. /// Therefore, AddrInst may not be valid when MovedAway is true and it must
  3526. /// not be referenced anymore.
  3527. bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
  3528. unsigned Depth,
  3529. bool *MovedAway) {
  3530. // Avoid exponential behavior on extremely deep expression trees.
  3531. if (Depth >= 5) return false;
  3532. // By default, all matched instructions stay in place.
  3533. if (MovedAway)
  3534. *MovedAway = false;
  3535. switch (Opcode) {
  3536. case Instruction::PtrToInt:
  3537. // PtrToInt is always a noop, as we know that the int type is pointer sized.
  3538. return matchAddr(AddrInst->getOperand(0), Depth);
  3539. case Instruction::IntToPtr: {
  3540. auto AS = AddrInst->getType()->getPointerAddressSpace();
  3541. auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
  3542. // This inttoptr is a no-op if the integer type is pointer sized.
  3543. if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
  3544. return matchAddr(AddrInst->getOperand(0), Depth);
  3545. return false;
  3546. }
  3547. case Instruction::BitCast:
  3548. // BitCast is always a noop, and we can handle it as long as it is
  3549. // int->int or pointer->pointer (we don't want int<->fp or something).
  3550. if (AddrInst->getOperand(0)->getType()->isIntOrPtrTy() &&
  3551. // Don't touch identity bitcasts. These were probably put here by LSR,
  3552. // and we don't want to mess around with them. Assume it knows what it
  3553. // is doing.
  3554. AddrInst->getOperand(0)->getType() != AddrInst->getType())
  3555. return matchAddr(AddrInst->getOperand(0), Depth);
  3556. return false;
  3557. case Instruction::AddrSpaceCast: {
  3558. unsigned SrcAS
  3559. = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
  3560. unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
  3561. if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
  3562. return matchAddr(AddrInst->getOperand(0), Depth);
  3563. return false;
  3564. }
  3565. case Instruction::Add: {
  3566. // Check to see if we can merge in the RHS then the LHS. If so, we win.
  3567. ExtAddrMode BackupAddrMode = AddrMode;
  3568. unsigned OldSize = AddrModeInsts.size();
  3569. // Start a transaction at this point.
  3570. // The LHS may match but not the RHS.
  3571. // Therefore, we need a higher level restoration point to undo partially
  3572. // matched operation.
  3573. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  3574. TPT.getRestorationPoint();
  3575. AddrMode.InBounds = false;
  3576. if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
  3577. matchAddr(AddrInst->getOperand(0), Depth+1))
  3578. return true;
  3579. // Restore the old addr mode info.
  3580. AddrMode = BackupAddrMode;
  3581. AddrModeInsts.resize(OldSize);
  3582. TPT.rollback(LastKnownGood);
  3583. // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
  3584. if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
  3585. matchAddr(AddrInst->getOperand(1), Depth+1))
  3586. return true;
  3587. // Otherwise we definitely can't merge the ADD in.
  3588. AddrMode = BackupAddrMode;
  3589. AddrModeInsts.resize(OldSize);
  3590. TPT.rollback(LastKnownGood);
  3591. break;
  3592. }
  3593. //case Instruction::Or:
  3594. // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
  3595. //break;
  3596. case Instruction::Mul:
  3597. case Instruction::Shl: {
  3598. // Can only handle X*C and X << C.
  3599. AddrMode.InBounds = false;
  3600. ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
  3601. if (!RHS || RHS->getBitWidth() > 64)
  3602. return false;
  3603. int64_t Scale = RHS->getSExtValue();
  3604. if (Opcode == Instruction::Shl)
  3605. Scale = 1LL << Scale;
  3606. return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
  3607. }
  3608. case Instruction::GetElementPtr: {
  3609. // Scan the GEP. We check it if it contains constant offsets and at most
  3610. // one variable offset.
  3611. int VariableOperand = -1;
  3612. unsigned VariableScale = 0;
  3613. int64_t ConstantOffset = 0;
  3614. gep_type_iterator GTI = gep_type_begin(AddrInst);
  3615. for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
  3616. if (StructType *STy = GTI.getStructTypeOrNull()) {
  3617. const StructLayout *SL = DL.getStructLayout(STy);
  3618. unsigned Idx =
  3619. cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
  3620. ConstantOffset += SL->getElementOffset(Idx);
  3621. } else {
  3622. uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
  3623. if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
  3624. const APInt &CVal = CI->getValue();
  3625. if (CVal.getMinSignedBits() <= 64) {
  3626. ConstantOffset += CVal.getSExtValue() * TypeSize;
  3627. continue;
  3628. }
  3629. }
  3630. if (TypeSize) { // Scales of zero don't do anything.
  3631. // We only allow one variable index at the moment.
  3632. if (VariableOperand != -1)
  3633. return false;
  3634. // Remember the variable index.
  3635. VariableOperand = i;
  3636. VariableScale = TypeSize;
  3637. }
  3638. }
  3639. }
  3640. // A common case is for the GEP to only do a constant offset. In this case,
  3641. // just add it to the disp field and check validity.
  3642. if (VariableOperand == -1) {
  3643. AddrMode.BaseOffs += ConstantOffset;
  3644. if (ConstantOffset == 0 ||
  3645. TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
  3646. // Check to see if we can fold the base pointer in too.
  3647. if (matchAddr(AddrInst->getOperand(0), Depth+1)) {
  3648. if (!cast<GEPOperator>(AddrInst)->isInBounds())
  3649. AddrMode.InBounds = false;
  3650. return true;
  3651. }
  3652. } else if (EnableGEPOffsetSplit && isa<GetElementPtrInst>(AddrInst) &&
  3653. TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 &&
  3654. ConstantOffset > 0) {
  3655. // Record GEPs with non-zero offsets as candidates for splitting in the
  3656. // event that the offset cannot fit into the r+i addressing mode.
  3657. // Simple and common case that only one GEP is used in calculating the
  3658. // address for the memory access.
  3659. Value *Base = AddrInst->getOperand(0);
  3660. auto *BaseI = dyn_cast<Instruction>(Base);
  3661. auto *GEP = cast<GetElementPtrInst>(AddrInst);
  3662. if (isa<Argument>(Base) || isa<GlobalValue>(Base) ||
  3663. (BaseI && !isa<CastInst>(BaseI) &&
  3664. !isa<GetElementPtrInst>(BaseI))) {
  3665. // Make sure the parent block allows inserting non-PHI instructions
  3666. // before the terminator.
  3667. BasicBlock *Parent =
  3668. BaseI ? BaseI->getParent() : &GEP->getFunction()->getEntryBlock();
  3669. if (!Parent->getTerminator()->isEHPad())
  3670. LargeOffsetGEP = std::make_pair(GEP, ConstantOffset);
  3671. }
  3672. }
  3673. AddrMode.BaseOffs -= ConstantOffset;
  3674. return false;
  3675. }
  3676. // Save the valid addressing mode in case we can't match.
  3677. ExtAddrMode BackupAddrMode = AddrMode;
  3678. unsigned OldSize = AddrModeInsts.size();
  3679. // See if the scale and offset amount is valid for this target.
  3680. AddrMode.BaseOffs += ConstantOffset;
  3681. if (!cast<GEPOperator>(AddrInst)->isInBounds())
  3682. AddrMode.InBounds = false;
  3683. // Match the base operand of the GEP.
  3684. if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
  3685. // If it couldn't be matched, just stuff the value in a register.
  3686. if (AddrMode.HasBaseReg) {
  3687. AddrMode = BackupAddrMode;
  3688. AddrModeInsts.resize(OldSize);
  3689. return false;
  3690. }
  3691. AddrMode.HasBaseReg = true;
  3692. AddrMode.BaseReg = AddrInst->getOperand(0);
  3693. }
  3694. // Match the remaining variable portion of the GEP.
  3695. if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
  3696. Depth)) {
  3697. // If it couldn't be matched, try stuffing the base into a register
  3698. // instead of matching it, and retrying the match of the scale.
  3699. AddrMode = BackupAddrMode;
  3700. AddrModeInsts.resize(OldSize);
  3701. if (AddrMode.HasBaseReg)
  3702. return false;
  3703. AddrMode.HasBaseReg = true;
  3704. AddrMode.BaseReg = AddrInst->getOperand(0);
  3705. AddrMode.BaseOffs += ConstantOffset;
  3706. if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
  3707. VariableScale, Depth)) {
  3708. // If even that didn't work, bail.
  3709. AddrMode = BackupAddrMode;
  3710. AddrModeInsts.resize(OldSize);
  3711. return false;
  3712. }
  3713. }
  3714. return true;
  3715. }
  3716. case Instruction::SExt:
  3717. case Instruction::ZExt: {
  3718. Instruction *Ext = dyn_cast<Instruction>(AddrInst);
  3719. if (!Ext)
  3720. return false;
  3721. // Try to move this ext out of the way of the addressing mode.
  3722. // Ask for a method for doing so.
  3723. TypePromotionHelper::Action TPH =
  3724. TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
  3725. if (!TPH)
  3726. return false;
  3727. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  3728. TPT.getRestorationPoint();
  3729. unsigned CreatedInstsCost = 0;
  3730. unsigned ExtCost = !TLI.isExtFree(Ext);
  3731. Value *PromotedOperand =
  3732. TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
  3733. // SExt has been moved away.
  3734. // Thus either it will be rematched later in the recursive calls or it is
  3735. // gone. Anyway, we must not fold it into the addressing mode at this point.
  3736. // E.g.,
  3737. // op = add opnd, 1
  3738. // idx = ext op
  3739. // addr = gep base, idx
  3740. // is now:
  3741. // promotedOpnd = ext opnd <- no match here
  3742. // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
  3743. // addr = gep base, op <- match
  3744. if (MovedAway)
  3745. *MovedAway = true;
  3746. assert(PromotedOperand &&
  3747. "TypePromotionHelper should have filtered out those cases");
  3748. ExtAddrMode BackupAddrMode = AddrMode;
  3749. unsigned OldSize = AddrModeInsts.size();
  3750. if (!matchAddr(PromotedOperand, Depth) ||
  3751. // The total of the new cost is equal to the cost of the created
  3752. // instructions.
  3753. // The total of the old cost is equal to the cost of the extension plus
  3754. // what we have saved in the addressing mode.
  3755. !isPromotionProfitable(CreatedInstsCost,
  3756. ExtCost + (AddrModeInsts.size() - OldSize),
  3757. PromotedOperand)) {
  3758. AddrMode = BackupAddrMode;
  3759. AddrModeInsts.resize(OldSize);
  3760. LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
  3761. TPT.rollback(LastKnownGood);
  3762. return false;
  3763. }
  3764. return true;
  3765. }
  3766. }
  3767. return false;
  3768. }
  3769. /// If we can, try to add the value of 'Addr' into the current addressing mode.
  3770. /// If Addr can't be added to AddrMode this returns false and leaves AddrMode
  3771. /// unmodified. This assumes that Addr is either a pointer type or intptr_t
  3772. /// for the target.
  3773. ///
  3774. bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
  3775. // Start a transaction at this point that we will rollback if the matching
  3776. // fails.
  3777. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  3778. TPT.getRestorationPoint();
  3779. if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
  3780. // Fold in immediates if legal for the target.
  3781. AddrMode.BaseOffs += CI->getSExtValue();
  3782. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  3783. return true;
  3784. AddrMode.BaseOffs -= CI->getSExtValue();
  3785. } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
  3786. // If this is a global variable, try to fold it into the addressing mode.
  3787. if (!AddrMode.BaseGV) {
  3788. AddrMode.BaseGV = GV;
  3789. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  3790. return true;
  3791. AddrMode.BaseGV = nullptr;
  3792. }
  3793. } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
  3794. ExtAddrMode BackupAddrMode = AddrMode;
  3795. unsigned OldSize = AddrModeInsts.size();
  3796. // Check to see if it is possible to fold this operation.
  3797. bool MovedAway = false;
  3798. if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
  3799. // This instruction may have been moved away. If so, there is nothing
  3800. // to check here.
  3801. if (MovedAway)
  3802. return true;
  3803. // Okay, it's possible to fold this. Check to see if it is actually
  3804. // *profitable* to do so. We use a simple cost model to avoid increasing
  3805. // register pressure too much.
  3806. if (I->hasOneUse() ||
  3807. isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
  3808. AddrModeInsts.push_back(I);
  3809. return true;
  3810. }
  3811. // It isn't profitable to do this, roll back.
  3812. //cerr << "NOT FOLDING: " << *I;
  3813. AddrMode = BackupAddrMode;
  3814. AddrModeInsts.resize(OldSize);
  3815. TPT.rollback(LastKnownGood);
  3816. }
  3817. } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
  3818. if (matchOperationAddr(CE, CE->getOpcode(), Depth))
  3819. return true;
  3820. TPT.rollback(LastKnownGood);
  3821. } else if (isa<ConstantPointerNull>(Addr)) {
  3822. // Null pointer gets folded without affecting the addressing mode.
  3823. return true;
  3824. }
  3825. // Worse case, the target should support [reg] addressing modes. :)
  3826. if (!AddrMode.HasBaseReg) {
  3827. AddrMode.HasBaseReg = true;
  3828. AddrMode.BaseReg = Addr;
  3829. // Still check for legality in case the target supports [imm] but not [i+r].
  3830. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  3831. return true;
  3832. AddrMode.HasBaseReg = false;
  3833. AddrMode.BaseReg = nullptr;
  3834. }
  3835. // If the base register is already taken, see if we can do [r+r].
  3836. if (AddrMode.Scale == 0) {
  3837. AddrMode.Scale = 1;
  3838. AddrMode.ScaledReg = Addr;
  3839. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  3840. return true;
  3841. AddrMode.Scale = 0;
  3842. AddrMode.ScaledReg = nullptr;
  3843. }
  3844. // Couldn't match.
  3845. TPT.rollback(LastKnownGood);
  3846. return false;
  3847. }
  3848. /// Check to see if all uses of OpVal by the specified inline asm call are due
  3849. /// to memory operands. If so, return true, otherwise return false.
  3850. static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
  3851. const TargetLowering &TLI,
  3852. const TargetRegisterInfo &TRI) {
  3853. const Function *F = CI->getFunction();
  3854. TargetLowering::AsmOperandInfoVector TargetConstraints =
  3855. TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
  3856. ImmutableCallSite(CI));
  3857. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  3858. TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
  3859. // Compute the constraint code and ConstraintType to use.
  3860. TLI.ComputeConstraintToUse(OpInfo, SDValue());
  3861. // If this asm operand is our Value*, and if it isn't an indirect memory
  3862. // operand, we can't fold it!
  3863. if (OpInfo.CallOperandVal == OpVal &&
  3864. (OpInfo.ConstraintType != TargetLowering::C_Memory ||
  3865. !OpInfo.isIndirect))
  3866. return false;
  3867. }
  3868. return true;
  3869. }
  3870. // Max number of memory uses to look at before aborting the search to conserve
  3871. // compile time.
  3872. static constexpr int MaxMemoryUsesToScan = 20;
  3873. /// Recursively walk all the uses of I until we find a memory use.
  3874. /// If we find an obviously non-foldable instruction, return true.
  3875. /// Add the ultimately found memory instructions to MemoryUses.
  3876. static bool FindAllMemoryUses(
  3877. Instruction *I,
  3878. SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
  3879. SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
  3880. const TargetRegisterInfo &TRI, int SeenInsts = 0) {
  3881. // If we already considered this instruction, we're done.
  3882. if (!ConsideredInsts.insert(I).second)
  3883. return false;
  3884. // If this is an obviously unfoldable instruction, bail out.
  3885. if (!MightBeFoldableInst(I))
  3886. return true;
  3887. const bool OptSize = I->getFunction()->hasOptSize();
  3888. // Loop over all the uses, recursively processing them.
  3889. for (Use &U : I->uses()) {
  3890. // Conservatively return true if we're seeing a large number or a deep chain
  3891. // of users. This avoids excessive compilation times in pathological cases.
  3892. if (SeenInsts++ >= MaxMemoryUsesToScan)
  3893. return true;
  3894. Instruction *UserI = cast<Instruction>(U.getUser());
  3895. if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
  3896. MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
  3897. continue;
  3898. }
  3899. if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
  3900. unsigned opNo = U.getOperandNo();
  3901. if (opNo != StoreInst::getPointerOperandIndex())
  3902. return true; // Storing addr, not into addr.
  3903. MemoryUses.push_back(std::make_pair(SI, opNo));
  3904. continue;
  3905. }
  3906. if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
  3907. unsigned opNo = U.getOperandNo();
  3908. if (opNo != AtomicRMWInst::getPointerOperandIndex())
  3909. return true; // Storing addr, not into addr.
  3910. MemoryUses.push_back(std::make_pair(RMW, opNo));
  3911. continue;
  3912. }
  3913. if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
  3914. unsigned opNo = U.getOperandNo();
  3915. if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
  3916. return true; // Storing addr, not into addr.
  3917. MemoryUses.push_back(std::make_pair(CmpX, opNo));
  3918. continue;
  3919. }
  3920. if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
  3921. // If this is a cold call, we can sink the addressing calculation into
  3922. // the cold path. See optimizeCallInst
  3923. if (!OptSize && CI->hasFnAttr(Attribute::Cold))
  3924. continue;
  3925. InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
  3926. if (!IA) return true;
  3927. // If this is a memory operand, we're cool, otherwise bail out.
  3928. if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
  3929. return true;
  3930. continue;
  3931. }
  3932. if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI,
  3933. SeenInsts))
  3934. return true;
  3935. }
  3936. return false;
  3937. }
  3938. /// Return true if Val is already known to be live at the use site that we're
  3939. /// folding it into. If so, there is no cost to include it in the addressing
  3940. /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
  3941. /// instruction already.
  3942. bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
  3943. Value *KnownLive2) {
  3944. // If Val is either of the known-live values, we know it is live!
  3945. if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
  3946. return true;
  3947. // All values other than instructions and arguments (e.g. constants) are live.
  3948. if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
  3949. // If Val is a constant sized alloca in the entry block, it is live, this is
  3950. // true because it is just a reference to the stack/frame pointer, which is
  3951. // live for the whole function.
  3952. if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
  3953. if (AI->isStaticAlloca())
  3954. return true;
  3955. // Check to see if this value is already used in the memory instruction's
  3956. // block. If so, it's already live into the block at the very least, so we
  3957. // can reasonably fold it.
  3958. return Val->isUsedInBasicBlock(MemoryInst->getParent());
  3959. }
  3960. /// It is possible for the addressing mode of the machine to fold the specified
  3961. /// instruction into a load or store that ultimately uses it.
  3962. /// However, the specified instruction has multiple uses.
  3963. /// Given this, it may actually increase register pressure to fold it
  3964. /// into the load. For example, consider this code:
  3965. ///
  3966. /// X = ...
  3967. /// Y = X+1
  3968. /// use(Y) -> nonload/store
  3969. /// Z = Y+1
  3970. /// load Z
  3971. ///
  3972. /// In this case, Y has multiple uses, and can be folded into the load of Z
  3973. /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
  3974. /// be live at the use(Y) line. If we don't fold Y into load Z, we use one
  3975. /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
  3976. /// number of computations either.
  3977. ///
  3978. /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
  3979. /// X was live across 'load Z' for other reasons, we actually *would* want to
  3980. /// fold the addressing mode in the Z case. This would make Y die earlier.
  3981. bool AddressingModeMatcher::
  3982. isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
  3983. ExtAddrMode &AMAfter) {
  3984. if (IgnoreProfitability) return true;
  3985. // AMBefore is the addressing mode before this instruction was folded into it,
  3986. // and AMAfter is the addressing mode after the instruction was folded. Get
  3987. // the set of registers referenced by AMAfter and subtract out those
  3988. // referenced by AMBefore: this is the set of values which folding in this
  3989. // address extends the lifetime of.
  3990. //
  3991. // Note that there are only two potential values being referenced here,
  3992. // BaseReg and ScaleReg (global addresses are always available, as are any
  3993. // folded immediates).
  3994. Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
  3995. // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
  3996. // lifetime wasn't extended by adding this instruction.
  3997. if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
  3998. BaseReg = nullptr;
  3999. if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
  4000. ScaledReg = nullptr;
  4001. // If folding this instruction (and it's subexprs) didn't extend any live
  4002. // ranges, we're ok with it.
  4003. if (!BaseReg && !ScaledReg)
  4004. return true;
  4005. // If all uses of this instruction can have the address mode sunk into them,
  4006. // we can remove the addressing mode and effectively trade one live register
  4007. // for another (at worst.) In this context, folding an addressing mode into
  4008. // the use is just a particularly nice way of sinking it.
  4009. SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
  4010. SmallPtrSet<Instruction*, 16> ConsideredInsts;
  4011. if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
  4012. return false; // Has a non-memory, non-foldable use!
  4013. // Now that we know that all uses of this instruction are part of a chain of
  4014. // computation involving only operations that could theoretically be folded
  4015. // into a memory use, loop over each of these memory operation uses and see
  4016. // if they could *actually* fold the instruction. The assumption is that
  4017. // addressing modes are cheap and that duplicating the computation involved
  4018. // many times is worthwhile, even on a fastpath. For sinking candidates
  4019. // (i.e. cold call sites), this serves as a way to prevent excessive code
  4020. // growth since most architectures have some reasonable small and fast way to
  4021. // compute an effective address. (i.e LEA on x86)
  4022. SmallVector<Instruction*, 32> MatchedAddrModeInsts;
  4023. for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
  4024. Instruction *User = MemoryUses[i].first;
  4025. unsigned OpNo = MemoryUses[i].second;
  4026. // Get the access type of this use. If the use isn't a pointer, we don't
  4027. // know what it accesses.
  4028. Value *Address = User->getOperand(OpNo);
  4029. PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
  4030. if (!AddrTy)
  4031. return false;
  4032. Type *AddressAccessTy = AddrTy->getElementType();
  4033. unsigned AS = AddrTy->getAddressSpace();
  4034. // Do a match against the root of this address, ignoring profitability. This
  4035. // will tell us if the addressing mode for the memory operation will
  4036. // *actually* cover the shared instruction.
  4037. ExtAddrMode Result;
  4038. std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
  4039. 0);
  4040. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  4041. TPT.getRestorationPoint();
  4042. AddressingModeMatcher Matcher(
  4043. MatchedAddrModeInsts, TLI, TRI, AddressAccessTy, AS, MemoryInst, Result,
  4044. InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP);
  4045. Matcher.IgnoreProfitability = true;
  4046. bool Success = Matcher.matchAddr(Address, 0);
  4047. (void)Success; assert(Success && "Couldn't select *anything*?");
  4048. // The match was to check the profitability, the changes made are not
  4049. // part of the original matcher. Therefore, they should be dropped
  4050. // otherwise the original matcher will not present the right state.
  4051. TPT.rollback(LastKnownGood);
  4052. // If the match didn't cover I, then it won't be shared by it.
  4053. if (!is_contained(MatchedAddrModeInsts, I))
  4054. return false;
  4055. MatchedAddrModeInsts.clear();
  4056. }
  4057. return true;
  4058. }
  4059. /// Return true if the specified values are defined in a
  4060. /// different basic block than BB.
  4061. static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
  4062. if (Instruction *I = dyn_cast<Instruction>(V))
  4063. return I->getParent() != BB;
  4064. return false;
  4065. }
  4066. /// Sink addressing mode computation immediate before MemoryInst if doing so
  4067. /// can be done without increasing register pressure. The need for the
  4068. /// register pressure constraint means this can end up being an all or nothing
  4069. /// decision for all uses of the same addressing computation.
  4070. ///
  4071. /// Load and Store Instructions often have addressing modes that can do
  4072. /// significant amounts of computation. As such, instruction selection will try
  4073. /// to get the load or store to do as much computation as possible for the
  4074. /// program. The problem is that isel can only see within a single block. As
  4075. /// such, we sink as much legal addressing mode work into the block as possible.
  4076. ///
  4077. /// This method is used to optimize both load/store and inline asms with memory
  4078. /// operands. It's also used to sink addressing computations feeding into cold
  4079. /// call sites into their (cold) basic block.
  4080. ///
  4081. /// The motivation for handling sinking into cold blocks is that doing so can
  4082. /// both enable other address mode sinking (by satisfying the register pressure
  4083. /// constraint above), and reduce register pressure globally (by removing the
  4084. /// addressing mode computation from the fast path entirely.).
  4085. bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
  4086. Type *AccessTy, unsigned AddrSpace) {
  4087. Value *Repl = Addr;
  4088. // Try to collapse single-value PHI nodes. This is necessary to undo
  4089. // unprofitable PRE transformations.
  4090. SmallVector<Value*, 8> worklist;
  4091. SmallPtrSet<Value*, 16> Visited;
  4092. worklist.push_back(Addr);
  4093. // Use a worklist to iteratively look through PHI and select nodes, and
  4094. // ensure that the addressing mode obtained from the non-PHI/select roots of
  4095. // the graph are compatible.
  4096. bool PhiOrSelectSeen = false;
  4097. SmallVector<Instruction*, 16> AddrModeInsts;
  4098. const SimplifyQuery SQ(*DL, TLInfo);
  4099. AddressingModeCombiner AddrModes(SQ, Addr);
  4100. TypePromotionTransaction TPT(RemovedInsts);
  4101. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  4102. TPT.getRestorationPoint();
  4103. while (!worklist.empty()) {
  4104. Value *V = worklist.back();
  4105. worklist.pop_back();
  4106. // We allow traversing cyclic Phi nodes.
  4107. // In case of success after this loop we ensure that traversing through
  4108. // Phi nodes ends up with all cases to compute address of the form
  4109. // BaseGV + Base + Scale * Index + Offset
  4110. // where Scale and Offset are constans and BaseGV, Base and Index
  4111. // are exactly the same Values in all cases.
  4112. // It means that BaseGV, Scale and Offset dominate our memory instruction
  4113. // and have the same value as they had in address computation represented
  4114. // as Phi. So we can safely sink address computation to memory instruction.
  4115. if (!Visited.insert(V).second)
  4116. continue;
  4117. // For a PHI node, push all of its incoming values.
  4118. if (PHINode *P = dyn_cast<PHINode>(V)) {
  4119. for (Value *IncValue : P->incoming_values())
  4120. worklist.push_back(IncValue);
  4121. PhiOrSelectSeen = true;
  4122. continue;
  4123. }
  4124. // Similar for select.
  4125. if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
  4126. worklist.push_back(SI->getFalseValue());
  4127. worklist.push_back(SI->getTrueValue());
  4128. PhiOrSelectSeen = true;
  4129. continue;
  4130. }
  4131. // For non-PHIs, determine the addressing mode being computed. Note that
  4132. // the result may differ depending on what other uses our candidate
  4133. // addressing instructions might have.
  4134. AddrModeInsts.clear();
  4135. std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
  4136. 0);
  4137. ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
  4138. V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *TRI,
  4139. InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP);
  4140. GetElementPtrInst *GEP = LargeOffsetGEP.first;
  4141. if (GEP && !NewGEPBases.count(GEP)) {
  4142. // If splitting the underlying data structure can reduce the offset of a
  4143. // GEP, collect the GEP. Skip the GEPs that are the new bases of
  4144. // previously split data structures.
  4145. LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(LargeOffsetGEP);
  4146. if (LargeOffsetGEPID.find(GEP) == LargeOffsetGEPID.end())
  4147. LargeOffsetGEPID[GEP] = LargeOffsetGEPID.size();
  4148. }
  4149. NewAddrMode.OriginalValue = V;
  4150. if (!AddrModes.addNewAddrMode(NewAddrMode))
  4151. break;
  4152. }
  4153. // Try to combine the AddrModes we've collected. If we couldn't collect any,
  4154. // or we have multiple but either couldn't combine them or combining them
  4155. // wouldn't do anything useful, bail out now.
  4156. if (!AddrModes.combineAddrModes()) {
  4157. TPT.rollback(LastKnownGood);
  4158. return false;
  4159. }
  4160. TPT.commit();
  4161. // Get the combined AddrMode (or the only AddrMode, if we only had one).
  4162. ExtAddrMode AddrMode = AddrModes.getAddrMode();
  4163. // If all the instructions matched are already in this BB, don't do anything.
  4164. // If we saw a Phi node then it is not local definitely, and if we saw a select
  4165. // then we want to push the address calculation past it even if it's already
  4166. // in this BB.
  4167. if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
  4168. return IsNonLocalValue(V, MemoryInst->getParent());
  4169. })) {
  4170. LLVM_DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode
  4171. << "\n");
  4172. return false;
  4173. }
  4174. // Insert this computation right after this user. Since our caller is
  4175. // scanning from the top of the BB to the bottom, reuse of the expr are
  4176. // guaranteed to happen later.
  4177. IRBuilder<> Builder(MemoryInst);
  4178. // Now that we determined the addressing expression we want to use and know
  4179. // that we have to sink it into this block. Check to see if we have already
  4180. // done this for some other load/store instr in this block. If so, reuse
  4181. // the computation. Before attempting reuse, check if the address is valid
  4182. // as it may have been erased.
  4183. WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
  4184. Value * SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
  4185. if (SunkAddr) {
  4186. LLVM_DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode
  4187. << " for " << *MemoryInst << "\n");
  4188. if (SunkAddr->getType() != Addr->getType())
  4189. SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
  4190. } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() &&
  4191. TM && SubtargetInfo->addrSinkUsingGEPs())) {
  4192. // By default, we use the GEP-based method when AA is used later. This
  4193. // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
  4194. LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
  4195. << " for " << *MemoryInst << "\n");
  4196. Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
  4197. Value *ResultPtr = nullptr, *ResultIndex = nullptr;
  4198. // First, find the pointer.
  4199. if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
  4200. ResultPtr = AddrMode.BaseReg;
  4201. AddrMode.BaseReg = nullptr;
  4202. }
  4203. if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
  4204. // We can't add more than one pointer together, nor can we scale a
  4205. // pointer (both of which seem meaningless).
  4206. if (ResultPtr || AddrMode.Scale != 1)
  4207. return false;
  4208. ResultPtr = AddrMode.ScaledReg;
  4209. AddrMode.Scale = 0;
  4210. }
  4211. // It is only safe to sign extend the BaseReg if we know that the math
  4212. // required to create it did not overflow before we extend it. Since
  4213. // the original IR value was tossed in favor of a constant back when
  4214. // the AddrMode was created we need to bail out gracefully if widths
  4215. // do not match instead of extending it.
  4216. //
  4217. // (See below for code to add the scale.)
  4218. if (AddrMode.Scale) {
  4219. Type *ScaledRegTy = AddrMode.ScaledReg->getType();
  4220. if (cast<IntegerType>(IntPtrTy)->getBitWidth() >
  4221. cast<IntegerType>(ScaledRegTy)->getBitWidth())
  4222. return false;
  4223. }
  4224. if (AddrMode.BaseGV) {
  4225. if (ResultPtr)
  4226. return false;
  4227. ResultPtr = AddrMode.BaseGV;
  4228. }
  4229. // If the real base value actually came from an inttoptr, then the matcher
  4230. // will look through it and provide only the integer value. In that case,
  4231. // use it here.
  4232. if (!DL->isNonIntegralPointerType(Addr->getType())) {
  4233. if (!ResultPtr && AddrMode.BaseReg) {
  4234. ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
  4235. "sunkaddr");
  4236. AddrMode.BaseReg = nullptr;
  4237. } else if (!ResultPtr && AddrMode.Scale == 1) {
  4238. ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
  4239. "sunkaddr");
  4240. AddrMode.Scale = 0;
  4241. }
  4242. }
  4243. if (!ResultPtr &&
  4244. !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
  4245. SunkAddr = Constant::getNullValue(Addr->getType());
  4246. } else if (!ResultPtr) {
  4247. return false;
  4248. } else {
  4249. Type *I8PtrTy =
  4250. Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
  4251. Type *I8Ty = Builder.getInt8Ty();
  4252. // Start with the base register. Do this first so that subsequent address
  4253. // matching finds it last, which will prevent it from trying to match it
  4254. // as the scaled value in case it happens to be a mul. That would be
  4255. // problematic if we've sunk a different mul for the scale, because then
  4256. // we'd end up sinking both muls.
  4257. if (AddrMode.BaseReg) {
  4258. Value *V = AddrMode.BaseReg;
  4259. if (V->getType() != IntPtrTy)
  4260. V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
  4261. ResultIndex = V;
  4262. }
  4263. // Add the scale value.
  4264. if (AddrMode.Scale) {
  4265. Value *V = AddrMode.ScaledReg;
  4266. if (V->getType() == IntPtrTy) {
  4267. // done.
  4268. } else {
  4269. assert(cast<IntegerType>(IntPtrTy)->getBitWidth() <
  4270. cast<IntegerType>(V->getType())->getBitWidth() &&
  4271. "We can't transform if ScaledReg is too narrow");
  4272. V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
  4273. }
  4274. if (AddrMode.Scale != 1)
  4275. V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
  4276. "sunkaddr");
  4277. if (ResultIndex)
  4278. ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
  4279. else
  4280. ResultIndex = V;
  4281. }
  4282. // Add in the Base Offset if present.
  4283. if (AddrMode.BaseOffs) {
  4284. Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
  4285. if (ResultIndex) {
  4286. // We need to add this separately from the scale above to help with
  4287. // SDAG consecutive load/store merging.
  4288. if (ResultPtr->getType() != I8PtrTy)
  4289. ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
  4290. ResultPtr =
  4291. AddrMode.InBounds
  4292. ? Builder.CreateInBoundsGEP(I8Ty, ResultPtr, ResultIndex,
  4293. "sunkaddr")
  4294. : Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
  4295. }
  4296. ResultIndex = V;
  4297. }
  4298. if (!ResultIndex) {
  4299. SunkAddr = ResultPtr;
  4300. } else {
  4301. if (ResultPtr->getType() != I8PtrTy)
  4302. ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
  4303. SunkAddr =
  4304. AddrMode.InBounds
  4305. ? Builder.CreateInBoundsGEP(I8Ty, ResultPtr, ResultIndex,
  4306. "sunkaddr")
  4307. : Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
  4308. }
  4309. if (SunkAddr->getType() != Addr->getType())
  4310. SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
  4311. }
  4312. } else {
  4313. // We'd require a ptrtoint/inttoptr down the line, which we can't do for
  4314. // non-integral pointers, so in that case bail out now.
  4315. Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
  4316. Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
  4317. PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
  4318. PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
  4319. if (DL->isNonIntegralPointerType(Addr->getType()) ||
  4320. (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
  4321. (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
  4322. (AddrMode.BaseGV &&
  4323. DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
  4324. return false;
  4325. LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
  4326. << " for " << *MemoryInst << "\n");
  4327. Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
  4328. Value *Result = nullptr;
  4329. // Start with the base register. Do this first so that subsequent address
  4330. // matching finds it last, which will prevent it from trying to match it
  4331. // as the scaled value in case it happens to be a mul. That would be
  4332. // problematic if we've sunk a different mul for the scale, because then
  4333. // we'd end up sinking both muls.
  4334. if (AddrMode.BaseReg) {
  4335. Value *V = AddrMode.BaseReg;
  4336. if (V->getType()->isPointerTy())
  4337. V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
  4338. if (V->getType() != IntPtrTy)
  4339. V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
  4340. Result = V;
  4341. }
  4342. // Add the scale value.
  4343. if (AddrMode.Scale) {
  4344. Value *V = AddrMode.ScaledReg;
  4345. if (V->getType() == IntPtrTy) {
  4346. // done.
  4347. } else if (V->getType()->isPointerTy()) {
  4348. V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
  4349. } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
  4350. cast<IntegerType>(V->getType())->getBitWidth()) {
  4351. V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
  4352. } else {
  4353. // It is only safe to sign extend the BaseReg if we know that the math
  4354. // required to create it did not overflow before we extend it. Since
  4355. // the original IR value was tossed in favor of a constant back when
  4356. // the AddrMode was created we need to bail out gracefully if widths
  4357. // do not match instead of extending it.
  4358. Instruction *I = dyn_cast_or_null<Instruction>(Result);
  4359. if (I && (Result != AddrMode.BaseReg))
  4360. I->eraseFromParent();
  4361. return false;
  4362. }
  4363. if (AddrMode.Scale != 1)
  4364. V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
  4365. "sunkaddr");
  4366. if (Result)
  4367. Result = Builder.CreateAdd(Result, V, "sunkaddr");
  4368. else
  4369. Result = V;
  4370. }
  4371. // Add in the BaseGV if present.
  4372. if (AddrMode.BaseGV) {
  4373. Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
  4374. if (Result)
  4375. Result = Builder.CreateAdd(Result, V, "sunkaddr");
  4376. else
  4377. Result = V;
  4378. }
  4379. // Add in the Base Offset if present.
  4380. if (AddrMode.BaseOffs) {
  4381. Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
  4382. if (Result)
  4383. Result = Builder.CreateAdd(Result, V, "sunkaddr");
  4384. else
  4385. Result = V;
  4386. }
  4387. if (!Result)
  4388. SunkAddr = Constant::getNullValue(Addr->getType());
  4389. else
  4390. SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
  4391. }
  4392. MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
  4393. // Store the newly computed address into the cache. In the case we reused a
  4394. // value, this should be idempotent.
  4395. SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
  4396. // If we have no uses, recursively delete the value and all dead instructions
  4397. // using it.
  4398. if (Repl->use_empty()) {
  4399. // This can cause recursive deletion, which can invalidate our iterator.
  4400. // Use a WeakTrackingVH to hold onto it in case this happens.
  4401. Value *CurValue = &*CurInstIterator;
  4402. WeakTrackingVH IterHandle(CurValue);
  4403. BasicBlock *BB = CurInstIterator->getParent();
  4404. RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
  4405. if (IterHandle != CurValue) {
  4406. // If the iterator instruction was recursively deleted, start over at the
  4407. // start of the block.
  4408. CurInstIterator = BB->begin();
  4409. SunkAddrs.clear();
  4410. }
  4411. }
  4412. ++NumMemoryInsts;
  4413. return true;
  4414. }
  4415. /// If there are any memory operands, use OptimizeMemoryInst to sink their
  4416. /// address computing into the block when possible / profitable.
  4417. bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
  4418. bool MadeChange = false;
  4419. const TargetRegisterInfo *TRI =
  4420. TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo();
  4421. TargetLowering::AsmOperandInfoVector TargetConstraints =
  4422. TLI->ParseConstraints(*DL, TRI, CS);
  4423. unsigned ArgNo = 0;
  4424. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  4425. TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
  4426. // Compute the constraint code and ConstraintType to use.
  4427. TLI->ComputeConstraintToUse(OpInfo, SDValue());
  4428. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  4429. OpInfo.isIndirect) {
  4430. Value *OpVal = CS->getArgOperand(ArgNo++);
  4431. MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
  4432. } else if (OpInfo.Type == InlineAsm::isInput)
  4433. ArgNo++;
  4434. }
  4435. return MadeChange;
  4436. }
  4437. /// Check if all the uses of \p Val are equivalent (or free) zero or
  4438. /// sign extensions.
  4439. static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
  4440. assert(!Val->use_empty() && "Input must have at least one use");
  4441. const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
  4442. bool IsSExt = isa<SExtInst>(FirstUser);
  4443. Type *ExtTy = FirstUser->getType();
  4444. for (const User *U : Val->users()) {
  4445. const Instruction *UI = cast<Instruction>(U);
  4446. if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
  4447. return false;
  4448. Type *CurTy = UI->getType();
  4449. // Same input and output types: Same instruction after CSE.
  4450. if (CurTy == ExtTy)
  4451. continue;
  4452. // If IsSExt is true, we are in this situation:
  4453. // a = Val
  4454. // b = sext ty1 a to ty2
  4455. // c = sext ty1 a to ty3
  4456. // Assuming ty2 is shorter than ty3, this could be turned into:
  4457. // a = Val
  4458. // b = sext ty1 a to ty2
  4459. // c = sext ty2 b to ty3
  4460. // However, the last sext is not free.
  4461. if (IsSExt)
  4462. return false;
  4463. // This is a ZExt, maybe this is free to extend from one type to another.
  4464. // In that case, we would not account for a different use.
  4465. Type *NarrowTy;
  4466. Type *LargeTy;
  4467. if (ExtTy->getScalarType()->getIntegerBitWidth() >
  4468. CurTy->getScalarType()->getIntegerBitWidth()) {
  4469. NarrowTy = CurTy;
  4470. LargeTy = ExtTy;
  4471. } else {
  4472. NarrowTy = ExtTy;
  4473. LargeTy = CurTy;
  4474. }
  4475. if (!TLI.isZExtFree(NarrowTy, LargeTy))
  4476. return false;
  4477. }
  4478. // All uses are the same or can be derived from one another for free.
  4479. return true;
  4480. }
  4481. /// Try to speculatively promote extensions in \p Exts and continue
  4482. /// promoting through newly promoted operands recursively as far as doing so is
  4483. /// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
  4484. /// When some promotion happened, \p TPT contains the proper state to revert
  4485. /// them.
  4486. ///
  4487. /// \return true if some promotion happened, false otherwise.
  4488. bool CodeGenPrepare::tryToPromoteExts(
  4489. TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
  4490. SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
  4491. unsigned CreatedInstsCost) {
  4492. bool Promoted = false;
  4493. // Iterate over all the extensions to try to promote them.
  4494. for (auto I : Exts) {
  4495. // Early check if we directly have ext(load).
  4496. if (isa<LoadInst>(I->getOperand(0))) {
  4497. ProfitablyMovedExts.push_back(I);
  4498. continue;
  4499. }
  4500. // Check whether or not we want to do any promotion. The reason we have
  4501. // this check inside the for loop is to catch the case where an extension
  4502. // is directly fed by a load because in such case the extension can be moved
  4503. // up without any promotion on its operands.
  4504. if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
  4505. return false;
  4506. // Get the action to perform the promotion.
  4507. TypePromotionHelper::Action TPH =
  4508. TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
  4509. // Check if we can promote.
  4510. if (!TPH) {
  4511. // Save the current extension as we cannot move up through its operand.
  4512. ProfitablyMovedExts.push_back(I);
  4513. continue;
  4514. }
  4515. // Save the current state.
  4516. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  4517. TPT.getRestorationPoint();
  4518. SmallVector<Instruction *, 4> NewExts;
  4519. unsigned NewCreatedInstsCost = 0;
  4520. unsigned ExtCost = !TLI->isExtFree(I);
  4521. // Promote.
  4522. Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
  4523. &NewExts, nullptr, *TLI);
  4524. assert(PromotedVal &&
  4525. "TypePromotionHelper should have filtered out those cases");
  4526. // We would be able to merge only one extension in a load.
  4527. // Therefore, if we have more than 1 new extension we heuristically
  4528. // cut this search path, because it means we degrade the code quality.
  4529. // With exactly 2, the transformation is neutral, because we will merge
  4530. // one extension but leave one. However, we optimistically keep going,
  4531. // because the new extension may be removed too.
  4532. long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
  4533. // FIXME: It would be possible to propagate a negative value instead of
  4534. // conservatively ceiling it to 0.
  4535. TotalCreatedInstsCost =
  4536. std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
  4537. if (!StressExtLdPromotion &&
  4538. (TotalCreatedInstsCost > 1 ||
  4539. !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
  4540. // This promotion is not profitable, rollback to the previous state, and
  4541. // save the current extension in ProfitablyMovedExts as the latest
  4542. // speculative promotion turned out to be unprofitable.
  4543. TPT.rollback(LastKnownGood);
  4544. ProfitablyMovedExts.push_back(I);
  4545. continue;
  4546. }
  4547. // Continue promoting NewExts as far as doing so is profitable.
  4548. SmallVector<Instruction *, 2> NewlyMovedExts;
  4549. (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
  4550. bool NewPromoted = false;
  4551. for (auto ExtInst : NewlyMovedExts) {
  4552. Instruction *MovedExt = cast<Instruction>(ExtInst);
  4553. Value *ExtOperand = MovedExt->getOperand(0);
  4554. // If we have reached to a load, we need this extra profitability check
  4555. // as it could potentially be merged into an ext(load).
  4556. if (isa<LoadInst>(ExtOperand) &&
  4557. !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
  4558. (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
  4559. continue;
  4560. ProfitablyMovedExts.push_back(MovedExt);
  4561. NewPromoted = true;
  4562. }
  4563. // If none of speculative promotions for NewExts is profitable, rollback
  4564. // and save the current extension (I) as the last profitable extension.
  4565. if (!NewPromoted) {
  4566. TPT.rollback(LastKnownGood);
  4567. ProfitablyMovedExts.push_back(I);
  4568. continue;
  4569. }
  4570. // The promotion is profitable.
  4571. Promoted = true;
  4572. }
  4573. return Promoted;
  4574. }
  4575. /// Merging redundant sexts when one is dominating the other.
  4576. bool CodeGenPrepare::mergeSExts(Function &F) {
  4577. bool Changed = false;
  4578. for (auto &Entry : ValToSExtendedUses) {
  4579. SExts &Insts = Entry.second;
  4580. SExts CurPts;
  4581. for (Instruction *Inst : Insts) {
  4582. if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
  4583. Inst->getOperand(0) != Entry.first)
  4584. continue;
  4585. bool inserted = false;
  4586. for (auto &Pt : CurPts) {
  4587. if (getDT(F).dominates(Inst, Pt)) {
  4588. Pt->replaceAllUsesWith(Inst);
  4589. RemovedInsts.insert(Pt);
  4590. Pt->removeFromParent();
  4591. Pt = Inst;
  4592. inserted = true;
  4593. Changed = true;
  4594. break;
  4595. }
  4596. if (!getDT(F).dominates(Pt, Inst))
  4597. // Give up if we need to merge in a common dominator as the
  4598. // experiments show it is not profitable.
  4599. continue;
  4600. Inst->replaceAllUsesWith(Pt);
  4601. RemovedInsts.insert(Inst);
  4602. Inst->removeFromParent();
  4603. inserted = true;
  4604. Changed = true;
  4605. break;
  4606. }
  4607. if (!inserted)
  4608. CurPts.push_back(Inst);
  4609. }
  4610. }
  4611. return Changed;
  4612. }
  4613. // Spliting large data structures so that the GEPs accessing them can have
  4614. // smaller offsets so that they can be sunk to the same blocks as their users.
  4615. // For example, a large struct starting from %base is splitted into two parts
  4616. // where the second part starts from %new_base.
  4617. //
  4618. // Before:
  4619. // BB0:
  4620. // %base =
  4621. //
  4622. // BB1:
  4623. // %gep0 = gep %base, off0
  4624. // %gep1 = gep %base, off1
  4625. // %gep2 = gep %base, off2
  4626. //
  4627. // BB2:
  4628. // %load1 = load %gep0
  4629. // %load2 = load %gep1
  4630. // %load3 = load %gep2
  4631. //
  4632. // After:
  4633. // BB0:
  4634. // %base =
  4635. // %new_base = gep %base, off0
  4636. //
  4637. // BB1:
  4638. // %new_gep0 = %new_base
  4639. // %new_gep1 = gep %new_base, off1 - off0
  4640. // %new_gep2 = gep %new_base, off2 - off0
  4641. //
  4642. // BB2:
  4643. // %load1 = load i32, i32* %new_gep0
  4644. // %load2 = load i32, i32* %new_gep1
  4645. // %load3 = load i32, i32* %new_gep2
  4646. //
  4647. // %new_gep1 and %new_gep2 can be sunk to BB2 now after the splitting because
  4648. // their offsets are smaller enough to fit into the addressing mode.
  4649. bool CodeGenPrepare::splitLargeGEPOffsets() {
  4650. bool Changed = false;
  4651. for (auto &Entry : LargeOffsetGEPMap) {
  4652. Value *OldBase = Entry.first;
  4653. SmallVectorImpl<std::pair<AssertingVH<GetElementPtrInst>, int64_t>>
  4654. &LargeOffsetGEPs = Entry.second;
  4655. auto compareGEPOffset =
  4656. [&](const std::pair<GetElementPtrInst *, int64_t> &LHS,
  4657. const std::pair<GetElementPtrInst *, int64_t> &RHS) {
  4658. if (LHS.first == RHS.first)
  4659. return false;
  4660. if (LHS.second != RHS.second)
  4661. return LHS.second < RHS.second;
  4662. return LargeOffsetGEPID[LHS.first] < LargeOffsetGEPID[RHS.first];
  4663. };
  4664. // Sorting all the GEPs of the same data structures based on the offsets.
  4665. llvm::sort(LargeOffsetGEPs, compareGEPOffset);
  4666. LargeOffsetGEPs.erase(
  4667. std::unique(LargeOffsetGEPs.begin(), LargeOffsetGEPs.end()),
  4668. LargeOffsetGEPs.end());
  4669. // Skip if all the GEPs have the same offsets.
  4670. if (LargeOffsetGEPs.front().second == LargeOffsetGEPs.back().second)
  4671. continue;
  4672. GetElementPtrInst *BaseGEP = LargeOffsetGEPs.begin()->first;
  4673. int64_t BaseOffset = LargeOffsetGEPs.begin()->second;
  4674. Value *NewBaseGEP = nullptr;
  4675. auto LargeOffsetGEP = LargeOffsetGEPs.begin();
  4676. while (LargeOffsetGEP != LargeOffsetGEPs.end()) {
  4677. GetElementPtrInst *GEP = LargeOffsetGEP->first;
  4678. int64_t Offset = LargeOffsetGEP->second;
  4679. if (Offset != BaseOffset) {
  4680. TargetLowering::AddrMode AddrMode;
  4681. AddrMode.BaseOffs = Offset - BaseOffset;
  4682. // The result type of the GEP might not be the type of the memory
  4683. // access.
  4684. if (!TLI->isLegalAddressingMode(*DL, AddrMode,
  4685. GEP->getResultElementType(),
  4686. GEP->getAddressSpace())) {
  4687. // We need to create a new base if the offset to the current base is
  4688. // too large to fit into the addressing mode. So, a very large struct
  4689. // may be splitted into several parts.
  4690. BaseGEP = GEP;
  4691. BaseOffset = Offset;
  4692. NewBaseGEP = nullptr;
  4693. }
  4694. }
  4695. // Generate a new GEP to replace the current one.
  4696. LLVMContext &Ctx = GEP->getContext();
  4697. Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
  4698. Type *I8PtrTy =
  4699. Type::getInt8PtrTy(Ctx, GEP->getType()->getPointerAddressSpace());
  4700. Type *I8Ty = Type::getInt8Ty(Ctx);
  4701. if (!NewBaseGEP) {
  4702. // Create a new base if we don't have one yet. Find the insertion
  4703. // pointer for the new base first.
  4704. BasicBlock::iterator NewBaseInsertPt;
  4705. BasicBlock *NewBaseInsertBB;
  4706. if (auto *BaseI = dyn_cast<Instruction>(OldBase)) {
  4707. // If the base of the struct is an instruction, the new base will be
  4708. // inserted close to it.
  4709. NewBaseInsertBB = BaseI->getParent();
  4710. if (isa<PHINode>(BaseI))
  4711. NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
  4712. else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(BaseI)) {
  4713. NewBaseInsertBB =
  4714. SplitEdge(NewBaseInsertBB, Invoke->getNormalDest());
  4715. NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
  4716. } else
  4717. NewBaseInsertPt = std::next(BaseI->getIterator());
  4718. } else {
  4719. // If the current base is an argument or global value, the new base
  4720. // will be inserted to the entry block.
  4721. NewBaseInsertBB = &BaseGEP->getFunction()->getEntryBlock();
  4722. NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
  4723. }
  4724. IRBuilder<> NewBaseBuilder(NewBaseInsertBB, NewBaseInsertPt);
  4725. // Create a new base.
  4726. Value *BaseIndex = ConstantInt::get(IntPtrTy, BaseOffset);
  4727. NewBaseGEP = OldBase;
  4728. if (NewBaseGEP->getType() != I8PtrTy)
  4729. NewBaseGEP = NewBaseBuilder.CreatePointerCast(NewBaseGEP, I8PtrTy);
  4730. NewBaseGEP =
  4731. NewBaseBuilder.CreateGEP(I8Ty, NewBaseGEP, BaseIndex, "splitgep");
  4732. NewGEPBases.insert(NewBaseGEP);
  4733. }
  4734. IRBuilder<> Builder(GEP);
  4735. Value *NewGEP = NewBaseGEP;
  4736. if (Offset == BaseOffset) {
  4737. if (GEP->getType() != I8PtrTy)
  4738. NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
  4739. } else {
  4740. // Calculate the new offset for the new GEP.
  4741. Value *Index = ConstantInt::get(IntPtrTy, Offset - BaseOffset);
  4742. NewGEP = Builder.CreateGEP(I8Ty, NewBaseGEP, Index);
  4743. if (GEP->getType() != I8PtrTy)
  4744. NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
  4745. }
  4746. GEP->replaceAllUsesWith(NewGEP);
  4747. LargeOffsetGEPID.erase(GEP);
  4748. LargeOffsetGEP = LargeOffsetGEPs.erase(LargeOffsetGEP);
  4749. GEP->eraseFromParent();
  4750. Changed = true;
  4751. }
  4752. }
  4753. return Changed;
  4754. }
  4755. /// Return true, if an ext(load) can be formed from an extension in
  4756. /// \p MovedExts.
  4757. bool CodeGenPrepare::canFormExtLd(
  4758. const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
  4759. Instruction *&Inst, bool HasPromoted) {
  4760. for (auto *MovedExtInst : MovedExts) {
  4761. if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
  4762. LI = cast<LoadInst>(MovedExtInst->getOperand(0));
  4763. Inst = MovedExtInst;
  4764. break;
  4765. }
  4766. }
  4767. if (!LI)
  4768. return false;
  4769. // If they're already in the same block, there's nothing to do.
  4770. // Make the cheap checks first if we did not promote.
  4771. // If we promoted, we need to check if it is indeed profitable.
  4772. if (!HasPromoted && LI->getParent() == Inst->getParent())
  4773. return false;
  4774. return TLI->isExtLoad(LI, Inst, *DL);
  4775. }
  4776. /// Move a zext or sext fed by a load into the same basic block as the load,
  4777. /// unless conditions are unfavorable. This allows SelectionDAG to fold the
  4778. /// extend into the load.
  4779. ///
  4780. /// E.g.,
  4781. /// \code
  4782. /// %ld = load i32* %addr
  4783. /// %add = add nuw i32 %ld, 4
  4784. /// %zext = zext i32 %add to i64
  4785. // \endcode
  4786. /// =>
  4787. /// \code
  4788. /// %ld = load i32* %addr
  4789. /// %zext = zext i32 %ld to i64
  4790. /// %add = add nuw i64 %zext, 4
  4791. /// \encode
  4792. /// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
  4793. /// allow us to match zext(load i32*) to i64.
  4794. ///
  4795. /// Also, try to promote the computations used to obtain a sign extended
  4796. /// value used into memory accesses.
  4797. /// E.g.,
  4798. /// \code
  4799. /// a = add nsw i32 b, 3
  4800. /// d = sext i32 a to i64
  4801. /// e = getelementptr ..., i64 d
  4802. /// \endcode
  4803. /// =>
  4804. /// \code
  4805. /// f = sext i32 b to i64
  4806. /// a = add nsw i64 f, 3
  4807. /// e = getelementptr ..., i64 a
  4808. /// \endcode
  4809. ///
  4810. /// \p Inst[in/out] the extension may be modified during the process if some
  4811. /// promotions apply.
  4812. bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
  4813. // ExtLoad formation and address type promotion infrastructure requires TLI to
  4814. // be effective.
  4815. if (!TLI)
  4816. return false;
  4817. bool AllowPromotionWithoutCommonHeader = false;
  4818. /// See if it is an interesting sext operations for the address type
  4819. /// promotion before trying to promote it, e.g., the ones with the right
  4820. /// type and used in memory accesses.
  4821. bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
  4822. *Inst, AllowPromotionWithoutCommonHeader);
  4823. TypePromotionTransaction TPT(RemovedInsts);
  4824. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  4825. TPT.getRestorationPoint();
  4826. SmallVector<Instruction *, 1> Exts;
  4827. SmallVector<Instruction *, 2> SpeculativelyMovedExts;
  4828. Exts.push_back(Inst);
  4829. bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
  4830. // Look for a load being extended.
  4831. LoadInst *LI = nullptr;
  4832. Instruction *ExtFedByLoad;
  4833. // Try to promote a chain of computation if it allows to form an extended
  4834. // load.
  4835. if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
  4836. assert(LI && ExtFedByLoad && "Expect a valid load and extension");
  4837. TPT.commit();
  4838. // Move the extend into the same block as the load
  4839. ExtFedByLoad->moveAfter(LI);
  4840. // CGP does not check if the zext would be speculatively executed when moved
  4841. // to the same basic block as the load. Preserving its original location
  4842. // would pessimize the debugging experience, as well as negatively impact
  4843. // the quality of sample pgo. We don't want to use "line 0" as that has a
  4844. // size cost in the line-table section and logically the zext can be seen as
  4845. // part of the load. Therefore we conservatively reuse the same debug
  4846. // location for the load and the zext.
  4847. ExtFedByLoad->setDebugLoc(LI->getDebugLoc());
  4848. ++NumExtsMoved;
  4849. Inst = ExtFedByLoad;
  4850. return true;
  4851. }
  4852. // Continue promoting SExts if known as considerable depending on targets.
  4853. if (ATPConsiderable &&
  4854. performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
  4855. HasPromoted, TPT, SpeculativelyMovedExts))
  4856. return true;
  4857. TPT.rollback(LastKnownGood);
  4858. return false;
  4859. }
  4860. // Perform address type promotion if doing so is profitable.
  4861. // If AllowPromotionWithoutCommonHeader == false, we should find other sext
  4862. // instructions that sign extended the same initial value. However, if
  4863. // AllowPromotionWithoutCommonHeader == true, we expect promoting the
  4864. // extension is just profitable.
  4865. bool CodeGenPrepare::performAddressTypePromotion(
  4866. Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
  4867. bool HasPromoted, TypePromotionTransaction &TPT,
  4868. SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
  4869. bool Promoted = false;
  4870. SmallPtrSet<Instruction *, 1> UnhandledExts;
  4871. bool AllSeenFirst = true;
  4872. for (auto I : SpeculativelyMovedExts) {
  4873. Value *HeadOfChain = I->getOperand(0);
  4874. DenseMap<Value *, Instruction *>::iterator AlreadySeen =
  4875. SeenChainsForSExt.find(HeadOfChain);
  4876. // If there is an unhandled SExt which has the same header, try to promote
  4877. // it as well.
  4878. if (AlreadySeen != SeenChainsForSExt.end()) {
  4879. if (AlreadySeen->second != nullptr)
  4880. UnhandledExts.insert(AlreadySeen->second);
  4881. AllSeenFirst = false;
  4882. }
  4883. }
  4884. if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
  4885. SpeculativelyMovedExts.size() == 1)) {
  4886. TPT.commit();
  4887. if (HasPromoted)
  4888. Promoted = true;
  4889. for (auto I : SpeculativelyMovedExts) {
  4890. Value *HeadOfChain = I->getOperand(0);
  4891. SeenChainsForSExt[HeadOfChain] = nullptr;
  4892. ValToSExtendedUses[HeadOfChain].push_back(I);
  4893. }
  4894. // Update Inst as promotion happen.
  4895. Inst = SpeculativelyMovedExts.pop_back_val();
  4896. } else {
  4897. // This is the first chain visited from the header, keep the current chain
  4898. // as unhandled. Defer to promote this until we encounter another SExt
  4899. // chain derived from the same header.
  4900. for (auto I : SpeculativelyMovedExts) {
  4901. Value *HeadOfChain = I->getOperand(0);
  4902. SeenChainsForSExt[HeadOfChain] = Inst;
  4903. }
  4904. return false;
  4905. }
  4906. if (!AllSeenFirst && !UnhandledExts.empty())
  4907. for (auto VisitedSExt : UnhandledExts) {
  4908. if (RemovedInsts.count(VisitedSExt))
  4909. continue;
  4910. TypePromotionTransaction TPT(RemovedInsts);
  4911. SmallVector<Instruction *, 1> Exts;
  4912. SmallVector<Instruction *, 2> Chains;
  4913. Exts.push_back(VisitedSExt);
  4914. bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
  4915. TPT.commit();
  4916. if (HasPromoted)
  4917. Promoted = true;
  4918. for (auto I : Chains) {
  4919. Value *HeadOfChain = I->getOperand(0);
  4920. // Mark this as handled.
  4921. SeenChainsForSExt[HeadOfChain] = nullptr;
  4922. ValToSExtendedUses[HeadOfChain].push_back(I);
  4923. }
  4924. }
  4925. return Promoted;
  4926. }
  4927. bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
  4928. BasicBlock *DefBB = I->getParent();
  4929. // If the result of a {s|z}ext and its source are both live out, rewrite all
  4930. // other uses of the source with result of extension.
  4931. Value *Src = I->getOperand(0);
  4932. if (Src->hasOneUse())
  4933. return false;
  4934. // Only do this xform if truncating is free.
  4935. if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
  4936. return false;
  4937. // Only safe to perform the optimization if the source is also defined in
  4938. // this block.
  4939. if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
  4940. return false;
  4941. bool DefIsLiveOut = false;
  4942. for (User *U : I->users()) {
  4943. Instruction *UI = cast<Instruction>(U);
  4944. // Figure out which BB this ext is used in.
  4945. BasicBlock *UserBB = UI->getParent();
  4946. if (UserBB == DefBB) continue;
  4947. DefIsLiveOut = true;
  4948. break;
  4949. }
  4950. if (!DefIsLiveOut)
  4951. return false;
  4952. // Make sure none of the uses are PHI nodes.
  4953. for (User *U : Src->users()) {
  4954. Instruction *UI = cast<Instruction>(U);
  4955. BasicBlock *UserBB = UI->getParent();
  4956. if (UserBB == DefBB) continue;
  4957. // Be conservative. We don't want this xform to end up introducing
  4958. // reloads just before load / store instructions.
  4959. if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
  4960. return false;
  4961. }
  4962. // InsertedTruncs - Only insert one trunc in each block once.
  4963. DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
  4964. bool MadeChange = false;
  4965. for (Use &U : Src->uses()) {
  4966. Instruction *User = cast<Instruction>(U.getUser());
  4967. // Figure out which BB this ext is used in.
  4968. BasicBlock *UserBB = User->getParent();
  4969. if (UserBB == DefBB) continue;
  4970. // Both src and def are live in this block. Rewrite the use.
  4971. Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
  4972. if (!InsertedTrunc) {
  4973. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  4974. assert(InsertPt != UserBB->end());
  4975. InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
  4976. InsertedInsts.insert(InsertedTrunc);
  4977. }
  4978. // Replace a use of the {s|z}ext source with a use of the result.
  4979. U = InsertedTrunc;
  4980. ++NumExtUses;
  4981. MadeChange = true;
  4982. }
  4983. return MadeChange;
  4984. }
  4985. // Find loads whose uses only use some of the loaded value's bits. Add an "and"
  4986. // just after the load if the target can fold this into one extload instruction,
  4987. // with the hope of eliminating some of the other later "and" instructions using
  4988. // the loaded value. "and"s that are made trivially redundant by the insertion
  4989. // of the new "and" are removed by this function, while others (e.g. those whose
  4990. // path from the load goes through a phi) are left for isel to potentially
  4991. // remove.
  4992. //
  4993. // For example:
  4994. //
  4995. // b0:
  4996. // x = load i32
  4997. // ...
  4998. // b1:
  4999. // y = and x, 0xff
  5000. // z = use y
  5001. //
  5002. // becomes:
  5003. //
  5004. // b0:
  5005. // x = load i32
  5006. // x' = and x, 0xff
  5007. // ...
  5008. // b1:
  5009. // z = use x'
  5010. //
  5011. // whereas:
  5012. //
  5013. // b0:
  5014. // x1 = load i32
  5015. // ...
  5016. // b1:
  5017. // x2 = load i32
  5018. // ...
  5019. // b2:
  5020. // x = phi x1, x2
  5021. // y = and x, 0xff
  5022. //
  5023. // becomes (after a call to optimizeLoadExt for each load):
  5024. //
  5025. // b0:
  5026. // x1 = load i32
  5027. // x1' = and x1, 0xff
  5028. // ...
  5029. // b1:
  5030. // x2 = load i32
  5031. // x2' = and x2, 0xff
  5032. // ...
  5033. // b2:
  5034. // x = phi x1', x2'
  5035. // y = and x, 0xff
  5036. bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
  5037. if (!Load->isSimple() || !Load->getType()->isIntOrPtrTy())
  5038. return false;
  5039. // Skip loads we've already transformed.
  5040. if (Load->hasOneUse() &&
  5041. InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
  5042. return false;
  5043. // Look at all uses of Load, looking through phis, to determine how many bits
  5044. // of the loaded value are needed.
  5045. SmallVector<Instruction *, 8> WorkList;
  5046. SmallPtrSet<Instruction *, 16> Visited;
  5047. SmallVector<Instruction *, 8> AndsToMaybeRemove;
  5048. for (auto *U : Load->users())
  5049. WorkList.push_back(cast<Instruction>(U));
  5050. EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
  5051. unsigned BitWidth = LoadResultVT.getSizeInBits();
  5052. APInt DemandBits(BitWidth, 0);
  5053. APInt WidestAndBits(BitWidth, 0);
  5054. while (!WorkList.empty()) {
  5055. Instruction *I = WorkList.back();
  5056. WorkList.pop_back();
  5057. // Break use-def graph loops.
  5058. if (!Visited.insert(I).second)
  5059. continue;
  5060. // For a PHI node, push all of its users.
  5061. if (auto *Phi = dyn_cast<PHINode>(I)) {
  5062. for (auto *U : Phi->users())
  5063. WorkList.push_back(cast<Instruction>(U));
  5064. continue;
  5065. }
  5066. switch (I->getOpcode()) {
  5067. case Instruction::And: {
  5068. auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
  5069. if (!AndC)
  5070. return false;
  5071. APInt AndBits = AndC->getValue();
  5072. DemandBits |= AndBits;
  5073. // Keep track of the widest and mask we see.
  5074. if (AndBits.ugt(WidestAndBits))
  5075. WidestAndBits = AndBits;
  5076. if (AndBits == WidestAndBits && I->getOperand(0) == Load)
  5077. AndsToMaybeRemove.push_back(I);
  5078. break;
  5079. }
  5080. case Instruction::Shl: {
  5081. auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
  5082. if (!ShlC)
  5083. return false;
  5084. uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
  5085. DemandBits.setLowBits(BitWidth - ShiftAmt);
  5086. break;
  5087. }
  5088. case Instruction::Trunc: {
  5089. EVT TruncVT = TLI->getValueType(*DL, I->getType());
  5090. unsigned TruncBitWidth = TruncVT.getSizeInBits();
  5091. DemandBits.setLowBits(TruncBitWidth);
  5092. break;
  5093. }
  5094. default:
  5095. return false;
  5096. }
  5097. }
  5098. uint32_t ActiveBits = DemandBits.getActiveBits();
  5099. // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
  5100. // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
  5101. // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
  5102. // (and (load x) 1) is not matched as a single instruction, rather as a LDR
  5103. // followed by an AND.
  5104. // TODO: Look into removing this restriction by fixing backends to either
  5105. // return false for isLoadExtLegal for i1 or have them select this pattern to
  5106. // a single instruction.
  5107. //
  5108. // Also avoid hoisting if we didn't see any ands with the exact DemandBits
  5109. // mask, since these are the only ands that will be removed by isel.
  5110. if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
  5111. WidestAndBits != DemandBits)
  5112. return false;
  5113. LLVMContext &Ctx = Load->getType()->getContext();
  5114. Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
  5115. EVT TruncVT = TLI->getValueType(*DL, TruncTy);
  5116. // Reject cases that won't be matched as extloads.
  5117. if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
  5118. !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
  5119. return false;
  5120. IRBuilder<> Builder(Load->getNextNode());
  5121. auto *NewAnd = cast<Instruction>(
  5122. Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
  5123. // Mark this instruction as "inserted by CGP", so that other
  5124. // optimizations don't touch it.
  5125. InsertedInsts.insert(NewAnd);
  5126. // Replace all uses of load with new and (except for the use of load in the
  5127. // new and itself).
  5128. Load->replaceAllUsesWith(NewAnd);
  5129. NewAnd->setOperand(0, Load);
  5130. // Remove any and instructions that are now redundant.
  5131. for (auto *And : AndsToMaybeRemove)
  5132. // Check that the and mask is the same as the one we decided to put on the
  5133. // new and.
  5134. if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
  5135. And->replaceAllUsesWith(NewAnd);
  5136. if (&*CurInstIterator == And)
  5137. CurInstIterator = std::next(And->getIterator());
  5138. And->eraseFromParent();
  5139. ++NumAndUses;
  5140. }
  5141. ++NumAndsAdded;
  5142. return true;
  5143. }
  5144. /// Check if V (an operand of a select instruction) is an expensive instruction
  5145. /// that is only used once.
  5146. static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
  5147. auto *I = dyn_cast<Instruction>(V);
  5148. // If it's safe to speculatively execute, then it should not have side
  5149. // effects; therefore, it's safe to sink and possibly *not* execute.
  5150. return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
  5151. TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
  5152. }
  5153. /// Returns true if a SelectInst should be turned into an explicit branch.
  5154. static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
  5155. const TargetLowering *TLI,
  5156. SelectInst *SI) {
  5157. // If even a predictable select is cheap, then a branch can't be cheaper.
  5158. if (!TLI->isPredictableSelectExpensive())
  5159. return false;
  5160. // FIXME: This should use the same heuristics as IfConversion to determine
  5161. // whether a select is better represented as a branch.
  5162. // If metadata tells us that the select condition is obviously predictable,
  5163. // then we want to replace the select with a branch.
  5164. uint64_t TrueWeight, FalseWeight;
  5165. if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
  5166. uint64_t Max = std::max(TrueWeight, FalseWeight);
  5167. uint64_t Sum = TrueWeight + FalseWeight;
  5168. if (Sum != 0) {
  5169. auto Probability = BranchProbability::getBranchProbability(Max, Sum);
  5170. if (Probability > TLI->getPredictableBranchThreshold())
  5171. return true;
  5172. }
  5173. }
  5174. CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
  5175. // If a branch is predictable, an out-of-order CPU can avoid blocking on its
  5176. // comparison condition. If the compare has more than one use, there's
  5177. // probably another cmov or setcc around, so it's not worth emitting a branch.
  5178. if (!Cmp || !Cmp->hasOneUse())
  5179. return false;
  5180. // If either operand of the select is expensive and only needed on one side
  5181. // of the select, we should form a branch.
  5182. if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
  5183. sinkSelectOperand(TTI, SI->getFalseValue()))
  5184. return true;
  5185. return false;
  5186. }
  5187. /// If \p isTrue is true, return the true value of \p SI, otherwise return
  5188. /// false value of \p SI. If the true/false value of \p SI is defined by any
  5189. /// select instructions in \p Selects, look through the defining select
  5190. /// instruction until the true/false value is not defined in \p Selects.
  5191. static Value *getTrueOrFalseValue(
  5192. SelectInst *SI, bool isTrue,
  5193. const SmallPtrSet<const Instruction *, 2> &Selects) {
  5194. Value *V = nullptr;
  5195. for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
  5196. DefSI = dyn_cast<SelectInst>(V)) {
  5197. assert(DefSI->getCondition() == SI->getCondition() &&
  5198. "The condition of DefSI does not match with SI");
  5199. V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
  5200. }
  5201. assert(V && "Failed to get select true/false value");
  5202. return V;
  5203. }
  5204. bool CodeGenPrepare::optimizeShiftInst(BinaryOperator *Shift) {
  5205. assert(Shift->isShift() && "Expected a shift");
  5206. // If this is (1) a vector shift, (2) shifts by scalars are cheaper than
  5207. // general vector shifts, and (3) the shift amount is a select-of-splatted
  5208. // values, hoist the shifts before the select:
  5209. // shift Op0, (select Cond, TVal, FVal) -->
  5210. // select Cond, (shift Op0, TVal), (shift Op0, FVal)
  5211. //
  5212. // This is inverting a generic IR transform when we know that the cost of a
  5213. // general vector shift is more than the cost of 2 shift-by-scalars.
  5214. // We can't do this effectively in SDAG because we may not be able to
  5215. // determine if the select operands are splats from within a basic block.
  5216. Type *Ty = Shift->getType();
  5217. if (!Ty->isVectorTy() || !TLI->isVectorShiftByScalarCheap(Ty))
  5218. return false;
  5219. Value *Cond, *TVal, *FVal;
  5220. if (!match(Shift->getOperand(1),
  5221. m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))))
  5222. return false;
  5223. if (!isSplatValue(TVal) || !isSplatValue(FVal))
  5224. return false;
  5225. IRBuilder<> Builder(Shift);
  5226. BinaryOperator::BinaryOps Opcode = Shift->getOpcode();
  5227. Value *NewTVal = Builder.CreateBinOp(Opcode, Shift->getOperand(0), TVal);
  5228. Value *NewFVal = Builder.CreateBinOp(Opcode, Shift->getOperand(0), FVal);
  5229. Value *NewSel = Builder.CreateSelect(Cond, NewTVal, NewFVal);
  5230. Shift->replaceAllUsesWith(NewSel);
  5231. Shift->eraseFromParent();
  5232. return true;
  5233. }
  5234. /// If we have a SelectInst that will likely profit from branch prediction,
  5235. /// turn it into a branch.
  5236. bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
  5237. // If branch conversion isn't desirable, exit early.
  5238. if (DisableSelectToBranch || OptSize || !TLI)
  5239. return false;
  5240. // Find all consecutive select instructions that share the same condition.
  5241. SmallVector<SelectInst *, 2> ASI;
  5242. ASI.push_back(SI);
  5243. for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
  5244. It != SI->getParent()->end(); ++It) {
  5245. SelectInst *I = dyn_cast<SelectInst>(&*It);
  5246. if (I && SI->getCondition() == I->getCondition()) {
  5247. ASI.push_back(I);
  5248. } else {
  5249. break;
  5250. }
  5251. }
  5252. SelectInst *LastSI = ASI.back();
  5253. // Increment the current iterator to skip all the rest of select instructions
  5254. // because they will be either "not lowered" or "all lowered" to branch.
  5255. CurInstIterator = std::next(LastSI->getIterator());
  5256. bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
  5257. // Can we convert the 'select' to CF ?
  5258. if (VectorCond || SI->getMetadata(LLVMContext::MD_unpredictable))
  5259. return false;
  5260. TargetLowering::SelectSupportKind SelectKind;
  5261. if (VectorCond)
  5262. SelectKind = TargetLowering::VectorMaskSelect;
  5263. else if (SI->getType()->isVectorTy())
  5264. SelectKind = TargetLowering::ScalarCondVectorVal;
  5265. else
  5266. SelectKind = TargetLowering::ScalarValSelect;
  5267. if (TLI->isSelectSupported(SelectKind) &&
  5268. !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
  5269. return false;
  5270. // The DominatorTree needs to be rebuilt by any consumers after this
  5271. // transformation. We simply reset here rather than setting the ModifiedDT
  5272. // flag to avoid restarting the function walk in runOnFunction for each
  5273. // select optimized.
  5274. DT.reset();
  5275. // Transform a sequence like this:
  5276. // start:
  5277. // %cmp = cmp uge i32 %a, %b
  5278. // %sel = select i1 %cmp, i32 %c, i32 %d
  5279. //
  5280. // Into:
  5281. // start:
  5282. // %cmp = cmp uge i32 %a, %b
  5283. // br i1 %cmp, label %select.true, label %select.false
  5284. // select.true:
  5285. // br label %select.end
  5286. // select.false:
  5287. // br label %select.end
  5288. // select.end:
  5289. // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
  5290. //
  5291. // In addition, we may sink instructions that produce %c or %d from
  5292. // the entry block into the destination(s) of the new branch.
  5293. // If the true or false blocks do not contain a sunken instruction, that
  5294. // block and its branch may be optimized away. In that case, one side of the
  5295. // first branch will point directly to select.end, and the corresponding PHI
  5296. // predecessor block will be the start block.
  5297. // First, we split the block containing the select into 2 blocks.
  5298. BasicBlock *StartBlock = SI->getParent();
  5299. BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
  5300. BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
  5301. // Delete the unconditional branch that was just created by the split.
  5302. StartBlock->getTerminator()->eraseFromParent();
  5303. // These are the new basic blocks for the conditional branch.
  5304. // At least one will become an actual new basic block.
  5305. BasicBlock *TrueBlock = nullptr;
  5306. BasicBlock *FalseBlock = nullptr;
  5307. BranchInst *TrueBranch = nullptr;
  5308. BranchInst *FalseBranch = nullptr;
  5309. // Sink expensive instructions into the conditional blocks to avoid executing
  5310. // them speculatively.
  5311. for (SelectInst *SI : ASI) {
  5312. if (sinkSelectOperand(TTI, SI->getTrueValue())) {
  5313. if (TrueBlock == nullptr) {
  5314. TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
  5315. EndBlock->getParent(), EndBlock);
  5316. TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
  5317. TrueBranch->setDebugLoc(SI->getDebugLoc());
  5318. }
  5319. auto *TrueInst = cast<Instruction>(SI->getTrueValue());
  5320. TrueInst->moveBefore(TrueBranch);
  5321. }
  5322. if (sinkSelectOperand(TTI, SI->getFalseValue())) {
  5323. if (FalseBlock == nullptr) {
  5324. FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
  5325. EndBlock->getParent(), EndBlock);
  5326. FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
  5327. FalseBranch->setDebugLoc(SI->getDebugLoc());
  5328. }
  5329. auto *FalseInst = cast<Instruction>(SI->getFalseValue());
  5330. FalseInst->moveBefore(FalseBranch);
  5331. }
  5332. }
  5333. // If there was nothing to sink, then arbitrarily choose the 'false' side
  5334. // for a new input value to the PHI.
  5335. if (TrueBlock == FalseBlock) {
  5336. assert(TrueBlock == nullptr &&
  5337. "Unexpected basic block transform while optimizing select");
  5338. FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
  5339. EndBlock->getParent(), EndBlock);
  5340. auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
  5341. FalseBranch->setDebugLoc(SI->getDebugLoc());
  5342. }
  5343. // Insert the real conditional branch based on the original condition.
  5344. // If we did not create a new block for one of the 'true' or 'false' paths
  5345. // of the condition, it means that side of the branch goes to the end block
  5346. // directly and the path originates from the start block from the point of
  5347. // view of the new PHI.
  5348. BasicBlock *TT, *FT;
  5349. if (TrueBlock == nullptr) {
  5350. TT = EndBlock;
  5351. FT = FalseBlock;
  5352. TrueBlock = StartBlock;
  5353. } else if (FalseBlock == nullptr) {
  5354. TT = TrueBlock;
  5355. FT = EndBlock;
  5356. FalseBlock = StartBlock;
  5357. } else {
  5358. TT = TrueBlock;
  5359. FT = FalseBlock;
  5360. }
  5361. IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
  5362. SmallPtrSet<const Instruction *, 2> INS;
  5363. INS.insert(ASI.begin(), ASI.end());
  5364. // Use reverse iterator because later select may use the value of the
  5365. // earlier select, and we need to propagate value through earlier select
  5366. // to get the PHI operand.
  5367. for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
  5368. SelectInst *SI = *It;
  5369. // The select itself is replaced with a PHI Node.
  5370. PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
  5371. PN->takeName(SI);
  5372. PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
  5373. PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
  5374. PN->setDebugLoc(SI->getDebugLoc());
  5375. SI->replaceAllUsesWith(PN);
  5376. SI->eraseFromParent();
  5377. INS.erase(SI);
  5378. ++NumSelectsExpanded;
  5379. }
  5380. // Instruct OptimizeBlock to skip to the next block.
  5381. CurInstIterator = StartBlock->end();
  5382. return true;
  5383. }
  5384. static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
  5385. SmallVector<int, 16> Mask(SVI->getShuffleMask());
  5386. int SplatElem = -1;
  5387. for (unsigned i = 0; i < Mask.size(); ++i) {
  5388. if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
  5389. return false;
  5390. SplatElem = Mask[i];
  5391. }
  5392. return true;
  5393. }
  5394. /// Some targets have expensive vector shifts if the lanes aren't all the same
  5395. /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
  5396. /// it's often worth sinking a shufflevector splat down to its use so that
  5397. /// codegen can spot all lanes are identical.
  5398. bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
  5399. BasicBlock *DefBB = SVI->getParent();
  5400. // Only do this xform if variable vector shifts are particularly expensive.
  5401. if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
  5402. return false;
  5403. // We only expect better codegen by sinking a shuffle if we can recognise a
  5404. // constant splat.
  5405. if (!isBroadcastShuffle(SVI))
  5406. return false;
  5407. // InsertedShuffles - Only insert a shuffle in each block once.
  5408. DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
  5409. bool MadeChange = false;
  5410. for (User *U : SVI->users()) {
  5411. Instruction *UI = cast<Instruction>(U);
  5412. // Figure out which BB this ext is used in.
  5413. BasicBlock *UserBB = UI->getParent();
  5414. if (UserBB == DefBB) continue;
  5415. // For now only apply this when the splat is used by a shift instruction.
  5416. if (!UI->isShift()) continue;
  5417. // Everything checks out, sink the shuffle if the user's block doesn't
  5418. // already have a copy.
  5419. Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
  5420. if (!InsertedShuffle) {
  5421. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  5422. assert(InsertPt != UserBB->end());
  5423. InsertedShuffle =
  5424. new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
  5425. SVI->getOperand(2), "", &*InsertPt);
  5426. InsertedShuffle->setDebugLoc(SVI->getDebugLoc());
  5427. }
  5428. UI->replaceUsesOfWith(SVI, InsertedShuffle);
  5429. MadeChange = true;
  5430. }
  5431. // If we removed all uses, nuke the shuffle.
  5432. if (SVI->use_empty()) {
  5433. SVI->eraseFromParent();
  5434. MadeChange = true;
  5435. }
  5436. return MadeChange;
  5437. }
  5438. bool CodeGenPrepare::tryToSinkFreeOperands(Instruction *I) {
  5439. // If the operands of I can be folded into a target instruction together with
  5440. // I, duplicate and sink them.
  5441. SmallVector<Use *, 4> OpsToSink;
  5442. if (!TLI || !TLI->shouldSinkOperands(I, OpsToSink))
  5443. return false;
  5444. // OpsToSink can contain multiple uses in a use chain (e.g.
  5445. // (%u1 with %u1 = shufflevector), (%u2 with %u2 = zext %u1)). The dominating
  5446. // uses must come first, so we process the ops in reverse order so as to not
  5447. // create invalid IR.
  5448. BasicBlock *TargetBB = I->getParent();
  5449. bool Changed = false;
  5450. SmallVector<Use *, 4> ToReplace;
  5451. for (Use *U : reverse(OpsToSink)) {
  5452. auto *UI = cast<Instruction>(U->get());
  5453. if (UI->getParent() == TargetBB || isa<PHINode>(UI))
  5454. continue;
  5455. ToReplace.push_back(U);
  5456. }
  5457. SetVector<Instruction *> MaybeDead;
  5458. DenseMap<Instruction *, Instruction *> NewInstructions;
  5459. Instruction *InsertPoint = I;
  5460. for (Use *U : ToReplace) {
  5461. auto *UI = cast<Instruction>(U->get());
  5462. Instruction *NI = UI->clone();
  5463. NewInstructions[UI] = NI;
  5464. MaybeDead.insert(UI);
  5465. LLVM_DEBUG(dbgs() << "Sinking " << *UI << " to user " << *I << "\n");
  5466. NI->insertBefore(InsertPoint);
  5467. InsertPoint = NI;
  5468. InsertedInsts.insert(NI);
  5469. // Update the use for the new instruction, making sure that we update the
  5470. // sunk instruction uses, if it is part of a chain that has already been
  5471. // sunk.
  5472. Instruction *OldI = cast<Instruction>(U->getUser());
  5473. if (NewInstructions.count(OldI))
  5474. NewInstructions[OldI]->setOperand(U->getOperandNo(), NI);
  5475. else
  5476. U->set(NI);
  5477. Changed = true;
  5478. }
  5479. // Remove instructions that are dead after sinking.
  5480. for (auto *I : MaybeDead) {
  5481. if (!I->hasNUsesOrMore(1)) {
  5482. LLVM_DEBUG(dbgs() << "Removing dead instruction: " << *I << "\n");
  5483. I->eraseFromParent();
  5484. }
  5485. }
  5486. return Changed;
  5487. }
  5488. bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
  5489. if (!TLI || !DL)
  5490. return false;
  5491. Value *Cond = SI->getCondition();
  5492. Type *OldType = Cond->getType();
  5493. LLVMContext &Context = Cond->getContext();
  5494. MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
  5495. unsigned RegWidth = RegType.getSizeInBits();
  5496. if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
  5497. return false;
  5498. // If the register width is greater than the type width, expand the condition
  5499. // of the switch instruction and each case constant to the width of the
  5500. // register. By widening the type of the switch condition, subsequent
  5501. // comparisons (for case comparisons) will not need to be extended to the
  5502. // preferred register width, so we will potentially eliminate N-1 extends,
  5503. // where N is the number of cases in the switch.
  5504. auto *NewType = Type::getIntNTy(Context, RegWidth);
  5505. // Zero-extend the switch condition and case constants unless the switch
  5506. // condition is a function argument that is already being sign-extended.
  5507. // In that case, we can avoid an unnecessary mask/extension by sign-extending
  5508. // everything instead.
  5509. Instruction::CastOps ExtType = Instruction::ZExt;
  5510. if (auto *Arg = dyn_cast<Argument>(Cond))
  5511. if (Arg->hasSExtAttr())
  5512. ExtType = Instruction::SExt;
  5513. auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
  5514. ExtInst->insertBefore(SI);
  5515. ExtInst->setDebugLoc(SI->getDebugLoc());
  5516. SI->setCondition(ExtInst);
  5517. for (auto Case : SI->cases()) {
  5518. APInt NarrowConst = Case.getCaseValue()->getValue();
  5519. APInt WideConst = (ExtType == Instruction::ZExt) ?
  5520. NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
  5521. Case.setValue(ConstantInt::get(Context, WideConst));
  5522. }
  5523. return true;
  5524. }
  5525. namespace {
  5526. /// Helper class to promote a scalar operation to a vector one.
  5527. /// This class is used to move downward extractelement transition.
  5528. /// E.g.,
  5529. /// a = vector_op <2 x i32>
  5530. /// b = extractelement <2 x i32> a, i32 0
  5531. /// c = scalar_op b
  5532. /// store c
  5533. ///
  5534. /// =>
  5535. /// a = vector_op <2 x i32>
  5536. /// c = vector_op a (equivalent to scalar_op on the related lane)
  5537. /// * d = extractelement <2 x i32> c, i32 0
  5538. /// * store d
  5539. /// Assuming both extractelement and store can be combine, we get rid of the
  5540. /// transition.
  5541. class VectorPromoteHelper {
  5542. /// DataLayout associated with the current module.
  5543. const DataLayout &DL;
  5544. /// Used to perform some checks on the legality of vector operations.
  5545. const TargetLowering &TLI;
  5546. /// Used to estimated the cost of the promoted chain.
  5547. const TargetTransformInfo &TTI;
  5548. /// The transition being moved downwards.
  5549. Instruction *Transition;
  5550. /// The sequence of instructions to be promoted.
  5551. SmallVector<Instruction *, 4> InstsToBePromoted;
  5552. /// Cost of combining a store and an extract.
  5553. unsigned StoreExtractCombineCost;
  5554. /// Instruction that will be combined with the transition.
  5555. Instruction *CombineInst = nullptr;
  5556. /// The instruction that represents the current end of the transition.
  5557. /// Since we are faking the promotion until we reach the end of the chain
  5558. /// of computation, we need a way to get the current end of the transition.
  5559. Instruction *getEndOfTransition() const {
  5560. if (InstsToBePromoted.empty())
  5561. return Transition;
  5562. return InstsToBePromoted.back();
  5563. }
  5564. /// Return the index of the original value in the transition.
  5565. /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
  5566. /// c, is at index 0.
  5567. unsigned getTransitionOriginalValueIdx() const {
  5568. assert(isa<ExtractElementInst>(Transition) &&
  5569. "Other kind of transitions are not supported yet");
  5570. return 0;
  5571. }
  5572. /// Return the index of the index in the transition.
  5573. /// E.g., for "extractelement <2 x i32> c, i32 0" the index
  5574. /// is at index 1.
  5575. unsigned getTransitionIdx() const {
  5576. assert(isa<ExtractElementInst>(Transition) &&
  5577. "Other kind of transitions are not supported yet");
  5578. return 1;
  5579. }
  5580. /// Get the type of the transition.
  5581. /// This is the type of the original value.
  5582. /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
  5583. /// transition is <2 x i32>.
  5584. Type *getTransitionType() const {
  5585. return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
  5586. }
  5587. /// Promote \p ToBePromoted by moving \p Def downward through.
  5588. /// I.e., we have the following sequence:
  5589. /// Def = Transition <ty1> a to <ty2>
  5590. /// b = ToBePromoted <ty2> Def, ...
  5591. /// =>
  5592. /// b = ToBePromoted <ty1> a, ...
  5593. /// Def = Transition <ty1> ToBePromoted to <ty2>
  5594. void promoteImpl(Instruction *ToBePromoted);
  5595. /// Check whether or not it is profitable to promote all the
  5596. /// instructions enqueued to be promoted.
  5597. bool isProfitableToPromote() {
  5598. Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
  5599. unsigned Index = isa<ConstantInt>(ValIdx)
  5600. ? cast<ConstantInt>(ValIdx)->getZExtValue()
  5601. : -1;
  5602. Type *PromotedType = getTransitionType();
  5603. StoreInst *ST = cast<StoreInst>(CombineInst);
  5604. unsigned AS = ST->getPointerAddressSpace();
  5605. unsigned Align = ST->getAlignment();
  5606. // Check if this store is supported.
  5607. if (!TLI.allowsMisalignedMemoryAccesses(
  5608. TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
  5609. Align)) {
  5610. // If this is not supported, there is no way we can combine
  5611. // the extract with the store.
  5612. return false;
  5613. }
  5614. // The scalar chain of computation has to pay for the transition
  5615. // scalar to vector.
  5616. // The vector chain has to account for the combining cost.
  5617. uint64_t ScalarCost =
  5618. TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
  5619. uint64_t VectorCost = StoreExtractCombineCost;
  5620. for (const auto &Inst : InstsToBePromoted) {
  5621. // Compute the cost.
  5622. // By construction, all instructions being promoted are arithmetic ones.
  5623. // Moreover, one argument is a constant that can be viewed as a splat
  5624. // constant.
  5625. Value *Arg0 = Inst->getOperand(0);
  5626. bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
  5627. isa<ConstantFP>(Arg0);
  5628. TargetTransformInfo::OperandValueKind Arg0OVK =
  5629. IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
  5630. : TargetTransformInfo::OK_AnyValue;
  5631. TargetTransformInfo::OperandValueKind Arg1OVK =
  5632. !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
  5633. : TargetTransformInfo::OK_AnyValue;
  5634. ScalarCost += TTI.getArithmeticInstrCost(
  5635. Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
  5636. VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
  5637. Arg0OVK, Arg1OVK);
  5638. }
  5639. LLVM_DEBUG(
  5640. dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
  5641. << ScalarCost << "\nVector: " << VectorCost << '\n');
  5642. return ScalarCost > VectorCost;
  5643. }
  5644. /// Generate a constant vector with \p Val with the same
  5645. /// number of elements as the transition.
  5646. /// \p UseSplat defines whether or not \p Val should be replicated
  5647. /// across the whole vector.
  5648. /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
  5649. /// otherwise we generate a vector with as many undef as possible:
  5650. /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
  5651. /// used at the index of the extract.
  5652. Value *getConstantVector(Constant *Val, bool UseSplat) const {
  5653. unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
  5654. if (!UseSplat) {
  5655. // If we cannot determine where the constant must be, we have to
  5656. // use a splat constant.
  5657. Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
  5658. if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
  5659. ExtractIdx = CstVal->getSExtValue();
  5660. else
  5661. UseSplat = true;
  5662. }
  5663. unsigned End = getTransitionType()->getVectorNumElements();
  5664. if (UseSplat)
  5665. return ConstantVector::getSplat(End, Val);
  5666. SmallVector<Constant *, 4> ConstVec;
  5667. UndefValue *UndefVal = UndefValue::get(Val->getType());
  5668. for (unsigned Idx = 0; Idx != End; ++Idx) {
  5669. if (Idx == ExtractIdx)
  5670. ConstVec.push_back(Val);
  5671. else
  5672. ConstVec.push_back(UndefVal);
  5673. }
  5674. return ConstantVector::get(ConstVec);
  5675. }
  5676. /// Check if promoting to a vector type an operand at \p OperandIdx
  5677. /// in \p Use can trigger undefined behavior.
  5678. static bool canCauseUndefinedBehavior(const Instruction *Use,
  5679. unsigned OperandIdx) {
  5680. // This is not safe to introduce undef when the operand is on
  5681. // the right hand side of a division-like instruction.
  5682. if (OperandIdx != 1)
  5683. return false;
  5684. switch (Use->getOpcode()) {
  5685. default:
  5686. return false;
  5687. case Instruction::SDiv:
  5688. case Instruction::UDiv:
  5689. case Instruction::SRem:
  5690. case Instruction::URem:
  5691. return true;
  5692. case Instruction::FDiv:
  5693. case Instruction::FRem:
  5694. return !Use->hasNoNaNs();
  5695. }
  5696. llvm_unreachable(nullptr);
  5697. }
  5698. public:
  5699. VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
  5700. const TargetTransformInfo &TTI, Instruction *Transition,
  5701. unsigned CombineCost)
  5702. : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
  5703. StoreExtractCombineCost(CombineCost) {
  5704. assert(Transition && "Do not know how to promote null");
  5705. }
  5706. /// Check if we can promote \p ToBePromoted to \p Type.
  5707. bool canPromote(const Instruction *ToBePromoted) const {
  5708. // We could support CastInst too.
  5709. return isa<BinaryOperator>(ToBePromoted);
  5710. }
  5711. /// Check if it is profitable to promote \p ToBePromoted
  5712. /// by moving downward the transition through.
  5713. bool shouldPromote(const Instruction *ToBePromoted) const {
  5714. // Promote only if all the operands can be statically expanded.
  5715. // Indeed, we do not want to introduce any new kind of transitions.
  5716. for (const Use &U : ToBePromoted->operands()) {
  5717. const Value *Val = U.get();
  5718. if (Val == getEndOfTransition()) {
  5719. // If the use is a division and the transition is on the rhs,
  5720. // we cannot promote the operation, otherwise we may create a
  5721. // division by zero.
  5722. if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
  5723. return false;
  5724. continue;
  5725. }
  5726. if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
  5727. !isa<ConstantFP>(Val))
  5728. return false;
  5729. }
  5730. // Check that the resulting operation is legal.
  5731. int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
  5732. if (!ISDOpcode)
  5733. return false;
  5734. return StressStoreExtract ||
  5735. TLI.isOperationLegalOrCustom(
  5736. ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
  5737. }
  5738. /// Check whether or not \p Use can be combined
  5739. /// with the transition.
  5740. /// I.e., is it possible to do Use(Transition) => AnotherUse?
  5741. bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
  5742. /// Record \p ToBePromoted as part of the chain to be promoted.
  5743. void enqueueForPromotion(Instruction *ToBePromoted) {
  5744. InstsToBePromoted.push_back(ToBePromoted);
  5745. }
  5746. /// Set the instruction that will be combined with the transition.
  5747. void recordCombineInstruction(Instruction *ToBeCombined) {
  5748. assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
  5749. CombineInst = ToBeCombined;
  5750. }
  5751. /// Promote all the instructions enqueued for promotion if it is
  5752. /// is profitable.
  5753. /// \return True if the promotion happened, false otherwise.
  5754. bool promote() {
  5755. // Check if there is something to promote.
  5756. // Right now, if we do not have anything to combine with,
  5757. // we assume the promotion is not profitable.
  5758. if (InstsToBePromoted.empty() || !CombineInst)
  5759. return false;
  5760. // Check cost.
  5761. if (!StressStoreExtract && !isProfitableToPromote())
  5762. return false;
  5763. // Promote.
  5764. for (auto &ToBePromoted : InstsToBePromoted)
  5765. promoteImpl(ToBePromoted);
  5766. InstsToBePromoted.clear();
  5767. return true;
  5768. }
  5769. };
  5770. } // end anonymous namespace
  5771. void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
  5772. // At this point, we know that all the operands of ToBePromoted but Def
  5773. // can be statically promoted.
  5774. // For Def, we need to use its parameter in ToBePromoted:
  5775. // b = ToBePromoted ty1 a
  5776. // Def = Transition ty1 b to ty2
  5777. // Move the transition down.
  5778. // 1. Replace all uses of the promoted operation by the transition.
  5779. // = ... b => = ... Def.
  5780. assert(ToBePromoted->getType() == Transition->getType() &&
  5781. "The type of the result of the transition does not match "
  5782. "the final type");
  5783. ToBePromoted->replaceAllUsesWith(Transition);
  5784. // 2. Update the type of the uses.
  5785. // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
  5786. Type *TransitionTy = getTransitionType();
  5787. ToBePromoted->mutateType(TransitionTy);
  5788. // 3. Update all the operands of the promoted operation with promoted
  5789. // operands.
  5790. // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
  5791. for (Use &U : ToBePromoted->operands()) {
  5792. Value *Val = U.get();
  5793. Value *NewVal = nullptr;
  5794. if (Val == Transition)
  5795. NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
  5796. else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
  5797. isa<ConstantFP>(Val)) {
  5798. // Use a splat constant if it is not safe to use undef.
  5799. NewVal = getConstantVector(
  5800. cast<Constant>(Val),
  5801. isa<UndefValue>(Val) ||
  5802. canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
  5803. } else
  5804. llvm_unreachable("Did you modified shouldPromote and forgot to update "
  5805. "this?");
  5806. ToBePromoted->setOperand(U.getOperandNo(), NewVal);
  5807. }
  5808. Transition->moveAfter(ToBePromoted);
  5809. Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
  5810. }
  5811. /// Some targets can do store(extractelement) with one instruction.
  5812. /// Try to push the extractelement towards the stores when the target
  5813. /// has this feature and this is profitable.
  5814. bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
  5815. unsigned CombineCost = std::numeric_limits<unsigned>::max();
  5816. if (DisableStoreExtract || !TLI ||
  5817. (!StressStoreExtract &&
  5818. !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
  5819. Inst->getOperand(1), CombineCost)))
  5820. return false;
  5821. // At this point we know that Inst is a vector to scalar transition.
  5822. // Try to move it down the def-use chain, until:
  5823. // - We can combine the transition with its single use
  5824. // => we got rid of the transition.
  5825. // - We escape the current basic block
  5826. // => we would need to check that we are moving it at a cheaper place and
  5827. // we do not do that for now.
  5828. BasicBlock *Parent = Inst->getParent();
  5829. LLVM_DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
  5830. VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
  5831. // If the transition has more than one use, assume this is not going to be
  5832. // beneficial.
  5833. while (Inst->hasOneUse()) {
  5834. Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
  5835. LLVM_DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
  5836. if (ToBePromoted->getParent() != Parent) {
  5837. LLVM_DEBUG(dbgs() << "Instruction to promote is in a different block ("
  5838. << ToBePromoted->getParent()->getName()
  5839. << ") than the transition (" << Parent->getName()
  5840. << ").\n");
  5841. return false;
  5842. }
  5843. if (VPH.canCombine(ToBePromoted)) {
  5844. LLVM_DEBUG(dbgs() << "Assume " << *Inst << '\n'
  5845. << "will be combined with: " << *ToBePromoted << '\n');
  5846. VPH.recordCombineInstruction(ToBePromoted);
  5847. bool Changed = VPH.promote();
  5848. NumStoreExtractExposed += Changed;
  5849. return Changed;
  5850. }
  5851. LLVM_DEBUG(dbgs() << "Try promoting.\n");
  5852. if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
  5853. return false;
  5854. LLVM_DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
  5855. VPH.enqueueForPromotion(ToBePromoted);
  5856. Inst = ToBePromoted;
  5857. }
  5858. return false;
  5859. }
  5860. /// For the instruction sequence of store below, F and I values
  5861. /// are bundled together as an i64 value before being stored into memory.
  5862. /// Sometimes it is more efficient to generate separate stores for F and I,
  5863. /// which can remove the bitwise instructions or sink them to colder places.
  5864. ///
  5865. /// (store (or (zext (bitcast F to i32) to i64),
  5866. /// (shl (zext I to i64), 32)), addr) -->
  5867. /// (store F, addr) and (store I, addr+4)
  5868. ///
  5869. /// Similarly, splitting for other merged store can also be beneficial, like:
  5870. /// For pair of {i32, i32}, i64 store --> two i32 stores.
  5871. /// For pair of {i32, i16}, i64 store --> two i32 stores.
  5872. /// For pair of {i16, i16}, i32 store --> two i16 stores.
  5873. /// For pair of {i16, i8}, i32 store --> two i16 stores.
  5874. /// For pair of {i8, i8}, i16 store --> two i8 stores.
  5875. ///
  5876. /// We allow each target to determine specifically which kind of splitting is
  5877. /// supported.
  5878. ///
  5879. /// The store patterns are commonly seen from the simple code snippet below
  5880. /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
  5881. /// void goo(const std::pair<int, float> &);
  5882. /// hoo() {
  5883. /// ...
  5884. /// goo(std::make_pair(tmp, ftmp));
  5885. /// ...
  5886. /// }
  5887. ///
  5888. /// Although we already have similar splitting in DAG Combine, we duplicate
  5889. /// it in CodeGenPrepare to catch the case in which pattern is across
  5890. /// multiple BBs. The logic in DAG Combine is kept to catch case generated
  5891. /// during code expansion.
  5892. static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
  5893. const TargetLowering &TLI) {
  5894. // Handle simple but common cases only.
  5895. Type *StoreType = SI.getValueOperand()->getType();
  5896. if (!DL.typeSizeEqualsStoreSize(StoreType) ||
  5897. DL.getTypeSizeInBits(StoreType) == 0)
  5898. return false;
  5899. unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
  5900. Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
  5901. if (!DL.typeSizeEqualsStoreSize(SplitStoreType))
  5902. return false;
  5903. // Don't split the store if it is volatile.
  5904. if (SI.isVolatile())
  5905. return false;
  5906. // Match the following patterns:
  5907. // (store (or (zext LValue to i64),
  5908. // (shl (zext HValue to i64), 32)), HalfValBitSize)
  5909. // or
  5910. // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
  5911. // (zext LValue to i64),
  5912. // Expect both operands of OR and the first operand of SHL have only
  5913. // one use.
  5914. Value *LValue, *HValue;
  5915. if (!match(SI.getValueOperand(),
  5916. m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
  5917. m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
  5918. m_SpecificInt(HalfValBitSize))))))
  5919. return false;
  5920. // Check LValue and HValue are int with size less or equal than 32.
  5921. if (!LValue->getType()->isIntegerTy() ||
  5922. DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
  5923. !HValue->getType()->isIntegerTy() ||
  5924. DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
  5925. return false;
  5926. // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
  5927. // as the input of target query.
  5928. auto *LBC = dyn_cast<BitCastInst>(LValue);
  5929. auto *HBC = dyn_cast<BitCastInst>(HValue);
  5930. EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
  5931. : EVT::getEVT(LValue->getType());
  5932. EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
  5933. : EVT::getEVT(HValue->getType());
  5934. if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
  5935. return false;
  5936. // Start to split store.
  5937. IRBuilder<> Builder(SI.getContext());
  5938. Builder.SetInsertPoint(&SI);
  5939. // If LValue/HValue is a bitcast in another BB, create a new one in current
  5940. // BB so it may be merged with the splitted stores by dag combiner.
  5941. if (LBC && LBC->getParent() != SI.getParent())
  5942. LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
  5943. if (HBC && HBC->getParent() != SI.getParent())
  5944. HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
  5945. bool IsLE = SI.getModule()->getDataLayout().isLittleEndian();
  5946. auto CreateSplitStore = [&](Value *V, bool Upper) {
  5947. V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
  5948. Value *Addr = Builder.CreateBitCast(
  5949. SI.getOperand(1),
  5950. SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
  5951. if ((IsLE && Upper) || (!IsLE && !Upper))
  5952. Addr = Builder.CreateGEP(
  5953. SplitStoreType, Addr,
  5954. ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
  5955. Builder.CreateAlignedStore(
  5956. V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
  5957. };
  5958. CreateSplitStore(LValue, false);
  5959. CreateSplitStore(HValue, true);
  5960. // Delete the old store.
  5961. SI.eraseFromParent();
  5962. return true;
  5963. }
  5964. // Return true if the GEP has two operands, the first operand is of a sequential
  5965. // type, and the second operand is a constant.
  5966. static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) {
  5967. gep_type_iterator I = gep_type_begin(*GEP);
  5968. return GEP->getNumOperands() == 2 &&
  5969. I.isSequential() &&
  5970. isa<ConstantInt>(GEP->getOperand(1));
  5971. }
  5972. // Try unmerging GEPs to reduce liveness interference (register pressure) across
  5973. // IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
  5974. // reducing liveness interference across those edges benefits global register
  5975. // allocation. Currently handles only certain cases.
  5976. //
  5977. // For example, unmerge %GEPI and %UGEPI as below.
  5978. //
  5979. // ---------- BEFORE ----------
  5980. // SrcBlock:
  5981. // ...
  5982. // %GEPIOp = ...
  5983. // ...
  5984. // %GEPI = gep %GEPIOp, Idx
  5985. // ...
  5986. // indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
  5987. // (* %GEPI is alive on the indirectbr edges due to other uses ahead)
  5988. // (* %GEPIOp is alive on the indirectbr edges only because of it's used by
  5989. // %UGEPI)
  5990. //
  5991. // DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
  5992. // DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
  5993. // ...
  5994. //
  5995. // DstBi:
  5996. // ...
  5997. // %UGEPI = gep %GEPIOp, UIdx
  5998. // ...
  5999. // ---------------------------
  6000. //
  6001. // ---------- AFTER ----------
  6002. // SrcBlock:
  6003. // ... (same as above)
  6004. // (* %GEPI is still alive on the indirectbr edges)
  6005. // (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
  6006. // unmerging)
  6007. // ...
  6008. //
  6009. // DstBi:
  6010. // ...
  6011. // %UGEPI = gep %GEPI, (UIdx-Idx)
  6012. // ...
  6013. // ---------------------------
  6014. //
  6015. // The register pressure on the IndirectBr edges is reduced because %GEPIOp is
  6016. // no longer alive on them.
  6017. //
  6018. // We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
  6019. // of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
  6020. // not to disable further simplications and optimizations as a result of GEP
  6021. // merging.
  6022. //
  6023. // Note this unmerging may increase the length of the data flow critical path
  6024. // (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
  6025. // between the register pressure and the length of data-flow critical
  6026. // path. Restricting this to the uncommon IndirectBr case would minimize the
  6027. // impact of potentially longer critical path, if any, and the impact on compile
  6028. // time.
  6029. static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI,
  6030. const TargetTransformInfo *TTI) {
  6031. BasicBlock *SrcBlock = GEPI->getParent();
  6032. // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
  6033. // (non-IndirectBr) cases exit early here.
  6034. if (!isa<IndirectBrInst>(SrcBlock->getTerminator()))
  6035. return false;
  6036. // Check that GEPI is a simple gep with a single constant index.
  6037. if (!GEPSequentialConstIndexed(GEPI))
  6038. return false;
  6039. ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1));
  6040. // Check that GEPI is a cheap one.
  6041. if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType())
  6042. > TargetTransformInfo::TCC_Basic)
  6043. return false;
  6044. Value *GEPIOp = GEPI->getOperand(0);
  6045. // Check that GEPIOp is an instruction that's also defined in SrcBlock.
  6046. if (!isa<Instruction>(GEPIOp))
  6047. return false;
  6048. auto *GEPIOpI = cast<Instruction>(GEPIOp);
  6049. if (GEPIOpI->getParent() != SrcBlock)
  6050. return false;
  6051. // Check that GEP is used outside the block, meaning it's alive on the
  6052. // IndirectBr edge(s).
  6053. if (find_if(GEPI->users(), [&](User *Usr) {
  6054. if (auto *I = dyn_cast<Instruction>(Usr)) {
  6055. if (I->getParent() != SrcBlock) {
  6056. return true;
  6057. }
  6058. }
  6059. return false;
  6060. }) == GEPI->users().end())
  6061. return false;
  6062. // The second elements of the GEP chains to be unmerged.
  6063. std::vector<GetElementPtrInst *> UGEPIs;
  6064. // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
  6065. // on IndirectBr edges.
  6066. for (User *Usr : GEPIOp->users()) {
  6067. if (Usr == GEPI) continue;
  6068. // Check if Usr is an Instruction. If not, give up.
  6069. if (!isa<Instruction>(Usr))
  6070. return false;
  6071. auto *UI = cast<Instruction>(Usr);
  6072. // Check if Usr in the same block as GEPIOp, which is fine, skip.
  6073. if (UI->getParent() == SrcBlock)
  6074. continue;
  6075. // Check if Usr is a GEP. If not, give up.
  6076. if (!isa<GetElementPtrInst>(Usr))
  6077. return false;
  6078. auto *UGEPI = cast<GetElementPtrInst>(Usr);
  6079. // Check if UGEPI is a simple gep with a single constant index and GEPIOp is
  6080. // the pointer operand to it. If so, record it in the vector. If not, give
  6081. // up.
  6082. if (!GEPSequentialConstIndexed(UGEPI))
  6083. return false;
  6084. if (UGEPI->getOperand(0) != GEPIOp)
  6085. return false;
  6086. if (GEPIIdx->getType() !=
  6087. cast<ConstantInt>(UGEPI->getOperand(1))->getType())
  6088. return false;
  6089. ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
  6090. if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType())
  6091. > TargetTransformInfo::TCC_Basic)
  6092. return false;
  6093. UGEPIs.push_back(UGEPI);
  6094. }
  6095. if (UGEPIs.size() == 0)
  6096. return false;
  6097. // Check the materializing cost of (Uidx-Idx).
  6098. for (GetElementPtrInst *UGEPI : UGEPIs) {
  6099. ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
  6100. APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
  6101. unsigned ImmCost = TTI->getIntImmCost(NewIdx, GEPIIdx->getType());
  6102. if (ImmCost > TargetTransformInfo::TCC_Basic)
  6103. return false;
  6104. }
  6105. // Now unmerge between GEPI and UGEPIs.
  6106. for (GetElementPtrInst *UGEPI : UGEPIs) {
  6107. UGEPI->setOperand(0, GEPI);
  6108. ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
  6109. Constant *NewUGEPIIdx =
  6110. ConstantInt::get(GEPIIdx->getType(),
  6111. UGEPIIdx->getValue() - GEPIIdx->getValue());
  6112. UGEPI->setOperand(1, NewUGEPIIdx);
  6113. // If GEPI is not inbounds but UGEPI is inbounds, change UGEPI to not
  6114. // inbounds to avoid UB.
  6115. if (!GEPI->isInBounds()) {
  6116. UGEPI->setIsInBounds(false);
  6117. }
  6118. }
  6119. // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
  6120. // alive on IndirectBr edges).
  6121. assert(find_if(GEPIOp->users(), [&](User *Usr) {
  6122. return cast<Instruction>(Usr)->getParent() != SrcBlock;
  6123. }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock");
  6124. return true;
  6125. }
  6126. bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) {
  6127. // Bail out if we inserted the instruction to prevent optimizations from
  6128. // stepping on each other's toes.
  6129. if (InsertedInsts.count(I))
  6130. return false;
  6131. // TODO: Move into the switch on opcode below here.
  6132. if (PHINode *P = dyn_cast<PHINode>(I)) {
  6133. // It is possible for very late stage optimizations (such as SimplifyCFG)
  6134. // to introduce PHI nodes too late to be cleaned up. If we detect such a
  6135. // trivial PHI, go ahead and zap it here.
  6136. if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) {
  6137. LargeOffsetGEPMap.erase(P);
  6138. P->replaceAllUsesWith(V);
  6139. P->eraseFromParent();
  6140. ++NumPHIsElim;
  6141. return true;
  6142. }
  6143. return false;
  6144. }
  6145. if (CastInst *CI = dyn_cast<CastInst>(I)) {
  6146. // If the source of the cast is a constant, then this should have
  6147. // already been constant folded. The only reason NOT to constant fold
  6148. // it is if something (e.g. LSR) was careful to place the constant
  6149. // evaluation in a block other than then one that uses it (e.g. to hoist
  6150. // the address of globals out of a loop). If this is the case, we don't
  6151. // want to forward-subst the cast.
  6152. if (isa<Constant>(CI->getOperand(0)))
  6153. return false;
  6154. if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
  6155. return true;
  6156. if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
  6157. /// Sink a zext or sext into its user blocks if the target type doesn't
  6158. /// fit in one register
  6159. if (TLI &&
  6160. TLI->getTypeAction(CI->getContext(),
  6161. TLI->getValueType(*DL, CI->getType())) ==
  6162. TargetLowering::TypeExpandInteger) {
  6163. return SinkCast(CI);
  6164. } else {
  6165. bool MadeChange = optimizeExt(I);
  6166. return MadeChange | optimizeExtUses(I);
  6167. }
  6168. }
  6169. return false;
  6170. }
  6171. if (auto *Cmp = dyn_cast<CmpInst>(I))
  6172. if (TLI && optimizeCmp(Cmp, ModifiedDT))
  6173. return true;
  6174. if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
  6175. LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
  6176. if (TLI) {
  6177. bool Modified = optimizeLoadExt(LI);
  6178. unsigned AS = LI->getPointerAddressSpace();
  6179. Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
  6180. return Modified;
  6181. }
  6182. return false;
  6183. }
  6184. if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
  6185. if (TLI && splitMergedValStore(*SI, *DL, *TLI))
  6186. return true;
  6187. SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
  6188. if (TLI) {
  6189. unsigned AS = SI->getPointerAddressSpace();
  6190. return optimizeMemoryInst(I, SI->getOperand(1),
  6191. SI->getOperand(0)->getType(), AS);
  6192. }
  6193. return false;
  6194. }
  6195. if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
  6196. unsigned AS = RMW->getPointerAddressSpace();
  6197. return optimizeMemoryInst(I, RMW->getPointerOperand(),
  6198. RMW->getType(), AS);
  6199. }
  6200. if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
  6201. unsigned AS = CmpX->getPointerAddressSpace();
  6202. return optimizeMemoryInst(I, CmpX->getPointerOperand(),
  6203. CmpX->getCompareOperand()->getType(), AS);
  6204. }
  6205. BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
  6206. if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
  6207. EnableAndCmpSinking && TLI)
  6208. return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
  6209. // TODO: Move this into the switch on opcode - it handles shifts already.
  6210. if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
  6211. BinOp->getOpcode() == Instruction::LShr)) {
  6212. ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
  6213. if (TLI && CI && TLI->hasExtractBitsInsn())
  6214. if (OptimizeExtractBits(BinOp, CI, *TLI, *DL))
  6215. return true;
  6216. }
  6217. if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
  6218. if (GEPI->hasAllZeroIndices()) {
  6219. /// The GEP operand must be a pointer, so must its result -> BitCast
  6220. Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
  6221. GEPI->getName(), GEPI);
  6222. NC->setDebugLoc(GEPI->getDebugLoc());
  6223. GEPI->replaceAllUsesWith(NC);
  6224. GEPI->eraseFromParent();
  6225. ++NumGEPsElim;
  6226. optimizeInst(NC, ModifiedDT);
  6227. return true;
  6228. }
  6229. if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) {
  6230. return true;
  6231. }
  6232. return false;
  6233. }
  6234. if (tryToSinkFreeOperands(I))
  6235. return true;
  6236. switch (I->getOpcode()) {
  6237. case Instruction::Shl:
  6238. case Instruction::LShr:
  6239. case Instruction::AShr:
  6240. return optimizeShiftInst(cast<BinaryOperator>(I));
  6241. case Instruction::Call:
  6242. return optimizeCallInst(cast<CallInst>(I), ModifiedDT);
  6243. case Instruction::Select:
  6244. return optimizeSelectInst(cast<SelectInst>(I));
  6245. case Instruction::ShuffleVector:
  6246. return optimizeShuffleVectorInst(cast<ShuffleVectorInst>(I));
  6247. case Instruction::Switch:
  6248. return optimizeSwitchInst(cast<SwitchInst>(I));
  6249. case Instruction::ExtractElement:
  6250. return optimizeExtractElementInst(cast<ExtractElementInst>(I));
  6251. }
  6252. return false;
  6253. }
  6254. /// Given an OR instruction, check to see if this is a bitreverse
  6255. /// idiom. If so, insert the new intrinsic and return true.
  6256. static bool makeBitReverse(Instruction &I, const DataLayout &DL,
  6257. const TargetLowering &TLI) {
  6258. if (!I.getType()->isIntegerTy() ||
  6259. !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
  6260. TLI.getValueType(DL, I.getType(), true)))
  6261. return false;
  6262. SmallVector<Instruction*, 4> Insts;
  6263. if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
  6264. return false;
  6265. Instruction *LastInst = Insts.back();
  6266. I.replaceAllUsesWith(LastInst);
  6267. RecursivelyDeleteTriviallyDeadInstructions(&I);
  6268. return true;
  6269. }
  6270. // In this pass we look for GEP and cast instructions that are used
  6271. // across basic blocks and rewrite them to improve basic-block-at-a-time
  6272. // selection.
  6273. bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) {
  6274. SunkAddrs.clear();
  6275. bool MadeChange = false;
  6276. CurInstIterator = BB.begin();
  6277. while (CurInstIterator != BB.end()) {
  6278. MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
  6279. if (ModifiedDT)
  6280. return true;
  6281. }
  6282. bool MadeBitReverse = true;
  6283. while (TLI && MadeBitReverse) {
  6284. MadeBitReverse = false;
  6285. for (auto &I : reverse(BB)) {
  6286. if (makeBitReverse(I, *DL, *TLI)) {
  6287. MadeBitReverse = MadeChange = true;
  6288. break;
  6289. }
  6290. }
  6291. }
  6292. MadeChange |= dupRetToEnableTailCallOpts(&BB, ModifiedDT);
  6293. return MadeChange;
  6294. }
  6295. // llvm.dbg.value is far away from the value then iSel may not be able
  6296. // handle it properly. iSel will drop llvm.dbg.value if it can not
  6297. // find a node corresponding to the value.
  6298. bool CodeGenPrepare::placeDbgValues(Function &F) {
  6299. bool MadeChange = false;
  6300. for (BasicBlock &BB : F) {
  6301. Instruction *PrevNonDbgInst = nullptr;
  6302. for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
  6303. Instruction *Insn = &*BI++;
  6304. DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
  6305. // Leave dbg.values that refer to an alloca alone. These
  6306. // intrinsics describe the address of a variable (= the alloca)
  6307. // being taken. They should not be moved next to the alloca
  6308. // (and to the beginning of the scope), but rather stay close to
  6309. // where said address is used.
  6310. if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
  6311. PrevNonDbgInst = Insn;
  6312. continue;
  6313. }
  6314. Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
  6315. if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
  6316. // If VI is a phi in a block with an EHPad terminator, we can't insert
  6317. // after it.
  6318. if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
  6319. continue;
  6320. LLVM_DEBUG(dbgs() << "Moving Debug Value before :\n"
  6321. << *DVI << ' ' << *VI);
  6322. DVI->removeFromParent();
  6323. if (isa<PHINode>(VI))
  6324. DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
  6325. else
  6326. DVI->insertAfter(VI);
  6327. MadeChange = true;
  6328. ++NumDbgValueMoved;
  6329. }
  6330. }
  6331. }
  6332. return MadeChange;
  6333. }
  6334. /// Scale down both weights to fit into uint32_t.
  6335. static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
  6336. uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
  6337. uint32_t Scale = (NewMax / std::numeric_limits<uint32_t>::max()) + 1;
  6338. NewTrue = NewTrue / Scale;
  6339. NewFalse = NewFalse / Scale;
  6340. }
  6341. /// Some targets prefer to split a conditional branch like:
  6342. /// \code
  6343. /// %0 = icmp ne i32 %a, 0
  6344. /// %1 = icmp ne i32 %b, 0
  6345. /// %or.cond = or i1 %0, %1
  6346. /// br i1 %or.cond, label %TrueBB, label %FalseBB
  6347. /// \endcode
  6348. /// into multiple branch instructions like:
  6349. /// \code
  6350. /// bb1:
  6351. /// %0 = icmp ne i32 %a, 0
  6352. /// br i1 %0, label %TrueBB, label %bb2
  6353. /// bb2:
  6354. /// %1 = icmp ne i32 %b, 0
  6355. /// br i1 %1, label %TrueBB, label %FalseBB
  6356. /// \endcode
  6357. /// This usually allows instruction selection to do even further optimizations
  6358. /// and combine the compare with the branch instruction. Currently this is
  6359. /// applied for targets which have "cheap" jump instructions.
  6360. ///
  6361. /// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
  6362. ///
  6363. bool CodeGenPrepare::splitBranchCondition(Function &F, bool &ModifiedDT) {
  6364. if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
  6365. return false;
  6366. bool MadeChange = false;
  6367. for (auto &BB : F) {
  6368. // Does this BB end with the following?
  6369. // %cond1 = icmp|fcmp|binary instruction ...
  6370. // %cond2 = icmp|fcmp|binary instruction ...
  6371. // %cond.or = or|and i1 %cond1, cond2
  6372. // br i1 %cond.or label %dest1, label %dest2"
  6373. BinaryOperator *LogicOp;
  6374. BasicBlock *TBB, *FBB;
  6375. if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
  6376. continue;
  6377. auto *Br1 = cast<BranchInst>(BB.getTerminator());
  6378. if (Br1->getMetadata(LLVMContext::MD_unpredictable))
  6379. continue;
  6380. unsigned Opc;
  6381. Value *Cond1, *Cond2;
  6382. if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
  6383. m_OneUse(m_Value(Cond2)))))
  6384. Opc = Instruction::And;
  6385. else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
  6386. m_OneUse(m_Value(Cond2)))))
  6387. Opc = Instruction::Or;
  6388. else
  6389. continue;
  6390. if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
  6391. !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
  6392. continue;
  6393. LLVM_DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
  6394. // Create a new BB.
  6395. auto TmpBB =
  6396. BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
  6397. BB.getParent(), BB.getNextNode());
  6398. // Update original basic block by using the first condition directly by the
  6399. // branch instruction and removing the no longer needed and/or instruction.
  6400. Br1->setCondition(Cond1);
  6401. LogicOp->eraseFromParent();
  6402. // Depending on the condition we have to either replace the true or the
  6403. // false successor of the original branch instruction.
  6404. if (Opc == Instruction::And)
  6405. Br1->setSuccessor(0, TmpBB);
  6406. else
  6407. Br1->setSuccessor(1, TmpBB);
  6408. // Fill in the new basic block.
  6409. auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
  6410. if (auto *I = dyn_cast<Instruction>(Cond2)) {
  6411. I->removeFromParent();
  6412. I->insertBefore(Br2);
  6413. }
  6414. // Update PHI nodes in both successors. The original BB needs to be
  6415. // replaced in one successor's PHI nodes, because the branch comes now from
  6416. // the newly generated BB (NewBB). In the other successor we need to add one
  6417. // incoming edge to the PHI nodes, because both branch instructions target
  6418. // now the same successor. Depending on the original branch condition
  6419. // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
  6420. // we perform the correct update for the PHI nodes.
  6421. // This doesn't change the successor order of the just created branch
  6422. // instruction (or any other instruction).
  6423. if (Opc == Instruction::Or)
  6424. std::swap(TBB, FBB);
  6425. // Replace the old BB with the new BB.
  6426. TBB->replacePhiUsesWith(&BB, TmpBB);
  6427. // Add another incoming edge form the new BB.
  6428. for (PHINode &PN : FBB->phis()) {
  6429. auto *Val = PN.getIncomingValueForBlock(&BB);
  6430. PN.addIncoming(Val, TmpBB);
  6431. }
  6432. // Update the branch weights (from SelectionDAGBuilder::
  6433. // FindMergedConditions).
  6434. if (Opc == Instruction::Or) {
  6435. // Codegen X | Y as:
  6436. // BB1:
  6437. // jmp_if_X TBB
  6438. // jmp TmpBB
  6439. // TmpBB:
  6440. // jmp_if_Y TBB
  6441. // jmp FBB
  6442. //
  6443. // We have flexibility in setting Prob for BB1 and Prob for NewBB.
  6444. // The requirement is that
  6445. // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
  6446. // = TrueProb for original BB.
  6447. // Assuming the original weights are A and B, one choice is to set BB1's
  6448. // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
  6449. // assumes that
  6450. // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
  6451. // Another choice is to assume TrueProb for BB1 equals to TrueProb for
  6452. // TmpBB, but the math is more complicated.
  6453. uint64_t TrueWeight, FalseWeight;
  6454. if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
  6455. uint64_t NewTrueWeight = TrueWeight;
  6456. uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
  6457. scaleWeights(NewTrueWeight, NewFalseWeight);
  6458. Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
  6459. .createBranchWeights(TrueWeight, FalseWeight));
  6460. NewTrueWeight = TrueWeight;
  6461. NewFalseWeight = 2 * FalseWeight;
  6462. scaleWeights(NewTrueWeight, NewFalseWeight);
  6463. Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
  6464. .createBranchWeights(TrueWeight, FalseWeight));
  6465. }
  6466. } else {
  6467. // Codegen X & Y as:
  6468. // BB1:
  6469. // jmp_if_X TmpBB
  6470. // jmp FBB
  6471. // TmpBB:
  6472. // jmp_if_Y TBB
  6473. // jmp FBB
  6474. //
  6475. // This requires creation of TmpBB after CurBB.
  6476. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  6477. // The requirement is that
  6478. // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
  6479. // = FalseProb for original BB.
  6480. // Assuming the original weights are A and B, one choice is to set BB1's
  6481. // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
  6482. // assumes that
  6483. // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
  6484. uint64_t TrueWeight, FalseWeight;
  6485. if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
  6486. uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
  6487. uint64_t NewFalseWeight = FalseWeight;
  6488. scaleWeights(NewTrueWeight, NewFalseWeight);
  6489. Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
  6490. .createBranchWeights(TrueWeight, FalseWeight));
  6491. NewTrueWeight = 2 * TrueWeight;
  6492. NewFalseWeight = FalseWeight;
  6493. scaleWeights(NewTrueWeight, NewFalseWeight);
  6494. Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
  6495. .createBranchWeights(TrueWeight, FalseWeight));
  6496. }
  6497. }
  6498. ModifiedDT = true;
  6499. MadeChange = true;
  6500. LLVM_DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
  6501. TmpBB->dump());
  6502. }
  6503. return MadeChange;
  6504. }