CodeGenPrepare.cpp 274 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361
  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. TruncInst *TruncI = dyn_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(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(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. PHINode *PHI = cast<PHINode>(V);
  2947. auto *CurrentPhi = dyn_cast<PHINode>(Current);
  2948. // Fill the Phi node with values from predecessors.
  2949. for (auto B : predecessors(PHI->getParent())) {
  2950. Value *PV = CurrentPhi->getIncomingValueForBlock(B);
  2951. assert(Map.find(PV) != Map.end() && "No predecessor Value!");
  2952. PHI->addIncoming(ST.Get(Map[PV]), B);
  2953. }
  2954. }
  2955. Map[Current] = ST.Simplify(V);
  2956. }
  2957. }
  2958. /// Starting from original value recursively iterates over def-use chain up to
  2959. /// known ending values represented in a map. For each traversed phi/select
  2960. /// inserts a placeholder Phi or Select.
  2961. /// Reports all new created Phi/Select nodes by adding them to set.
  2962. /// Also reports and order in what values have been traversed.
  2963. void InsertPlaceholders(FoldAddrToValueMapping &Map,
  2964. SmallVectorImpl<Value *> &TraverseOrder,
  2965. SimplificationTracker &ST) {
  2966. SmallVector<Value *, 32> Worklist;
  2967. assert((isa<PHINode>(Original) || isa<SelectInst>(Original)) &&
  2968. "Address must be a Phi or Select node");
  2969. auto *Dummy = UndefValue::get(CommonType);
  2970. Worklist.push_back(Original);
  2971. while (!Worklist.empty()) {
  2972. Value *Current = Worklist.pop_back_val();
  2973. // if it is already visited or it is an ending value then skip it.
  2974. if (Map.find(Current) != Map.end())
  2975. continue;
  2976. TraverseOrder.push_back(Current);
  2977. // CurrentValue must be a Phi node or select. All others must be covered
  2978. // by anchors.
  2979. if (SelectInst *CurrentSelect = dyn_cast<SelectInst>(Current)) {
  2980. // Is it OK to get metadata from OrigSelect?!
  2981. // Create a Select placeholder with dummy value.
  2982. SelectInst *Select = SelectInst::Create(
  2983. CurrentSelect->getCondition(), Dummy, Dummy,
  2984. CurrentSelect->getName(), CurrentSelect, CurrentSelect);
  2985. Map[Current] = Select;
  2986. ST.insertNewSelect(Select);
  2987. // We are interested in True and False values.
  2988. Worklist.push_back(CurrentSelect->getTrueValue());
  2989. Worklist.push_back(CurrentSelect->getFalseValue());
  2990. } else {
  2991. // It must be a Phi node then.
  2992. PHINode *CurrentPhi = cast<PHINode>(Current);
  2993. unsigned PredCount = CurrentPhi->getNumIncomingValues();
  2994. PHINode *PHI =
  2995. PHINode::Create(CommonType, PredCount, "sunk_phi", CurrentPhi);
  2996. Map[Current] = PHI;
  2997. ST.insertNewPhi(PHI);
  2998. for (Value *P : CurrentPhi->incoming_values())
  2999. Worklist.push_back(P);
  3000. }
  3001. }
  3002. }
  3003. bool addrModeCombiningAllowed() {
  3004. if (DisableComplexAddrModes)
  3005. return false;
  3006. switch (DifferentField) {
  3007. default:
  3008. return false;
  3009. case ExtAddrMode::BaseRegField:
  3010. return AddrSinkCombineBaseReg;
  3011. case ExtAddrMode::BaseGVField:
  3012. return AddrSinkCombineBaseGV;
  3013. case ExtAddrMode::BaseOffsField:
  3014. return AddrSinkCombineBaseOffs;
  3015. case ExtAddrMode::ScaledRegField:
  3016. return AddrSinkCombineScaledReg;
  3017. }
  3018. }
  3019. };
  3020. } // end anonymous namespace
  3021. /// Try adding ScaleReg*Scale to the current addressing mode.
  3022. /// Return true and update AddrMode if this addr mode is legal for the target,
  3023. /// false if not.
  3024. bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
  3025. unsigned Depth) {
  3026. // If Scale is 1, then this is the same as adding ScaleReg to the addressing
  3027. // mode. Just process that directly.
  3028. if (Scale == 1)
  3029. return matchAddr(ScaleReg, Depth);
  3030. // If the scale is 0, it takes nothing to add this.
  3031. if (Scale == 0)
  3032. return true;
  3033. // If we already have a scale of this value, we can add to it, otherwise, we
  3034. // need an available scale field.
  3035. if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
  3036. return false;
  3037. ExtAddrMode TestAddrMode = AddrMode;
  3038. // Add scale to turn X*4+X*3 -> X*7. This could also do things like
  3039. // [A+B + A*7] -> [B+A*8].
  3040. TestAddrMode.Scale += Scale;
  3041. TestAddrMode.ScaledReg = ScaleReg;
  3042. // If the new address isn't legal, bail out.
  3043. if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
  3044. return false;
  3045. // It was legal, so commit it.
  3046. AddrMode = TestAddrMode;
  3047. // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
  3048. // to see if ScaleReg is actually X+C. If so, we can turn this into adding
  3049. // X*Scale + C*Scale to addr mode.
  3050. ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
  3051. if (isa<Instruction>(ScaleReg) && // not a constant expr.
  3052. match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
  3053. TestAddrMode.InBounds = false;
  3054. TestAddrMode.ScaledReg = AddLHS;
  3055. TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
  3056. // If this addressing mode is legal, commit it and remember that we folded
  3057. // this instruction.
  3058. if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
  3059. AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
  3060. AddrMode = TestAddrMode;
  3061. return true;
  3062. }
  3063. }
  3064. // Otherwise, not (x+c)*scale, just return what we have.
  3065. return true;
  3066. }
  3067. /// This is a little filter, which returns true if an addressing computation
  3068. /// involving I might be folded into a load/store accessing it.
  3069. /// This doesn't need to be perfect, but needs to accept at least
  3070. /// the set of instructions that MatchOperationAddr can.
  3071. static bool MightBeFoldableInst(Instruction *I) {
  3072. switch (I->getOpcode()) {
  3073. case Instruction::BitCast:
  3074. case Instruction::AddrSpaceCast:
  3075. // Don't touch identity bitcasts.
  3076. if (I->getType() == I->getOperand(0)->getType())
  3077. return false;
  3078. return I->getType()->isIntOrPtrTy();
  3079. case Instruction::PtrToInt:
  3080. // PtrToInt is always a noop, as we know that the int type is pointer sized.
  3081. return true;
  3082. case Instruction::IntToPtr:
  3083. // We know the input is intptr_t, so this is foldable.
  3084. return true;
  3085. case Instruction::Add:
  3086. return true;
  3087. case Instruction::Mul:
  3088. case Instruction::Shl:
  3089. // Can only handle X*C and X << C.
  3090. return isa<ConstantInt>(I->getOperand(1));
  3091. case Instruction::GetElementPtr:
  3092. return true;
  3093. default:
  3094. return false;
  3095. }
  3096. }
  3097. /// Check whether or not \p Val is a legal instruction for \p TLI.
  3098. /// \note \p Val is assumed to be the product of some type promotion.
  3099. /// Therefore if \p Val has an undefined state in \p TLI, this is assumed
  3100. /// to be legal, as the non-promoted value would have had the same state.
  3101. static bool isPromotedInstructionLegal(const TargetLowering &TLI,
  3102. const DataLayout &DL, Value *Val) {
  3103. Instruction *PromotedInst = dyn_cast<Instruction>(Val);
  3104. if (!PromotedInst)
  3105. return false;
  3106. int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
  3107. // If the ISDOpcode is undefined, it was undefined before the promotion.
  3108. if (!ISDOpcode)
  3109. return true;
  3110. // Otherwise, check if the promoted instruction is legal or not.
  3111. return TLI.isOperationLegalOrCustom(
  3112. ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
  3113. }
  3114. namespace {
  3115. /// Hepler class to perform type promotion.
  3116. class TypePromotionHelper {
  3117. /// Utility function to add a promoted instruction \p ExtOpnd to
  3118. /// \p PromotedInsts and record the type of extension we have seen.
  3119. static void addPromotedInst(InstrToOrigTy &PromotedInsts,
  3120. Instruction *ExtOpnd,
  3121. bool IsSExt) {
  3122. ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
  3123. InstrToOrigTy::iterator It = PromotedInsts.find(ExtOpnd);
  3124. if (It != PromotedInsts.end()) {
  3125. // If the new extension is same as original, the information in
  3126. // PromotedInsts[ExtOpnd] is still correct.
  3127. if (It->second.getInt() == ExtTy)
  3128. return;
  3129. // Now the new extension is different from old extension, we make
  3130. // the type information invalid by setting extension type to
  3131. // BothExtension.
  3132. ExtTy = BothExtension;
  3133. }
  3134. PromotedInsts[ExtOpnd] = TypeIsSExt(ExtOpnd->getType(), ExtTy);
  3135. }
  3136. /// Utility function to query the original type of instruction \p Opnd
  3137. /// with a matched extension type. If the extension doesn't match, we
  3138. /// cannot use the information we had on the original type.
  3139. /// BothExtension doesn't match any extension type.
  3140. static const Type *getOrigType(const InstrToOrigTy &PromotedInsts,
  3141. Instruction *Opnd,
  3142. bool IsSExt) {
  3143. ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
  3144. InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
  3145. if (It != PromotedInsts.end() && It->second.getInt() == ExtTy)
  3146. return It->second.getPointer();
  3147. return nullptr;
  3148. }
  3149. /// Utility function to check whether or not a sign or zero extension
  3150. /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
  3151. /// either using the operands of \p Inst or promoting \p Inst.
  3152. /// The type of the extension is defined by \p IsSExt.
  3153. /// In other words, check if:
  3154. /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
  3155. /// #1 Promotion applies:
  3156. /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
  3157. /// #2 Operand reuses:
  3158. /// ext opnd1 to ConsideredExtType.
  3159. /// \p PromotedInsts maps the instructions to their type before promotion.
  3160. static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
  3161. const InstrToOrigTy &PromotedInsts, bool IsSExt);
  3162. /// Utility function to determine if \p OpIdx should be promoted when
  3163. /// promoting \p Inst.
  3164. static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
  3165. return !(isa<SelectInst>(Inst) && OpIdx == 0);
  3166. }
  3167. /// Utility function to promote the operand of \p Ext when this
  3168. /// operand is a promotable trunc or sext or zext.
  3169. /// \p PromotedInsts maps the instructions to their type before promotion.
  3170. /// \p CreatedInstsCost[out] contains the cost of all instructions
  3171. /// created to promote the operand of Ext.
  3172. /// Newly added extensions are inserted in \p Exts.
  3173. /// Newly added truncates are inserted in \p Truncs.
  3174. /// Should never be called directly.
  3175. /// \return The promoted value which is used instead of Ext.
  3176. static Value *promoteOperandForTruncAndAnyExt(
  3177. Instruction *Ext, TypePromotionTransaction &TPT,
  3178. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  3179. SmallVectorImpl<Instruction *> *Exts,
  3180. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
  3181. /// Utility function to promote the operand of \p Ext when this
  3182. /// operand is promotable and is not a supported trunc or sext.
  3183. /// \p PromotedInsts maps the instructions to their type before promotion.
  3184. /// \p CreatedInstsCost[out] contains the cost of all the instructions
  3185. /// created to promote the operand of Ext.
  3186. /// Newly added extensions are inserted in \p Exts.
  3187. /// Newly added truncates are inserted in \p Truncs.
  3188. /// Should never be called directly.
  3189. /// \return The promoted value which is used instead of Ext.
  3190. static Value *promoteOperandForOther(Instruction *Ext,
  3191. TypePromotionTransaction &TPT,
  3192. InstrToOrigTy &PromotedInsts,
  3193. unsigned &CreatedInstsCost,
  3194. SmallVectorImpl<Instruction *> *Exts,
  3195. SmallVectorImpl<Instruction *> *Truncs,
  3196. const TargetLowering &TLI, bool IsSExt);
  3197. /// \see promoteOperandForOther.
  3198. static Value *signExtendOperandForOther(
  3199. Instruction *Ext, TypePromotionTransaction &TPT,
  3200. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  3201. SmallVectorImpl<Instruction *> *Exts,
  3202. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
  3203. return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
  3204. Exts, Truncs, TLI, true);
  3205. }
  3206. /// \see promoteOperandForOther.
  3207. static Value *zeroExtendOperandForOther(
  3208. Instruction *Ext, TypePromotionTransaction &TPT,
  3209. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  3210. SmallVectorImpl<Instruction *> *Exts,
  3211. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
  3212. return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
  3213. Exts, Truncs, TLI, false);
  3214. }
  3215. public:
  3216. /// Type for the utility function that promotes the operand of Ext.
  3217. using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
  3218. InstrToOrigTy &PromotedInsts,
  3219. unsigned &CreatedInstsCost,
  3220. SmallVectorImpl<Instruction *> *Exts,
  3221. SmallVectorImpl<Instruction *> *Truncs,
  3222. const TargetLowering &TLI);
  3223. /// Given a sign/zero extend instruction \p Ext, return the appropriate
  3224. /// action to promote the operand of \p Ext instead of using Ext.
  3225. /// \return NULL if no promotable action is possible with the current
  3226. /// sign extension.
  3227. /// \p InsertedInsts keeps track of all the instructions inserted by the
  3228. /// other CodeGenPrepare optimizations. This information is important
  3229. /// because we do not want to promote these instructions as CodeGenPrepare
  3230. /// will reinsert them later. Thus creating an infinite loop: create/remove.
  3231. /// \p PromotedInsts maps the instructions to their type before promotion.
  3232. static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
  3233. const TargetLowering &TLI,
  3234. const InstrToOrigTy &PromotedInsts);
  3235. };
  3236. } // end anonymous namespace
  3237. bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
  3238. Type *ConsideredExtType,
  3239. const InstrToOrigTy &PromotedInsts,
  3240. bool IsSExt) {
  3241. // The promotion helper does not know how to deal with vector types yet.
  3242. // To be able to fix that, we would need to fix the places where we
  3243. // statically extend, e.g., constants and such.
  3244. if (Inst->getType()->isVectorTy())
  3245. return false;
  3246. // We can always get through zext.
  3247. if (isa<ZExtInst>(Inst))
  3248. return true;
  3249. // sext(sext) is ok too.
  3250. if (IsSExt && isa<SExtInst>(Inst))
  3251. return true;
  3252. // We can get through binary operator, if it is legal. In other words, the
  3253. // binary operator must have a nuw or nsw flag.
  3254. const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
  3255. if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
  3256. ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
  3257. (IsSExt && BinOp->hasNoSignedWrap())))
  3258. return true;
  3259. // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst))
  3260. if ((Inst->getOpcode() == Instruction::And ||
  3261. Inst->getOpcode() == Instruction::Or))
  3262. return true;
  3263. // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst))
  3264. if (Inst->getOpcode() == Instruction::Xor) {
  3265. const ConstantInt *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1));
  3266. // Make sure it is not a NOT.
  3267. if (Cst && !Cst->getValue().isAllOnesValue())
  3268. return true;
  3269. }
  3270. // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst))
  3271. // It may change a poisoned value into a regular value, like
  3272. // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12
  3273. // poisoned value regular value
  3274. // It should be OK since undef covers valid value.
  3275. if (Inst->getOpcode() == Instruction::LShr && !IsSExt)
  3276. return true;
  3277. // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst)
  3278. // It may change a poisoned value into a regular value, like
  3279. // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12
  3280. // poisoned value regular value
  3281. // It should be OK since undef covers valid value.
  3282. if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) {
  3283. const Instruction *ExtInst =
  3284. dyn_cast<const Instruction>(*Inst->user_begin());
  3285. if (ExtInst->hasOneUse()) {
  3286. const Instruction *AndInst =
  3287. dyn_cast<const Instruction>(*ExtInst->user_begin());
  3288. if (AndInst && AndInst->getOpcode() == Instruction::And) {
  3289. const ConstantInt *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1));
  3290. if (Cst &&
  3291. Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth()))
  3292. return true;
  3293. }
  3294. }
  3295. }
  3296. // Check if we can do the following simplification.
  3297. // ext(trunc(opnd)) --> ext(opnd)
  3298. if (!isa<TruncInst>(Inst))
  3299. return false;
  3300. Value *OpndVal = Inst->getOperand(0);
  3301. // Check if we can use this operand in the extension.
  3302. // If the type is larger than the result type of the extension, we cannot.
  3303. if (!OpndVal->getType()->isIntegerTy() ||
  3304. OpndVal->getType()->getIntegerBitWidth() >
  3305. ConsideredExtType->getIntegerBitWidth())
  3306. return false;
  3307. // If the operand of the truncate is not an instruction, we will not have
  3308. // any information on the dropped bits.
  3309. // (Actually we could for constant but it is not worth the extra logic).
  3310. Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
  3311. if (!Opnd)
  3312. return false;
  3313. // Check if the source of the type is narrow enough.
  3314. // I.e., check that trunc just drops extended bits of the same kind of
  3315. // the extension.
  3316. // #1 get the type of the operand and check the kind of the extended bits.
  3317. const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt);
  3318. if (OpndType)
  3319. ;
  3320. else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
  3321. OpndType = Opnd->getOperand(0)->getType();
  3322. else
  3323. return false;
  3324. // #2 check that the truncate just drops extended bits.
  3325. return Inst->getType()->getIntegerBitWidth() >=
  3326. OpndType->getIntegerBitWidth();
  3327. }
  3328. TypePromotionHelper::Action TypePromotionHelper::getAction(
  3329. Instruction *Ext, const SetOfInstrs &InsertedInsts,
  3330. const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
  3331. assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
  3332. "Unexpected instruction type");
  3333. Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
  3334. Type *ExtTy = Ext->getType();
  3335. bool IsSExt = isa<SExtInst>(Ext);
  3336. // If the operand of the extension is not an instruction, we cannot
  3337. // get through.
  3338. // If it, check we can get through.
  3339. if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
  3340. return nullptr;
  3341. // Do not promote if the operand has been added by codegenprepare.
  3342. // Otherwise, it means we are undoing an optimization that is likely to be
  3343. // redone, thus causing potential infinite loop.
  3344. if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
  3345. return nullptr;
  3346. // SExt or Trunc instructions.
  3347. // Return the related handler.
  3348. if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
  3349. isa<ZExtInst>(ExtOpnd))
  3350. return promoteOperandForTruncAndAnyExt;
  3351. // Regular instruction.
  3352. // Abort early if we will have to insert non-free instructions.
  3353. if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
  3354. return nullptr;
  3355. return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
  3356. }
  3357. Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
  3358. Instruction *SExt, TypePromotionTransaction &TPT,
  3359. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  3360. SmallVectorImpl<Instruction *> *Exts,
  3361. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
  3362. // By construction, the operand of SExt is an instruction. Otherwise we cannot
  3363. // get through it and this method should not be called.
  3364. Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
  3365. Value *ExtVal = SExt;
  3366. bool HasMergedNonFreeExt = false;
  3367. if (isa<ZExtInst>(SExtOpnd)) {
  3368. // Replace s|zext(zext(opnd))
  3369. // => zext(opnd).
  3370. HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
  3371. Value *ZExt =
  3372. TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
  3373. TPT.replaceAllUsesWith(SExt, ZExt);
  3374. TPT.eraseInstruction(SExt);
  3375. ExtVal = ZExt;
  3376. } else {
  3377. // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
  3378. // => z|sext(opnd).
  3379. TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
  3380. }
  3381. CreatedInstsCost = 0;
  3382. // Remove dead code.
  3383. if (SExtOpnd->use_empty())
  3384. TPT.eraseInstruction(SExtOpnd);
  3385. // Check if the extension is still needed.
  3386. Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
  3387. if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
  3388. if (ExtInst) {
  3389. if (Exts)
  3390. Exts->push_back(ExtInst);
  3391. CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
  3392. }
  3393. return ExtVal;
  3394. }
  3395. // At this point we have: ext ty opnd to ty.
  3396. // Reassign the uses of ExtInst to the opnd and remove ExtInst.
  3397. Value *NextVal = ExtInst->getOperand(0);
  3398. TPT.eraseInstruction(ExtInst, NextVal);
  3399. return NextVal;
  3400. }
  3401. Value *TypePromotionHelper::promoteOperandForOther(
  3402. Instruction *Ext, TypePromotionTransaction &TPT,
  3403. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  3404. SmallVectorImpl<Instruction *> *Exts,
  3405. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
  3406. bool IsSExt) {
  3407. // By construction, the operand of Ext is an instruction. Otherwise we cannot
  3408. // get through it and this method should not be called.
  3409. Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
  3410. CreatedInstsCost = 0;
  3411. if (!ExtOpnd->hasOneUse()) {
  3412. // ExtOpnd will be promoted.
  3413. // All its uses, but Ext, will need to use a truncated value of the
  3414. // promoted version.
  3415. // Create the truncate now.
  3416. Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
  3417. if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
  3418. // Insert it just after the definition.
  3419. ITrunc->moveAfter(ExtOpnd);
  3420. if (Truncs)
  3421. Truncs->push_back(ITrunc);
  3422. }
  3423. TPT.replaceAllUsesWith(ExtOpnd, Trunc);
  3424. // Restore the operand of Ext (which has been replaced by the previous call
  3425. // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
  3426. TPT.setOperand(Ext, 0, ExtOpnd);
  3427. }
  3428. // Get through the Instruction:
  3429. // 1. Update its type.
  3430. // 2. Replace the uses of Ext by Inst.
  3431. // 3. Extend each operand that needs to be extended.
  3432. // Remember the original type of the instruction before promotion.
  3433. // This is useful to know that the high bits are sign extended bits.
  3434. addPromotedInst(PromotedInsts, ExtOpnd, IsSExt);
  3435. // Step #1.
  3436. TPT.mutateType(ExtOpnd, Ext->getType());
  3437. // Step #2.
  3438. TPT.replaceAllUsesWith(Ext, ExtOpnd);
  3439. // Step #3.
  3440. Instruction *ExtForOpnd = Ext;
  3441. LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n");
  3442. for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
  3443. ++OpIdx) {
  3444. LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
  3445. if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
  3446. !shouldExtOperand(ExtOpnd, OpIdx)) {
  3447. LLVM_DEBUG(dbgs() << "No need to propagate\n");
  3448. continue;
  3449. }
  3450. // Check if we can statically extend the operand.
  3451. Value *Opnd = ExtOpnd->getOperand(OpIdx);
  3452. if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
  3453. LLVM_DEBUG(dbgs() << "Statically extend\n");
  3454. unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
  3455. APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
  3456. : Cst->getValue().zext(BitWidth);
  3457. TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
  3458. continue;
  3459. }
  3460. // UndefValue are typed, so we have to statically sign extend them.
  3461. if (isa<UndefValue>(Opnd)) {
  3462. LLVM_DEBUG(dbgs() << "Statically extend\n");
  3463. TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
  3464. continue;
  3465. }
  3466. // Otherwise we have to explicitly sign extend the operand.
  3467. // Check if Ext was reused to extend an operand.
  3468. if (!ExtForOpnd) {
  3469. // If yes, create a new one.
  3470. LLVM_DEBUG(dbgs() << "More operands to ext\n");
  3471. Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
  3472. : TPT.createZExt(Ext, Opnd, Ext->getType());
  3473. if (!isa<Instruction>(ValForExtOpnd)) {
  3474. TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
  3475. continue;
  3476. }
  3477. ExtForOpnd = cast<Instruction>(ValForExtOpnd);
  3478. }
  3479. if (Exts)
  3480. Exts->push_back(ExtForOpnd);
  3481. TPT.setOperand(ExtForOpnd, 0, Opnd);
  3482. // Move the sign extension before the insertion point.
  3483. TPT.moveBefore(ExtForOpnd, ExtOpnd);
  3484. TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
  3485. CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
  3486. // If more sext are required, new instructions will have to be created.
  3487. ExtForOpnd = nullptr;
  3488. }
  3489. if (ExtForOpnd == Ext) {
  3490. LLVM_DEBUG(dbgs() << "Extension is useless now\n");
  3491. TPT.eraseInstruction(Ext);
  3492. }
  3493. return ExtOpnd;
  3494. }
  3495. /// Check whether or not promoting an instruction to a wider type is profitable.
  3496. /// \p NewCost gives the cost of extension instructions created by the
  3497. /// promotion.
  3498. /// \p OldCost gives the cost of extension instructions before the promotion
  3499. /// plus the number of instructions that have been
  3500. /// matched in the addressing mode the promotion.
  3501. /// \p PromotedOperand is the value that has been promoted.
  3502. /// \return True if the promotion is profitable, false otherwise.
  3503. bool AddressingModeMatcher::isPromotionProfitable(
  3504. unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
  3505. LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost
  3506. << '\n');
  3507. // The cost of the new extensions is greater than the cost of the
  3508. // old extension plus what we folded.
  3509. // This is not profitable.
  3510. if (NewCost > OldCost)
  3511. return false;
  3512. if (NewCost < OldCost)
  3513. return true;
  3514. // The promotion is neutral but it may help folding the sign extension in
  3515. // loads for instance.
  3516. // Check that we did not create an illegal instruction.
  3517. return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
  3518. }
  3519. /// Given an instruction or constant expr, see if we can fold the operation
  3520. /// into the addressing mode. If so, update the addressing mode and return
  3521. /// true, otherwise return false without modifying AddrMode.
  3522. /// If \p MovedAway is not NULL, it contains the information of whether or
  3523. /// not AddrInst has to be folded into the addressing mode on success.
  3524. /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
  3525. /// because it has been moved away.
  3526. /// Thus AddrInst must not be added in the matched instructions.
  3527. /// This state can happen when AddrInst is a sext, since it may be moved away.
  3528. /// Therefore, AddrInst may not be valid when MovedAway is true and it must
  3529. /// not be referenced anymore.
  3530. bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
  3531. unsigned Depth,
  3532. bool *MovedAway) {
  3533. // Avoid exponential behavior on extremely deep expression trees.
  3534. if (Depth >= 5) return false;
  3535. // By default, all matched instructions stay in place.
  3536. if (MovedAway)
  3537. *MovedAway = false;
  3538. switch (Opcode) {
  3539. case Instruction::PtrToInt:
  3540. // PtrToInt is always a noop, as we know that the int type is pointer sized.
  3541. return matchAddr(AddrInst->getOperand(0), Depth);
  3542. case Instruction::IntToPtr: {
  3543. auto AS = AddrInst->getType()->getPointerAddressSpace();
  3544. auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
  3545. // This inttoptr is a no-op if the integer type is pointer sized.
  3546. if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
  3547. return matchAddr(AddrInst->getOperand(0), Depth);
  3548. return false;
  3549. }
  3550. case Instruction::BitCast:
  3551. // BitCast is always a noop, and we can handle it as long as it is
  3552. // int->int or pointer->pointer (we don't want int<->fp or something).
  3553. if (AddrInst->getOperand(0)->getType()->isIntOrPtrTy() &&
  3554. // Don't touch identity bitcasts. These were probably put here by LSR,
  3555. // and we don't want to mess around with them. Assume it knows what it
  3556. // is doing.
  3557. AddrInst->getOperand(0)->getType() != AddrInst->getType())
  3558. return matchAddr(AddrInst->getOperand(0), Depth);
  3559. return false;
  3560. case Instruction::AddrSpaceCast: {
  3561. unsigned SrcAS
  3562. = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
  3563. unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
  3564. if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
  3565. return matchAddr(AddrInst->getOperand(0), Depth);
  3566. return false;
  3567. }
  3568. case Instruction::Add: {
  3569. // Check to see if we can merge in the RHS then the LHS. If so, we win.
  3570. ExtAddrMode BackupAddrMode = AddrMode;
  3571. unsigned OldSize = AddrModeInsts.size();
  3572. // Start a transaction at this point.
  3573. // The LHS may match but not the RHS.
  3574. // Therefore, we need a higher level restoration point to undo partially
  3575. // matched operation.
  3576. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  3577. TPT.getRestorationPoint();
  3578. AddrMode.InBounds = false;
  3579. if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
  3580. matchAddr(AddrInst->getOperand(0), Depth+1))
  3581. return true;
  3582. // Restore the old addr mode info.
  3583. AddrMode = BackupAddrMode;
  3584. AddrModeInsts.resize(OldSize);
  3585. TPT.rollback(LastKnownGood);
  3586. // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
  3587. if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
  3588. matchAddr(AddrInst->getOperand(1), Depth+1))
  3589. return true;
  3590. // Otherwise we definitely can't merge the ADD in.
  3591. AddrMode = BackupAddrMode;
  3592. AddrModeInsts.resize(OldSize);
  3593. TPT.rollback(LastKnownGood);
  3594. break;
  3595. }
  3596. //case Instruction::Or:
  3597. // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
  3598. //break;
  3599. case Instruction::Mul:
  3600. case Instruction::Shl: {
  3601. // Can only handle X*C and X << C.
  3602. AddrMode.InBounds = false;
  3603. ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
  3604. if (!RHS || RHS->getBitWidth() > 64)
  3605. return false;
  3606. int64_t Scale = RHS->getSExtValue();
  3607. if (Opcode == Instruction::Shl)
  3608. Scale = 1LL << Scale;
  3609. return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
  3610. }
  3611. case Instruction::GetElementPtr: {
  3612. // Scan the GEP. We check it if it contains constant offsets and at most
  3613. // one variable offset.
  3614. int VariableOperand = -1;
  3615. unsigned VariableScale = 0;
  3616. int64_t ConstantOffset = 0;
  3617. gep_type_iterator GTI = gep_type_begin(AddrInst);
  3618. for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
  3619. if (StructType *STy = GTI.getStructTypeOrNull()) {
  3620. const StructLayout *SL = DL.getStructLayout(STy);
  3621. unsigned Idx =
  3622. cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
  3623. ConstantOffset += SL->getElementOffset(Idx);
  3624. } else {
  3625. uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
  3626. if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
  3627. const APInt &CVal = CI->getValue();
  3628. if (CVal.getMinSignedBits() <= 64) {
  3629. ConstantOffset += CVal.getSExtValue() * TypeSize;
  3630. continue;
  3631. }
  3632. }
  3633. if (TypeSize) { // Scales of zero don't do anything.
  3634. // We only allow one variable index at the moment.
  3635. if (VariableOperand != -1)
  3636. return false;
  3637. // Remember the variable index.
  3638. VariableOperand = i;
  3639. VariableScale = TypeSize;
  3640. }
  3641. }
  3642. }
  3643. // A common case is for the GEP to only do a constant offset. In this case,
  3644. // just add it to the disp field and check validity.
  3645. if (VariableOperand == -1) {
  3646. AddrMode.BaseOffs += ConstantOffset;
  3647. if (ConstantOffset == 0 ||
  3648. TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
  3649. // Check to see if we can fold the base pointer in too.
  3650. if (matchAddr(AddrInst->getOperand(0), Depth+1)) {
  3651. if (!cast<GEPOperator>(AddrInst)->isInBounds())
  3652. AddrMode.InBounds = false;
  3653. return true;
  3654. }
  3655. } else if (EnableGEPOffsetSplit && isa<GetElementPtrInst>(AddrInst) &&
  3656. TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 &&
  3657. ConstantOffset > 0) {
  3658. // Record GEPs with non-zero offsets as candidates for splitting in the
  3659. // event that the offset cannot fit into the r+i addressing mode.
  3660. // Simple and common case that only one GEP is used in calculating the
  3661. // address for the memory access.
  3662. Value *Base = AddrInst->getOperand(0);
  3663. auto *BaseI = dyn_cast<Instruction>(Base);
  3664. auto *GEP = cast<GetElementPtrInst>(AddrInst);
  3665. if (isa<Argument>(Base) || isa<GlobalValue>(Base) ||
  3666. (BaseI && !isa<CastInst>(BaseI) &&
  3667. !isa<GetElementPtrInst>(BaseI))) {
  3668. // Make sure the parent block allows inserting non-PHI instructions
  3669. // before the terminator.
  3670. BasicBlock *Parent =
  3671. BaseI ? BaseI->getParent() : &GEP->getFunction()->getEntryBlock();
  3672. if (!Parent->getTerminator()->isEHPad())
  3673. LargeOffsetGEP = std::make_pair(GEP, ConstantOffset);
  3674. }
  3675. }
  3676. AddrMode.BaseOffs -= ConstantOffset;
  3677. return false;
  3678. }
  3679. // Save the valid addressing mode in case we can't match.
  3680. ExtAddrMode BackupAddrMode = AddrMode;
  3681. unsigned OldSize = AddrModeInsts.size();
  3682. // See if the scale and offset amount is valid for this target.
  3683. AddrMode.BaseOffs += ConstantOffset;
  3684. if (!cast<GEPOperator>(AddrInst)->isInBounds())
  3685. AddrMode.InBounds = false;
  3686. // Match the base operand of the GEP.
  3687. if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
  3688. // If it couldn't be matched, just stuff the value in a register.
  3689. if (AddrMode.HasBaseReg) {
  3690. AddrMode = BackupAddrMode;
  3691. AddrModeInsts.resize(OldSize);
  3692. return false;
  3693. }
  3694. AddrMode.HasBaseReg = true;
  3695. AddrMode.BaseReg = AddrInst->getOperand(0);
  3696. }
  3697. // Match the remaining variable portion of the GEP.
  3698. if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
  3699. Depth)) {
  3700. // If it couldn't be matched, try stuffing the base into a register
  3701. // instead of matching it, and retrying the match of the scale.
  3702. AddrMode = BackupAddrMode;
  3703. AddrModeInsts.resize(OldSize);
  3704. if (AddrMode.HasBaseReg)
  3705. return false;
  3706. AddrMode.HasBaseReg = true;
  3707. AddrMode.BaseReg = AddrInst->getOperand(0);
  3708. AddrMode.BaseOffs += ConstantOffset;
  3709. if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
  3710. VariableScale, Depth)) {
  3711. // If even that didn't work, bail.
  3712. AddrMode = BackupAddrMode;
  3713. AddrModeInsts.resize(OldSize);
  3714. return false;
  3715. }
  3716. }
  3717. return true;
  3718. }
  3719. case Instruction::SExt:
  3720. case Instruction::ZExt: {
  3721. Instruction *Ext = dyn_cast<Instruction>(AddrInst);
  3722. if (!Ext)
  3723. return false;
  3724. // Try to move this ext out of the way of the addressing mode.
  3725. // Ask for a method for doing so.
  3726. TypePromotionHelper::Action TPH =
  3727. TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
  3728. if (!TPH)
  3729. return false;
  3730. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  3731. TPT.getRestorationPoint();
  3732. unsigned CreatedInstsCost = 0;
  3733. unsigned ExtCost = !TLI.isExtFree(Ext);
  3734. Value *PromotedOperand =
  3735. TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
  3736. // SExt has been moved away.
  3737. // Thus either it will be rematched later in the recursive calls or it is
  3738. // gone. Anyway, we must not fold it into the addressing mode at this point.
  3739. // E.g.,
  3740. // op = add opnd, 1
  3741. // idx = ext op
  3742. // addr = gep base, idx
  3743. // is now:
  3744. // promotedOpnd = ext opnd <- no match here
  3745. // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
  3746. // addr = gep base, op <- match
  3747. if (MovedAway)
  3748. *MovedAway = true;
  3749. assert(PromotedOperand &&
  3750. "TypePromotionHelper should have filtered out those cases");
  3751. ExtAddrMode BackupAddrMode = AddrMode;
  3752. unsigned OldSize = AddrModeInsts.size();
  3753. if (!matchAddr(PromotedOperand, Depth) ||
  3754. // The total of the new cost is equal to the cost of the created
  3755. // instructions.
  3756. // The total of the old cost is equal to the cost of the extension plus
  3757. // what we have saved in the addressing mode.
  3758. !isPromotionProfitable(CreatedInstsCost,
  3759. ExtCost + (AddrModeInsts.size() - OldSize),
  3760. PromotedOperand)) {
  3761. AddrMode = BackupAddrMode;
  3762. AddrModeInsts.resize(OldSize);
  3763. LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
  3764. TPT.rollback(LastKnownGood);
  3765. return false;
  3766. }
  3767. return true;
  3768. }
  3769. }
  3770. return false;
  3771. }
  3772. /// If we can, try to add the value of 'Addr' into the current addressing mode.
  3773. /// If Addr can't be added to AddrMode this returns false and leaves AddrMode
  3774. /// unmodified. This assumes that Addr is either a pointer type or intptr_t
  3775. /// for the target.
  3776. ///
  3777. bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
  3778. // Start a transaction at this point that we will rollback if the matching
  3779. // fails.
  3780. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  3781. TPT.getRestorationPoint();
  3782. if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
  3783. // Fold in immediates if legal for the target.
  3784. AddrMode.BaseOffs += CI->getSExtValue();
  3785. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  3786. return true;
  3787. AddrMode.BaseOffs -= CI->getSExtValue();
  3788. } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
  3789. // If this is a global variable, try to fold it into the addressing mode.
  3790. if (!AddrMode.BaseGV) {
  3791. AddrMode.BaseGV = GV;
  3792. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  3793. return true;
  3794. AddrMode.BaseGV = nullptr;
  3795. }
  3796. } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
  3797. ExtAddrMode BackupAddrMode = AddrMode;
  3798. unsigned OldSize = AddrModeInsts.size();
  3799. // Check to see if it is possible to fold this operation.
  3800. bool MovedAway = false;
  3801. if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
  3802. // This instruction may have been moved away. If so, there is nothing
  3803. // to check here.
  3804. if (MovedAway)
  3805. return true;
  3806. // Okay, it's possible to fold this. Check to see if it is actually
  3807. // *profitable* to do so. We use a simple cost model to avoid increasing
  3808. // register pressure too much.
  3809. if (I->hasOneUse() ||
  3810. isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
  3811. AddrModeInsts.push_back(I);
  3812. return true;
  3813. }
  3814. // It isn't profitable to do this, roll back.
  3815. //cerr << "NOT FOLDING: " << *I;
  3816. AddrMode = BackupAddrMode;
  3817. AddrModeInsts.resize(OldSize);
  3818. TPT.rollback(LastKnownGood);
  3819. }
  3820. } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
  3821. if (matchOperationAddr(CE, CE->getOpcode(), Depth))
  3822. return true;
  3823. TPT.rollback(LastKnownGood);
  3824. } else if (isa<ConstantPointerNull>(Addr)) {
  3825. // Null pointer gets folded without affecting the addressing mode.
  3826. return true;
  3827. }
  3828. // Worse case, the target should support [reg] addressing modes. :)
  3829. if (!AddrMode.HasBaseReg) {
  3830. AddrMode.HasBaseReg = true;
  3831. AddrMode.BaseReg = Addr;
  3832. // Still check for legality in case the target supports [imm] but not [i+r].
  3833. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  3834. return true;
  3835. AddrMode.HasBaseReg = false;
  3836. AddrMode.BaseReg = nullptr;
  3837. }
  3838. // If the base register is already taken, see if we can do [r+r].
  3839. if (AddrMode.Scale == 0) {
  3840. AddrMode.Scale = 1;
  3841. AddrMode.ScaledReg = Addr;
  3842. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  3843. return true;
  3844. AddrMode.Scale = 0;
  3845. AddrMode.ScaledReg = nullptr;
  3846. }
  3847. // Couldn't match.
  3848. TPT.rollback(LastKnownGood);
  3849. return false;
  3850. }
  3851. /// Check to see if all uses of OpVal by the specified inline asm call are due
  3852. /// to memory operands. If so, return true, otherwise return false.
  3853. static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
  3854. const TargetLowering &TLI,
  3855. const TargetRegisterInfo &TRI) {
  3856. const Function *F = CI->getFunction();
  3857. TargetLowering::AsmOperandInfoVector TargetConstraints =
  3858. TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
  3859. ImmutableCallSite(CI));
  3860. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  3861. TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
  3862. // Compute the constraint code and ConstraintType to use.
  3863. TLI.ComputeConstraintToUse(OpInfo, SDValue());
  3864. // If this asm operand is our Value*, and if it isn't an indirect memory
  3865. // operand, we can't fold it!
  3866. if (OpInfo.CallOperandVal == OpVal &&
  3867. (OpInfo.ConstraintType != TargetLowering::C_Memory ||
  3868. !OpInfo.isIndirect))
  3869. return false;
  3870. }
  3871. return true;
  3872. }
  3873. // Max number of memory uses to look at before aborting the search to conserve
  3874. // compile time.
  3875. static constexpr int MaxMemoryUsesToScan = 20;
  3876. /// Recursively walk all the uses of I until we find a memory use.
  3877. /// If we find an obviously non-foldable instruction, return true.
  3878. /// Add the ultimately found memory instructions to MemoryUses.
  3879. static bool FindAllMemoryUses(
  3880. Instruction *I,
  3881. SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
  3882. SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
  3883. const TargetRegisterInfo &TRI, int SeenInsts = 0) {
  3884. // If we already considered this instruction, we're done.
  3885. if (!ConsideredInsts.insert(I).second)
  3886. return false;
  3887. // If this is an obviously unfoldable instruction, bail out.
  3888. if (!MightBeFoldableInst(I))
  3889. return true;
  3890. const bool OptSize = I->getFunction()->hasOptSize();
  3891. // Loop over all the uses, recursively processing them.
  3892. for (Use &U : I->uses()) {
  3893. // Conservatively return true if we're seeing a large number or a deep chain
  3894. // of users. This avoids excessive compilation times in pathological cases.
  3895. if (SeenInsts++ >= MaxMemoryUsesToScan)
  3896. return true;
  3897. Instruction *UserI = cast<Instruction>(U.getUser());
  3898. if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
  3899. MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
  3900. continue;
  3901. }
  3902. if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
  3903. unsigned opNo = U.getOperandNo();
  3904. if (opNo != StoreInst::getPointerOperandIndex())
  3905. return true; // Storing addr, not into addr.
  3906. MemoryUses.push_back(std::make_pair(SI, opNo));
  3907. continue;
  3908. }
  3909. if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
  3910. unsigned opNo = U.getOperandNo();
  3911. if (opNo != AtomicRMWInst::getPointerOperandIndex())
  3912. return true; // Storing addr, not into addr.
  3913. MemoryUses.push_back(std::make_pair(RMW, opNo));
  3914. continue;
  3915. }
  3916. if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
  3917. unsigned opNo = U.getOperandNo();
  3918. if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
  3919. return true; // Storing addr, not into addr.
  3920. MemoryUses.push_back(std::make_pair(CmpX, opNo));
  3921. continue;
  3922. }
  3923. if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
  3924. // If this is a cold call, we can sink the addressing calculation into
  3925. // the cold path. See optimizeCallInst
  3926. if (!OptSize && CI->hasFnAttr(Attribute::Cold))
  3927. continue;
  3928. InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
  3929. if (!IA) return true;
  3930. // If this is a memory operand, we're cool, otherwise bail out.
  3931. if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
  3932. return true;
  3933. continue;
  3934. }
  3935. if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI,
  3936. SeenInsts))
  3937. return true;
  3938. }
  3939. return false;
  3940. }
  3941. /// Return true if Val is already known to be live at the use site that we're
  3942. /// folding it into. If so, there is no cost to include it in the addressing
  3943. /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
  3944. /// instruction already.
  3945. bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
  3946. Value *KnownLive2) {
  3947. // If Val is either of the known-live values, we know it is live!
  3948. if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
  3949. return true;
  3950. // All values other than instructions and arguments (e.g. constants) are live.
  3951. if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
  3952. // If Val is a constant sized alloca in the entry block, it is live, this is
  3953. // true because it is just a reference to the stack/frame pointer, which is
  3954. // live for the whole function.
  3955. if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
  3956. if (AI->isStaticAlloca())
  3957. return true;
  3958. // Check to see if this value is already used in the memory instruction's
  3959. // block. If so, it's already live into the block at the very least, so we
  3960. // can reasonably fold it.
  3961. return Val->isUsedInBasicBlock(MemoryInst->getParent());
  3962. }
  3963. /// It is possible for the addressing mode of the machine to fold the specified
  3964. /// instruction into a load or store that ultimately uses it.
  3965. /// However, the specified instruction has multiple uses.
  3966. /// Given this, it may actually increase register pressure to fold it
  3967. /// into the load. For example, consider this code:
  3968. ///
  3969. /// X = ...
  3970. /// Y = X+1
  3971. /// use(Y) -> nonload/store
  3972. /// Z = Y+1
  3973. /// load Z
  3974. ///
  3975. /// In this case, Y has multiple uses, and can be folded into the load of Z
  3976. /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
  3977. /// be live at the use(Y) line. If we don't fold Y into load Z, we use one
  3978. /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
  3979. /// number of computations either.
  3980. ///
  3981. /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
  3982. /// X was live across 'load Z' for other reasons, we actually *would* want to
  3983. /// fold the addressing mode in the Z case. This would make Y die earlier.
  3984. bool AddressingModeMatcher::
  3985. isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
  3986. ExtAddrMode &AMAfter) {
  3987. if (IgnoreProfitability) return true;
  3988. // AMBefore is the addressing mode before this instruction was folded into it,
  3989. // and AMAfter is the addressing mode after the instruction was folded. Get
  3990. // the set of registers referenced by AMAfter and subtract out those
  3991. // referenced by AMBefore: this is the set of values which folding in this
  3992. // address extends the lifetime of.
  3993. //
  3994. // Note that there are only two potential values being referenced here,
  3995. // BaseReg and ScaleReg (global addresses are always available, as are any
  3996. // folded immediates).
  3997. Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
  3998. // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
  3999. // lifetime wasn't extended by adding this instruction.
  4000. if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
  4001. BaseReg = nullptr;
  4002. if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
  4003. ScaledReg = nullptr;
  4004. // If folding this instruction (and it's subexprs) didn't extend any live
  4005. // ranges, we're ok with it.
  4006. if (!BaseReg && !ScaledReg)
  4007. return true;
  4008. // If all uses of this instruction can have the address mode sunk into them,
  4009. // we can remove the addressing mode and effectively trade one live register
  4010. // for another (at worst.) In this context, folding an addressing mode into
  4011. // the use is just a particularly nice way of sinking it.
  4012. SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
  4013. SmallPtrSet<Instruction*, 16> ConsideredInsts;
  4014. if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
  4015. return false; // Has a non-memory, non-foldable use!
  4016. // Now that we know that all uses of this instruction are part of a chain of
  4017. // computation involving only operations that could theoretically be folded
  4018. // into a memory use, loop over each of these memory operation uses and see
  4019. // if they could *actually* fold the instruction. The assumption is that
  4020. // addressing modes are cheap and that duplicating the computation involved
  4021. // many times is worthwhile, even on a fastpath. For sinking candidates
  4022. // (i.e. cold call sites), this serves as a way to prevent excessive code
  4023. // growth since most architectures have some reasonable small and fast way to
  4024. // compute an effective address. (i.e LEA on x86)
  4025. SmallVector<Instruction*, 32> MatchedAddrModeInsts;
  4026. for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
  4027. Instruction *User = MemoryUses[i].first;
  4028. unsigned OpNo = MemoryUses[i].second;
  4029. // Get the access type of this use. If the use isn't a pointer, we don't
  4030. // know what it accesses.
  4031. Value *Address = User->getOperand(OpNo);
  4032. PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
  4033. if (!AddrTy)
  4034. return false;
  4035. Type *AddressAccessTy = AddrTy->getElementType();
  4036. unsigned AS = AddrTy->getAddressSpace();
  4037. // Do a match against the root of this address, ignoring profitability. This
  4038. // will tell us if the addressing mode for the memory operation will
  4039. // *actually* cover the shared instruction.
  4040. ExtAddrMode Result;
  4041. std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
  4042. 0);
  4043. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  4044. TPT.getRestorationPoint();
  4045. AddressingModeMatcher Matcher(
  4046. MatchedAddrModeInsts, TLI, TRI, AddressAccessTy, AS, MemoryInst, Result,
  4047. InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP);
  4048. Matcher.IgnoreProfitability = true;
  4049. bool Success = Matcher.matchAddr(Address, 0);
  4050. (void)Success; assert(Success && "Couldn't select *anything*?");
  4051. // The match was to check the profitability, the changes made are not
  4052. // part of the original matcher. Therefore, they should be dropped
  4053. // otherwise the original matcher will not present the right state.
  4054. TPT.rollback(LastKnownGood);
  4055. // If the match didn't cover I, then it won't be shared by it.
  4056. if (!is_contained(MatchedAddrModeInsts, I))
  4057. return false;
  4058. MatchedAddrModeInsts.clear();
  4059. }
  4060. return true;
  4061. }
  4062. /// Return true if the specified values are defined in a
  4063. /// different basic block than BB.
  4064. static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
  4065. if (Instruction *I = dyn_cast<Instruction>(V))
  4066. return I->getParent() != BB;
  4067. return false;
  4068. }
  4069. /// Sink addressing mode computation immediate before MemoryInst if doing so
  4070. /// can be done without increasing register pressure. The need for the
  4071. /// register pressure constraint means this can end up being an all or nothing
  4072. /// decision for all uses of the same addressing computation.
  4073. ///
  4074. /// Load and Store Instructions often have addressing modes that can do
  4075. /// significant amounts of computation. As such, instruction selection will try
  4076. /// to get the load or store to do as much computation as possible for the
  4077. /// program. The problem is that isel can only see within a single block. As
  4078. /// such, we sink as much legal addressing mode work into the block as possible.
  4079. ///
  4080. /// This method is used to optimize both load/store and inline asms with memory
  4081. /// operands. It's also used to sink addressing computations feeding into cold
  4082. /// call sites into their (cold) basic block.
  4083. ///
  4084. /// The motivation for handling sinking into cold blocks is that doing so can
  4085. /// both enable other address mode sinking (by satisfying the register pressure
  4086. /// constraint above), and reduce register pressure globally (by removing the
  4087. /// addressing mode computation from the fast path entirely.).
  4088. bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
  4089. Type *AccessTy, unsigned AddrSpace) {
  4090. Value *Repl = Addr;
  4091. // Try to collapse single-value PHI nodes. This is necessary to undo
  4092. // unprofitable PRE transformations.
  4093. SmallVector<Value*, 8> worklist;
  4094. SmallPtrSet<Value*, 16> Visited;
  4095. worklist.push_back(Addr);
  4096. // Use a worklist to iteratively look through PHI and select nodes, and
  4097. // ensure that the addressing mode obtained from the non-PHI/select roots of
  4098. // the graph are compatible.
  4099. bool PhiOrSelectSeen = false;
  4100. SmallVector<Instruction*, 16> AddrModeInsts;
  4101. const SimplifyQuery SQ(*DL, TLInfo);
  4102. AddressingModeCombiner AddrModes(SQ, Addr);
  4103. TypePromotionTransaction TPT(RemovedInsts);
  4104. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  4105. TPT.getRestorationPoint();
  4106. while (!worklist.empty()) {
  4107. Value *V = worklist.back();
  4108. worklist.pop_back();
  4109. // We allow traversing cyclic Phi nodes.
  4110. // In case of success after this loop we ensure that traversing through
  4111. // Phi nodes ends up with all cases to compute address of the form
  4112. // BaseGV + Base + Scale * Index + Offset
  4113. // where Scale and Offset are constans and BaseGV, Base and Index
  4114. // are exactly the same Values in all cases.
  4115. // It means that BaseGV, Scale and Offset dominate our memory instruction
  4116. // and have the same value as they had in address computation represented
  4117. // as Phi. So we can safely sink address computation to memory instruction.
  4118. if (!Visited.insert(V).second)
  4119. continue;
  4120. // For a PHI node, push all of its incoming values.
  4121. if (PHINode *P = dyn_cast<PHINode>(V)) {
  4122. for (Value *IncValue : P->incoming_values())
  4123. worklist.push_back(IncValue);
  4124. PhiOrSelectSeen = true;
  4125. continue;
  4126. }
  4127. // Similar for select.
  4128. if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
  4129. worklist.push_back(SI->getFalseValue());
  4130. worklist.push_back(SI->getTrueValue());
  4131. PhiOrSelectSeen = true;
  4132. continue;
  4133. }
  4134. // For non-PHIs, determine the addressing mode being computed. Note that
  4135. // the result may differ depending on what other uses our candidate
  4136. // addressing instructions might have.
  4137. AddrModeInsts.clear();
  4138. std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
  4139. 0);
  4140. ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
  4141. V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *TRI,
  4142. InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP);
  4143. GetElementPtrInst *GEP = LargeOffsetGEP.first;
  4144. if (GEP && !NewGEPBases.count(GEP)) {
  4145. // If splitting the underlying data structure can reduce the offset of a
  4146. // GEP, collect the GEP. Skip the GEPs that are the new bases of
  4147. // previously split data structures.
  4148. LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(LargeOffsetGEP);
  4149. if (LargeOffsetGEPID.find(GEP) == LargeOffsetGEPID.end())
  4150. LargeOffsetGEPID[GEP] = LargeOffsetGEPID.size();
  4151. }
  4152. NewAddrMode.OriginalValue = V;
  4153. if (!AddrModes.addNewAddrMode(NewAddrMode))
  4154. break;
  4155. }
  4156. // Try to combine the AddrModes we've collected. If we couldn't collect any,
  4157. // or we have multiple but either couldn't combine them or combining them
  4158. // wouldn't do anything useful, bail out now.
  4159. if (!AddrModes.combineAddrModes()) {
  4160. TPT.rollback(LastKnownGood);
  4161. return false;
  4162. }
  4163. TPT.commit();
  4164. // Get the combined AddrMode (or the only AddrMode, if we only had one).
  4165. ExtAddrMode AddrMode = AddrModes.getAddrMode();
  4166. // If all the instructions matched are already in this BB, don't do anything.
  4167. // If we saw a Phi node then it is not local definitely, and if we saw a select
  4168. // then we want to push the address calculation past it even if it's already
  4169. // in this BB.
  4170. if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
  4171. return IsNonLocalValue(V, MemoryInst->getParent());
  4172. })) {
  4173. LLVM_DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode
  4174. << "\n");
  4175. return false;
  4176. }
  4177. // Insert this computation right after this user. Since our caller is
  4178. // scanning from the top of the BB to the bottom, reuse of the expr are
  4179. // guaranteed to happen later.
  4180. IRBuilder<> Builder(MemoryInst);
  4181. // Now that we determined the addressing expression we want to use and know
  4182. // that we have to sink it into this block. Check to see if we have already
  4183. // done this for some other load/store instr in this block. If so, reuse
  4184. // the computation. Before attempting reuse, check if the address is valid
  4185. // as it may have been erased.
  4186. WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
  4187. Value * SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
  4188. if (SunkAddr) {
  4189. LLVM_DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode
  4190. << " for " << *MemoryInst << "\n");
  4191. if (SunkAddr->getType() != Addr->getType())
  4192. SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
  4193. } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() &&
  4194. TM && SubtargetInfo->addrSinkUsingGEPs())) {
  4195. // By default, we use the GEP-based method when AA is used later. This
  4196. // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
  4197. LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
  4198. << " for " << *MemoryInst << "\n");
  4199. Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
  4200. Value *ResultPtr = nullptr, *ResultIndex = nullptr;
  4201. // First, find the pointer.
  4202. if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
  4203. ResultPtr = AddrMode.BaseReg;
  4204. AddrMode.BaseReg = nullptr;
  4205. }
  4206. if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
  4207. // We can't add more than one pointer together, nor can we scale a
  4208. // pointer (both of which seem meaningless).
  4209. if (ResultPtr || AddrMode.Scale != 1)
  4210. return false;
  4211. ResultPtr = AddrMode.ScaledReg;
  4212. AddrMode.Scale = 0;
  4213. }
  4214. // It is only safe to sign extend the BaseReg if we know that the math
  4215. // required to create it did not overflow before we extend it. Since
  4216. // the original IR value was tossed in favor of a constant back when
  4217. // the AddrMode was created we need to bail out gracefully if widths
  4218. // do not match instead of extending it.
  4219. //
  4220. // (See below for code to add the scale.)
  4221. if (AddrMode.Scale) {
  4222. Type *ScaledRegTy = AddrMode.ScaledReg->getType();
  4223. if (cast<IntegerType>(IntPtrTy)->getBitWidth() >
  4224. cast<IntegerType>(ScaledRegTy)->getBitWidth())
  4225. return false;
  4226. }
  4227. if (AddrMode.BaseGV) {
  4228. if (ResultPtr)
  4229. return false;
  4230. ResultPtr = AddrMode.BaseGV;
  4231. }
  4232. // If the real base value actually came from an inttoptr, then the matcher
  4233. // will look through it and provide only the integer value. In that case,
  4234. // use it here.
  4235. if (!DL->isNonIntegralPointerType(Addr->getType())) {
  4236. if (!ResultPtr && AddrMode.BaseReg) {
  4237. ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
  4238. "sunkaddr");
  4239. AddrMode.BaseReg = nullptr;
  4240. } else if (!ResultPtr && AddrMode.Scale == 1) {
  4241. ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
  4242. "sunkaddr");
  4243. AddrMode.Scale = 0;
  4244. }
  4245. }
  4246. if (!ResultPtr &&
  4247. !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
  4248. SunkAddr = Constant::getNullValue(Addr->getType());
  4249. } else if (!ResultPtr) {
  4250. return false;
  4251. } else {
  4252. Type *I8PtrTy =
  4253. Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
  4254. Type *I8Ty = Builder.getInt8Ty();
  4255. // Start with the base register. Do this first so that subsequent address
  4256. // matching finds it last, which will prevent it from trying to match it
  4257. // as the scaled value in case it happens to be a mul. That would be
  4258. // problematic if we've sunk a different mul for the scale, because then
  4259. // we'd end up sinking both muls.
  4260. if (AddrMode.BaseReg) {
  4261. Value *V = AddrMode.BaseReg;
  4262. if (V->getType() != IntPtrTy)
  4263. V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
  4264. ResultIndex = V;
  4265. }
  4266. // Add the scale value.
  4267. if (AddrMode.Scale) {
  4268. Value *V = AddrMode.ScaledReg;
  4269. if (V->getType() == IntPtrTy) {
  4270. // done.
  4271. } else {
  4272. assert(cast<IntegerType>(IntPtrTy)->getBitWidth() <
  4273. cast<IntegerType>(V->getType())->getBitWidth() &&
  4274. "We can't transform if ScaledReg is too narrow");
  4275. V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
  4276. }
  4277. if (AddrMode.Scale != 1)
  4278. V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
  4279. "sunkaddr");
  4280. if (ResultIndex)
  4281. ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
  4282. else
  4283. ResultIndex = V;
  4284. }
  4285. // Add in the Base Offset if present.
  4286. if (AddrMode.BaseOffs) {
  4287. Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
  4288. if (ResultIndex) {
  4289. // We need to add this separately from the scale above to help with
  4290. // SDAG consecutive load/store merging.
  4291. if (ResultPtr->getType() != I8PtrTy)
  4292. ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
  4293. ResultPtr =
  4294. AddrMode.InBounds
  4295. ? Builder.CreateInBoundsGEP(I8Ty, ResultPtr, ResultIndex,
  4296. "sunkaddr")
  4297. : Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
  4298. }
  4299. ResultIndex = V;
  4300. }
  4301. if (!ResultIndex) {
  4302. SunkAddr = ResultPtr;
  4303. } else {
  4304. if (ResultPtr->getType() != I8PtrTy)
  4305. ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
  4306. SunkAddr =
  4307. AddrMode.InBounds
  4308. ? Builder.CreateInBoundsGEP(I8Ty, ResultPtr, ResultIndex,
  4309. "sunkaddr")
  4310. : Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
  4311. }
  4312. if (SunkAddr->getType() != Addr->getType())
  4313. SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
  4314. }
  4315. } else {
  4316. // We'd require a ptrtoint/inttoptr down the line, which we can't do for
  4317. // non-integral pointers, so in that case bail out now.
  4318. Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
  4319. Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
  4320. PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
  4321. PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
  4322. if (DL->isNonIntegralPointerType(Addr->getType()) ||
  4323. (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
  4324. (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
  4325. (AddrMode.BaseGV &&
  4326. DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
  4327. return false;
  4328. LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
  4329. << " for " << *MemoryInst << "\n");
  4330. Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
  4331. Value *Result = nullptr;
  4332. // Start with the base register. Do this first so that subsequent address
  4333. // matching finds it last, which will prevent it from trying to match it
  4334. // as the scaled value in case it happens to be a mul. That would be
  4335. // problematic if we've sunk a different mul for the scale, because then
  4336. // we'd end up sinking both muls.
  4337. if (AddrMode.BaseReg) {
  4338. Value *V = AddrMode.BaseReg;
  4339. if (V->getType()->isPointerTy())
  4340. V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
  4341. if (V->getType() != IntPtrTy)
  4342. V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
  4343. Result = V;
  4344. }
  4345. // Add the scale value.
  4346. if (AddrMode.Scale) {
  4347. Value *V = AddrMode.ScaledReg;
  4348. if (V->getType() == IntPtrTy) {
  4349. // done.
  4350. } else if (V->getType()->isPointerTy()) {
  4351. V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
  4352. } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
  4353. cast<IntegerType>(V->getType())->getBitWidth()) {
  4354. V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
  4355. } else {
  4356. // It is only safe to sign extend the BaseReg if we know that the math
  4357. // required to create it did not overflow before we extend it. Since
  4358. // the original IR value was tossed in favor of a constant back when
  4359. // the AddrMode was created we need to bail out gracefully if widths
  4360. // do not match instead of extending it.
  4361. Instruction *I = dyn_cast_or_null<Instruction>(Result);
  4362. if (I && (Result != AddrMode.BaseReg))
  4363. I->eraseFromParent();
  4364. return false;
  4365. }
  4366. if (AddrMode.Scale != 1)
  4367. V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
  4368. "sunkaddr");
  4369. if (Result)
  4370. Result = Builder.CreateAdd(Result, V, "sunkaddr");
  4371. else
  4372. Result = V;
  4373. }
  4374. // Add in the BaseGV if present.
  4375. if (AddrMode.BaseGV) {
  4376. Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
  4377. if (Result)
  4378. Result = Builder.CreateAdd(Result, V, "sunkaddr");
  4379. else
  4380. Result = V;
  4381. }
  4382. // Add in the Base Offset if present.
  4383. if (AddrMode.BaseOffs) {
  4384. Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
  4385. if (Result)
  4386. Result = Builder.CreateAdd(Result, V, "sunkaddr");
  4387. else
  4388. Result = V;
  4389. }
  4390. if (!Result)
  4391. SunkAddr = Constant::getNullValue(Addr->getType());
  4392. else
  4393. SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
  4394. }
  4395. MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
  4396. // Store the newly computed address into the cache. In the case we reused a
  4397. // value, this should be idempotent.
  4398. SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
  4399. // If we have no uses, recursively delete the value and all dead instructions
  4400. // using it.
  4401. if (Repl->use_empty()) {
  4402. // This can cause recursive deletion, which can invalidate our iterator.
  4403. // Use a WeakTrackingVH to hold onto it in case this happens.
  4404. Value *CurValue = &*CurInstIterator;
  4405. WeakTrackingVH IterHandle(CurValue);
  4406. BasicBlock *BB = CurInstIterator->getParent();
  4407. RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
  4408. if (IterHandle != CurValue) {
  4409. // If the iterator instruction was recursively deleted, start over at the
  4410. // start of the block.
  4411. CurInstIterator = BB->begin();
  4412. SunkAddrs.clear();
  4413. }
  4414. }
  4415. ++NumMemoryInsts;
  4416. return true;
  4417. }
  4418. /// If there are any memory operands, use OptimizeMemoryInst to sink their
  4419. /// address computing into the block when possible / profitable.
  4420. bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
  4421. bool MadeChange = false;
  4422. const TargetRegisterInfo *TRI =
  4423. TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo();
  4424. TargetLowering::AsmOperandInfoVector TargetConstraints =
  4425. TLI->ParseConstraints(*DL, TRI, CS);
  4426. unsigned ArgNo = 0;
  4427. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  4428. TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
  4429. // Compute the constraint code and ConstraintType to use.
  4430. TLI->ComputeConstraintToUse(OpInfo, SDValue());
  4431. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  4432. OpInfo.isIndirect) {
  4433. Value *OpVal = CS->getArgOperand(ArgNo++);
  4434. MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
  4435. } else if (OpInfo.Type == InlineAsm::isInput)
  4436. ArgNo++;
  4437. }
  4438. return MadeChange;
  4439. }
  4440. /// Check if all the uses of \p Val are equivalent (or free) zero or
  4441. /// sign extensions.
  4442. static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
  4443. assert(!Val->use_empty() && "Input must have at least one use");
  4444. const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
  4445. bool IsSExt = isa<SExtInst>(FirstUser);
  4446. Type *ExtTy = FirstUser->getType();
  4447. for (const User *U : Val->users()) {
  4448. const Instruction *UI = cast<Instruction>(U);
  4449. if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
  4450. return false;
  4451. Type *CurTy = UI->getType();
  4452. // Same input and output types: Same instruction after CSE.
  4453. if (CurTy == ExtTy)
  4454. continue;
  4455. // If IsSExt is true, we are in this situation:
  4456. // a = Val
  4457. // b = sext ty1 a to ty2
  4458. // c = sext ty1 a to ty3
  4459. // Assuming ty2 is shorter than ty3, this could be turned into:
  4460. // a = Val
  4461. // b = sext ty1 a to ty2
  4462. // c = sext ty2 b to ty3
  4463. // However, the last sext is not free.
  4464. if (IsSExt)
  4465. return false;
  4466. // This is a ZExt, maybe this is free to extend from one type to another.
  4467. // In that case, we would not account for a different use.
  4468. Type *NarrowTy;
  4469. Type *LargeTy;
  4470. if (ExtTy->getScalarType()->getIntegerBitWidth() >
  4471. CurTy->getScalarType()->getIntegerBitWidth()) {
  4472. NarrowTy = CurTy;
  4473. LargeTy = ExtTy;
  4474. } else {
  4475. NarrowTy = ExtTy;
  4476. LargeTy = CurTy;
  4477. }
  4478. if (!TLI.isZExtFree(NarrowTy, LargeTy))
  4479. return false;
  4480. }
  4481. // All uses are the same or can be derived from one another for free.
  4482. return true;
  4483. }
  4484. /// Try to speculatively promote extensions in \p Exts and continue
  4485. /// promoting through newly promoted operands recursively as far as doing so is
  4486. /// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
  4487. /// When some promotion happened, \p TPT contains the proper state to revert
  4488. /// them.
  4489. ///
  4490. /// \return true if some promotion happened, false otherwise.
  4491. bool CodeGenPrepare::tryToPromoteExts(
  4492. TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
  4493. SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
  4494. unsigned CreatedInstsCost) {
  4495. bool Promoted = false;
  4496. // Iterate over all the extensions to try to promote them.
  4497. for (auto I : Exts) {
  4498. // Early check if we directly have ext(load).
  4499. if (isa<LoadInst>(I->getOperand(0))) {
  4500. ProfitablyMovedExts.push_back(I);
  4501. continue;
  4502. }
  4503. // Check whether or not we want to do any promotion. The reason we have
  4504. // this check inside the for loop is to catch the case where an extension
  4505. // is directly fed by a load because in such case the extension can be moved
  4506. // up without any promotion on its operands.
  4507. if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
  4508. return false;
  4509. // Get the action to perform the promotion.
  4510. TypePromotionHelper::Action TPH =
  4511. TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
  4512. // Check if we can promote.
  4513. if (!TPH) {
  4514. // Save the current extension as we cannot move up through its operand.
  4515. ProfitablyMovedExts.push_back(I);
  4516. continue;
  4517. }
  4518. // Save the current state.
  4519. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  4520. TPT.getRestorationPoint();
  4521. SmallVector<Instruction *, 4> NewExts;
  4522. unsigned NewCreatedInstsCost = 0;
  4523. unsigned ExtCost = !TLI->isExtFree(I);
  4524. // Promote.
  4525. Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
  4526. &NewExts, nullptr, *TLI);
  4527. assert(PromotedVal &&
  4528. "TypePromotionHelper should have filtered out those cases");
  4529. // We would be able to merge only one extension in a load.
  4530. // Therefore, if we have more than 1 new extension we heuristically
  4531. // cut this search path, because it means we degrade the code quality.
  4532. // With exactly 2, the transformation is neutral, because we will merge
  4533. // one extension but leave one. However, we optimistically keep going,
  4534. // because the new extension may be removed too.
  4535. long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
  4536. // FIXME: It would be possible to propagate a negative value instead of
  4537. // conservatively ceiling it to 0.
  4538. TotalCreatedInstsCost =
  4539. std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
  4540. if (!StressExtLdPromotion &&
  4541. (TotalCreatedInstsCost > 1 ||
  4542. !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
  4543. // This promotion is not profitable, rollback to the previous state, and
  4544. // save the current extension in ProfitablyMovedExts as the latest
  4545. // speculative promotion turned out to be unprofitable.
  4546. TPT.rollback(LastKnownGood);
  4547. ProfitablyMovedExts.push_back(I);
  4548. continue;
  4549. }
  4550. // Continue promoting NewExts as far as doing so is profitable.
  4551. SmallVector<Instruction *, 2> NewlyMovedExts;
  4552. (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
  4553. bool NewPromoted = false;
  4554. for (auto ExtInst : NewlyMovedExts) {
  4555. Instruction *MovedExt = cast<Instruction>(ExtInst);
  4556. Value *ExtOperand = MovedExt->getOperand(0);
  4557. // If we have reached to a load, we need this extra profitability check
  4558. // as it could potentially be merged into an ext(load).
  4559. if (isa<LoadInst>(ExtOperand) &&
  4560. !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
  4561. (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
  4562. continue;
  4563. ProfitablyMovedExts.push_back(MovedExt);
  4564. NewPromoted = true;
  4565. }
  4566. // If none of speculative promotions for NewExts is profitable, rollback
  4567. // and save the current extension (I) as the last profitable extension.
  4568. if (!NewPromoted) {
  4569. TPT.rollback(LastKnownGood);
  4570. ProfitablyMovedExts.push_back(I);
  4571. continue;
  4572. }
  4573. // The promotion is profitable.
  4574. Promoted = true;
  4575. }
  4576. return Promoted;
  4577. }
  4578. /// Merging redundant sexts when one is dominating the other.
  4579. bool CodeGenPrepare::mergeSExts(Function &F) {
  4580. bool Changed = false;
  4581. for (auto &Entry : ValToSExtendedUses) {
  4582. SExts &Insts = Entry.second;
  4583. SExts CurPts;
  4584. for (Instruction *Inst : Insts) {
  4585. if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
  4586. Inst->getOperand(0) != Entry.first)
  4587. continue;
  4588. bool inserted = false;
  4589. for (auto &Pt : CurPts) {
  4590. if (getDT(F).dominates(Inst, Pt)) {
  4591. Pt->replaceAllUsesWith(Inst);
  4592. RemovedInsts.insert(Pt);
  4593. Pt->removeFromParent();
  4594. Pt = Inst;
  4595. inserted = true;
  4596. Changed = true;
  4597. break;
  4598. }
  4599. if (!getDT(F).dominates(Pt, Inst))
  4600. // Give up if we need to merge in a common dominator as the
  4601. // experiments show it is not profitable.
  4602. continue;
  4603. Inst->replaceAllUsesWith(Pt);
  4604. RemovedInsts.insert(Inst);
  4605. Inst->removeFromParent();
  4606. inserted = true;
  4607. Changed = true;
  4608. break;
  4609. }
  4610. if (!inserted)
  4611. CurPts.push_back(Inst);
  4612. }
  4613. }
  4614. return Changed;
  4615. }
  4616. // Spliting large data structures so that the GEPs accessing them can have
  4617. // smaller offsets so that they can be sunk to the same blocks as their users.
  4618. // For example, a large struct starting from %base is splitted into two parts
  4619. // where the second part starts from %new_base.
  4620. //
  4621. // Before:
  4622. // BB0:
  4623. // %base =
  4624. //
  4625. // BB1:
  4626. // %gep0 = gep %base, off0
  4627. // %gep1 = gep %base, off1
  4628. // %gep2 = gep %base, off2
  4629. //
  4630. // BB2:
  4631. // %load1 = load %gep0
  4632. // %load2 = load %gep1
  4633. // %load3 = load %gep2
  4634. //
  4635. // After:
  4636. // BB0:
  4637. // %base =
  4638. // %new_base = gep %base, off0
  4639. //
  4640. // BB1:
  4641. // %new_gep0 = %new_base
  4642. // %new_gep1 = gep %new_base, off1 - off0
  4643. // %new_gep2 = gep %new_base, off2 - off0
  4644. //
  4645. // BB2:
  4646. // %load1 = load i32, i32* %new_gep0
  4647. // %load2 = load i32, i32* %new_gep1
  4648. // %load3 = load i32, i32* %new_gep2
  4649. //
  4650. // %new_gep1 and %new_gep2 can be sunk to BB2 now after the splitting because
  4651. // their offsets are smaller enough to fit into the addressing mode.
  4652. bool CodeGenPrepare::splitLargeGEPOffsets() {
  4653. bool Changed = false;
  4654. for (auto &Entry : LargeOffsetGEPMap) {
  4655. Value *OldBase = Entry.first;
  4656. SmallVectorImpl<std::pair<AssertingVH<GetElementPtrInst>, int64_t>>
  4657. &LargeOffsetGEPs = Entry.second;
  4658. auto compareGEPOffset =
  4659. [&](const std::pair<GetElementPtrInst *, int64_t> &LHS,
  4660. const std::pair<GetElementPtrInst *, int64_t> &RHS) {
  4661. if (LHS.first == RHS.first)
  4662. return false;
  4663. if (LHS.second != RHS.second)
  4664. return LHS.second < RHS.second;
  4665. return LargeOffsetGEPID[LHS.first] < LargeOffsetGEPID[RHS.first];
  4666. };
  4667. // Sorting all the GEPs of the same data structures based on the offsets.
  4668. llvm::sort(LargeOffsetGEPs, compareGEPOffset);
  4669. LargeOffsetGEPs.erase(
  4670. std::unique(LargeOffsetGEPs.begin(), LargeOffsetGEPs.end()),
  4671. LargeOffsetGEPs.end());
  4672. // Skip if all the GEPs have the same offsets.
  4673. if (LargeOffsetGEPs.front().second == LargeOffsetGEPs.back().second)
  4674. continue;
  4675. GetElementPtrInst *BaseGEP = LargeOffsetGEPs.begin()->first;
  4676. int64_t BaseOffset = LargeOffsetGEPs.begin()->second;
  4677. Value *NewBaseGEP = nullptr;
  4678. auto LargeOffsetGEP = LargeOffsetGEPs.begin();
  4679. while (LargeOffsetGEP != LargeOffsetGEPs.end()) {
  4680. GetElementPtrInst *GEP = LargeOffsetGEP->first;
  4681. int64_t Offset = LargeOffsetGEP->second;
  4682. if (Offset != BaseOffset) {
  4683. TargetLowering::AddrMode AddrMode;
  4684. AddrMode.BaseOffs = Offset - BaseOffset;
  4685. // The result type of the GEP might not be the type of the memory
  4686. // access.
  4687. if (!TLI->isLegalAddressingMode(*DL, AddrMode,
  4688. GEP->getResultElementType(),
  4689. GEP->getAddressSpace())) {
  4690. // We need to create a new base if the offset to the current base is
  4691. // too large to fit into the addressing mode. So, a very large struct
  4692. // may be splitted into several parts.
  4693. BaseGEP = GEP;
  4694. BaseOffset = Offset;
  4695. NewBaseGEP = nullptr;
  4696. }
  4697. }
  4698. // Generate a new GEP to replace the current one.
  4699. LLVMContext &Ctx = GEP->getContext();
  4700. Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
  4701. Type *I8PtrTy =
  4702. Type::getInt8PtrTy(Ctx, GEP->getType()->getPointerAddressSpace());
  4703. Type *I8Ty = Type::getInt8Ty(Ctx);
  4704. if (!NewBaseGEP) {
  4705. // Create a new base if we don't have one yet. Find the insertion
  4706. // pointer for the new base first.
  4707. BasicBlock::iterator NewBaseInsertPt;
  4708. BasicBlock *NewBaseInsertBB;
  4709. if (auto *BaseI = dyn_cast<Instruction>(OldBase)) {
  4710. // If the base of the struct is an instruction, the new base will be
  4711. // inserted close to it.
  4712. NewBaseInsertBB = BaseI->getParent();
  4713. if (isa<PHINode>(BaseI))
  4714. NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
  4715. else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(BaseI)) {
  4716. NewBaseInsertBB =
  4717. SplitEdge(NewBaseInsertBB, Invoke->getNormalDest());
  4718. NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
  4719. } else
  4720. NewBaseInsertPt = std::next(BaseI->getIterator());
  4721. } else {
  4722. // If the current base is an argument or global value, the new base
  4723. // will be inserted to the entry block.
  4724. NewBaseInsertBB = &BaseGEP->getFunction()->getEntryBlock();
  4725. NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
  4726. }
  4727. IRBuilder<> NewBaseBuilder(NewBaseInsertBB, NewBaseInsertPt);
  4728. // Create a new base.
  4729. Value *BaseIndex = ConstantInt::get(IntPtrTy, BaseOffset);
  4730. NewBaseGEP = OldBase;
  4731. if (NewBaseGEP->getType() != I8PtrTy)
  4732. NewBaseGEP = NewBaseBuilder.CreatePointerCast(NewBaseGEP, I8PtrTy);
  4733. NewBaseGEP =
  4734. NewBaseBuilder.CreateGEP(I8Ty, NewBaseGEP, BaseIndex, "splitgep");
  4735. NewGEPBases.insert(NewBaseGEP);
  4736. }
  4737. IRBuilder<> Builder(GEP);
  4738. Value *NewGEP = NewBaseGEP;
  4739. if (Offset == BaseOffset) {
  4740. if (GEP->getType() != I8PtrTy)
  4741. NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
  4742. } else {
  4743. // Calculate the new offset for the new GEP.
  4744. Value *Index = ConstantInt::get(IntPtrTy, Offset - BaseOffset);
  4745. NewGEP = Builder.CreateGEP(I8Ty, NewBaseGEP, Index);
  4746. if (GEP->getType() != I8PtrTy)
  4747. NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
  4748. }
  4749. GEP->replaceAllUsesWith(NewGEP);
  4750. LargeOffsetGEPID.erase(GEP);
  4751. LargeOffsetGEP = LargeOffsetGEPs.erase(LargeOffsetGEP);
  4752. GEP->eraseFromParent();
  4753. Changed = true;
  4754. }
  4755. }
  4756. return Changed;
  4757. }
  4758. /// Return true, if an ext(load) can be formed from an extension in
  4759. /// \p MovedExts.
  4760. bool CodeGenPrepare::canFormExtLd(
  4761. const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
  4762. Instruction *&Inst, bool HasPromoted) {
  4763. for (auto *MovedExtInst : MovedExts) {
  4764. if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
  4765. LI = cast<LoadInst>(MovedExtInst->getOperand(0));
  4766. Inst = MovedExtInst;
  4767. break;
  4768. }
  4769. }
  4770. if (!LI)
  4771. return false;
  4772. // If they're already in the same block, there's nothing to do.
  4773. // Make the cheap checks first if we did not promote.
  4774. // If we promoted, we need to check if it is indeed profitable.
  4775. if (!HasPromoted && LI->getParent() == Inst->getParent())
  4776. return false;
  4777. return TLI->isExtLoad(LI, Inst, *DL);
  4778. }
  4779. /// Move a zext or sext fed by a load into the same basic block as the load,
  4780. /// unless conditions are unfavorable. This allows SelectionDAG to fold the
  4781. /// extend into the load.
  4782. ///
  4783. /// E.g.,
  4784. /// \code
  4785. /// %ld = load i32* %addr
  4786. /// %add = add nuw i32 %ld, 4
  4787. /// %zext = zext i32 %add to i64
  4788. // \endcode
  4789. /// =>
  4790. /// \code
  4791. /// %ld = load i32* %addr
  4792. /// %zext = zext i32 %ld to i64
  4793. /// %add = add nuw i64 %zext, 4
  4794. /// \encode
  4795. /// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
  4796. /// allow us to match zext(load i32*) to i64.
  4797. ///
  4798. /// Also, try to promote the computations used to obtain a sign extended
  4799. /// value used into memory accesses.
  4800. /// E.g.,
  4801. /// \code
  4802. /// a = add nsw i32 b, 3
  4803. /// d = sext i32 a to i64
  4804. /// e = getelementptr ..., i64 d
  4805. /// \endcode
  4806. /// =>
  4807. /// \code
  4808. /// f = sext i32 b to i64
  4809. /// a = add nsw i64 f, 3
  4810. /// e = getelementptr ..., i64 a
  4811. /// \endcode
  4812. ///
  4813. /// \p Inst[in/out] the extension may be modified during the process if some
  4814. /// promotions apply.
  4815. bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
  4816. // ExtLoad formation and address type promotion infrastructure requires TLI to
  4817. // be effective.
  4818. if (!TLI)
  4819. return false;
  4820. bool AllowPromotionWithoutCommonHeader = false;
  4821. /// See if it is an interesting sext operations for the address type
  4822. /// promotion before trying to promote it, e.g., the ones with the right
  4823. /// type and used in memory accesses.
  4824. bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
  4825. *Inst, AllowPromotionWithoutCommonHeader);
  4826. TypePromotionTransaction TPT(RemovedInsts);
  4827. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  4828. TPT.getRestorationPoint();
  4829. SmallVector<Instruction *, 1> Exts;
  4830. SmallVector<Instruction *, 2> SpeculativelyMovedExts;
  4831. Exts.push_back(Inst);
  4832. bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
  4833. // Look for a load being extended.
  4834. LoadInst *LI = nullptr;
  4835. Instruction *ExtFedByLoad;
  4836. // Try to promote a chain of computation if it allows to form an extended
  4837. // load.
  4838. if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
  4839. assert(LI && ExtFedByLoad && "Expect a valid load and extension");
  4840. TPT.commit();
  4841. // Move the extend into the same block as the load
  4842. ExtFedByLoad->moveAfter(LI);
  4843. // CGP does not check if the zext would be speculatively executed when moved
  4844. // to the same basic block as the load. Preserving its original location
  4845. // would pessimize the debugging experience, as well as negatively impact
  4846. // the quality of sample pgo. We don't want to use "line 0" as that has a
  4847. // size cost in the line-table section and logically the zext can be seen as
  4848. // part of the load. Therefore we conservatively reuse the same debug
  4849. // location for the load and the zext.
  4850. ExtFedByLoad->setDebugLoc(LI->getDebugLoc());
  4851. ++NumExtsMoved;
  4852. Inst = ExtFedByLoad;
  4853. return true;
  4854. }
  4855. // Continue promoting SExts if known as considerable depending on targets.
  4856. if (ATPConsiderable &&
  4857. performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
  4858. HasPromoted, TPT, SpeculativelyMovedExts))
  4859. return true;
  4860. TPT.rollback(LastKnownGood);
  4861. return false;
  4862. }
  4863. // Perform address type promotion if doing so is profitable.
  4864. // If AllowPromotionWithoutCommonHeader == false, we should find other sext
  4865. // instructions that sign extended the same initial value. However, if
  4866. // AllowPromotionWithoutCommonHeader == true, we expect promoting the
  4867. // extension is just profitable.
  4868. bool CodeGenPrepare::performAddressTypePromotion(
  4869. Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
  4870. bool HasPromoted, TypePromotionTransaction &TPT,
  4871. SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
  4872. bool Promoted = false;
  4873. SmallPtrSet<Instruction *, 1> UnhandledExts;
  4874. bool AllSeenFirst = true;
  4875. for (auto I : SpeculativelyMovedExts) {
  4876. Value *HeadOfChain = I->getOperand(0);
  4877. DenseMap<Value *, Instruction *>::iterator AlreadySeen =
  4878. SeenChainsForSExt.find(HeadOfChain);
  4879. // If there is an unhandled SExt which has the same header, try to promote
  4880. // it as well.
  4881. if (AlreadySeen != SeenChainsForSExt.end()) {
  4882. if (AlreadySeen->second != nullptr)
  4883. UnhandledExts.insert(AlreadySeen->second);
  4884. AllSeenFirst = false;
  4885. }
  4886. }
  4887. if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
  4888. SpeculativelyMovedExts.size() == 1)) {
  4889. TPT.commit();
  4890. if (HasPromoted)
  4891. Promoted = true;
  4892. for (auto I : SpeculativelyMovedExts) {
  4893. Value *HeadOfChain = I->getOperand(0);
  4894. SeenChainsForSExt[HeadOfChain] = nullptr;
  4895. ValToSExtendedUses[HeadOfChain].push_back(I);
  4896. }
  4897. // Update Inst as promotion happen.
  4898. Inst = SpeculativelyMovedExts.pop_back_val();
  4899. } else {
  4900. // This is the first chain visited from the header, keep the current chain
  4901. // as unhandled. Defer to promote this until we encounter another SExt
  4902. // chain derived from the same header.
  4903. for (auto I : SpeculativelyMovedExts) {
  4904. Value *HeadOfChain = I->getOperand(0);
  4905. SeenChainsForSExt[HeadOfChain] = Inst;
  4906. }
  4907. return false;
  4908. }
  4909. if (!AllSeenFirst && !UnhandledExts.empty())
  4910. for (auto VisitedSExt : UnhandledExts) {
  4911. if (RemovedInsts.count(VisitedSExt))
  4912. continue;
  4913. TypePromotionTransaction TPT(RemovedInsts);
  4914. SmallVector<Instruction *, 1> Exts;
  4915. SmallVector<Instruction *, 2> Chains;
  4916. Exts.push_back(VisitedSExt);
  4917. bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
  4918. TPT.commit();
  4919. if (HasPromoted)
  4920. Promoted = true;
  4921. for (auto I : Chains) {
  4922. Value *HeadOfChain = I->getOperand(0);
  4923. // Mark this as handled.
  4924. SeenChainsForSExt[HeadOfChain] = nullptr;
  4925. ValToSExtendedUses[HeadOfChain].push_back(I);
  4926. }
  4927. }
  4928. return Promoted;
  4929. }
  4930. bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
  4931. BasicBlock *DefBB = I->getParent();
  4932. // If the result of a {s|z}ext and its source are both live out, rewrite all
  4933. // other uses of the source with result of extension.
  4934. Value *Src = I->getOperand(0);
  4935. if (Src->hasOneUse())
  4936. return false;
  4937. // Only do this xform if truncating is free.
  4938. if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
  4939. return false;
  4940. // Only safe to perform the optimization if the source is also defined in
  4941. // this block.
  4942. if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
  4943. return false;
  4944. bool DefIsLiveOut = false;
  4945. for (User *U : I->users()) {
  4946. Instruction *UI = cast<Instruction>(U);
  4947. // Figure out which BB this ext is used in.
  4948. BasicBlock *UserBB = UI->getParent();
  4949. if (UserBB == DefBB) continue;
  4950. DefIsLiveOut = true;
  4951. break;
  4952. }
  4953. if (!DefIsLiveOut)
  4954. return false;
  4955. // Make sure none of the uses are PHI nodes.
  4956. for (User *U : Src->users()) {
  4957. Instruction *UI = cast<Instruction>(U);
  4958. BasicBlock *UserBB = UI->getParent();
  4959. if (UserBB == DefBB) continue;
  4960. // Be conservative. We don't want this xform to end up introducing
  4961. // reloads just before load / store instructions.
  4962. if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
  4963. return false;
  4964. }
  4965. // InsertedTruncs - Only insert one trunc in each block once.
  4966. DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
  4967. bool MadeChange = false;
  4968. for (Use &U : Src->uses()) {
  4969. Instruction *User = cast<Instruction>(U.getUser());
  4970. // Figure out which BB this ext is used in.
  4971. BasicBlock *UserBB = User->getParent();
  4972. if (UserBB == DefBB) continue;
  4973. // Both src and def are live in this block. Rewrite the use.
  4974. Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
  4975. if (!InsertedTrunc) {
  4976. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  4977. assert(InsertPt != UserBB->end());
  4978. InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
  4979. InsertedInsts.insert(InsertedTrunc);
  4980. }
  4981. // Replace a use of the {s|z}ext source with a use of the result.
  4982. U = InsertedTrunc;
  4983. ++NumExtUses;
  4984. MadeChange = true;
  4985. }
  4986. return MadeChange;
  4987. }
  4988. // Find loads whose uses only use some of the loaded value's bits. Add an "and"
  4989. // just after the load if the target can fold this into one extload instruction,
  4990. // with the hope of eliminating some of the other later "and" instructions using
  4991. // the loaded value. "and"s that are made trivially redundant by the insertion
  4992. // of the new "and" are removed by this function, while others (e.g. those whose
  4993. // path from the load goes through a phi) are left for isel to potentially
  4994. // remove.
  4995. //
  4996. // For example:
  4997. //
  4998. // b0:
  4999. // x = load i32
  5000. // ...
  5001. // b1:
  5002. // y = and x, 0xff
  5003. // z = use y
  5004. //
  5005. // becomes:
  5006. //
  5007. // b0:
  5008. // x = load i32
  5009. // x' = and x, 0xff
  5010. // ...
  5011. // b1:
  5012. // z = use x'
  5013. //
  5014. // whereas:
  5015. //
  5016. // b0:
  5017. // x1 = load i32
  5018. // ...
  5019. // b1:
  5020. // x2 = load i32
  5021. // ...
  5022. // b2:
  5023. // x = phi x1, x2
  5024. // y = and x, 0xff
  5025. //
  5026. // becomes (after a call to optimizeLoadExt for each load):
  5027. //
  5028. // b0:
  5029. // x1 = load i32
  5030. // x1' = and x1, 0xff
  5031. // ...
  5032. // b1:
  5033. // x2 = load i32
  5034. // x2' = and x2, 0xff
  5035. // ...
  5036. // b2:
  5037. // x = phi x1', x2'
  5038. // y = and x, 0xff
  5039. bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
  5040. if (!Load->isSimple() || !Load->getType()->isIntOrPtrTy())
  5041. return false;
  5042. // Skip loads we've already transformed.
  5043. if (Load->hasOneUse() &&
  5044. InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
  5045. return false;
  5046. // Look at all uses of Load, looking through phis, to determine how many bits
  5047. // of the loaded value are needed.
  5048. SmallVector<Instruction *, 8> WorkList;
  5049. SmallPtrSet<Instruction *, 16> Visited;
  5050. SmallVector<Instruction *, 8> AndsToMaybeRemove;
  5051. for (auto *U : Load->users())
  5052. WorkList.push_back(cast<Instruction>(U));
  5053. EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
  5054. unsigned BitWidth = LoadResultVT.getSizeInBits();
  5055. APInt DemandBits(BitWidth, 0);
  5056. APInt WidestAndBits(BitWidth, 0);
  5057. while (!WorkList.empty()) {
  5058. Instruction *I = WorkList.back();
  5059. WorkList.pop_back();
  5060. // Break use-def graph loops.
  5061. if (!Visited.insert(I).second)
  5062. continue;
  5063. // For a PHI node, push all of its users.
  5064. if (auto *Phi = dyn_cast<PHINode>(I)) {
  5065. for (auto *U : Phi->users())
  5066. WorkList.push_back(cast<Instruction>(U));
  5067. continue;
  5068. }
  5069. switch (I->getOpcode()) {
  5070. case Instruction::And: {
  5071. auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
  5072. if (!AndC)
  5073. return false;
  5074. APInt AndBits = AndC->getValue();
  5075. DemandBits |= AndBits;
  5076. // Keep track of the widest and mask we see.
  5077. if (AndBits.ugt(WidestAndBits))
  5078. WidestAndBits = AndBits;
  5079. if (AndBits == WidestAndBits && I->getOperand(0) == Load)
  5080. AndsToMaybeRemove.push_back(I);
  5081. break;
  5082. }
  5083. case Instruction::Shl: {
  5084. auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
  5085. if (!ShlC)
  5086. return false;
  5087. uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
  5088. DemandBits.setLowBits(BitWidth - ShiftAmt);
  5089. break;
  5090. }
  5091. case Instruction::Trunc: {
  5092. EVT TruncVT = TLI->getValueType(*DL, I->getType());
  5093. unsigned TruncBitWidth = TruncVT.getSizeInBits();
  5094. DemandBits.setLowBits(TruncBitWidth);
  5095. break;
  5096. }
  5097. default:
  5098. return false;
  5099. }
  5100. }
  5101. uint32_t ActiveBits = DemandBits.getActiveBits();
  5102. // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
  5103. // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
  5104. // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
  5105. // (and (load x) 1) is not matched as a single instruction, rather as a LDR
  5106. // followed by an AND.
  5107. // TODO: Look into removing this restriction by fixing backends to either
  5108. // return false for isLoadExtLegal for i1 or have them select this pattern to
  5109. // a single instruction.
  5110. //
  5111. // Also avoid hoisting if we didn't see any ands with the exact DemandBits
  5112. // mask, since these are the only ands that will be removed by isel.
  5113. if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
  5114. WidestAndBits != DemandBits)
  5115. return false;
  5116. LLVMContext &Ctx = Load->getType()->getContext();
  5117. Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
  5118. EVT TruncVT = TLI->getValueType(*DL, TruncTy);
  5119. // Reject cases that won't be matched as extloads.
  5120. if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
  5121. !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
  5122. return false;
  5123. IRBuilder<> Builder(Load->getNextNode());
  5124. auto *NewAnd = dyn_cast<Instruction>(
  5125. Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
  5126. // Mark this instruction as "inserted by CGP", so that other
  5127. // optimizations don't touch it.
  5128. InsertedInsts.insert(NewAnd);
  5129. // Replace all uses of load with new and (except for the use of load in the
  5130. // new and itself).
  5131. Load->replaceAllUsesWith(NewAnd);
  5132. NewAnd->setOperand(0, Load);
  5133. // Remove any and instructions that are now redundant.
  5134. for (auto *And : AndsToMaybeRemove)
  5135. // Check that the and mask is the same as the one we decided to put on the
  5136. // new and.
  5137. if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
  5138. And->replaceAllUsesWith(NewAnd);
  5139. if (&*CurInstIterator == And)
  5140. CurInstIterator = std::next(And->getIterator());
  5141. And->eraseFromParent();
  5142. ++NumAndUses;
  5143. }
  5144. ++NumAndsAdded;
  5145. return true;
  5146. }
  5147. /// Check if V (an operand of a select instruction) is an expensive instruction
  5148. /// that is only used once.
  5149. static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
  5150. auto *I = dyn_cast<Instruction>(V);
  5151. // If it's safe to speculatively execute, then it should not have side
  5152. // effects; therefore, it's safe to sink and possibly *not* execute.
  5153. return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
  5154. TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
  5155. }
  5156. /// Returns true if a SelectInst should be turned into an explicit branch.
  5157. static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
  5158. const TargetLowering *TLI,
  5159. SelectInst *SI) {
  5160. // If even a predictable select is cheap, then a branch can't be cheaper.
  5161. if (!TLI->isPredictableSelectExpensive())
  5162. return false;
  5163. // FIXME: This should use the same heuristics as IfConversion to determine
  5164. // whether a select is better represented as a branch.
  5165. // If metadata tells us that the select condition is obviously predictable,
  5166. // then we want to replace the select with a branch.
  5167. uint64_t TrueWeight, FalseWeight;
  5168. if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
  5169. uint64_t Max = std::max(TrueWeight, FalseWeight);
  5170. uint64_t Sum = TrueWeight + FalseWeight;
  5171. if (Sum != 0) {
  5172. auto Probability = BranchProbability::getBranchProbability(Max, Sum);
  5173. if (Probability > TLI->getPredictableBranchThreshold())
  5174. return true;
  5175. }
  5176. }
  5177. CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
  5178. // If a branch is predictable, an out-of-order CPU can avoid blocking on its
  5179. // comparison condition. If the compare has more than one use, there's
  5180. // probably another cmov or setcc around, so it's not worth emitting a branch.
  5181. if (!Cmp || !Cmp->hasOneUse())
  5182. return false;
  5183. // If either operand of the select is expensive and only needed on one side
  5184. // of the select, we should form a branch.
  5185. if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
  5186. sinkSelectOperand(TTI, SI->getFalseValue()))
  5187. return true;
  5188. return false;
  5189. }
  5190. /// If \p isTrue is true, return the true value of \p SI, otherwise return
  5191. /// false value of \p SI. If the true/false value of \p SI is defined by any
  5192. /// select instructions in \p Selects, look through the defining select
  5193. /// instruction until the true/false value is not defined in \p Selects.
  5194. static Value *getTrueOrFalseValue(
  5195. SelectInst *SI, bool isTrue,
  5196. const SmallPtrSet<const Instruction *, 2> &Selects) {
  5197. Value *V = nullptr;
  5198. for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
  5199. DefSI = dyn_cast<SelectInst>(V)) {
  5200. assert(DefSI->getCondition() == SI->getCondition() &&
  5201. "The condition of DefSI does not match with SI");
  5202. V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
  5203. }
  5204. assert(V && "Failed to get select true/false value");
  5205. return V;
  5206. }
  5207. bool CodeGenPrepare::optimizeShiftInst(BinaryOperator *Shift) {
  5208. assert(Shift->isShift() && "Expected a shift");
  5209. // If this is (1) a vector shift, (2) shifts by scalars are cheaper than
  5210. // general vector shifts, and (3) the shift amount is a select-of-splatted
  5211. // values, hoist the shifts before the select:
  5212. // shift Op0, (select Cond, TVal, FVal) -->
  5213. // select Cond, (shift Op0, TVal), (shift Op0, FVal)
  5214. //
  5215. // This is inverting a generic IR transform when we know that the cost of a
  5216. // general vector shift is more than the cost of 2 shift-by-scalars.
  5217. // We can't do this effectively in SDAG because we may not be able to
  5218. // determine if the select operands are splats from within a basic block.
  5219. Type *Ty = Shift->getType();
  5220. if (!Ty->isVectorTy() || !TLI->isVectorShiftByScalarCheap(Ty))
  5221. return false;
  5222. Value *Cond, *TVal, *FVal;
  5223. if (!match(Shift->getOperand(1),
  5224. m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))))
  5225. return false;
  5226. if (!isSplatValue(TVal) || !isSplatValue(FVal))
  5227. return false;
  5228. IRBuilder<> Builder(Shift);
  5229. BinaryOperator::BinaryOps Opcode = Shift->getOpcode();
  5230. Value *NewTVal = Builder.CreateBinOp(Opcode, Shift->getOperand(0), TVal);
  5231. Value *NewFVal = Builder.CreateBinOp(Opcode, Shift->getOperand(0), FVal);
  5232. Value *NewSel = Builder.CreateSelect(Cond, NewTVal, NewFVal);
  5233. Shift->replaceAllUsesWith(NewSel);
  5234. Shift->eraseFromParent();
  5235. return true;
  5236. }
  5237. /// If we have a SelectInst that will likely profit from branch prediction,
  5238. /// turn it into a branch.
  5239. bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
  5240. // If branch conversion isn't desirable, exit early.
  5241. if (DisableSelectToBranch || OptSize || !TLI)
  5242. return false;
  5243. // Find all consecutive select instructions that share the same condition.
  5244. SmallVector<SelectInst *, 2> ASI;
  5245. ASI.push_back(SI);
  5246. for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
  5247. It != SI->getParent()->end(); ++It) {
  5248. SelectInst *I = dyn_cast<SelectInst>(&*It);
  5249. if (I && SI->getCondition() == I->getCondition()) {
  5250. ASI.push_back(I);
  5251. } else {
  5252. break;
  5253. }
  5254. }
  5255. SelectInst *LastSI = ASI.back();
  5256. // Increment the current iterator to skip all the rest of select instructions
  5257. // because they will be either "not lowered" or "all lowered" to branch.
  5258. CurInstIterator = std::next(LastSI->getIterator());
  5259. bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
  5260. // Can we convert the 'select' to CF ?
  5261. if (VectorCond || SI->getMetadata(LLVMContext::MD_unpredictable))
  5262. return false;
  5263. TargetLowering::SelectSupportKind SelectKind;
  5264. if (VectorCond)
  5265. SelectKind = TargetLowering::VectorMaskSelect;
  5266. else if (SI->getType()->isVectorTy())
  5267. SelectKind = TargetLowering::ScalarCondVectorVal;
  5268. else
  5269. SelectKind = TargetLowering::ScalarValSelect;
  5270. if (TLI->isSelectSupported(SelectKind) &&
  5271. !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
  5272. return false;
  5273. // The DominatorTree needs to be rebuilt by any consumers after this
  5274. // transformation. We simply reset here rather than setting the ModifiedDT
  5275. // flag to avoid restarting the function walk in runOnFunction for each
  5276. // select optimized.
  5277. DT.reset();
  5278. // Transform a sequence like this:
  5279. // start:
  5280. // %cmp = cmp uge i32 %a, %b
  5281. // %sel = select i1 %cmp, i32 %c, i32 %d
  5282. //
  5283. // Into:
  5284. // start:
  5285. // %cmp = cmp uge i32 %a, %b
  5286. // br i1 %cmp, label %select.true, label %select.false
  5287. // select.true:
  5288. // br label %select.end
  5289. // select.false:
  5290. // br label %select.end
  5291. // select.end:
  5292. // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
  5293. //
  5294. // In addition, we may sink instructions that produce %c or %d from
  5295. // the entry block into the destination(s) of the new branch.
  5296. // If the true or false blocks do not contain a sunken instruction, that
  5297. // block and its branch may be optimized away. In that case, one side of the
  5298. // first branch will point directly to select.end, and the corresponding PHI
  5299. // predecessor block will be the start block.
  5300. // First, we split the block containing the select into 2 blocks.
  5301. BasicBlock *StartBlock = SI->getParent();
  5302. BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
  5303. BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
  5304. // Delete the unconditional branch that was just created by the split.
  5305. StartBlock->getTerminator()->eraseFromParent();
  5306. // These are the new basic blocks for the conditional branch.
  5307. // At least one will become an actual new basic block.
  5308. BasicBlock *TrueBlock = nullptr;
  5309. BasicBlock *FalseBlock = nullptr;
  5310. BranchInst *TrueBranch = nullptr;
  5311. BranchInst *FalseBranch = nullptr;
  5312. // Sink expensive instructions into the conditional blocks to avoid executing
  5313. // them speculatively.
  5314. for (SelectInst *SI : ASI) {
  5315. if (sinkSelectOperand(TTI, SI->getTrueValue())) {
  5316. if (TrueBlock == nullptr) {
  5317. TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
  5318. EndBlock->getParent(), EndBlock);
  5319. TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
  5320. TrueBranch->setDebugLoc(SI->getDebugLoc());
  5321. }
  5322. auto *TrueInst = cast<Instruction>(SI->getTrueValue());
  5323. TrueInst->moveBefore(TrueBranch);
  5324. }
  5325. if (sinkSelectOperand(TTI, SI->getFalseValue())) {
  5326. if (FalseBlock == nullptr) {
  5327. FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
  5328. EndBlock->getParent(), EndBlock);
  5329. FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
  5330. FalseBranch->setDebugLoc(SI->getDebugLoc());
  5331. }
  5332. auto *FalseInst = cast<Instruction>(SI->getFalseValue());
  5333. FalseInst->moveBefore(FalseBranch);
  5334. }
  5335. }
  5336. // If there was nothing to sink, then arbitrarily choose the 'false' side
  5337. // for a new input value to the PHI.
  5338. if (TrueBlock == FalseBlock) {
  5339. assert(TrueBlock == nullptr &&
  5340. "Unexpected basic block transform while optimizing select");
  5341. FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
  5342. EndBlock->getParent(), EndBlock);
  5343. auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
  5344. FalseBranch->setDebugLoc(SI->getDebugLoc());
  5345. }
  5346. // Insert the real conditional branch based on the original condition.
  5347. // If we did not create a new block for one of the 'true' or 'false' paths
  5348. // of the condition, it means that side of the branch goes to the end block
  5349. // directly and the path originates from the start block from the point of
  5350. // view of the new PHI.
  5351. BasicBlock *TT, *FT;
  5352. if (TrueBlock == nullptr) {
  5353. TT = EndBlock;
  5354. FT = FalseBlock;
  5355. TrueBlock = StartBlock;
  5356. } else if (FalseBlock == nullptr) {
  5357. TT = TrueBlock;
  5358. FT = EndBlock;
  5359. FalseBlock = StartBlock;
  5360. } else {
  5361. TT = TrueBlock;
  5362. FT = FalseBlock;
  5363. }
  5364. IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
  5365. SmallPtrSet<const Instruction *, 2> INS;
  5366. INS.insert(ASI.begin(), ASI.end());
  5367. // Use reverse iterator because later select may use the value of the
  5368. // earlier select, and we need to propagate value through earlier select
  5369. // to get the PHI operand.
  5370. for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
  5371. SelectInst *SI = *It;
  5372. // The select itself is replaced with a PHI Node.
  5373. PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
  5374. PN->takeName(SI);
  5375. PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
  5376. PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
  5377. PN->setDebugLoc(SI->getDebugLoc());
  5378. SI->replaceAllUsesWith(PN);
  5379. SI->eraseFromParent();
  5380. INS.erase(SI);
  5381. ++NumSelectsExpanded;
  5382. }
  5383. // Instruct OptimizeBlock to skip to the next block.
  5384. CurInstIterator = StartBlock->end();
  5385. return true;
  5386. }
  5387. static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
  5388. SmallVector<int, 16> Mask(SVI->getShuffleMask());
  5389. int SplatElem = -1;
  5390. for (unsigned i = 0; i < Mask.size(); ++i) {
  5391. if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
  5392. return false;
  5393. SplatElem = Mask[i];
  5394. }
  5395. return true;
  5396. }
  5397. /// Some targets have expensive vector shifts if the lanes aren't all the same
  5398. /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
  5399. /// it's often worth sinking a shufflevector splat down to its use so that
  5400. /// codegen can spot all lanes are identical.
  5401. bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
  5402. BasicBlock *DefBB = SVI->getParent();
  5403. // Only do this xform if variable vector shifts are particularly expensive.
  5404. if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
  5405. return false;
  5406. // We only expect better codegen by sinking a shuffle if we can recognise a
  5407. // constant splat.
  5408. if (!isBroadcastShuffle(SVI))
  5409. return false;
  5410. // InsertedShuffles - Only insert a shuffle in each block once.
  5411. DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
  5412. bool MadeChange = false;
  5413. for (User *U : SVI->users()) {
  5414. Instruction *UI = cast<Instruction>(U);
  5415. // Figure out which BB this ext is used in.
  5416. BasicBlock *UserBB = UI->getParent();
  5417. if (UserBB == DefBB) continue;
  5418. // For now only apply this when the splat is used by a shift instruction.
  5419. if (!UI->isShift()) continue;
  5420. // Everything checks out, sink the shuffle if the user's block doesn't
  5421. // already have a copy.
  5422. Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
  5423. if (!InsertedShuffle) {
  5424. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  5425. assert(InsertPt != UserBB->end());
  5426. InsertedShuffle =
  5427. new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
  5428. SVI->getOperand(2), "", &*InsertPt);
  5429. InsertedShuffle->setDebugLoc(SVI->getDebugLoc());
  5430. }
  5431. UI->replaceUsesOfWith(SVI, InsertedShuffle);
  5432. MadeChange = true;
  5433. }
  5434. // If we removed all uses, nuke the shuffle.
  5435. if (SVI->use_empty()) {
  5436. SVI->eraseFromParent();
  5437. MadeChange = true;
  5438. }
  5439. return MadeChange;
  5440. }
  5441. bool CodeGenPrepare::tryToSinkFreeOperands(Instruction *I) {
  5442. // If the operands of I can be folded into a target instruction together with
  5443. // I, duplicate and sink them.
  5444. SmallVector<Use *, 4> OpsToSink;
  5445. if (!TLI || !TLI->shouldSinkOperands(I, OpsToSink))
  5446. return false;
  5447. // OpsToSink can contain multiple uses in a use chain (e.g.
  5448. // (%u1 with %u1 = shufflevector), (%u2 with %u2 = zext %u1)). The dominating
  5449. // uses must come first, so we process the ops in reverse order so as to not
  5450. // create invalid IR.
  5451. BasicBlock *TargetBB = I->getParent();
  5452. bool Changed = false;
  5453. SmallVector<Use *, 4> ToReplace;
  5454. for (Use *U : reverse(OpsToSink)) {
  5455. auto *UI = cast<Instruction>(U->get());
  5456. if (UI->getParent() == TargetBB || isa<PHINode>(UI))
  5457. continue;
  5458. ToReplace.push_back(U);
  5459. }
  5460. SetVector<Instruction *> MaybeDead;
  5461. DenseMap<Instruction *, Instruction *> NewInstructions;
  5462. Instruction *InsertPoint = I;
  5463. for (Use *U : ToReplace) {
  5464. auto *UI = cast<Instruction>(U->get());
  5465. Instruction *NI = UI->clone();
  5466. NewInstructions[UI] = NI;
  5467. MaybeDead.insert(UI);
  5468. LLVM_DEBUG(dbgs() << "Sinking " << *UI << " to user " << *I << "\n");
  5469. NI->insertBefore(InsertPoint);
  5470. InsertPoint = NI;
  5471. InsertedInsts.insert(NI);
  5472. // Update the use for the new instruction, making sure that we update the
  5473. // sunk instruction uses, if it is part of a chain that has already been
  5474. // sunk.
  5475. Instruction *OldI = cast<Instruction>(U->getUser());
  5476. if (NewInstructions.count(OldI))
  5477. NewInstructions[OldI]->setOperand(U->getOperandNo(), NI);
  5478. else
  5479. U->set(NI);
  5480. Changed = true;
  5481. }
  5482. // Remove instructions that are dead after sinking.
  5483. for (auto *I : MaybeDead) {
  5484. if (!I->hasNUsesOrMore(1)) {
  5485. LLVM_DEBUG(dbgs() << "Removing dead instruction: " << *I << "\n");
  5486. I->eraseFromParent();
  5487. }
  5488. }
  5489. return Changed;
  5490. }
  5491. bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
  5492. if (!TLI || !DL)
  5493. return false;
  5494. Value *Cond = SI->getCondition();
  5495. Type *OldType = Cond->getType();
  5496. LLVMContext &Context = Cond->getContext();
  5497. MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
  5498. unsigned RegWidth = RegType.getSizeInBits();
  5499. if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
  5500. return false;
  5501. // If the register width is greater than the type width, expand the condition
  5502. // of the switch instruction and each case constant to the width of the
  5503. // register. By widening the type of the switch condition, subsequent
  5504. // comparisons (for case comparisons) will not need to be extended to the
  5505. // preferred register width, so we will potentially eliminate N-1 extends,
  5506. // where N is the number of cases in the switch.
  5507. auto *NewType = Type::getIntNTy(Context, RegWidth);
  5508. // Zero-extend the switch condition and case constants unless the switch
  5509. // condition is a function argument that is already being sign-extended.
  5510. // In that case, we can avoid an unnecessary mask/extension by sign-extending
  5511. // everything instead.
  5512. Instruction::CastOps ExtType = Instruction::ZExt;
  5513. if (auto *Arg = dyn_cast<Argument>(Cond))
  5514. if (Arg->hasSExtAttr())
  5515. ExtType = Instruction::SExt;
  5516. auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
  5517. ExtInst->insertBefore(SI);
  5518. ExtInst->setDebugLoc(SI->getDebugLoc());
  5519. SI->setCondition(ExtInst);
  5520. for (auto Case : SI->cases()) {
  5521. APInt NarrowConst = Case.getCaseValue()->getValue();
  5522. APInt WideConst = (ExtType == Instruction::ZExt) ?
  5523. NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
  5524. Case.setValue(ConstantInt::get(Context, WideConst));
  5525. }
  5526. return true;
  5527. }
  5528. namespace {
  5529. /// Helper class to promote a scalar operation to a vector one.
  5530. /// This class is used to move downward extractelement transition.
  5531. /// E.g.,
  5532. /// a = vector_op <2 x i32>
  5533. /// b = extractelement <2 x i32> a, i32 0
  5534. /// c = scalar_op b
  5535. /// store c
  5536. ///
  5537. /// =>
  5538. /// a = vector_op <2 x i32>
  5539. /// c = vector_op a (equivalent to scalar_op on the related lane)
  5540. /// * d = extractelement <2 x i32> c, i32 0
  5541. /// * store d
  5542. /// Assuming both extractelement and store can be combine, we get rid of the
  5543. /// transition.
  5544. class VectorPromoteHelper {
  5545. /// DataLayout associated with the current module.
  5546. const DataLayout &DL;
  5547. /// Used to perform some checks on the legality of vector operations.
  5548. const TargetLowering &TLI;
  5549. /// Used to estimated the cost of the promoted chain.
  5550. const TargetTransformInfo &TTI;
  5551. /// The transition being moved downwards.
  5552. Instruction *Transition;
  5553. /// The sequence of instructions to be promoted.
  5554. SmallVector<Instruction *, 4> InstsToBePromoted;
  5555. /// Cost of combining a store and an extract.
  5556. unsigned StoreExtractCombineCost;
  5557. /// Instruction that will be combined with the transition.
  5558. Instruction *CombineInst = nullptr;
  5559. /// The instruction that represents the current end of the transition.
  5560. /// Since we are faking the promotion until we reach the end of the chain
  5561. /// of computation, we need a way to get the current end of the transition.
  5562. Instruction *getEndOfTransition() const {
  5563. if (InstsToBePromoted.empty())
  5564. return Transition;
  5565. return InstsToBePromoted.back();
  5566. }
  5567. /// Return the index of the original value in the transition.
  5568. /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
  5569. /// c, is at index 0.
  5570. unsigned getTransitionOriginalValueIdx() const {
  5571. assert(isa<ExtractElementInst>(Transition) &&
  5572. "Other kind of transitions are not supported yet");
  5573. return 0;
  5574. }
  5575. /// Return the index of the index in the transition.
  5576. /// E.g., for "extractelement <2 x i32> c, i32 0" the index
  5577. /// is at index 1.
  5578. unsigned getTransitionIdx() const {
  5579. assert(isa<ExtractElementInst>(Transition) &&
  5580. "Other kind of transitions are not supported yet");
  5581. return 1;
  5582. }
  5583. /// Get the type of the transition.
  5584. /// This is the type of the original value.
  5585. /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
  5586. /// transition is <2 x i32>.
  5587. Type *getTransitionType() const {
  5588. return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
  5589. }
  5590. /// Promote \p ToBePromoted by moving \p Def downward through.
  5591. /// I.e., we have the following sequence:
  5592. /// Def = Transition <ty1> a to <ty2>
  5593. /// b = ToBePromoted <ty2> Def, ...
  5594. /// =>
  5595. /// b = ToBePromoted <ty1> a, ...
  5596. /// Def = Transition <ty1> ToBePromoted to <ty2>
  5597. void promoteImpl(Instruction *ToBePromoted);
  5598. /// Check whether or not it is profitable to promote all the
  5599. /// instructions enqueued to be promoted.
  5600. bool isProfitableToPromote() {
  5601. Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
  5602. unsigned Index = isa<ConstantInt>(ValIdx)
  5603. ? cast<ConstantInt>(ValIdx)->getZExtValue()
  5604. : -1;
  5605. Type *PromotedType = getTransitionType();
  5606. StoreInst *ST = cast<StoreInst>(CombineInst);
  5607. unsigned AS = ST->getPointerAddressSpace();
  5608. unsigned Align = ST->getAlignment();
  5609. // Check if this store is supported.
  5610. if (!TLI.allowsMisalignedMemoryAccesses(
  5611. TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
  5612. Align)) {
  5613. // If this is not supported, there is no way we can combine
  5614. // the extract with the store.
  5615. return false;
  5616. }
  5617. // The scalar chain of computation has to pay for the transition
  5618. // scalar to vector.
  5619. // The vector chain has to account for the combining cost.
  5620. uint64_t ScalarCost =
  5621. TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
  5622. uint64_t VectorCost = StoreExtractCombineCost;
  5623. for (const auto &Inst : InstsToBePromoted) {
  5624. // Compute the cost.
  5625. // By construction, all instructions being promoted are arithmetic ones.
  5626. // Moreover, one argument is a constant that can be viewed as a splat
  5627. // constant.
  5628. Value *Arg0 = Inst->getOperand(0);
  5629. bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
  5630. isa<ConstantFP>(Arg0);
  5631. TargetTransformInfo::OperandValueKind Arg0OVK =
  5632. IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
  5633. : TargetTransformInfo::OK_AnyValue;
  5634. TargetTransformInfo::OperandValueKind Arg1OVK =
  5635. !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
  5636. : TargetTransformInfo::OK_AnyValue;
  5637. ScalarCost += TTI.getArithmeticInstrCost(
  5638. Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
  5639. VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
  5640. Arg0OVK, Arg1OVK);
  5641. }
  5642. LLVM_DEBUG(
  5643. dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
  5644. << ScalarCost << "\nVector: " << VectorCost << '\n');
  5645. return ScalarCost > VectorCost;
  5646. }
  5647. /// Generate a constant vector with \p Val with the same
  5648. /// number of elements as the transition.
  5649. /// \p UseSplat defines whether or not \p Val should be replicated
  5650. /// across the whole vector.
  5651. /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
  5652. /// otherwise we generate a vector with as many undef as possible:
  5653. /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
  5654. /// used at the index of the extract.
  5655. Value *getConstantVector(Constant *Val, bool UseSplat) const {
  5656. unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
  5657. if (!UseSplat) {
  5658. // If we cannot determine where the constant must be, we have to
  5659. // use a splat constant.
  5660. Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
  5661. if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
  5662. ExtractIdx = CstVal->getSExtValue();
  5663. else
  5664. UseSplat = true;
  5665. }
  5666. unsigned End = getTransitionType()->getVectorNumElements();
  5667. if (UseSplat)
  5668. return ConstantVector::getSplat(End, Val);
  5669. SmallVector<Constant *, 4> ConstVec;
  5670. UndefValue *UndefVal = UndefValue::get(Val->getType());
  5671. for (unsigned Idx = 0; Idx != End; ++Idx) {
  5672. if (Idx == ExtractIdx)
  5673. ConstVec.push_back(Val);
  5674. else
  5675. ConstVec.push_back(UndefVal);
  5676. }
  5677. return ConstantVector::get(ConstVec);
  5678. }
  5679. /// Check if promoting to a vector type an operand at \p OperandIdx
  5680. /// in \p Use can trigger undefined behavior.
  5681. static bool canCauseUndefinedBehavior(const Instruction *Use,
  5682. unsigned OperandIdx) {
  5683. // This is not safe to introduce undef when the operand is on
  5684. // the right hand side of a division-like instruction.
  5685. if (OperandIdx != 1)
  5686. return false;
  5687. switch (Use->getOpcode()) {
  5688. default:
  5689. return false;
  5690. case Instruction::SDiv:
  5691. case Instruction::UDiv:
  5692. case Instruction::SRem:
  5693. case Instruction::URem:
  5694. return true;
  5695. case Instruction::FDiv:
  5696. case Instruction::FRem:
  5697. return !Use->hasNoNaNs();
  5698. }
  5699. llvm_unreachable(nullptr);
  5700. }
  5701. public:
  5702. VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
  5703. const TargetTransformInfo &TTI, Instruction *Transition,
  5704. unsigned CombineCost)
  5705. : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
  5706. StoreExtractCombineCost(CombineCost) {
  5707. assert(Transition && "Do not know how to promote null");
  5708. }
  5709. /// Check if we can promote \p ToBePromoted to \p Type.
  5710. bool canPromote(const Instruction *ToBePromoted) const {
  5711. // We could support CastInst too.
  5712. return isa<BinaryOperator>(ToBePromoted);
  5713. }
  5714. /// Check if it is profitable to promote \p ToBePromoted
  5715. /// by moving downward the transition through.
  5716. bool shouldPromote(const Instruction *ToBePromoted) const {
  5717. // Promote only if all the operands can be statically expanded.
  5718. // Indeed, we do not want to introduce any new kind of transitions.
  5719. for (const Use &U : ToBePromoted->operands()) {
  5720. const Value *Val = U.get();
  5721. if (Val == getEndOfTransition()) {
  5722. // If the use is a division and the transition is on the rhs,
  5723. // we cannot promote the operation, otherwise we may create a
  5724. // division by zero.
  5725. if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
  5726. return false;
  5727. continue;
  5728. }
  5729. if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
  5730. !isa<ConstantFP>(Val))
  5731. return false;
  5732. }
  5733. // Check that the resulting operation is legal.
  5734. int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
  5735. if (!ISDOpcode)
  5736. return false;
  5737. return StressStoreExtract ||
  5738. TLI.isOperationLegalOrCustom(
  5739. ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
  5740. }
  5741. /// Check whether or not \p Use can be combined
  5742. /// with the transition.
  5743. /// I.e., is it possible to do Use(Transition) => AnotherUse?
  5744. bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
  5745. /// Record \p ToBePromoted as part of the chain to be promoted.
  5746. void enqueueForPromotion(Instruction *ToBePromoted) {
  5747. InstsToBePromoted.push_back(ToBePromoted);
  5748. }
  5749. /// Set the instruction that will be combined with the transition.
  5750. void recordCombineInstruction(Instruction *ToBeCombined) {
  5751. assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
  5752. CombineInst = ToBeCombined;
  5753. }
  5754. /// Promote all the instructions enqueued for promotion if it is
  5755. /// is profitable.
  5756. /// \return True if the promotion happened, false otherwise.
  5757. bool promote() {
  5758. // Check if there is something to promote.
  5759. // Right now, if we do not have anything to combine with,
  5760. // we assume the promotion is not profitable.
  5761. if (InstsToBePromoted.empty() || !CombineInst)
  5762. return false;
  5763. // Check cost.
  5764. if (!StressStoreExtract && !isProfitableToPromote())
  5765. return false;
  5766. // Promote.
  5767. for (auto &ToBePromoted : InstsToBePromoted)
  5768. promoteImpl(ToBePromoted);
  5769. InstsToBePromoted.clear();
  5770. return true;
  5771. }
  5772. };
  5773. } // end anonymous namespace
  5774. void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
  5775. // At this point, we know that all the operands of ToBePromoted but Def
  5776. // can be statically promoted.
  5777. // For Def, we need to use its parameter in ToBePromoted:
  5778. // b = ToBePromoted ty1 a
  5779. // Def = Transition ty1 b to ty2
  5780. // Move the transition down.
  5781. // 1. Replace all uses of the promoted operation by the transition.
  5782. // = ... b => = ... Def.
  5783. assert(ToBePromoted->getType() == Transition->getType() &&
  5784. "The type of the result of the transition does not match "
  5785. "the final type");
  5786. ToBePromoted->replaceAllUsesWith(Transition);
  5787. // 2. Update the type of the uses.
  5788. // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
  5789. Type *TransitionTy = getTransitionType();
  5790. ToBePromoted->mutateType(TransitionTy);
  5791. // 3. Update all the operands of the promoted operation with promoted
  5792. // operands.
  5793. // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
  5794. for (Use &U : ToBePromoted->operands()) {
  5795. Value *Val = U.get();
  5796. Value *NewVal = nullptr;
  5797. if (Val == Transition)
  5798. NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
  5799. else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
  5800. isa<ConstantFP>(Val)) {
  5801. // Use a splat constant if it is not safe to use undef.
  5802. NewVal = getConstantVector(
  5803. cast<Constant>(Val),
  5804. isa<UndefValue>(Val) ||
  5805. canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
  5806. } else
  5807. llvm_unreachable("Did you modified shouldPromote and forgot to update "
  5808. "this?");
  5809. ToBePromoted->setOperand(U.getOperandNo(), NewVal);
  5810. }
  5811. Transition->moveAfter(ToBePromoted);
  5812. Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
  5813. }
  5814. /// Some targets can do store(extractelement) with one instruction.
  5815. /// Try to push the extractelement towards the stores when the target
  5816. /// has this feature and this is profitable.
  5817. bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
  5818. unsigned CombineCost = std::numeric_limits<unsigned>::max();
  5819. if (DisableStoreExtract || !TLI ||
  5820. (!StressStoreExtract &&
  5821. !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
  5822. Inst->getOperand(1), CombineCost)))
  5823. return false;
  5824. // At this point we know that Inst is a vector to scalar transition.
  5825. // Try to move it down the def-use chain, until:
  5826. // - We can combine the transition with its single use
  5827. // => we got rid of the transition.
  5828. // - We escape the current basic block
  5829. // => we would need to check that we are moving it at a cheaper place and
  5830. // we do not do that for now.
  5831. BasicBlock *Parent = Inst->getParent();
  5832. LLVM_DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
  5833. VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
  5834. // If the transition has more than one use, assume this is not going to be
  5835. // beneficial.
  5836. while (Inst->hasOneUse()) {
  5837. Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
  5838. LLVM_DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
  5839. if (ToBePromoted->getParent() != Parent) {
  5840. LLVM_DEBUG(dbgs() << "Instruction to promote is in a different block ("
  5841. << ToBePromoted->getParent()->getName()
  5842. << ") than the transition (" << Parent->getName()
  5843. << ").\n");
  5844. return false;
  5845. }
  5846. if (VPH.canCombine(ToBePromoted)) {
  5847. LLVM_DEBUG(dbgs() << "Assume " << *Inst << '\n'
  5848. << "will be combined with: " << *ToBePromoted << '\n');
  5849. VPH.recordCombineInstruction(ToBePromoted);
  5850. bool Changed = VPH.promote();
  5851. NumStoreExtractExposed += Changed;
  5852. return Changed;
  5853. }
  5854. LLVM_DEBUG(dbgs() << "Try promoting.\n");
  5855. if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
  5856. return false;
  5857. LLVM_DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
  5858. VPH.enqueueForPromotion(ToBePromoted);
  5859. Inst = ToBePromoted;
  5860. }
  5861. return false;
  5862. }
  5863. /// For the instruction sequence of store below, F and I values
  5864. /// are bundled together as an i64 value before being stored into memory.
  5865. /// Sometimes it is more efficient to generate separate stores for F and I,
  5866. /// which can remove the bitwise instructions or sink them to colder places.
  5867. ///
  5868. /// (store (or (zext (bitcast F to i32) to i64),
  5869. /// (shl (zext I to i64), 32)), addr) -->
  5870. /// (store F, addr) and (store I, addr+4)
  5871. ///
  5872. /// Similarly, splitting for other merged store can also be beneficial, like:
  5873. /// For pair of {i32, i32}, i64 store --> two i32 stores.
  5874. /// For pair of {i32, i16}, i64 store --> two i32 stores.
  5875. /// For pair of {i16, i16}, i32 store --> two i16 stores.
  5876. /// For pair of {i16, i8}, i32 store --> two i16 stores.
  5877. /// For pair of {i8, i8}, i16 store --> two i8 stores.
  5878. ///
  5879. /// We allow each target to determine specifically which kind of splitting is
  5880. /// supported.
  5881. ///
  5882. /// The store patterns are commonly seen from the simple code snippet below
  5883. /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
  5884. /// void goo(const std::pair<int, float> &);
  5885. /// hoo() {
  5886. /// ...
  5887. /// goo(std::make_pair(tmp, ftmp));
  5888. /// ...
  5889. /// }
  5890. ///
  5891. /// Although we already have similar splitting in DAG Combine, we duplicate
  5892. /// it in CodeGenPrepare to catch the case in which pattern is across
  5893. /// multiple BBs. The logic in DAG Combine is kept to catch case generated
  5894. /// during code expansion.
  5895. static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
  5896. const TargetLowering &TLI) {
  5897. // Handle simple but common cases only.
  5898. Type *StoreType = SI.getValueOperand()->getType();
  5899. if (!DL.typeSizeEqualsStoreSize(StoreType) ||
  5900. DL.getTypeSizeInBits(StoreType) == 0)
  5901. return false;
  5902. unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
  5903. Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
  5904. if (!DL.typeSizeEqualsStoreSize(SplitStoreType))
  5905. return false;
  5906. // Don't split the store if it is volatile.
  5907. if (SI.isVolatile())
  5908. return false;
  5909. // Match the following patterns:
  5910. // (store (or (zext LValue to i64),
  5911. // (shl (zext HValue to i64), 32)), HalfValBitSize)
  5912. // or
  5913. // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
  5914. // (zext LValue to i64),
  5915. // Expect both operands of OR and the first operand of SHL have only
  5916. // one use.
  5917. Value *LValue, *HValue;
  5918. if (!match(SI.getValueOperand(),
  5919. m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
  5920. m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
  5921. m_SpecificInt(HalfValBitSize))))))
  5922. return false;
  5923. // Check LValue and HValue are int with size less or equal than 32.
  5924. if (!LValue->getType()->isIntegerTy() ||
  5925. DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
  5926. !HValue->getType()->isIntegerTy() ||
  5927. DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
  5928. return false;
  5929. // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
  5930. // as the input of target query.
  5931. auto *LBC = dyn_cast<BitCastInst>(LValue);
  5932. auto *HBC = dyn_cast<BitCastInst>(HValue);
  5933. EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
  5934. : EVT::getEVT(LValue->getType());
  5935. EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
  5936. : EVT::getEVT(HValue->getType());
  5937. if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
  5938. return false;
  5939. // Start to split store.
  5940. IRBuilder<> Builder(SI.getContext());
  5941. Builder.SetInsertPoint(&SI);
  5942. // If LValue/HValue is a bitcast in another BB, create a new one in current
  5943. // BB so it may be merged with the splitted stores by dag combiner.
  5944. if (LBC && LBC->getParent() != SI.getParent())
  5945. LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
  5946. if (HBC && HBC->getParent() != SI.getParent())
  5947. HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
  5948. bool IsLE = SI.getModule()->getDataLayout().isLittleEndian();
  5949. auto CreateSplitStore = [&](Value *V, bool Upper) {
  5950. V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
  5951. Value *Addr = Builder.CreateBitCast(
  5952. SI.getOperand(1),
  5953. SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
  5954. if ((IsLE && Upper) || (!IsLE && !Upper))
  5955. Addr = Builder.CreateGEP(
  5956. SplitStoreType, Addr,
  5957. ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
  5958. Builder.CreateAlignedStore(
  5959. V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
  5960. };
  5961. CreateSplitStore(LValue, false);
  5962. CreateSplitStore(HValue, true);
  5963. // Delete the old store.
  5964. SI.eraseFromParent();
  5965. return true;
  5966. }
  5967. // Return true if the GEP has two operands, the first operand is of a sequential
  5968. // type, and the second operand is a constant.
  5969. static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) {
  5970. gep_type_iterator I = gep_type_begin(*GEP);
  5971. return GEP->getNumOperands() == 2 &&
  5972. I.isSequential() &&
  5973. isa<ConstantInt>(GEP->getOperand(1));
  5974. }
  5975. // Try unmerging GEPs to reduce liveness interference (register pressure) across
  5976. // IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
  5977. // reducing liveness interference across those edges benefits global register
  5978. // allocation. Currently handles only certain cases.
  5979. //
  5980. // For example, unmerge %GEPI and %UGEPI as below.
  5981. //
  5982. // ---------- BEFORE ----------
  5983. // SrcBlock:
  5984. // ...
  5985. // %GEPIOp = ...
  5986. // ...
  5987. // %GEPI = gep %GEPIOp, Idx
  5988. // ...
  5989. // indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
  5990. // (* %GEPI is alive on the indirectbr edges due to other uses ahead)
  5991. // (* %GEPIOp is alive on the indirectbr edges only because of it's used by
  5992. // %UGEPI)
  5993. //
  5994. // DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
  5995. // DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
  5996. // ...
  5997. //
  5998. // DstBi:
  5999. // ...
  6000. // %UGEPI = gep %GEPIOp, UIdx
  6001. // ...
  6002. // ---------------------------
  6003. //
  6004. // ---------- AFTER ----------
  6005. // SrcBlock:
  6006. // ... (same as above)
  6007. // (* %GEPI is still alive on the indirectbr edges)
  6008. // (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
  6009. // unmerging)
  6010. // ...
  6011. //
  6012. // DstBi:
  6013. // ...
  6014. // %UGEPI = gep %GEPI, (UIdx-Idx)
  6015. // ...
  6016. // ---------------------------
  6017. //
  6018. // The register pressure on the IndirectBr edges is reduced because %GEPIOp is
  6019. // no longer alive on them.
  6020. //
  6021. // We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
  6022. // of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
  6023. // not to disable further simplications and optimizations as a result of GEP
  6024. // merging.
  6025. //
  6026. // Note this unmerging may increase the length of the data flow critical path
  6027. // (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
  6028. // between the register pressure and the length of data-flow critical
  6029. // path. Restricting this to the uncommon IndirectBr case would minimize the
  6030. // impact of potentially longer critical path, if any, and the impact on compile
  6031. // time.
  6032. static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI,
  6033. const TargetTransformInfo *TTI) {
  6034. BasicBlock *SrcBlock = GEPI->getParent();
  6035. // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
  6036. // (non-IndirectBr) cases exit early here.
  6037. if (!isa<IndirectBrInst>(SrcBlock->getTerminator()))
  6038. return false;
  6039. // Check that GEPI is a simple gep with a single constant index.
  6040. if (!GEPSequentialConstIndexed(GEPI))
  6041. return false;
  6042. ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1));
  6043. // Check that GEPI is a cheap one.
  6044. if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType())
  6045. > TargetTransformInfo::TCC_Basic)
  6046. return false;
  6047. Value *GEPIOp = GEPI->getOperand(0);
  6048. // Check that GEPIOp is an instruction that's also defined in SrcBlock.
  6049. if (!isa<Instruction>(GEPIOp))
  6050. return false;
  6051. auto *GEPIOpI = cast<Instruction>(GEPIOp);
  6052. if (GEPIOpI->getParent() != SrcBlock)
  6053. return false;
  6054. // Check that GEP is used outside the block, meaning it's alive on the
  6055. // IndirectBr edge(s).
  6056. if (find_if(GEPI->users(), [&](User *Usr) {
  6057. if (auto *I = dyn_cast<Instruction>(Usr)) {
  6058. if (I->getParent() != SrcBlock) {
  6059. return true;
  6060. }
  6061. }
  6062. return false;
  6063. }) == GEPI->users().end())
  6064. return false;
  6065. // The second elements of the GEP chains to be unmerged.
  6066. std::vector<GetElementPtrInst *> UGEPIs;
  6067. // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
  6068. // on IndirectBr edges.
  6069. for (User *Usr : GEPIOp->users()) {
  6070. if (Usr == GEPI) continue;
  6071. // Check if Usr is an Instruction. If not, give up.
  6072. if (!isa<Instruction>(Usr))
  6073. return false;
  6074. auto *UI = cast<Instruction>(Usr);
  6075. // Check if Usr in the same block as GEPIOp, which is fine, skip.
  6076. if (UI->getParent() == SrcBlock)
  6077. continue;
  6078. // Check if Usr is a GEP. If not, give up.
  6079. if (!isa<GetElementPtrInst>(Usr))
  6080. return false;
  6081. auto *UGEPI = cast<GetElementPtrInst>(Usr);
  6082. // Check if UGEPI is a simple gep with a single constant index and GEPIOp is
  6083. // the pointer operand to it. If so, record it in the vector. If not, give
  6084. // up.
  6085. if (!GEPSequentialConstIndexed(UGEPI))
  6086. return false;
  6087. if (UGEPI->getOperand(0) != GEPIOp)
  6088. return false;
  6089. if (GEPIIdx->getType() !=
  6090. cast<ConstantInt>(UGEPI->getOperand(1))->getType())
  6091. return false;
  6092. ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
  6093. if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType())
  6094. > TargetTransformInfo::TCC_Basic)
  6095. return false;
  6096. UGEPIs.push_back(UGEPI);
  6097. }
  6098. if (UGEPIs.size() == 0)
  6099. return false;
  6100. // Check the materializing cost of (Uidx-Idx).
  6101. for (GetElementPtrInst *UGEPI : UGEPIs) {
  6102. ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
  6103. APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
  6104. unsigned ImmCost = TTI->getIntImmCost(NewIdx, GEPIIdx->getType());
  6105. if (ImmCost > TargetTransformInfo::TCC_Basic)
  6106. return false;
  6107. }
  6108. // Now unmerge between GEPI and UGEPIs.
  6109. for (GetElementPtrInst *UGEPI : UGEPIs) {
  6110. UGEPI->setOperand(0, GEPI);
  6111. ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
  6112. Constant *NewUGEPIIdx =
  6113. ConstantInt::get(GEPIIdx->getType(),
  6114. UGEPIIdx->getValue() - GEPIIdx->getValue());
  6115. UGEPI->setOperand(1, NewUGEPIIdx);
  6116. // If GEPI is not inbounds but UGEPI is inbounds, change UGEPI to not
  6117. // inbounds to avoid UB.
  6118. if (!GEPI->isInBounds()) {
  6119. UGEPI->setIsInBounds(false);
  6120. }
  6121. }
  6122. // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
  6123. // alive on IndirectBr edges).
  6124. assert(find_if(GEPIOp->users(), [&](User *Usr) {
  6125. return cast<Instruction>(Usr)->getParent() != SrcBlock;
  6126. }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock");
  6127. return true;
  6128. }
  6129. bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) {
  6130. // Bail out if we inserted the instruction to prevent optimizations from
  6131. // stepping on each other's toes.
  6132. if (InsertedInsts.count(I))
  6133. return false;
  6134. // TODO: Move into the switch on opcode below here.
  6135. if (PHINode *P = dyn_cast<PHINode>(I)) {
  6136. // It is possible for very late stage optimizations (such as SimplifyCFG)
  6137. // to introduce PHI nodes too late to be cleaned up. If we detect such a
  6138. // trivial PHI, go ahead and zap it here.
  6139. if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) {
  6140. LargeOffsetGEPMap.erase(P);
  6141. P->replaceAllUsesWith(V);
  6142. P->eraseFromParent();
  6143. ++NumPHIsElim;
  6144. return true;
  6145. }
  6146. return false;
  6147. }
  6148. if (CastInst *CI = dyn_cast<CastInst>(I)) {
  6149. // If the source of the cast is a constant, then this should have
  6150. // already been constant folded. The only reason NOT to constant fold
  6151. // it is if something (e.g. LSR) was careful to place the constant
  6152. // evaluation in a block other than then one that uses it (e.g. to hoist
  6153. // the address of globals out of a loop). If this is the case, we don't
  6154. // want to forward-subst the cast.
  6155. if (isa<Constant>(CI->getOperand(0)))
  6156. return false;
  6157. if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
  6158. return true;
  6159. if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
  6160. /// Sink a zext or sext into its user blocks if the target type doesn't
  6161. /// fit in one register
  6162. if (TLI &&
  6163. TLI->getTypeAction(CI->getContext(),
  6164. TLI->getValueType(*DL, CI->getType())) ==
  6165. TargetLowering::TypeExpandInteger) {
  6166. return SinkCast(CI);
  6167. } else {
  6168. bool MadeChange = optimizeExt(I);
  6169. return MadeChange | optimizeExtUses(I);
  6170. }
  6171. }
  6172. return false;
  6173. }
  6174. if (auto *Cmp = dyn_cast<CmpInst>(I))
  6175. if (TLI && optimizeCmp(Cmp, ModifiedDT))
  6176. return true;
  6177. if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
  6178. LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
  6179. if (TLI) {
  6180. bool Modified = optimizeLoadExt(LI);
  6181. unsigned AS = LI->getPointerAddressSpace();
  6182. Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
  6183. return Modified;
  6184. }
  6185. return false;
  6186. }
  6187. if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
  6188. if (TLI && splitMergedValStore(*SI, *DL, *TLI))
  6189. return true;
  6190. SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
  6191. if (TLI) {
  6192. unsigned AS = SI->getPointerAddressSpace();
  6193. return optimizeMemoryInst(I, SI->getOperand(1),
  6194. SI->getOperand(0)->getType(), AS);
  6195. }
  6196. return false;
  6197. }
  6198. if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
  6199. unsigned AS = RMW->getPointerAddressSpace();
  6200. return optimizeMemoryInst(I, RMW->getPointerOperand(),
  6201. RMW->getType(), AS);
  6202. }
  6203. if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
  6204. unsigned AS = CmpX->getPointerAddressSpace();
  6205. return optimizeMemoryInst(I, CmpX->getPointerOperand(),
  6206. CmpX->getCompareOperand()->getType(), AS);
  6207. }
  6208. BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
  6209. if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
  6210. EnableAndCmpSinking && TLI)
  6211. return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
  6212. // TODO: Move this into the switch on opcode - it handles shifts already.
  6213. if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
  6214. BinOp->getOpcode() == Instruction::LShr)) {
  6215. ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
  6216. if (TLI && CI && TLI->hasExtractBitsInsn())
  6217. if (OptimizeExtractBits(BinOp, CI, *TLI, *DL))
  6218. return true;
  6219. }
  6220. if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
  6221. if (GEPI->hasAllZeroIndices()) {
  6222. /// The GEP operand must be a pointer, so must its result -> BitCast
  6223. Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
  6224. GEPI->getName(), GEPI);
  6225. NC->setDebugLoc(GEPI->getDebugLoc());
  6226. GEPI->replaceAllUsesWith(NC);
  6227. GEPI->eraseFromParent();
  6228. ++NumGEPsElim;
  6229. optimizeInst(NC, ModifiedDT);
  6230. return true;
  6231. }
  6232. if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) {
  6233. return true;
  6234. }
  6235. return false;
  6236. }
  6237. if (tryToSinkFreeOperands(I))
  6238. return true;
  6239. switch (I->getOpcode()) {
  6240. case Instruction::Shl:
  6241. case Instruction::LShr:
  6242. case Instruction::AShr:
  6243. return optimizeShiftInst(cast<BinaryOperator>(I));
  6244. case Instruction::Call:
  6245. return optimizeCallInst(cast<CallInst>(I), ModifiedDT);
  6246. case Instruction::Select:
  6247. return optimizeSelectInst(cast<SelectInst>(I));
  6248. case Instruction::ShuffleVector:
  6249. return optimizeShuffleVectorInst(cast<ShuffleVectorInst>(I));
  6250. case Instruction::Switch:
  6251. return optimizeSwitchInst(cast<SwitchInst>(I));
  6252. case Instruction::ExtractElement:
  6253. return optimizeExtractElementInst(cast<ExtractElementInst>(I));
  6254. }
  6255. return false;
  6256. }
  6257. /// Given an OR instruction, check to see if this is a bitreverse
  6258. /// idiom. If so, insert the new intrinsic and return true.
  6259. static bool makeBitReverse(Instruction &I, const DataLayout &DL,
  6260. const TargetLowering &TLI) {
  6261. if (!I.getType()->isIntegerTy() ||
  6262. !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
  6263. TLI.getValueType(DL, I.getType(), true)))
  6264. return false;
  6265. SmallVector<Instruction*, 4> Insts;
  6266. if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
  6267. return false;
  6268. Instruction *LastInst = Insts.back();
  6269. I.replaceAllUsesWith(LastInst);
  6270. RecursivelyDeleteTriviallyDeadInstructions(&I);
  6271. return true;
  6272. }
  6273. // In this pass we look for GEP and cast instructions that are used
  6274. // across basic blocks and rewrite them to improve basic-block-at-a-time
  6275. // selection.
  6276. bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) {
  6277. SunkAddrs.clear();
  6278. bool MadeChange = false;
  6279. CurInstIterator = BB.begin();
  6280. while (CurInstIterator != BB.end()) {
  6281. MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
  6282. if (ModifiedDT)
  6283. return true;
  6284. }
  6285. bool MadeBitReverse = true;
  6286. while (TLI && MadeBitReverse) {
  6287. MadeBitReverse = false;
  6288. for (auto &I : reverse(BB)) {
  6289. if (makeBitReverse(I, *DL, *TLI)) {
  6290. MadeBitReverse = MadeChange = true;
  6291. break;
  6292. }
  6293. }
  6294. }
  6295. MadeChange |= dupRetToEnableTailCallOpts(&BB, ModifiedDT);
  6296. return MadeChange;
  6297. }
  6298. // llvm.dbg.value is far away from the value then iSel may not be able
  6299. // handle it properly. iSel will drop llvm.dbg.value if it can not
  6300. // find a node corresponding to the value.
  6301. bool CodeGenPrepare::placeDbgValues(Function &F) {
  6302. bool MadeChange = false;
  6303. for (BasicBlock &BB : F) {
  6304. Instruction *PrevNonDbgInst = nullptr;
  6305. for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
  6306. Instruction *Insn = &*BI++;
  6307. DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
  6308. // Leave dbg.values that refer to an alloca alone. These
  6309. // intrinsics describe the address of a variable (= the alloca)
  6310. // being taken. They should not be moved next to the alloca
  6311. // (and to the beginning of the scope), but rather stay close to
  6312. // where said address is used.
  6313. if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
  6314. PrevNonDbgInst = Insn;
  6315. continue;
  6316. }
  6317. Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
  6318. if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
  6319. // If VI is a phi in a block with an EHPad terminator, we can't insert
  6320. // after it.
  6321. if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
  6322. continue;
  6323. LLVM_DEBUG(dbgs() << "Moving Debug Value before :\n"
  6324. << *DVI << ' ' << *VI);
  6325. DVI->removeFromParent();
  6326. if (isa<PHINode>(VI))
  6327. DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
  6328. else
  6329. DVI->insertAfter(VI);
  6330. MadeChange = true;
  6331. ++NumDbgValueMoved;
  6332. }
  6333. }
  6334. }
  6335. return MadeChange;
  6336. }
  6337. /// Scale down both weights to fit into uint32_t.
  6338. static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
  6339. uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
  6340. uint32_t Scale = (NewMax / std::numeric_limits<uint32_t>::max()) + 1;
  6341. NewTrue = NewTrue / Scale;
  6342. NewFalse = NewFalse / Scale;
  6343. }
  6344. /// Some targets prefer to split a conditional branch like:
  6345. /// \code
  6346. /// %0 = icmp ne i32 %a, 0
  6347. /// %1 = icmp ne i32 %b, 0
  6348. /// %or.cond = or i1 %0, %1
  6349. /// br i1 %or.cond, label %TrueBB, label %FalseBB
  6350. /// \endcode
  6351. /// into multiple branch instructions like:
  6352. /// \code
  6353. /// bb1:
  6354. /// %0 = icmp ne i32 %a, 0
  6355. /// br i1 %0, label %TrueBB, label %bb2
  6356. /// bb2:
  6357. /// %1 = icmp ne i32 %b, 0
  6358. /// br i1 %1, label %TrueBB, label %FalseBB
  6359. /// \endcode
  6360. /// This usually allows instruction selection to do even further optimizations
  6361. /// and combine the compare with the branch instruction. Currently this is
  6362. /// applied for targets which have "cheap" jump instructions.
  6363. ///
  6364. /// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
  6365. ///
  6366. bool CodeGenPrepare::splitBranchCondition(Function &F, bool &ModifiedDT) {
  6367. if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
  6368. return false;
  6369. bool MadeChange = false;
  6370. for (auto &BB : F) {
  6371. // Does this BB end with the following?
  6372. // %cond1 = icmp|fcmp|binary instruction ...
  6373. // %cond2 = icmp|fcmp|binary instruction ...
  6374. // %cond.or = or|and i1 %cond1, cond2
  6375. // br i1 %cond.or label %dest1, label %dest2"
  6376. BinaryOperator *LogicOp;
  6377. BasicBlock *TBB, *FBB;
  6378. if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
  6379. continue;
  6380. auto *Br1 = cast<BranchInst>(BB.getTerminator());
  6381. if (Br1->getMetadata(LLVMContext::MD_unpredictable))
  6382. continue;
  6383. unsigned Opc;
  6384. Value *Cond1, *Cond2;
  6385. if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
  6386. m_OneUse(m_Value(Cond2)))))
  6387. Opc = Instruction::And;
  6388. else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
  6389. m_OneUse(m_Value(Cond2)))))
  6390. Opc = Instruction::Or;
  6391. else
  6392. continue;
  6393. if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
  6394. !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
  6395. continue;
  6396. LLVM_DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
  6397. // Create a new BB.
  6398. auto TmpBB =
  6399. BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
  6400. BB.getParent(), BB.getNextNode());
  6401. // Update original basic block by using the first condition directly by the
  6402. // branch instruction and removing the no longer needed and/or instruction.
  6403. Br1->setCondition(Cond1);
  6404. LogicOp->eraseFromParent();
  6405. // Depending on the condition we have to either replace the true or the
  6406. // false successor of the original branch instruction.
  6407. if (Opc == Instruction::And)
  6408. Br1->setSuccessor(0, TmpBB);
  6409. else
  6410. Br1->setSuccessor(1, TmpBB);
  6411. // Fill in the new basic block.
  6412. auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
  6413. if (auto *I = dyn_cast<Instruction>(Cond2)) {
  6414. I->removeFromParent();
  6415. I->insertBefore(Br2);
  6416. }
  6417. // Update PHI nodes in both successors. The original BB needs to be
  6418. // replaced in one successor's PHI nodes, because the branch comes now from
  6419. // the newly generated BB (NewBB). In the other successor we need to add one
  6420. // incoming edge to the PHI nodes, because both branch instructions target
  6421. // now the same successor. Depending on the original branch condition
  6422. // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
  6423. // we perform the correct update for the PHI nodes.
  6424. // This doesn't change the successor order of the just created branch
  6425. // instruction (or any other instruction).
  6426. if (Opc == Instruction::Or)
  6427. std::swap(TBB, FBB);
  6428. // Replace the old BB with the new BB.
  6429. TBB->replacePhiUsesWith(&BB, TmpBB);
  6430. // Add another incoming edge form the new BB.
  6431. for (PHINode &PN : FBB->phis()) {
  6432. auto *Val = PN.getIncomingValueForBlock(&BB);
  6433. PN.addIncoming(Val, TmpBB);
  6434. }
  6435. // Update the branch weights (from SelectionDAGBuilder::
  6436. // FindMergedConditions).
  6437. if (Opc == Instruction::Or) {
  6438. // Codegen X | Y as:
  6439. // BB1:
  6440. // jmp_if_X TBB
  6441. // jmp TmpBB
  6442. // TmpBB:
  6443. // jmp_if_Y TBB
  6444. // jmp FBB
  6445. //
  6446. // We have flexibility in setting Prob for BB1 and Prob for NewBB.
  6447. // The requirement is that
  6448. // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
  6449. // = TrueProb for original BB.
  6450. // Assuming the original weights are A and B, one choice is to set BB1's
  6451. // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
  6452. // assumes that
  6453. // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
  6454. // Another choice is to assume TrueProb for BB1 equals to TrueProb for
  6455. // TmpBB, but the math is more complicated.
  6456. uint64_t TrueWeight, FalseWeight;
  6457. if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
  6458. uint64_t NewTrueWeight = TrueWeight;
  6459. uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
  6460. scaleWeights(NewTrueWeight, NewFalseWeight);
  6461. Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
  6462. .createBranchWeights(TrueWeight, FalseWeight));
  6463. NewTrueWeight = TrueWeight;
  6464. NewFalseWeight = 2 * FalseWeight;
  6465. scaleWeights(NewTrueWeight, NewFalseWeight);
  6466. Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
  6467. .createBranchWeights(TrueWeight, FalseWeight));
  6468. }
  6469. } else {
  6470. // Codegen X & Y as:
  6471. // BB1:
  6472. // jmp_if_X TmpBB
  6473. // jmp FBB
  6474. // TmpBB:
  6475. // jmp_if_Y TBB
  6476. // jmp FBB
  6477. //
  6478. // This requires creation of TmpBB after CurBB.
  6479. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  6480. // The requirement is that
  6481. // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
  6482. // = FalseProb for original BB.
  6483. // Assuming the original weights are A and B, one choice is to set BB1's
  6484. // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
  6485. // assumes that
  6486. // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
  6487. uint64_t TrueWeight, FalseWeight;
  6488. if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
  6489. uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
  6490. uint64_t NewFalseWeight = FalseWeight;
  6491. scaleWeights(NewTrueWeight, NewFalseWeight);
  6492. Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
  6493. .createBranchWeights(TrueWeight, FalseWeight));
  6494. NewTrueWeight = 2 * TrueWeight;
  6495. NewFalseWeight = FalseWeight;
  6496. scaleWeights(NewTrueWeight, NewFalseWeight);
  6497. Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
  6498. .createBranchWeights(TrueWeight, FalseWeight));
  6499. }
  6500. }
  6501. ModifiedDT = true;
  6502. MadeChange = true;
  6503. LLVM_DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
  6504. TmpBB->dump());
  6505. }
  6506. return MadeChange;
  6507. }