CodeGenPrepare.cpp 257 KB

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